diff --git a/.gitattributes b/.gitattributes index 19c90f40..c23249d2 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,12 +3,12 @@ /.github export-ignore /.gitignore export-ignore /.php_cs.dist export-ignore -/.sami.php export-ignore /.scrutinizer.yml export-ignore /CHANGELOG.PHPExcel.md export-ignore /bin export-ignore /composer.lock export-ignore /docs export-ignore +/infra export-ignore /mkdocs.yml export-ignore /phpunit.xml.dist export-ignore /samples export-ignore diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..68ac78ad --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,8 @@ +version: 2 +updates: +- package-ecosystem: composer + directory: "/" + schedule: + interval: monthly + time: "11:00" + open-pull-requests-limit: 10 diff --git a/.github/workflows/github-pages.yml b/.github/workflows/github-pages.yml index 3bdeea1d..a7850833 100644 --- a/.github/workflows/github-pages.yml +++ b/.github/workflows/github-pages.yml @@ -19,7 +19,7 @@ jobs: - name: Build API documentation run: | - curl -LO https://github.com/phpDocumentor/phpDocumentor/releases/download/v3.0.0-rc/phpDocumentor.phar + curl -LO https://github.com/phpDocumentor/phpDocumentor/releases/download/v3.0.0/phpDocumentor.phar php phpDocumentor.phar --directory src/ --target docs/api - name: Deploy to GithHub Pages diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index a01892ae..32dd510a 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -5,6 +5,8 @@ jobs: runs-on: ubuntu-latest strategy: matrix: + experimental: + - false php-version: - '7.2' - '7.3' @@ -38,13 +40,13 @@ jobs: - name: Delete composer lock file id: composer-lock - if: ${{ matrix.php-version == '8.0' || matrix.php-version == '8.1' }} + if: ${{ matrix.php-version == '8.1' }} run: | rm composer.lock echo "::set-output name=flags::--ignore-platform-reqs" - name: Install dependencies - run: composer install --no-progress --prefer-dist --optimize-autoloader ${{ steps.composer-lock.outputs.flags }} + run: composer update --no-progress --prefer-dist --optimize-autoloader ${{ steps.composer-lock.outputs.flags }} - name: Setup problem matchers for PHP run: echo "::add-matcher::${{ runner.tool_cache }}/php.json" @@ -52,8 +54,10 @@ jobs: - name: Setup problem matchers for PHPUnit run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" - - name: Test with PHPUnit - run: ./vendor/bin/phpunit + - name: "Run PHPUnit tests (Experimental: ${{ matrix.experimental }})" + env: + FAILURE_ACTION: "${{ matrix.experimental == true }}" + run: vendor/bin/phpunit --verbose || $FAILURE_ACTION php-cs-fixer: runs-on: ubuntu-latest @@ -117,6 +121,68 @@ jobs: - name: Code style with PHP_CodeSniffer run: ./vendor/bin/phpcs -q --report=checkstyle | cs2pr + versions: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Setup PHP, with composer and extensions + uses: shivammathur/setup-php@v2 + with: + php-version: 7.4 + extensions: ctype, dom, gd, iconv, fileinfo, libxml, mbstring, simplexml, xml, xmlreader, xmlwriter, zip, zlib + coverage: none + tools: cs2pr + + - name: Get composer cache directory + id: composer-cache + run: echo "::set-output name=dir::$(composer config cache-files-dir)" + + - name: Cache composer dependencies + uses: actions/cache@v2 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} + restore-keys: ${{ runner.os }}-composer- + + - name: Install dependencies + run: composer install --no-progress --prefer-dist --optimize-autoloader + + - name: Code Version Compatibility check with PHP_CodeSniffer + run: ./vendor/bin/phpcs -q --report-width=200 --report=summary,full src/ --standard=PHPCompatibility --runtime-set testVersion 7.2- + + phpstan: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Setup PHP, with composer and extensions + uses: shivammathur/setup-php@v2 + with: + php-version: 7.4 + extensions: ctype, dom, gd, iconv, fileinfo, libxml, mbstring, simplexml, xml, xmlreader, xmlwriter, zip, zlib + coverage: none + tools: cs2pr + + - name: Get composer cache directory + id: composer-cache + run: echo "::set-output name=dir::$(composer config cache-files-dir)" + + - name: Cache composer dependencies + uses: actions/cache@v2 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} + restore-keys: ${{ runner.os }}-composer- + + - name: Install dependencies + run: composer install --no-progress --prefer-dist --optimize-autoloader + + - name: Static analysis with PHPStan + run: ./vendor/bin/phpstan analyse + coverage: runs-on: ubuntu-latest steps: diff --git a/.gitignore b/.gitignore index 0723541d..eac08567 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,6 @@ *.project /.settings /.idea + +## mkdocs output +/site diff --git a/.php_cs.dist b/.php_cs.dist index f8797e88..1a646420 100644 --- a/.php_cs.dist +++ b/.php_cs.dist @@ -160,7 +160,7 @@ return PhpCsFixer\Config::create() 'php_unit_test_annotation' => true, 'php_unit_test_case_static_method_calls' => ['call_type' => 'self'], 'php_unit_test_class_requires_covers' => false, // We don't care as much as we should about coverage - 'phpdoc_add_missing_param_annotation' => true, + 'phpdoc_add_missing_param_annotation' => false, // Don't add things that bring no value 'phpdoc_align' => false, // Waste of time 'phpdoc_annotation_without_dot' => true, 'phpdoc_indent' => true, diff --git a/CHANGELOG.PHPExcel.md b/CHANGELOG.PHPExcel.md index 3c299020..c92feda9 100644 --- a/CHANGELOG.PHPExcel.md +++ b/CHANGELOG.PHPExcel.md @@ -1518,7 +1518,7 @@ documentation for more information on entering dates into a cell. ### Bugfixes - PHPExcel->removeSheetByIndex now re-orders sheets after deletion, so no array indexes are lost - @JV -- PHPExcel_Writer_Excel2007_Worksheet::_writeCols() used direct assignment to $pSheet->getColumnDimension('A')->Width instead of $pSheet->getColumnDimension('A')->setWidth() - @JV +- PHPExcel_Writer_Excel2007_Worksheet::_writeCols() used direct assignment to $pSheet->getColumnDimension('A')->Width instead of ~~~~$pSheet->getColumnDimension('A')->setWidth() - @JV - DocumentProperties used $this->LastModifiedBy instead of $this->_lastModifiedBy. - @JV ### General diff --git a/CHANGELOG.md b/CHANGELOG.md index 04b99dfd..80e97885 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,8 +8,28 @@ and this project adheres to [Semantic Versioning](https://semver.org). ## Unreleased - TBD ### Added - -- CSV Reader - Best Guess for Encoding, and Handle Null-string Escape [#1647](https://github.com/PHPOffice/PhpSpreadsheet/issues/1647) +- Ability to set style on named range, and validate input to setSelectedCells. +[Issue #2279](https://github.com/PHPOffice/PhpSpreadsheet/issues/2279) +[PR #2280](https://github.com/PHPOffice/PhpSpreadsheet/pull/2280) +- Process comments in Sylk file. +[Issue #2276](https://github.com/PHPOffice/PhpSpreadsheet/issues/2276) +[PR #2277](https://github.com/PHPOffice/PhpSpreadsheet/pull/2277) +- Addition of Custom Properties to Ods Writer, and 32-bit-safe timestamps for Document Properties. +[PR #2113](https://github.com/PHPOffice/PhpSpreadsheet/pull/2113) +- Added callback to CSV reader to set user-specified defaults for various properties (especially for escape which has a poor PHP-inherited default of backslash which does not correspond with Excel). +[PR #2103](https://github.com/PHPOffice/PhpSpreadsheet/pull/2103) +- Phase 1 of better namespace handling for Xlsx, resolving many open issues. +[PR #2173](https://github.com/PHPOffice/PhpSpreadsheet/pull/2173) +[PR #2204](https://github.com/PHPOffice/PhpSpreadsheet/pull/2204) +[PR #2303](https://github.com/PHPOffice/PhpSpreadsheet/pull/2303) +- Add ability to extract images if source is a URL. [Issue #1997](https://github.com/PHPOffice/PhpSpreadsheet/issues/1997) [PR #2072](https://github.com/PHPOffice/PhpSpreadsheet/pull/2072) +- Support for passing flags in the Reader `load()` and Writer `save()`methods, and through the IOFactory, to set behaviours. [PR #2136](https://github.com/PHPOffice/PhpSpreadsheet/pull/2136) + - See [documentation](https://phpspreadsheet.readthedocs.io/en/latest/topics/reading-and-writing-to-file/) for details +- More flexibility in the StringValueBinder to determine what datatypes should be treated as strings [PR #2138](https://github.com/PHPOffice/PhpSpreadsheet/pull/2138) +- Helper class for conversion between css size Units of measure (`px`, `pt`, `pc`, `in`, `cm`, `mm`). [PR #2152](https://github.com/PHPOffice/PhpSpreadsheet/issues/2145) +- Allow Row height and Column Width to be set using different units of measure (`px`, `pt`, `pc`, `in`, `cm`, `mm`), rather than only in points or MS Excel column width units. [PR #2152](https://github.com/PHPOffice/PhpSpreadsheet/issues/2145) +- Ability to stream to an Amazon S3 bucket + [Issue #2249](https://github.com/PHPOffice/PhpSpreadsheet/issues/2249) - Provided a Size Helper class to validate size values (pt, px, em) ### Changed @@ -18,29 +38,247 @@ and this project adheres to [Semantic Versioning](https://semver.org). ### Deprecated +- PHP8.1 will deprecate auto_detect_line_endings. As a result of this change, Csv Reader using PHP8.1+ will no longer be able to handle a Csv with Mac line endings. + +### Removed + - Nothing. +### Fixed +- Unexpected format in Xlsx Timestamp +[Issue #2331](https://github.com/PHPOffice/PhpSpreadsheet/issues/2331) +[PR #2332](https://github.com/PHPOffice/PhpSpreadsheet/pull/2332) +- Corrections for HLOOKUP +[Issue #2123](https://github.com/PHPOffice/PhpSpreadsheet/issues/2123) +[PR #2330](https://github.com/PHPOffice/PhpSpreadsheet/pull/2330) +- Corrections for Xlsx Read Comments +[Issue #2316](https://github.com/PHPOffice/PhpSpreadsheet/issues/2316) +[PR #2329](https://github.com/PHPOffice/PhpSpreadsheet/pull/2329) +- Lowercase Calibri font names +[Issue #2273](https://github.com/PHPOffice/PhpSpreadsheet/issues/2273) +[PR #2325](https://github.com/PHPOffice/PhpSpreadsheet/pull/2325) +- isFormula Referencing Sheet with Space in Title +[Issue #2304](https://github.com/PHPOffice/PhpSpreadsheet/issues/2304) +[PR #2306](https://github.com/PHPOffice/PhpSpreadsheet/pull/2306) +- Xls Reader Fatal Error due to Undefined Offset +[Issue #1114](https://github.com/PHPOffice/PhpSpreadsheet/issues/1114) +[PR #2308](https://github.com/PHPOffice/PhpSpreadsheet/pull/2308) +- Permit Csv Reader delimiter to be set to null. +[Issue #2287](https://github.com/PHPOffice/PhpSpreadsheet/issues/2287) +[PR #2288](https://github.com/PHPOffice/PhpSpreadsheet/pull/2288) +- Csv Reader did not handle booleans correctly. +[PR #2232](https://github.com/PHPOffice/PhpSpreadsheet/pull/2232) +- Problems when deleting sheet with local defined name. +[Issue #2266](https://github.com/PHPOffice/PhpSpreadsheet/issues/2266) +[PR #2284](https://github.com/PHPOffice/PhpSpreadsheet/pull/2284) +- Worksheet passwords were not always handled correctly. +[Issue #1897](https://github.com/PHPOffice/PhpSpreadsheet/issues/1897) +[PR #2197](https://github.com/PHPOffice/PhpSpreadsheet/pull/2197) +- Gnumeric Reader will now distinguish between Created and Modified timestamp. +[PR #2133](https://github.com/PHPOffice/PhpSpreadsheet/pull/2133) +- Xls Reader will now handle MACCENTRALEUROPE with or without hyphen. +[Issue #549](https://github.com/PHPOffice/PhpSpreadsheet/issues/549) +[PR #2213](https://github.com/PHPOffice/PhpSpreadsheet/pull/2213) +- Tweaks to input file validation. +[Issue #1718](https://github.com/PHPOffice/PhpSpreadsheet/issues/1718) +[PR #2217](https://github.com/PHPOffice/PhpSpreadsheet/pull/2217) +- Html Reader did not handle comments correctly. +[Issue #2234](https://github.com/PHPOffice/PhpSpreadsheet/issues/2234) +[PR #2235](https://github.com/PHPOffice/PhpSpreadsheet/pull/2235) +- Apache OpenOffice Uses Unexpected Case for General format. +[Issue #2239](https://github.com/PHPOffice/PhpSpreadsheet/issues/2239) +[PR #2242](https://github.com/PHPOffice/PhpSpreadsheet/pull/2242) +- Problems with fraction formatting. +[Issue #2253](https://github.com/PHPOffice/PhpSpreadsheet/issues/2253) +[PR #2254](https://github.com/PHPOffice/PhpSpreadsheet/pull/2254) +- Xlsx Reader had problems reading file with no styles.xml or empty styles.xml. +[Issue #2246](https://github.com/PHPOffice/PhpSpreadsheet/issues/2246) +[PR #2247](https://github.com/PHPOffice/PhpSpreadsheet/pull/2247) +- Xlsx Reader did not read Data Validation flags correctly. +[Issue #2224](https://github.com/PHPOffice/PhpSpreadsheet/issues/2224) +[PR #2225](https://github.com/PHPOffice/PhpSpreadsheet/pull/2225) +- Better handling of empty arguments in Calculation engine. +[PR #2143](https://github.com/PHPOffice/PhpSpreadsheet/pull/2143) +- Many fixes for Autofilter. +[Issue #2216](https://github.com/PHPOffice/PhpSpreadsheet/issues/2216) +[PR #2141](https://github.com/PHPOffice/PhpSpreadsheet/pull/2141) +[PR #2162](https://github.com/PHPOffice/PhpSpreadsheet/pull/2162) +[PR #2218](https://github.com/PHPOffice/PhpSpreadsheet/pull/2218) +- Locale generator will now use Unix line endings even on Windows. +[Issue #2172](https://github.com/PHPOffice/PhpSpreadsheet/issues/2172) +[PR #2174](https://github.com/PHPOffice/PhpSpreadsheet/pull/2174) +- Support differences in implementation of Text functions between Excel/Ods/Gnumeric. +[PR #2151](https://github.com/PHPOffice/PhpSpreadsheet/pull/2151) +- Fixes to places where PHP8.1 enforces new or previously unenforced restrictions. +[PR #2137](https://github.com/PHPOffice/PhpSpreadsheet/pull/2137) +[PR #2191](https://github.com/PHPOffice/PhpSpreadsheet/pull/2191) +[PR #2231](https://github.com/PHPOffice/PhpSpreadsheet/pull/2231) +- Clone for HashTable was incorrect. +[PR #2130](https://github.com/PHPOffice/PhpSpreadsheet/pull/2130) +- Xlsx Reader was not evaluating Document Security Lock correctly. +[PR #2128](https://github.com/PHPOffice/PhpSpreadsheet/pull/2128) +- Error in COUPNCD handling end of month. +[Issue #2116](https://github.com/PHPOffice/PhpSpreadsheet/issues/2116) +[PR #2119](https://github.com/PHPOffice/PhpSpreadsheet/pull/2119) +- Xls Writer Parser did not handle concatenation operator correctly. +[PR #2080](https://github.com/PHPOffice/PhpSpreadsheet/pull/2080) +- Xlsx Writer did not handle boolean false correctly. +[Issue #2082](https://github.com/PHPOffice/PhpSpreadsheet/issues/2082) +[PR #2087](https://github.com/PHPOffice/PhpSpreadsheet/pull/2087) +- SUM needs to treat invalid strings differently depending on whether they come from a cell or are used as literals. +[Issue #2042](https://github.com/PHPOffice/PhpSpreadsheet/issues/2042) +[PR #2045](https://github.com/PHPOffice/PhpSpreadsheet/pull/2045) +- Html reader could have set illegal coordinates when dealing with embedded tables. +[Issue #2029](https://github.com/PHPOffice/PhpSpreadsheet/issues/2029) +[PR #2032](https://github.com/PHPOffice/PhpSpreadsheet/pull/2032) +- Documentation for printing gridlines was wrong. +[PR #2188](https://github.com/PHPOffice/PhpSpreadsheet/pull/2188) +- Return Value Error - DatabaseAbstruct::buildQuery() return null but must be string [Issue #2158](https://github.com/PHPOffice/PhpSpreadsheet/issues/2158) [PR #2160](https://github.com/PHPOffice/PhpSpreadsheet/pull/2160) +- Xlsx reader not recognize data validations that references another sheet +[Issue #1432](https://github.com/PHPOffice/PhpSpreadsheet/issues/1432) +[Issue #2149](https://github.com/PHPOffice/PhpSpreadsheet/issues/2149) +[PR #2150](https://github.com/PHPOffice/PhpSpreadsheet/pull/2150) +[PR #2265](https://github.com/PHPOffice/PhpSpreadsheet/pull/2265) +- Don't calculate cell width for autosize columns if a cell contains a null or empty string value [Issue #2165](https://github.com/PHPOffice/PhpSpreadsheet/issues/2165) [PR #2167](https://github.com/PHPOffice/PhpSpreadsheet/pull/2167) +- Allow negative interest rate values in a number of the Financial functions (`PPMT()`, `PMT()`, `FV()`, `PV()`, `NPER()`, etc) [Issue #2163](https://github.com/PHPOffice/PhpSpreadsheet/issues/2163) [PR #2164](https://github.com/PHPOffice/PhpSpreadsheet/pull/2164) +- Xls Reader changing grey background to black in Excel template [Issue #2147](Changing grey background to black in Excel template) [PR #2156](https://github.com/PHPOffice/PhpSpreadsheet/pull/2156) +- Column width and Row height styles in the Html Reader when the value includes a unit of measure. [Issue #2145](https://github.com/PHPOffice/PhpSpreadsheet/issues/2145). +- Data Validation flags not set correctly when reading XLSX files. [Issue #2224](https://github.com/PHPOffice/PhpSpreadsheet/issues/2224) [PR #2225](https://github.com/PHPOffice/PhpSpreadsheet/pull/2225) +- Reading XLSX files without styles.xml throws an exception. [Issue #2246](https://github.com/PHPOffice/PhpSpreadsheet/issues/2246) +- Improved performance of `Style::applyFromArray()` when applied to several cells. [PR #1785](https://github.com/PHPOffice/PhpSpreadsheet/issues/1785). +- Improve XLSX parsing speed if no readFilter is applied (again) - [#772](https://github.com/PHPOffice/PhpSpreadsheet/issues/772) + +## 1.18.0 - 2021-05-31 + +### Added +- Enhancements to CSV Reader, allowing options to be set when using `IOFactory::load()` with a callback to set delimiter, enclosure, charset etc. [PR #2103](https://github.com/PHPOffice/PhpSpreadsheet/pull/2103) - See [documentation](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/docs/topics/reading-and-writing-to-file.md#csv-comma-separated-values) for details. +- Implemented basic AutoFiltering for Ods Reader and Writer [PR #2053](https://github.com/PHPOffice/PhpSpreadsheet/pull/2053) +- Implemented basic AutoFiltering for Gnumeric Reader [PR #2055](https://github.com/PHPOffice/PhpSpreadsheet/pull/2055) +- Improved support for Row and Column ranges in formulae [Issue #1755](https://github.com/PHPOffice/PhpSpreadsheet/issues/1755) [PR #2028](https://github.com/PHPOffice/PhpSpreadsheet/pull/2028) +- Implemented URLENCODE() Web Function +- Implemented the CHITEST(), CHISQ.DIST() and CHISQ.INV() and equivalent Statistical functions, for both left- and right-tailed distributions. +- Support for ActiveSheet and SelectedCells in the ODS Reader and Writer. [PR #1908](https://github.com/PHPOffice/PhpSpreadsheet/pull/1908) +- Support for notContainsText Conditional Style in xlsx [Issue #984](https://github.com/PHPOffice/PhpSpreadsheet/issues/984) + +### Changed + +- Use of `nb` rather than `no` as the locale code for Norsk Bokmål. + +### Deprecated + +- All Excel Function implementations in `Calculation\Database`, `Calculation\DateTime`, `Calculation\Engineering`, `Calculation\Financial`, `Calculation\Logical`, `Calculation\LookupRef`, `Calculation\MathTrig`, `Calculation\Statistical`, `Calculation\TextData` and `Calculation\Web` have been moved to dedicated classes for individual functions or groups of related functions. See the docblocks against all the deprecated methods for details of the new methods to call instead. At some point, these old classes will be deleted. + +### Removed + +- Use of `nb` rather than `no` as the locale language code for Norsk Bokmål. + +### Fixed +- Fixed error in COUPNCD() calculation for end of month [Issue #2116](https://github.com/PHPOffice/PhpSpreadsheet/issues/2116) - [PR #2119](https://github.com/PHPOffice/PhpSpreadsheet/pull/2119) +- Resolve default values when a null argument is passed for HLOOKUP(), VLOOKUP() and ADDRESS() functions [Issue #2120](https://github.com/PHPOffice/PhpSpreadsheet/issues/2120) - [PR #2121](https://github.com/PHPOffice/PhpSpreadsheet/pull/2121) +- Fixed incorrect R1C1 to A1 subtraction formula conversion (`R[-2]C-R[2]C`) [Issue #2076](https://github.com/PHPOffice/PhpSpreadsheet/pull/2076) [PR #2086](https://github.com/PHPOffice/PhpSpreadsheet/pull/2086) +- Correctly handle absolute A1 references when converting to R1C1 format [PR #2060](https://github.com/PHPOffice/PhpSpreadsheet/pull/2060) +- Correct default fill style for conditional without a pattern defined [Issue #2035](https://github.com/PHPOffice/PhpSpreadsheet/issues/2035) [PR #2050](https://github.com/PHPOffice/PhpSpreadsheet/pull/2050) +- Fixed issue where array key check for existince before accessing arrays in Xlsx.php. [PR #1970](https://github.com/PHPOffice/PhpSpreadsheet/pull/1970) +- Fixed issue with quoted strings in number format mask rendered with toFormattedString() [Issue 1972#](https://github.com/PHPOffice/PhpSpreadsheet/issues/1972) [PR #1978](https://github.com/PHPOffice/PhpSpreadsheet/pull/1978) +- Fixed issue with percentage formats in number format mask rendered with toFormattedString() [Issue 1929#](https://github.com/PHPOffice/PhpSpreadsheet/issues/1929) [PR #1928](https://github.com/PHPOffice/PhpSpreadsheet/pull/1928) +- Fixed issue with _ spacing character in number format mask corrupting output from toFormattedString() [Issue 1924#](https://github.com/PHPOffice/PhpSpreadsheet/issues/1924) [PR #1927](https://github.com/PHPOffice/PhpSpreadsheet/pull/1927) +- Fix for [Issue #1887](https://github.com/PHPOffice/PhpSpreadsheet/issues/1887) - Lose Track of Selected Cells After Save +- Fixed issue with Xlsx@listWorksheetInfo not returning any data +- Fixed invalid arguments triggering mb_substr() error in LEFT(), MID() and RIGHT() text functions. [Issue #640](https://github.com/PHPOffice/PhpSpreadsheet/issues/640) +- Fix for [Issue #1916](https://github.com/PHPOffice/PhpSpreadsheet/issues/1916) - Invalid signature check for XML files +- Fix change in `Font::setSize()` behavior for PHP8. [PR #2100](https://github.com/PHPOffice/PhpSpreadsheet/pull/2100) + +## 1.17.1 - 2021-03-01 + +### Added + +- Implementation of the Excel `AVERAGEIFS()` functions as part of a restructuring of Database functions and Conditional Statistical functions. +- Support for date values and percentages in query parameters for Database functions, and the IF expressions in functions like COUNTIF() and AVERAGEIF(). [#1875](https://github.com/PHPOffice/PhpSpreadsheet/pull/1875) +- Support for booleans, and for wildcard text search in query parameters for Database functions, and the IF expressions in functions like COUNTIF() and AVERAGEIF(). [#1876](https://github.com/PHPOffice/PhpSpreadsheet/pull/1876) +- Implemented DataBar for conditional formatting in Xlsx, providing read/write and creation of (type, value, direction, fills, border, axis position, color settings) as DataBar options in Excel. [#1754](https://github.com/PHPOffice/PhpSpreadsheet/pull/1754) +- Alignment for ODS Writer [#1796](https://github.com/PHPOffice/PhpSpreadsheet/issues/1796) +- Basic implementation of the PERMUTATIONA() Statistical Function + +### Changed + +- Formula functions that previously called PHP functions directly are now processed through the Excel Functions classes; resolving issues with PHP8 stricter typing. [#1789](https://github.com/PHPOffice/PhpSpreadsheet/issues/1789) + + The following MathTrig functions are affected: + `ABS()`, `ACOS()`, `ACOSH()`, `ASIN()`, `ASINH()`, `ATAN()`, `ATANH()`, + `COS()`, `COSH()`, `DEGREES()` (rad2deg), `EXP()`, `LN()` (log), `LOG10()`, + `RADIANS()` (deg2rad), `SIN()`, `SINH()`, `SQRT()`, `TAN()`, `TANH()`. + + One TextData function is also affected: `REPT()` (str_repeat). +- `formatAsDate` correctly matches language metadata, reverting c55272e +- Formulae that previously crashed on sub function call returning excel error value now return said value. + The following functions are affected `CUMPRINC()`, `CUMIPMT()`, `AMORLINC()`, + `AMORDEGRC()`. +- Adapt some function error return value to match excel's error. + The following functions are affected `PPMT()`, `IPMT()`. + +### Deprecated + +- Calling many of the Excel formula functions directly rather than through the Calculation Engine. + + The logic for these Functions is now being moved out of the categorised `Database`, `DateTime`, `Engineering`, `Financial`, `Logical`, `LookupRef`, `MathTrig`, `Statistical`, `TextData` and `Web` classes into small, dedicated classes for individual functions or related groups of functions. + + This makes the logic in these classes easier to maintain; and will reduce the memory footprint required to execute formulae when calling these functions. + ### Removed - Nothing. ### Fixed +- Avoid Duplicate Titles When Reading Multiple HTML Files.[Issue #1823](https://github.com/PHPOffice/PhpSpreadsheet/issues/1823) [PR #1829](https://github.com/PHPOffice/PhpSpreadsheet/pull/1829) +- Fixed issue with Worksheet's `getCell()` method when trying to get a cell by defined name. [#1858](https://github.com/PHPOffice/PhpSpreadsheet/issues/1858) +- Fix possible endless loop in NumberFormat Masks [#1792](https://github.com/PHPOffice/PhpSpreadsheet/issues/1792) +- Fix problem resulting from literal dot inside quotes in number format masks. [PR #1830](https://github.com/PHPOffice/PhpSpreadsheet/pull/1830) +- Resolve Google Sheets Xlsx charts issue. Google Sheets uses oneCellAnchor positioning and does not include *Cache values in the exported Xlsx. [PR #1761](https://github.com/PHPOffice/PhpSpreadsheet/pull/1761) +- Fix for Xlsx Chart axis titles mapping to correct X or Y axis label when only one is present. [PR #1760](https://github.com/PHPOffice/PhpSpreadsheet/pull/1760) +- Fix For Null Exception on ODS Read of Page Settings. [#1772](https://github.com/PHPOffice/PhpSpreadsheet/issues/1772) +- Fix Xlsx reader overriding manually set number format with builtin number format. [PR #1805](https://github.com/PHPOffice/PhpSpreadsheet/pull/1805) +- Fix Xlsx reader cell alignment. [PR #1710](https://github.com/PHPOffice/PhpSpreadsheet/pull/1710) +- Fix for not yet implemented data-types in Open Document writer [Issue #1674](https://github.com/PHPOffice/PhpSpreadsheet/issues/1674) +- Fix XLSX reader when having a corrupt numeric cell data type [PR #1664](https://github.com/phpoffice/phpspreadsheet/pull/1664) +- Fix on `CUMPRINC()`, `CUMIPMT()`, `AMORLINC()`, `AMORDEGRC()` usage. When those functions called one of `YEARFRAC()`, `PPMT()`, `IPMT()` and they would get back an error value (represented as a string), trying to use numeral operands (`+`, `/`, `-`, `*`) on said return value and a number (`float or `int`) would fail. + +## 1.16.0 - 2020-12-31 + +### Added + +- CSV Reader - Best Guess for Encoding, and Handle Null-string Escape [#1647](https://github.com/PHPOffice/PhpSpreadsheet/issues/1647) + +### Changed + +- Updated the CONVERT() function to support all current MS Excel categories and Units of Measure. + +### Deprecated + +- All Excel Function implementations in `Calculation\Database`, `Calculation\DateTime`, `Calculation\Engineering`, `Calculation\Financial`, `Calculation\Logical`, `Calculation\LookupRef`, `Calculation\MathTrig`, `Calculation\Statistical`, `Calculation\TextData` and `Calculation\Web` have been moved to dedicated classes for individual functions or groups of related functions. See the docblocks against all the deprecated methods for details of the new methods to call instead. At some point, these old classes will be deleted. + +### Removed + +- Nothing. + +### Fixed + +- Fixed issue with absolute path in worksheets' Target. [PR #1769](https://github.com/PHPOffice/PhpSpreadsheet/pull/1769) - Fix for Xls Reader when SST has a bad length [#1592](https://github.com/PHPOffice/PhpSpreadsheet/issues/1592) -- Resolve Xlsx loader issue whe hyperlinks don't have a destination +- Resolve Xlsx loader issue whe hyperlinks don't have a destination - Resolve issues when printer settings resources IDs clash with drawing IDs - Resolve issue with SLK long filenames [#1612](https://github.com/PHPOffice/PhpSpreadsheet/issues/1612) - ROUNDUP and ROUNDDOWN return incorrect results for values of 0 [#1627](https://github.com/phpoffice/phpspreadsheet/pull/1627) - Apply Column and Row Styles to Existing Cells [#1712](https://github.com/PHPOffice/PhpSpreadsheet/issues/1712) [PR #1721](https://github.com/PHPOffice/PhpSpreadsheet/pull/1721) - Resolve issues with defined names where worksheet doesn't exist (#1686)[https://github.com/PHPOffice/PhpSpreadsheet/issues/1686] and [#1723](https://github.com/PHPOffice/PhpSpreadsheet/issues/1723) - [PR #1742](https://github.com/PHPOffice/PhpSpreadsheet/pull/1742) -- Fix for issue [#1735](https://github.com/PHPOffice/PhpSpreadsheet/issues/1735) Incorrect activeSheetIndex after RemoveSheetByIndex - [PR #1743](https://github.com/PHPOffice/PhpSpreadsheet/pull/1743) +- Fix for issue [#1735](https://github.com/PHPOffice/PhpSpreadsheet/issues/1735) Incorrect activeSheetIndex after RemoveSheetByIndex - [PR #1743](https://github.com/PHPOffice/PhpSpreadsheet/pull/1743) - Ensure that the list of shared formulae is maintained when an xlsx file is chunked with readFilter[Issue #169](https://github.com/PHPOffice/PhpSpreadsheet/issues/1669). - Fix for notice during accessing "cached magnification factor" offset [#1354](https://github.com/PHPOffice/PhpSpreadsheet/pull/1354) - Fix compatibility with ext-gd on php 8 ### Security Fix (CVE-2020-7776) -- Prevent XSS through cell comments in the HTML Writer. +- Prevent XSS through cell comments in the HTML Writer. ## 1.15.0 - 2020-10-11 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index aed13fe2..f5953533 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -9,3 +9,12 @@ If you would like to contribute, here are some notes and guidelines: - All code changes must be validated by `composer check` - [Helpful article about forking](https://help.github.com/articles/fork-a-repo/ "Forking a GitHub repository") - [Helpful article about pull requests](https://help.github.com/articles/using-pull-requests/ "Pull Requests") + +## How to release + +1. Complete CHANGELOG.md and commit +2. Create an annotated tag + 1. `git tag -a 1.2.3` + 2. Tag subject must be the version number, eg: `1.2.3` + 3. Tag body must be a copy-paste of the changelog entries +3. Push tag with `git push --tags`, GitHub Actions will create a GitHub release automatically diff --git a/bin/generate-document b/bin/generate-document index d44ec624..a8f334c9 100755 --- a/bin/generate-document +++ b/bin/generate-document @@ -2,12 +2,13 @@ getProperty('phpSpreadsheetFunctions'); + $phpSpreadsheetFunctionsProperty = (new ReflectionClass(Calculation::class)) + ->getProperty('phpSpreadsheetFunctions'); $phpSpreadsheetFunctionsProperty->setAccessible(true); $phpSpreadsheetFunctions = $phpSpreadsheetFunctionsProperty->getValue(); ksort($phpSpreadsheetFunctions); diff --git a/bin/generate-locales b/bin/generate-locales new file mode 100644 index 00000000..30b9c556 --- /dev/null +++ b/bin/generate-locales @@ -0,0 +1,25 @@ +#!/usr/bin/env php +getProperty('phpSpreadsheetFunctions'); + $phpSpreadsheetFunctionsProperty->setAccessible(true); + $phpSpreadsheetFunctions = $phpSpreadsheetFunctionsProperty->getValue(); + + $localeGenerator = new LocaleGenerator( + realpath(__DIR__ . '/../src/PhpSpreadsheet/Calculation/locale/'), + 'Translations.xlsx', + $phpSpreadsheetFunctions, + true + ); + $localeGenerator->generateLocales(); +} catch (\Exception $e) { + fwrite(STDERR, (string) $e); + exit(1); +} diff --git a/composer.json b/composer.json index c6f8e30e..dff99d7e 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,19 @@ { "name": "phpoffice/phpspreadsheet", "description": "PHPSpreadsheet - Read, Create and Write Spreadsheet documents in PHP - Spreadsheet engine", - "keywords": ["PHP", "OpenXML", "Excel", "xlsx", "xls", "ods", "gnumeric", "spreadsheet"], + "keywords": [ + "PHP", + "OpenXML", + "Excel", + "xlsx", + "xls", + "ods", + "gnumeric", + "spreadsheet" + ], + "config": { + "sort-packages": true + }, "homepage": "https://github.com/PHPOffice/PhpSpreadsheet", "type": "library", "license": "MIT", @@ -29,7 +41,8 @@ "check": [ "php-cs-fixer fix --ansi --dry-run --diff", "phpcs", - "phpunit --color=always" + "phpunit --color=always", + "phpstan analyse --ansi" ], "fix": [ "php-cs-fixer fix --ansi" @@ -39,35 +52,38 @@ ] }, "require": { - "php": "^7.2||^8.0", + "php": "^7.2 || ^8.0", "ext-ctype": "*", "ext-dom": "*", + "ext-fileinfo": "*", "ext-gd": "*", "ext-iconv": "*", - "ext-fileinfo": "*", "ext-libxml": "*", "ext-mbstring": "*", - "ext-SimpleXML": "*", + "ext-simplexml": "*", "ext-xml": "*", "ext-xmlreader": "*", "ext-xmlwriter": "*", "ext-zip": "*", "ext-zlib": "*", + "ezyang/htmlpurifier": "^4.13", "maennchen/zipstream-php": "^2.1", - "markbaker/complex": "^1.5||^2.0", - "markbaker/matrix": "^1.2||^2.0", - "psr/simple-cache": "^1.0", + "markbaker/complex": "^3.0", + "markbaker/matrix": "^3.0", "psr/http-client": "^1.0", "psr/http-factory": "^1.0", - "ezyang/htmlpurifier": "^4.13" + "psr/simple-cache": "^1.0" }, "require-dev": { - "dompdf/dompdf": "^0.8.5", - "friendsofphp/php-cs-fixer": "^2.16", + "dealerdirect/phpcodesniffer-composer-installer": "dev-master", + "dompdf/dompdf": "^1.0", + "friendsofphp/php-cs-fixer": "^2.18", "jpgraph/jpgraph": "^4.0", "mpdf/mpdf": "^8.0", "phpcompatibility/php-compatibility": "^9.3", - "phpunit/phpunit": "^8.5||^9.3", + "phpstan/phpstan": "^0.12.82", + "phpstan/phpstan-phpunit": "^0.12.18", + "phpunit/phpunit": "^8.5", "squizlabs/php_codesniffer": "^3.5", "tecnickcom/tcpdf": "^6.3" }, @@ -84,7 +100,8 @@ }, "autoload-dev": { "psr-4": { - "PhpOffice\\PhpSpreadsheetTests\\": "tests/PhpSpreadsheetTests" + "PhpOffice\\PhpSpreadsheetTests\\": "tests/PhpSpreadsheetTests", + "PhpOffice\\PhpSpreadsheetInfra\\": "infra" } } } diff --git a/composer.lock b/composer.lock index a1fb99b7..f5670fd3 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "458fe4e974b469230da589a8781d1e0e", + "content-hash": "08bcc40376dc4b219b21d172e40c622d", "packages": [ { "name": "ezyang/htmlpurifier", @@ -119,20 +119,30 @@ "stream", "zip" ], + "support": { + "issues": "https://github.com/maennchen/ZipStream-PHP/issues", + "source": "https://github.com/maennchen/ZipStream-PHP/tree/master" + }, + "funding": [ + { + "url": "https://opencollective.com/zipstream", + "type": "open_collective" + } + ], "time": "2020-05-30T13:11:16+00:00" }, { "name": "markbaker/complex", - "version": "2.0.0", + "version": "3.0.1", "source": { "type": "git", "url": "https://github.com/MarkBaker/PHPComplex.git", - "reference": "9999f1432fae467bc93c53f357105b4c31bb994c" + "reference": "ab8bc271e404909db09ff2d5ffa1e538085c0f22" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/MarkBaker/PHPComplex/zipball/9999f1432fae467bc93c53f357105b4c31bb994c", - "reference": "9999f1432fae467bc93c53f357105b4c31bb994c", + "url": "https://api.github.com/repos/MarkBaker/PHPComplex/zipball/ab8bc271e404909db09ff2d5ffa1e538085c0f22", + "reference": "ab8bc271e404909db09ff2d5ffa1e538085c0f22", "shasum": "" }, "require": { @@ -141,62 +151,14 @@ "require-dev": { "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0", "phpcompatibility/php-compatibility": "^9.0", - "phpdocumentor/phpdocumentor": "2.*", - "phploc/phploc": "^4.0", - "phpmd/phpmd": "2.*", "phpunit/phpunit": "^7.0 || ^8.0 || ^9.3", - "sebastian/phpcpd": "^4.0", "squizlabs/php_codesniffer": "^3.4" }, "type": "library", "autoload": { "psr-4": { "Complex\\": "classes/src/" - }, - "files": [ - "classes/src/functions/abs.php", - "classes/src/functions/acos.php", - "classes/src/functions/acosh.php", - "classes/src/functions/acot.php", - "classes/src/functions/acoth.php", - "classes/src/functions/acsc.php", - "classes/src/functions/acsch.php", - "classes/src/functions/argument.php", - "classes/src/functions/asec.php", - "classes/src/functions/asech.php", - "classes/src/functions/asin.php", - "classes/src/functions/asinh.php", - "classes/src/functions/atan.php", - "classes/src/functions/atanh.php", - "classes/src/functions/conjugate.php", - "classes/src/functions/cos.php", - "classes/src/functions/cosh.php", - "classes/src/functions/cot.php", - "classes/src/functions/coth.php", - "classes/src/functions/csc.php", - "classes/src/functions/csch.php", - "classes/src/functions/exp.php", - "classes/src/functions/inverse.php", - "classes/src/functions/ln.php", - "classes/src/functions/log2.php", - "classes/src/functions/log10.php", - "classes/src/functions/negative.php", - "classes/src/functions/pow.php", - "classes/src/functions/rho.php", - "classes/src/functions/sec.php", - "classes/src/functions/sech.php", - "classes/src/functions/sin.php", - "classes/src/functions/sinh.php", - "classes/src/functions/sqrt.php", - "classes/src/functions/tan.php", - "classes/src/functions/tanh.php", - "classes/src/functions/theta.php", - "classes/src/operations/add.php", - "classes/src/operations/subtract.php", - "classes/src/operations/multiply.php", - "classes/src/operations/divideby.php", - "classes/src/operations/divideinto.php" - ] + } }, "notification-url": "https://packagist.org/downloads/", "license": [ @@ -214,24 +176,28 @@ "complex", "mathematics" ], - "time": "2020-08-26T10:42:07+00:00" + "support": { + "issues": "https://github.com/MarkBaker/PHPComplex/issues", + "source": "https://github.com/MarkBaker/PHPComplex/tree/3.0.1" + }, + "time": "2021-06-29T15:32:53+00:00" }, { "name": "markbaker/matrix", - "version": "2.0.0", + "version": "3.0.0", "source": { "type": "git", "url": "https://github.com/MarkBaker/PHPMatrix.git", - "reference": "9567d9c4c519fbe40de01dbd1e4469dbbb66f46a" + "reference": "c66aefcafb4f6c269510e9ac46b82619a904c576" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/MarkBaker/PHPMatrix/zipball/9567d9c4c519fbe40de01dbd1e4469dbbb66f46a", - "reference": "9567d9c4c519fbe40de01dbd1e4469dbbb66f46a", + "url": "https://api.github.com/repos/MarkBaker/PHPMatrix/zipball/c66aefcafb4f6c269510e9ac46b82619a904c576", + "reference": "c66aefcafb4f6c269510e9ac46b82619a904c576", "shasum": "" }, "require": { - "php": "^7.2 || ^8.0" + "php": "^7.1 || ^8.0" }, "require-dev": { "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0", @@ -247,25 +213,7 @@ "autoload": { "psr-4": { "Matrix\\": "classes/src/" - }, - "files": [ - "classes/src/functions/adjoint.php", - "classes/src/functions/antidiagonal.php", - "classes/src/functions/cofactors.php", - "classes/src/functions/determinant.php", - "classes/src/functions/diagonal.php", - "classes/src/functions/identity.php", - "classes/src/functions/inverse.php", - "classes/src/functions/minors.php", - "classes/src/functions/trace.php", - "classes/src/functions/transpose.php", - "classes/src/operations/add.php", - "classes/src/operations/directsum.php", - "classes/src/operations/subtract.php", - "classes/src/operations/multiply.php", - "classes/src/operations/divideby.php", - "classes/src/operations/divideinto.php" - ] + } }, "notification-url": "https://packagist.org/downloads/", "license": [ @@ -284,20 +232,24 @@ "matrix", "vector" ], - "time": "2020-08-28T17:11:00+00:00" + "support": { + "issues": "https://github.com/MarkBaker/PHPMatrix/issues", + "source": "https://github.com/MarkBaker/PHPMatrix/tree/3.0.0" + }, + "time": "2021-07-01T19:01:15+00:00" }, { "name": "myclabs/php-enum", - "version": "1.7.6", + "version": "1.7.7", "source": { "type": "git", "url": "https://github.com/myclabs/php-enum.git", - "reference": "5f36467c7a87e20fbdc51e524fd8f9d1de80187c" + "reference": "d178027d1e679832db9f38248fcc7200647dc2b7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/myclabs/php-enum/zipball/5f36467c7a87e20fbdc51e524fd8f9d1de80187c", - "reference": "5f36467c7a87e20fbdc51e524fd8f9d1de80187c", + "url": "https://api.github.com/repos/myclabs/php-enum/zipball/d178027d1e679832db9f38248fcc7200647dc2b7", + "reference": "d178027d1e679832db9f38248fcc7200647dc2b7", "shasum": "" }, "require": { @@ -330,7 +282,21 @@ "keywords": [ "enum" ], - "time": "2020-02-14T08:15:52+00:00" + "support": { + "issues": "https://github.com/myclabs/php-enum/issues", + "source": "https://github.com/myclabs/php-enum/tree/1.7.7" + }, + "funding": [ + { + "url": "https://github.com/mnapoli", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/myclabs/php-enum", + "type": "tidelift" + } + ], + "time": "2020-11-14T18:14:52+00:00" }, { "name": "psr/http-client", @@ -379,6 +345,9 @@ "psr", "psr-18" ], + "support": { + "source": "https://github.com/php-fig/http-client/tree/master" + }, "time": "2020-06-29T06:28:15+00:00" }, { @@ -431,6 +400,9 @@ "request", "response" ], + "support": { + "source": "https://github.com/php-fig/http-factory/tree/master" + }, "time": "2019-04-30T12:38:16+00:00" }, { @@ -481,6 +453,9 @@ "request", "response" ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/master" + }, "time": "2016-08-06T14:39:51+00:00" }, { @@ -529,24 +504,27 @@ "psr-16", "simple-cache" ], + "support": { + "source": "https://github.com/php-fig/simple-cache/tree/master" + }, "time": "2017-10-23T01:57:42+00:00" }, { "name": "symfony/polyfill-mbstring", - "version": "v1.18.1", + "version": "v1.23.1", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-mbstring.git", - "reference": "a6977d63bf9a0ad4c65cd352709e230876f9904a" + "reference": "9174a3d80210dca8daa7f31fec659150bbeabfc6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/a6977d63bf9a0ad4c65cd352709e230876f9904a", - "reference": "a6977d63bf9a0ad4c65cd352709e230876f9904a", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/9174a3d80210dca8daa7f31fec659150bbeabfc6", + "reference": "9174a3d80210dca8daa7f31fec659150bbeabfc6", "shasum": "" }, "require": { - "php": ">=5.3.3" + "php": ">=7.1" }, "suggest": { "ext-mbstring": "For best performance" @@ -554,7 +532,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.18-dev" + "dev-main": "1.23-dev" }, "thanks": { "name": "symfony/polyfill", @@ -592,6 +570,9 @@ "portable", "shim" ], + "support": { + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.23.1" + }, "funding": [ { "url": "https://symfony.com/sponsor", @@ -606,34 +587,35 @@ "type": "tidelift" } ], - "time": "2020-07-14T12:35:20+00:00" + "time": "2021-05-27T12:26:48+00:00" } ], "packages-dev": [ { "name": "composer/semver", - "version": "1.7.1", + "version": "3.2.6", "source": { "type": "git", "url": "https://github.com/composer/semver.git", - "reference": "38276325bd896f90dfcfe30029aa5db40df387a7" + "reference": "83e511e247de329283478496f7a1e114c9517506" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/composer/semver/zipball/38276325bd896f90dfcfe30029aa5db40df387a7", - "reference": "38276325bd896f90dfcfe30029aa5db40df387a7", + "url": "https://api.github.com/repos/composer/semver/zipball/83e511e247de329283478496f7a1e114c9517506", + "reference": "83e511e247de329283478496f7a1e114c9517506", "shasum": "" }, "require": { - "php": "^5.3.2 || ^7.0" + "php": "^5.3.2 || ^7.0 || ^8.0" }, "require-dev": { - "phpunit/phpunit": "^4.5 || ^5.0.5" + "phpstan/phpstan": "^0.12.54", + "symfony/phpunit-bridge": "^4.2 || ^5" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.x-dev" + "dev-main": "3.x-dev" } }, "autoload": { @@ -669,6 +651,11 @@ "validation", "versioning" ], + "support": { + "irc": "irc://irc.freenode.org/composer", + "issues": "https://github.com/composer/semver/issues", + "source": "https://github.com/composer/semver/tree/3.2.6" + }, "funding": [ { "url": "https://packagist.com", @@ -683,28 +670,29 @@ "type": "tidelift" } ], - "time": "2020-09-27T13:13:07+00:00" + "time": "2021-10-25T11:34:17+00:00" }, { "name": "composer/xdebug-handler", - "version": "1.4.3", + "version": "2.0.2", "source": { "type": "git", "url": "https://github.com/composer/xdebug-handler.git", - "reference": "ebd27a9866ae8254e873866f795491f02418c5a5" + "reference": "84674dd3a7575ba617f5a76d7e9e29a7d3891339" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/composer/xdebug-handler/zipball/ebd27a9866ae8254e873866f795491f02418c5a5", - "reference": "ebd27a9866ae8254e873866f795491f02418c5a5", + "url": "https://api.github.com/repos/composer/xdebug-handler/zipball/84674dd3a7575ba617f5a76d7e9e29a7d3891339", + "reference": "84674dd3a7575ba617f5a76d7e9e29a7d3891339", "shasum": "" }, "require": { "php": "^5.3.2 || ^7.0 || ^8.0", - "psr/log": "^1.0" + "psr/log": "^1 || ^2 || ^3" }, "require-dev": { - "phpunit/phpunit": "^4.8.35 || ^5.7 || 6.5 - 8" + "phpstan/phpstan": "^0.12.55", + "symfony/phpunit-bridge": "^4.2 || ^5" }, "type": "library", "autoload": { @@ -727,6 +715,11 @@ "Xdebug", "performance" ], + "support": { + "irc": "irc://irc.freenode.org/composer", + "issues": "https://github.com/composer/xdebug-handler/issues", + "source": "https://github.com/composer/xdebug-handler/tree/2.0.2" + }, "funding": [ { "url": "https://packagist.com", @@ -741,38 +734,107 @@ "type": "tidelift" } ], - "time": "2020-08-19T10:27:58+00:00" + "time": "2021-07-31T17:03:58+00:00" }, { - "name": "doctrine/annotations", - "version": "1.10.4", + "name": "dealerdirect/phpcodesniffer-composer-installer", + "version": "dev-master", "source": { "type": "git", - "url": "https://github.com/doctrine/annotations.git", - "reference": "bfe91e31984e2ba76df1c1339681770401ec262f" + "url": "https://github.com/Dealerdirect/phpcodesniffer-composer-installer.git", + "reference": "7d5cb8826ed72d4ca4c07acf005bba2282e5a7c7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/doctrine/annotations/zipball/bfe91e31984e2ba76df1c1339681770401ec262f", - "reference": "bfe91e31984e2ba76df1c1339681770401ec262f", + "url": "https://api.github.com/repos/Dealerdirect/phpcodesniffer-composer-installer/zipball/7d5cb8826ed72d4ca4c07acf005bba2282e5a7c7", + "reference": "7d5cb8826ed72d4ca4c07acf005bba2282e5a7c7", + "shasum": "" + }, + "require": { + "composer-plugin-api": "^1.0 || ^2.0", + "php": ">=5.3", + "squizlabs/php_codesniffer": "^2.0 || ^3.0 || ^4.0" + }, + "require-dev": { + "composer/composer": "*", + "php-parallel-lint/php-parallel-lint": "^1.3", + "phpcompatibility/php-compatibility": "^9.0" + }, + "default-branch": true, + "type": "composer-plugin", + "extra": { + "class": "Dealerdirect\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\Plugin" + }, + "autoload": { + "psr-4": { + "Dealerdirect\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Franck Nijhof", + "email": "franck.nijhof@dealerdirect.com", + "homepage": "http://www.frenck.nl", + "role": "Developer / IT Manager" + } + ], + "description": "PHP_CodeSniffer Standards Composer Installer Plugin", + "homepage": "http://www.dealerdirect.com", + "keywords": [ + "PHPCodeSniffer", + "PHP_CodeSniffer", + "code quality", + "codesniffer", + "composer", + "installer", + "phpcs", + "plugin", + "qa", + "quality", + "standard", + "standards", + "style guide", + "stylecheck", + "tests" + ], + "support": { + "issues": "https://github.com/dealerdirect/phpcodesniffer-composer-installer/issues", + "source": "https://github.com/dealerdirect/phpcodesniffer-composer-installer" + }, + "time": "2021-08-16T14:43:41+00:00" + }, + { + "name": "doctrine/annotations", + "version": "1.13.2", + "source": { + "type": "git", + "url": "https://github.com/doctrine/annotations.git", + "reference": "5b668aef16090008790395c02c893b1ba13f7e08" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/annotations/zipball/5b668aef16090008790395c02c893b1ba13f7e08", + "reference": "5b668aef16090008790395c02c893b1ba13f7e08", "shasum": "" }, "require": { "doctrine/lexer": "1.*", "ext-tokenizer": "*", - "php": "^7.1 || ^8.0" + "php": "^7.1 || ^8.0", + "psr/cache": "^1 || ^2 || ^3" }, "require-dev": { - "doctrine/cache": "1.*", + "doctrine/cache": "^1.11 || ^2.0", + "doctrine/coding-standard": "^6.0 || ^8.1", "phpstan/phpstan": "^0.12.20", - "phpunit/phpunit": "^7.5 || ^9.1.5" + "phpunit/phpunit": "^7.5 || ^8.0 || ^9.1.5", + "symfony/cache": "^4.4 || ^5.2" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.9.x-dev" - } - }, "autoload": { "psr-4": { "Doctrine\\Common\\Annotations\\": "lib/Doctrine/Common/Annotations" @@ -805,46 +867,45 @@ } ], "description": "Docblock Annotations Parser", - "homepage": "http://www.doctrine-project.org", + "homepage": "https://www.doctrine-project.org/projects/annotations.html", "keywords": [ "annotations", "docblock", "parser" ], - "time": "2020-08-10T19:35:50+00:00" + "support": { + "issues": "https://github.com/doctrine/annotations/issues", + "source": "https://github.com/doctrine/annotations/tree/1.13.2" + }, + "time": "2021-08-05T19:00:23+00:00" }, { "name": "doctrine/instantiator", - "version": "1.3.1", + "version": "1.4.0", "source": { "type": "git", "url": "https://github.com/doctrine/instantiator.git", - "reference": "f350df0268e904597e3bd9c4685c53e0e333feea" + "reference": "d56bf6102915de5702778fe20f2de3b2fe570b5b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/doctrine/instantiator/zipball/f350df0268e904597e3bd9c4685c53e0e333feea", - "reference": "f350df0268e904597e3bd9c4685c53e0e333feea", + "url": "https://api.github.com/repos/doctrine/instantiator/zipball/d56bf6102915de5702778fe20f2de3b2fe570b5b", + "reference": "d56bf6102915de5702778fe20f2de3b2fe570b5b", "shasum": "" }, "require": { "php": "^7.1 || ^8.0" }, "require-dev": { - "doctrine/coding-standard": "^6.0", + "doctrine/coding-standard": "^8.0", "ext-pdo": "*", "ext-phar": "*", - "phpbench/phpbench": "^0.13", - "phpstan/phpstan-phpunit": "^0.11", - "phpstan/phpstan-shim": "^0.11", - "phpunit/phpunit": "^7.0" + "phpbench/phpbench": "^0.13 || 1.0.0-alpha2", + "phpstan/phpstan": "^0.12", + "phpstan/phpstan-phpunit": "^0.12", + "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.2.x-dev" - } - }, "autoload": { "psr-4": { "Doctrine\\Instantiator\\": "src/Doctrine/Instantiator/" @@ -858,7 +919,7 @@ { "name": "Marco Pivetta", "email": "ocramius@gmail.com", - "homepage": "http://ocramius.github.com/" + "homepage": "https://ocramius.github.io/" } ], "description": "A small, lightweight utility to instantiate objects in PHP without invoking their constructors", @@ -867,7 +928,25 @@ "constructor", "instantiate" ], - "time": "2020-05-29T17:27:14+00:00" + "support": { + "issues": "https://github.com/doctrine/instantiator/issues", + "source": "https://github.com/doctrine/instantiator/tree/1.4.0" + }, + "funding": [ + { + "url": "https://www.doctrine-project.org/sponsorship.html", + "type": "custom" + }, + { + "url": "https://www.patreon.com/phpdoctrine", + "type": "patreon" + }, + { + "url": "https://tidelift.com/funding/github/packagist/doctrine%2Finstantiator", + "type": "tidelift" + } + ], + "time": "2020-11-10T18:47:58+00:00" }, { "name": "doctrine/lexer", @@ -929,20 +1008,38 @@ "parser", "php" ], + "support": { + "issues": "https://github.com/doctrine/lexer/issues", + "source": "https://github.com/doctrine/lexer/tree/1.2.1" + }, + "funding": [ + { + "url": "https://www.doctrine-project.org/sponsorship.html", + "type": "custom" + }, + { + "url": "https://www.patreon.com/phpdoctrine", + "type": "patreon" + }, + { + "url": "https://tidelift.com/funding/github/packagist/doctrine%2Flexer", + "type": "tidelift" + } + ], "time": "2020-05-25T17:44:05+00:00" }, { "name": "dompdf/dompdf", - "version": "v0.8.6", + "version": "v1.0.2", "source": { "type": "git", "url": "https://github.com/dompdf/dompdf.git", - "reference": "db91d81866c69a42dad1d2926f61515a1e3f42c5" + "reference": "8768448244967a46d6e67b891d30878e0e15d25c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/dompdf/dompdf/zipball/db91d81866c69a42dad1d2926f61515a1e3f42c5", - "reference": "db91d81866c69a42dad1d2926f61515a1e3f42c5", + "url": "https://api.github.com/repos/dompdf/dompdf/zipball/8768448244967a46d6e67b891d30878e0e15d25c", + "reference": "8768448244967a46d6e67b891d30878e0e15d25c", "shasum": "" }, "require": { @@ -950,11 +1047,11 @@ "ext-mbstring": "*", "phenx/php-font-lib": "^0.5.2", "phenx/php-svg-lib": "^0.3.3", - "php": "^7.1" + "php": "^7.1 || ^8.0" }, "require-dev": { "mockery/mockery": "^1.3", - "phpunit/phpunit": "^7.5", + "phpunit/phpunit": "^7.5 || ^8 || ^9", "squizlabs/php_codesniffer": "^3.5" }, "suggest": { @@ -997,31 +1094,35 @@ ], "description": "DOMPDF is a CSS 2.1 compliant HTML to PDF converter", "homepage": "https://github.com/dompdf/dompdf", - "time": "2020-08-30T22:54:22+00:00" + "support": { + "issues": "https://github.com/dompdf/dompdf/issues", + "source": "https://github.com/dompdf/dompdf/tree/v1.0.2" + }, + "time": "2021-01-08T14:18:52+00:00" }, { "name": "friendsofphp/php-cs-fixer", - "version": "v2.16.4", + "version": "v2.19.2", "source": { "type": "git", "url": "https://github.com/FriendsOfPHP/PHP-CS-Fixer.git", - "reference": "1023c3458137ab052f6ff1e09621a721bfdeca13" + "reference": "d5c737c2e18ba502b75b44832b31fe627f82e307" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/FriendsOfPHP/PHP-CS-Fixer/zipball/1023c3458137ab052f6ff1e09621a721bfdeca13", - "reference": "1023c3458137ab052f6ff1e09621a721bfdeca13", + "url": "https://api.github.com/repos/FriendsOfPHP/PHP-CS-Fixer/zipball/d5c737c2e18ba502b75b44832b31fe627f82e307", + "reference": "d5c737c2e18ba502b75b44832b31fe627f82e307", "shasum": "" }, "require": { - "composer/semver": "^1.4", - "composer/xdebug-handler": "^1.2", + "composer/semver": "^1.4 || ^2.0 || ^3.0", + "composer/xdebug-handler": "^1.2 || ^2.0", "doctrine/annotations": "^1.2", "ext-json": "*", "ext-tokenizer": "*", - "php": "^5.6 || ^7.0", + "php": "^5.6 || ^7.0 || ^8.0", "php-cs-fixer/diff": "^1.3", - "symfony/console": "^3.4.17 || ^4.1.6 || ^5.0", + "symfony/console": "^3.4.43 || ^4.1.6 || ^5.0", "symfony/event-dispatcher": "^3.0 || ^4.0 || ^5.0", "symfony/filesystem": "^3.0 || ^4.0 || ^5.0", "symfony/finder": "^3.0 || ^4.0 || ^5.0", @@ -1032,17 +1133,19 @@ "symfony/stopwatch": "^3.0 || ^4.0 || ^5.0" }, "require-dev": { - "johnkary/phpunit-speedtrap": "^1.1 || ^2.0 || ^3.0", "justinrainbow/json-schema": "^5.0", - "keradus/cli-executor": "^1.2", + "keradus/cli-executor": "^1.4", "mikey179/vfsstream": "^1.6", - "php-coveralls/php-coveralls": "^2.1", + "php-coveralls/php-coveralls": "^2.4.2", "php-cs-fixer/accessible-object": "^1.0", - "php-cs-fixer/phpunit-constraint-isidenticalstring": "^1.1", - "php-cs-fixer/phpunit-constraint-xmlmatchesxsd": "^1.1", - "phpunit/phpunit": "^5.7.27 || ^6.5.14 || ^7.1", - "phpunitgoodpractices/traits": "^1.8", - "symfony/phpunit-bridge": "^5.1", + "php-cs-fixer/phpunit-constraint-isidenticalstring": "^1.2", + "php-cs-fixer/phpunit-constraint-xmlmatchesxsd": "^1.2.1", + "phpspec/prophecy-phpunit": "^1.1 || ^2.0", + "phpunit/phpunit": "^5.7.27 || ^6.5.14 || ^7.5.20 || ^8.5.13 || ^9.5", + "phpunitgoodpractices/polyfill": "^1.5", + "phpunitgoodpractices/traits": "^1.9.1", + "sanmai/phpunit-legacy-adapter": "^6.4 || ^8.2.1", + "symfony/phpunit-bridge": "^5.2.1", "symfony/yaml": "^3.0 || ^4.0 || ^5.0" }, "suggest": { @@ -1056,6 +1159,11 @@ "php-cs-fixer" ], "type": "application", + "extra": { + "branch-alias": { + "dev-master": "2.19-dev" + } + }, "autoload": { "psr-4": { "PhpCsFixer\\": "src/" @@ -1070,6 +1178,7 @@ "tests/Test/IntegrationCaseFactoryInterface.php", "tests/Test/InternalIntegrationCaseFactory.php", "tests/Test/IsIdenticalConstraint.php", + "tests/Test/TokensWithObservedTransformers.php", "tests/TestCase.php" ] }, @@ -1088,7 +1197,17 @@ } ], "description": "A tool to automatically fix PHP code style", - "time": "2020-06-27T23:57:46+00:00" + "support": { + "issues": "https://github.com/FriendsOfPHP/PHP-CS-Fixer/issues", + "source": "https://github.com/FriendsOfPHP/PHP-CS-Fixer/tree/v2.19.2" + }, + "funding": [ + { + "url": "https://github.com/keradus", + "type": "github" + } + ], + "time": "2021-08-18T19:55:46+00:00" }, { "name": "jpgraph/jpgraph", @@ -1128,38 +1247,42 @@ "jpgraph", "pie" ], + "support": { + "issues": "https://github.com/ztec/JpGraph/issues", + "source": "https://github.com/ztec/JpGraph/tree/4.x" + }, "abandoned": true, "time": "2017-02-23T09:44:15+00:00" }, { "name": "mpdf/mpdf", - "version": "v8.0.7", + "version": "v8.0.13", "source": { "type": "git", "url": "https://github.com/mpdf/mpdf.git", - "reference": "7daf07f15334ed59a276bd52131dcca48794cdbd" + "reference": "42f145615cfe830fd432474da1d2e1f927efe402" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/mpdf/mpdf/zipball/7daf07f15334ed59a276bd52131dcca48794cdbd", - "reference": "7daf07f15334ed59a276bd52131dcca48794cdbd", + "url": "https://api.github.com/repos/mpdf/mpdf/zipball/42f145615cfe830fd432474da1d2e1f927efe402", + "reference": "42f145615cfe830fd432474da1d2e1f927efe402", "shasum": "" }, "require": { "ext-gd": "*", "ext-mbstring": "*", "myclabs/deep-copy": "^1.7", - "paragonie/random_compat": "^1.4|^2.0|9.99.99", - "php": "^5.6 || ~7.0.0 || ~7.1.0 || ~7.2.0 || ~7.3.0 || ~7.4.0", + "paragonie/random_compat": "^1.4|^2.0|^9.99.99", + "php": "^5.6 || ^7.0 || ~8.0.0 || ~8.1.0", "psr/log": "^1.0", "setasign/fpdi": "^2.1" }, "require-dev": { - "mockery/mockery": "^0.9.5", - "mpdf/qrcode": "^1.0.0", - "phpunit/phpunit": "^5.0", + "mockery/mockery": "^1.3.0", + "mpdf/qrcode": "^1.1.0", "squizlabs/php_codesniffer": "^3.5.0", - "tracy/tracy": "^2.4" + "tracy/tracy": "^2.4", + "yoast/phpunit-polyfills": "^1.0" }, "suggest": { "ext-bcmath": "Needed for generation of some types of barcodes", @@ -1167,11 +1290,6 @@ "ext-zlib": "Needed for compression of embedded resources, such as fonts" }, "type": "library", - "extra": { - "branch-alias": { - "dev-development": "7.x-dev" - } - }, "autoload": { "psr-4": { "Mpdf\\": "src/" @@ -1198,26 +1316,31 @@ "php", "utf-8" ], + "support": { + "docs": "http://mpdf.github.io", + "issues": "https://github.com/mpdf/mpdf/issues", + "source": "https://github.com/mpdf/mpdf" + }, "funding": [ { "url": "https://www.paypal.me/mpdf", "type": "custom" } ], - "time": "2020-07-15T09:48:00+00:00" + "time": "2021-09-10T10:09:59+00:00" }, { "name": "myclabs/deep-copy", - "version": "1.10.1", + "version": "1.10.2", "source": { "type": "git", "url": "https://github.com/myclabs/DeepCopy.git", - "reference": "969b211f9a51aa1f6c01d1d2aef56d3bd91598e5" + "reference": "776f831124e9c62e1a2c601ecc52e776d8bb7220" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/969b211f9a51aa1f6c01d1d2aef56d3bd91598e5", - "reference": "969b211f9a51aa1f6c01d1d2aef56d3bd91598e5", + "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/776f831124e9c62e1a2c601ecc52e776d8bb7220", + "reference": "776f831124e9c62e1a2c601ecc52e776d8bb7220", "shasum": "" }, "require": { @@ -1252,30 +1375,34 @@ "object", "object graph" ], + "support": { + "issues": "https://github.com/myclabs/DeepCopy/issues", + "source": "https://github.com/myclabs/DeepCopy/tree/1.10.2" + }, "funding": [ { "url": "https://tidelift.com/funding/github/packagist/myclabs/deep-copy", "type": "tidelift" } ], - "time": "2020-06-29T13:22:24+00:00" + "time": "2020-11-13T09:40:50+00:00" }, { "name": "paragonie/random_compat", - "version": "v9.99.99", + "version": "v9.99.100", "source": { "type": "git", "url": "https://github.com/paragonie/random_compat.git", - "reference": "84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95" + "reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/paragonie/random_compat/zipball/84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95", - "reference": "84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95", + "url": "https://api.github.com/repos/paragonie/random_compat/zipball/996434e5492cb4c3edcb9168db6fbb1359ef965a", + "reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a", "shasum": "" }, "require": { - "php": "^7" + "php": ">= 7" }, "require-dev": { "phpunit/phpunit": "4.*|5.*", @@ -1303,32 +1430,38 @@ "pseudorandom", "random" ], - "time": "2018-07-02T15:55:56+00:00" + "support": { + "email": "info@paragonie.com", + "issues": "https://github.com/paragonie/random_compat/issues", + "source": "https://github.com/paragonie/random_compat" + }, + "time": "2020-10-15T08:29:30+00:00" }, { "name": "phar-io/manifest", - "version": "1.0.3", + "version": "2.0.3", "source": { "type": "git", "url": "https://github.com/phar-io/manifest.git", - "reference": "7761fcacf03b4d4f16e7ccb606d4879ca431fcf4" + "reference": "97803eca37d319dfa7826cc2437fc020857acb53" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phar-io/manifest/zipball/7761fcacf03b4d4f16e7ccb606d4879ca431fcf4", - "reference": "7761fcacf03b4d4f16e7ccb606d4879ca431fcf4", + "url": "https://api.github.com/repos/phar-io/manifest/zipball/97803eca37d319dfa7826cc2437fc020857acb53", + "reference": "97803eca37d319dfa7826cc2437fc020857acb53", "shasum": "" }, "require": { "ext-dom": "*", "ext-phar": "*", - "phar-io/version": "^2.0", - "php": "^5.6 || ^7.0" + "ext-xmlwriter": "*", + "phar-io/version": "^3.0.1", + "php": "^7.2 || ^8.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.0.x-dev" + "dev-master": "2.0.x-dev" } }, "autoload": { @@ -1358,24 +1491,28 @@ } ], "description": "Component for reading phar.io manifest information from a PHP Archive (PHAR)", - "time": "2018-07-08T19:23:20+00:00" + "support": { + "issues": "https://github.com/phar-io/manifest/issues", + "source": "https://github.com/phar-io/manifest/tree/2.0.3" + }, + "time": "2021-07-20T11:28:43+00:00" }, { "name": "phar-io/version", - "version": "2.0.1", + "version": "3.1.0", "source": { "type": "git", "url": "https://github.com/phar-io/version.git", - "reference": "45a2ec53a73c70ce41d55cedef9063630abaf1b6" + "reference": "bae7c545bef187884426f042434e561ab1ddb182" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phar-io/version/zipball/45a2ec53a73c70ce41d55cedef9063630abaf1b6", - "reference": "45a2ec53a73c70ce41d55cedef9063630abaf1b6", + "url": "https://api.github.com/repos/phar-io/version/zipball/bae7c545bef187884426f042434e561ab1ddb182", + "reference": "bae7c545bef187884426f042434e561ab1ddb182", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0" + "php": "^7.2 || ^8.0" }, "type": "library", "autoload": { @@ -1405,7 +1542,11 @@ } ], "description": "Library for handling version information and constraints", - "time": "2018-07-08T19:19:57+00:00" + "support": { + "issues": "https://github.com/phar-io/version/issues", + "source": "https://github.com/phar-io/version/tree/3.1.0" + }, + "time": "2021-02-23T14:00:09+00:00" }, { "name": "phenx/php-font-lib", @@ -1442,6 +1583,10 @@ ], "description": "A library to read, parse, export and make subsets of different types of font files.", "homepage": "https://github.com/PhenX/php-font-lib", + "support": { + "issues": "https://github.com/PhenX/php-font-lib/issues", + "source": "https://github.com/PhenX/php-font-lib/tree/0.5.2" + }, "time": "2020-03-08T15:31:32+00:00" }, { @@ -1482,6 +1627,10 @@ ], "description": "A library to read, parse and export to PDF SVG files.", "homepage": "https://github.com/PhenX/php-svg-lib", + "support": { + "issues": "https://github.com/PhenX/php-svg-lib/issues", + "source": "https://github.com/PhenX/php-svg-lib/tree/master" + }, "time": "2019-09-11T20:02:13+00:00" }, { @@ -1533,6 +1682,10 @@ "keywords": [ "diff" ], + "support": { + "issues": "https://github.com/PHP-CS-Fixer/diff/issues", + "source": "https://github.com/PHP-CS-Fixer/diff/tree/v1.3.1" + }, "time": "2020-10-14T08:39:05+00:00" }, { @@ -1591,6 +1744,10 @@ "phpcs", "standards" ], + "support": { + "issues": "https://github.com/PHPCompatibility/PHPCompatibility/issues", + "source": "https://github.com/PHPCompatibility/PHPCompatibility" + }, "time": "2019-12-27T09:44:58+00:00" }, { @@ -1640,20 +1797,24 @@ "reflection", "static analysis" ], + "support": { + "issues": "https://github.com/phpDocumentor/ReflectionCommon/issues", + "source": "https://github.com/phpDocumentor/ReflectionCommon/tree/2.x" + }, "time": "2020-06-27T09:03:43+00:00" }, { "name": "phpdocumentor/reflection-docblock", - "version": "5.2.2", + "version": "5.3.0", "source": { "type": "git", "url": "https://github.com/phpDocumentor/ReflectionDocBlock.git", - "reference": "069a785b2141f5bcf49f3e353548dc1cce6df556" + "reference": "622548b623e81ca6d78b721c5e029f4ce664f170" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/069a785b2141f5bcf49f3e353548dc1cce6df556", - "reference": "069a785b2141f5bcf49f3e353548dc1cce6df556", + "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/622548b623e81ca6d78b721c5e029f4ce664f170", + "reference": "622548b623e81ca6d78b721c5e029f4ce664f170", "shasum": "" }, "require": { @@ -1664,7 +1825,8 @@ "webmozart/assert": "^1.9.1" }, "require-dev": { - "mockery/mockery": "~1.3.2" + "mockery/mockery": "~1.3.2", + "psalm/phar": "^4.8" }, "type": "library", "extra": { @@ -1692,20 +1854,24 @@ } ], "description": "With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.", - "time": "2020-09-03T19:13:55+00:00" + "support": { + "issues": "https://github.com/phpDocumentor/ReflectionDocBlock/issues", + "source": "https://github.com/phpDocumentor/ReflectionDocBlock/tree/5.3.0" + }, + "time": "2021-10-19T17:43:47+00:00" }, { "name": "phpdocumentor/type-resolver", - "version": "1.4.0", + "version": "1.5.1", "source": { "type": "git", "url": "https://github.com/phpDocumentor/TypeResolver.git", - "reference": "6a467b8989322d92aa1c8bf2bebcc6e5c2ba55c0" + "reference": "a12f7e301eb7258bb68acd89d4aefa05c2906cae" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/6a467b8989322d92aa1c8bf2bebcc6e5c2ba55c0", - "reference": "6a467b8989322d92aa1c8bf2bebcc6e5c2ba55c0", + "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/a12f7e301eb7258bb68acd89d4aefa05c2906cae", + "reference": "a12f7e301eb7258bb68acd89d4aefa05c2906cae", "shasum": "" }, "require": { @@ -1713,7 +1879,8 @@ "phpdocumentor/reflection-common": "^2.0" }, "require-dev": { - "ext-tokenizer": "*" + "ext-tokenizer": "*", + "psalm/phar": "^4.8" }, "type": "library", "extra": { @@ -1737,37 +1904,41 @@ } ], "description": "A PSR-5 based resolver of Class names, Types and Structural Element Names", - "time": "2020-09-17T18:55:26+00:00" + "support": { + "issues": "https://github.com/phpDocumentor/TypeResolver/issues", + "source": "https://github.com/phpDocumentor/TypeResolver/tree/1.5.1" + }, + "time": "2021-10-02T14:08:47+00:00" }, { "name": "phpspec/prophecy", - "version": "1.12.1", + "version": "1.14.0", "source": { "type": "git", "url": "https://github.com/phpspec/prophecy.git", - "reference": "8ce87516be71aae9b956f81906aaf0338e0d8a2d" + "reference": "d86dfc2e2a3cd366cee475e52c6bb3bbc371aa0e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpspec/prophecy/zipball/8ce87516be71aae9b956f81906aaf0338e0d8a2d", - "reference": "8ce87516be71aae9b956f81906aaf0338e0d8a2d", + "url": "https://api.github.com/repos/phpspec/prophecy/zipball/d86dfc2e2a3cd366cee475e52c6bb3bbc371aa0e", + "reference": "d86dfc2e2a3cd366cee475e52c6bb3bbc371aa0e", "shasum": "" }, "require": { "doctrine/instantiator": "^1.2", - "php": "^7.2 || ~8.0, <8.1", + "php": "^7.2 || ~8.0, <8.2", "phpdocumentor/reflection-docblock": "^5.2", "sebastian/comparator": "^3.0 || ^4.0", "sebastian/recursion-context": "^3.0 || ^4.0" }, "require-dev": { - "phpspec/phpspec": "^6.0", - "phpunit/phpunit": "^8.0 || ^9.0 <9.3" + "phpspec/phpspec": "^6.0 || ^7.0", + "phpunit/phpunit": "^8.0 || ^9.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.11.x-dev" + "dev-master": "1.x-dev" } }, "autoload": { @@ -1800,29 +1971,151 @@ "spy", "stub" ], - "time": "2020-09-29T09:10:42+00:00" + "support": { + "issues": "https://github.com/phpspec/prophecy/issues", + "source": "https://github.com/phpspec/prophecy/tree/1.14.0" + }, + "time": "2021-09-10T09:02:12+00:00" }, { - "name": "phpunit/php-code-coverage", - "version": "7.0.10", + "name": "phpstan/phpstan", + "version": "0.12.99", "source": { "type": "git", - "url": "https://github.com/sebastianbergmann/php-code-coverage.git", - "reference": "f1884187926fbb755a9aaf0b3836ad3165b478bf" + "url": "https://github.com/phpstan/phpstan.git", + "reference": "b4d40f1d759942f523be267a1bab6884f46ca3f7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/f1884187926fbb755a9aaf0b3836ad3165b478bf", - "reference": "f1884187926fbb755a9aaf0b3836ad3165b478bf", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/b4d40f1d759942f523be267a1bab6884f46ca3f7", + "reference": "b4d40f1d759942f523be267a1bab6884f46ca3f7", + "shasum": "" + }, + "require": { + "php": "^7.1|^8.0" + }, + "conflict": { + "phpstan/phpstan-shim": "*" + }, + "bin": [ + "phpstan", + "phpstan.phar" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "0.12-dev" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHPStan - PHP Static Analysis Tool", + "support": { + "issues": "https://github.com/phpstan/phpstan/issues", + "source": "https://github.com/phpstan/phpstan/tree/0.12.99" + }, + "funding": [ + { + "url": "https://github.com/ondrejmirtes", + "type": "github" + }, + { + "url": "https://github.com/phpstan", + "type": "github" + }, + { + "url": "https://www.patreon.com/phpstan", + "type": "patreon" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpstan/phpstan", + "type": "tidelift" + } + ], + "time": "2021-09-12T20:09:55+00:00" + }, + { + "name": "phpstan/phpstan-phpunit", + "version": "0.12.22", + "source": { + "type": "git", + "url": "https://github.com/phpstan/phpstan-phpunit.git", + "reference": "7c01ef93bf128b4ac8bdad38c54b2a4fd6b0b3cc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpstan-phpunit/zipball/7c01ef93bf128b4ac8bdad38c54b2a4fd6b0b3cc", + "reference": "7c01ef93bf128b4ac8bdad38c54b2a4fd6b0b3cc", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0", + "phpstan/phpstan": "^0.12.92" + }, + "conflict": { + "phpunit/phpunit": "<7.0" + }, + "require-dev": { + "php-parallel-lint/php-parallel-lint": "^1.2", + "phpstan/phpstan-strict-rules": "^0.12.6", + "phpunit/phpunit": "^9.5" + }, + "type": "phpstan-extension", + "extra": { + "branch-alias": { + "dev-master": "0.12-dev" + }, + "phpstan": { + "includes": [ + "extension.neon", + "rules.neon" + ] + } + }, + "autoload": { + "psr-4": { + "PHPStan\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHPUnit extensions and rules for PHPStan", + "support": { + "issues": "https://github.com/phpstan/phpstan-phpunit/issues", + "source": "https://github.com/phpstan/phpstan-phpunit/tree/0.12.22" + }, + "time": "2021-08-12T10:53:43+00:00" + }, + { + "name": "phpunit/php-code-coverage", + "version": "7.0.15", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-code-coverage.git", + "reference": "819f92bba8b001d4363065928088de22f25a3a48" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/819f92bba8b001d4363065928088de22f25a3a48", + "reference": "819f92bba8b001d4363065928088de22f25a3a48", "shasum": "" }, "require": { "ext-dom": "*", "ext-xmlwriter": "*", - "php": "^7.2", + "php": ">=7.2", "phpunit/php-file-iterator": "^2.0.2", "phpunit/php-text-template": "^1.2.1", - "phpunit/php-token-stream": "^3.1.1", + "phpunit/php-token-stream": "^3.1.3 || ^4.0", "sebastian/code-unit-reverse-lookup": "^1.0.1", "sebastian/environment": "^4.2.2", "sebastian/version": "^2.0.1", @@ -1863,27 +2156,37 @@ "testing", "xunit" ], - "time": "2019-11-20T13:55:58+00:00" + "support": { + "issues": "https://github.com/sebastianbergmann/php-code-coverage/issues", + "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/7.0.15" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2021-07-26T12:20:09+00:00" }, { "name": "phpunit/php-file-iterator", - "version": "2.0.2", + "version": "2.0.4", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-file-iterator.git", - "reference": "050bedf145a257b1ff02746c31894800e5122946" + "reference": "28af674ff175d0768a5a978e6de83f697d4a7f05" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/050bedf145a257b1ff02746c31894800e5122946", - "reference": "050bedf145a257b1ff02746c31894800e5122946", + "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/28af674ff175d0768a5a978e6de83f697d4a7f05", + "reference": "28af674ff175d0768a5a978e6de83f697d4a7f05", "shasum": "" }, "require": { - "php": "^7.1" + "php": ">=7.1" }, "require-dev": { - "phpunit/phpunit": "^7.1" + "phpunit/phpunit": "^8.5" }, "type": "library", "extra": { @@ -1913,7 +2216,17 @@ "filesystem", "iterator" ], - "time": "2018-09-13T20:33:42+00:00" + "support": { + "issues": "https://github.com/sebastianbergmann/php-file-iterator/issues", + "source": "https://github.com/sebastianbergmann/php-file-iterator/tree/2.0.4" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2021-07-19T06:46:01+00:00" }, { "name": "phpunit/php-text-template", @@ -1954,27 +2267,31 @@ "keywords": [ "template" ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-text-template/issues", + "source": "https://github.com/sebastianbergmann/php-text-template/tree/1.2.1" + }, "time": "2015-06-21T13:50:34+00:00" }, { "name": "phpunit/php-timer", - "version": "2.1.2", + "version": "2.1.3", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-timer.git", - "reference": "1038454804406b0b5f5f520358e78c1c2f71501e" + "reference": "2454ae1765516d20c4ffe103d85a58a9a3bd5662" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/1038454804406b0b5f5f520358e78c1c2f71501e", - "reference": "1038454804406b0b5f5f520358e78c1c2f71501e", + "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/2454ae1765516d20c4ffe103d85a58a9a3bd5662", + "reference": "2454ae1765516d20c4ffe103d85a58a9a3bd5662", "shasum": "" }, "require": { - "php": "^7.1" + "php": ">=7.1" }, "require-dev": { - "phpunit/phpunit": "^7.0" + "phpunit/phpunit": "^8.5" }, "type": "library", "extra": { @@ -2003,25 +2320,35 @@ "keywords": [ "timer" ], - "time": "2019-06-07T04:22:29+00:00" + "support": { + "issues": "https://github.com/sebastianbergmann/php-timer/issues", + "source": "https://github.com/sebastianbergmann/php-timer/tree/2.1.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-11-30T08:20:02+00:00" }, { "name": "phpunit/php-token-stream", - "version": "3.1.1", + "version": "3.1.3", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-token-stream.git", - "reference": "995192df77f63a59e47f025390d2d1fdf8f425ff" + "reference": "9c1da83261628cb24b6a6df371b6e312b3954768" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/995192df77f63a59e47f025390d2d1fdf8f425ff", - "reference": "995192df77f63a59e47f025390d2d1fdf8f425ff", + "url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/9c1da83261628cb24b6a6df371b6e312b3954768", + "reference": "9c1da83261628cb24b6a6df371b6e312b3954768", "shasum": "" }, "require": { "ext-tokenizer": "*", - "php": "^7.1" + "php": ">=7.1" }, "require-dev": { "phpunit/phpunit": "^7.0" @@ -2052,43 +2379,54 @@ "keywords": [ "tokenizer" ], - "time": "2019-09-17T06:23:10+00:00" + "support": { + "issues": "https://github.com/sebastianbergmann/php-token-stream/issues", + "source": "https://github.com/sebastianbergmann/php-token-stream/tree/3.1.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "abandoned": true, + "time": "2021-07-26T12:15:06+00:00" }, { "name": "phpunit/phpunit", - "version": "8.5.8", + "version": "8.5.21", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "34c18baa6a44f1d1fbf0338907139e9dce95b997" + "reference": "50a58a60b85947b0bee4c8ecfe0f4bbdcf20e984" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/34c18baa6a44f1d1fbf0338907139e9dce95b997", - "reference": "34c18baa6a44f1d1fbf0338907139e9dce95b997", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/50a58a60b85947b0bee4c8ecfe0f4bbdcf20e984", + "reference": "50a58a60b85947b0bee4c8ecfe0f4bbdcf20e984", "shasum": "" }, "require": { - "doctrine/instantiator": "^1.2.0", + "doctrine/instantiator": "^1.3.1", "ext-dom": "*", "ext-json": "*", "ext-libxml": "*", "ext-mbstring": "*", "ext-xml": "*", "ext-xmlwriter": "*", - "myclabs/deep-copy": "^1.9.1", - "phar-io/manifest": "^1.0.3", - "phar-io/version": "^2.0.1", - "php": "^7.2", - "phpspec/prophecy": "^1.8.1", - "phpunit/php-code-coverage": "^7.0.7", - "phpunit/php-file-iterator": "^2.0.2", + "myclabs/deep-copy": "^1.10.0", + "phar-io/manifest": "^2.0.3", + "phar-io/version": "^3.0.2", + "php": ">=7.2", + "phpspec/prophecy": "^1.10.3", + "phpunit/php-code-coverage": "^7.0.12", + "phpunit/php-file-iterator": "^2.0.4", "phpunit/php-text-template": "^1.2.1", "phpunit/php-timer": "^2.1.2", "sebastian/comparator": "^3.0.2", "sebastian/diff": "^3.0.2", - "sebastian/environment": "^4.2.2", - "sebastian/exporter": "^3.1.1", + "sebastian/environment": "^4.2.3", + "sebastian/exporter": "^3.1.2", "sebastian/global-state": "^3.0.0", "sebastian/object-enumerator": "^3.0.3", "sebastian/resource-operations": "^2.0.1", @@ -2135,20 +2473,34 @@ "testing", "xunit" ], - "time": "2020-06-22T07:06:58+00:00" + "support": { + "issues": "https://github.com/sebastianbergmann/phpunit/issues", + "source": "https://github.com/sebastianbergmann/phpunit/tree/8.5.21" + }, + "funding": [ + { + "url": "https://phpunit.de/donate.html", + "type": "custom" + }, + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2021-09-25T07:37:20+00:00" }, { - "name": "psr/container", - "version": "1.0.0", + "name": "psr/cache", + "version": "1.0.1", "source": { "type": "git", - "url": "https://github.com/php-fig/container.git", - "reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f" + "url": "https://github.com/php-fig/cache.git", + "reference": "d11b50ad223250cf17b86e38383413f5a6764bf8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-fig/container/zipball/b7ce3b176482dbbc1245ebf52b181af44c2cf55f", - "reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f", + "url": "https://api.github.com/repos/php-fig/cache/zipball/d11b50ad223250cf17b86e38383413f5a6764bf8", + "reference": "d11b50ad223250cf17b86e38383413f5a6764bf8", "shasum": "" }, "require": { @@ -2162,7 +2514,7 @@ }, "autoload": { "psr-4": { - "Psr\\Container\\": "src/" + "Psr\\Cache\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", @@ -2175,6 +2527,50 @@ "homepage": "http://www.php-fig.org/" } ], + "description": "Common interface for caching libraries", + "keywords": [ + "cache", + "psr", + "psr-6" + ], + "support": { + "source": "https://github.com/php-fig/cache/tree/master" + }, + "time": "2016-08-06T20:24:11+00:00" + }, + { + "name": "psr/container", + "version": "1.1.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "8622567409010282b7aeebe4bb841fe98b58dcaf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/8622567409010282b7aeebe4bb841fe98b58dcaf", + "reference": "8622567409010282b7aeebe4bb841fe98b58dcaf", + "shasum": "" + }, + "require": { + "php": ">=7.2.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], "description": "Common Container Interface (PHP FIG PSR-11)", "homepage": "https://github.com/php-fig/container", "keywords": [ @@ -2184,7 +2580,11 @@ "container-interop", "psr" ], - "time": "2017-02-14T16:28:37+00:00" + "support": { + "issues": "https://github.com/php-fig/container/issues", + "source": "https://github.com/php-fig/container/tree/1.1.1" + }, + "time": "2021-03-05T17:36:06+00:00" }, { "name": "psr/event-dispatcher", @@ -2230,20 +2630,24 @@ "psr", "psr-14" ], + "support": { + "issues": "https://github.com/php-fig/event-dispatcher/issues", + "source": "https://github.com/php-fig/event-dispatcher/tree/1.0.0" + }, "time": "2019-01-08T18:20:26+00:00" }, { "name": "psr/log", - "version": "1.1.3", + "version": "1.1.4", "source": { "type": "git", "url": "https://github.com/php-fig/log.git", - "reference": "0f73288fd15629204f9d42b7055f72dacbe811fc" + "reference": "d49695b909c3b7628b6289db5479a1c204601f11" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-fig/log/zipball/0f73288fd15629204f9d42b7055f72dacbe811fc", - "reference": "0f73288fd15629204f9d42b7055f72dacbe811fc", + "url": "https://api.github.com/repos/php-fig/log/zipball/d49695b909c3b7628b6289db5479a1c204601f11", + "reference": "d49695b909c3b7628b6289db5479a1c204601f11", "shasum": "" }, "require": { @@ -2267,7 +2671,7 @@ "authors": [ { "name": "PHP-FIG", - "homepage": "http://www.php-fig.org/" + "homepage": "https://www.php-fig.org/" } ], "description": "Common interface for logging libraries", @@ -2277,7 +2681,10 @@ "psr", "psr-3" ], - "time": "2020-03-23T09:12:05+00:00" + "support": { + "source": "https://github.com/php-fig/log/tree/1.1.4" + }, + "time": "2021-05-03T11:20:27+00:00" }, { "name": "sabberworm/php-css-parser", @@ -2322,27 +2729,31 @@ "parser", "stylesheet" ], + "support": { + "issues": "https://github.com/sabberworm/PHP-CSS-Parser/issues", + "source": "https://github.com/sabberworm/PHP-CSS-Parser/tree/8.3.1" + }, "time": "2020-06-01T09:10:00+00:00" }, { "name": "sebastian/code-unit-reverse-lookup", - "version": "1.0.1", + "version": "1.0.2", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/code-unit-reverse-lookup.git", - "reference": "4419fcdb5eabb9caa61a27c7a1db532a6b55dd18" + "reference": "1de8cd5c010cb153fcd68b8d0f64606f523f7619" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/4419fcdb5eabb9caa61a27c7a1db532a6b55dd18", - "reference": "4419fcdb5eabb9caa61a27c7a1db532a6b55dd18", + "url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/1de8cd5c010cb153fcd68b8d0f64606f523f7619", + "reference": "1de8cd5c010cb153fcd68b8d0f64606f523f7619", "shasum": "" }, "require": { - "php": "^5.6 || ^7.0" + "php": ">=5.6" }, "require-dev": { - "phpunit/phpunit": "^5.7 || ^6.0" + "phpunit/phpunit": "^8.5" }, "type": "library", "extra": { @@ -2367,29 +2778,39 @@ ], "description": "Looks up which function or method a line of code belongs to", "homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/", - "time": "2017-03-04T06:30:41+00:00" + "support": { + "issues": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/issues", + "source": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/tree/1.0.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-11-30T08:15:22+00:00" }, { "name": "sebastian/comparator", - "version": "3.0.2", + "version": "3.0.3", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/comparator.git", - "reference": "5de4fc177adf9bce8df98d8d141a7559d7ccf6da" + "reference": "1071dfcef776a57013124ff35e1fc41ccd294758" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/5de4fc177adf9bce8df98d8d141a7559d7ccf6da", - "reference": "5de4fc177adf9bce8df98d8d141a7559d7ccf6da", + "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/1071dfcef776a57013124ff35e1fc41ccd294758", + "reference": "1071dfcef776a57013124ff35e1fc41ccd294758", "shasum": "" }, "require": { - "php": "^7.1", + "php": ">=7.1", "sebastian/diff": "^3.0", "sebastian/exporter": "^3.1" }, "require-dev": { - "phpunit/phpunit": "^7.1" + "phpunit/phpunit": "^8.5" }, "type": "library", "extra": { @@ -2407,6 +2828,10 @@ "BSD-3-Clause" ], "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, { "name": "Jeff Welch", "email": "whatthejeff@gmail.com" @@ -2418,10 +2843,6 @@ { "name": "Bernhard Schussek", "email": "bschussek@2bepublished.at" - }, - { - "name": "Sebastian Bergmann", - "email": "sebastian@phpunit.de" } ], "description": "Provides the functionality to compare PHP values for equality", @@ -2431,24 +2852,34 @@ "compare", "equality" ], - "time": "2018-07-12T15:12:46+00:00" + "support": { + "issues": "https://github.com/sebastianbergmann/comparator/issues", + "source": "https://github.com/sebastianbergmann/comparator/tree/3.0.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-11-30T08:04:30+00:00" }, { "name": "sebastian/diff", - "version": "3.0.2", + "version": "3.0.3", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/diff.git", - "reference": "720fcc7e9b5cf384ea68d9d930d480907a0c1a29" + "reference": "14f72dd46eaf2f2293cbe79c93cc0bc43161a211" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/720fcc7e9b5cf384ea68d9d930d480907a0c1a29", - "reference": "720fcc7e9b5cf384ea68d9d930d480907a0c1a29", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/14f72dd46eaf2f2293cbe79c93cc0bc43161a211", + "reference": "14f72dd46eaf2f2293cbe79c93cc0bc43161a211", "shasum": "" }, "require": { - "php": "^7.1" + "php": ">=7.1" }, "require-dev": { "phpunit/phpunit": "^7.5 || ^8.0", @@ -2470,13 +2901,13 @@ "BSD-3-Clause" ], "authors": [ - { - "name": "Kore Nordmann", - "email": "mail@kore-nordmann.de" - }, { "name": "Sebastian Bergmann", "email": "sebastian@phpunit.de" + }, + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" } ], "description": "Diff implementation", @@ -2487,24 +2918,34 @@ "unidiff", "unified diff" ], - "time": "2019-02-04T06:01:07+00:00" + "support": { + "issues": "https://github.com/sebastianbergmann/diff/issues", + "source": "https://github.com/sebastianbergmann/diff/tree/3.0.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-11-30T07:59:04+00:00" }, { "name": "sebastian/environment", - "version": "4.2.3", + "version": "4.2.4", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/environment.git", - "reference": "464c90d7bdf5ad4e8a6aea15c091fec0603d4368" + "reference": "d47bbbad83711771f167c72d4e3f25f7fcc1f8b0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/464c90d7bdf5ad4e8a6aea15c091fec0603d4368", - "reference": "464c90d7bdf5ad4e8a6aea15c091fec0603d4368", + "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/d47bbbad83711771f167c72d4e3f25f7fcc1f8b0", + "reference": "d47bbbad83711771f167c72d4e3f25f7fcc1f8b0", "shasum": "" }, "require": { - "php": "^7.1" + "php": ">=7.1" }, "require-dev": { "phpunit/phpunit": "^7.5" @@ -2540,24 +2981,34 @@ "environment", "hhvm" ], - "time": "2019-11-20T08:46:58+00:00" + "support": { + "issues": "https://github.com/sebastianbergmann/environment/issues", + "source": "https://github.com/sebastianbergmann/environment/tree/4.2.4" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-11-30T07:53:42+00:00" }, { "name": "sebastian/exporter", - "version": "3.1.2", + "version": "3.1.3", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/exporter.git", - "reference": "68609e1261d215ea5b21b7987539cbfbe156ec3e" + "reference": "6b853149eab67d4da22291d36f5b0631c0fd856e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/68609e1261d215ea5b21b7987539cbfbe156ec3e", - "reference": "68609e1261d215ea5b21b7987539cbfbe156ec3e", + "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/6b853149eab67d4da22291d36f5b0631c0fd856e", + "reference": "6b853149eab67d4da22291d36f5b0631c0fd856e", "shasum": "" }, "require": { - "php": "^7.0", + "php": ">=7.0", "sebastian/recursion-context": "^3.0" }, "require-dev": { @@ -2607,24 +3058,34 @@ "export", "exporter" ], - "time": "2019-09-14T09:02:43+00:00" + "support": { + "issues": "https://github.com/sebastianbergmann/exporter/issues", + "source": "https://github.com/sebastianbergmann/exporter/tree/3.1.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-11-30T07:47:53+00:00" }, { "name": "sebastian/global-state", - "version": "3.0.0", + "version": "3.0.1", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/global-state.git", - "reference": "edf8a461cf1d4005f19fb0b6b8b95a9f7fa0adc4" + "reference": "474fb9edb7ab891665d3bfc6317f42a0a150454b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/edf8a461cf1d4005f19fb0b6b8b95a9f7fa0adc4", - "reference": "edf8a461cf1d4005f19fb0b6b8b95a9f7fa0adc4", + "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/474fb9edb7ab891665d3bfc6317f42a0a150454b", + "reference": "474fb9edb7ab891665d3bfc6317f42a0a150454b", "shasum": "" }, "require": { - "php": "^7.2", + "php": ">=7.2", "sebastian/object-reflector": "^1.1.1", "sebastian/recursion-context": "^3.0" }, @@ -2661,24 +3122,34 @@ "keywords": [ "global state" ], - "time": "2019-02-01T05:30:01+00:00" + "support": { + "issues": "https://github.com/sebastianbergmann/global-state/issues", + "source": "https://github.com/sebastianbergmann/global-state/tree/3.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-11-30T07:43:24+00:00" }, { "name": "sebastian/object-enumerator", - "version": "3.0.3", + "version": "3.0.4", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/object-enumerator.git", - "reference": "7cfd9e65d11ffb5af41198476395774d4c8a84c5" + "reference": "e67f6d32ebd0c749cf9d1dbd9f226c727043cdf2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/7cfd9e65d11ffb5af41198476395774d4c8a84c5", - "reference": "7cfd9e65d11ffb5af41198476395774d4c8a84c5", + "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/e67f6d32ebd0c749cf9d1dbd9f226c727043cdf2", + "reference": "e67f6d32ebd0c749cf9d1dbd9f226c727043cdf2", "shasum": "" }, "require": { - "php": "^7.0", + "php": ">=7.0", "sebastian/object-reflector": "^1.1.1", "sebastian/recursion-context": "^3.0" }, @@ -2708,24 +3179,34 @@ ], "description": "Traverses array structures and object graphs to enumerate all referenced objects", "homepage": "https://github.com/sebastianbergmann/object-enumerator/", - "time": "2017-08-03T12:35:26+00:00" + "support": { + "issues": "https://github.com/sebastianbergmann/object-enumerator/issues", + "source": "https://github.com/sebastianbergmann/object-enumerator/tree/3.0.4" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-11-30T07:40:27+00:00" }, { "name": "sebastian/object-reflector", - "version": "1.1.1", + "version": "1.1.2", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/object-reflector.git", - "reference": "773f97c67f28de00d397be301821b06708fca0be" + "reference": "9b8772b9cbd456ab45d4a598d2dd1a1bced6363d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/773f97c67f28de00d397be301821b06708fca0be", - "reference": "773f97c67f28de00d397be301821b06708fca0be", + "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/9b8772b9cbd456ab45d4a598d2dd1a1bced6363d", + "reference": "9b8772b9cbd456ab45d4a598d2dd1a1bced6363d", "shasum": "" }, "require": { - "php": "^7.0" + "php": ">=7.0" }, "require-dev": { "phpunit/phpunit": "^6.0" @@ -2753,24 +3234,34 @@ ], "description": "Allows reflection of object attributes, including inherited and non-public ones", "homepage": "https://github.com/sebastianbergmann/object-reflector/", - "time": "2017-03-29T09:07:27+00:00" + "support": { + "issues": "https://github.com/sebastianbergmann/object-reflector/issues", + "source": "https://github.com/sebastianbergmann/object-reflector/tree/1.1.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-11-30T07:37:18+00:00" }, { "name": "sebastian/recursion-context", - "version": "3.0.0", + "version": "3.0.1", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/recursion-context.git", - "reference": "5b0cd723502bac3b006cbf3dbf7a1e3fcefe4fa8" + "reference": "367dcba38d6e1977be014dc4b22f47a484dac7fb" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/5b0cd723502bac3b006cbf3dbf7a1e3fcefe4fa8", - "reference": "5b0cd723502bac3b006cbf3dbf7a1e3fcefe4fa8", + "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/367dcba38d6e1977be014dc4b22f47a484dac7fb", + "reference": "367dcba38d6e1977be014dc4b22f47a484dac7fb", "shasum": "" }, "require": { - "php": "^7.0" + "php": ">=7.0" }, "require-dev": { "phpunit/phpunit": "^6.0" @@ -2791,14 +3282,14 @@ "BSD-3-Clause" ], "authors": [ - { - "name": "Jeff Welch", - "email": "whatthejeff@gmail.com" - }, { "name": "Sebastian Bergmann", "email": "sebastian@phpunit.de" }, + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, { "name": "Adam Harvey", "email": "aharvey@php.net" @@ -2806,24 +3297,34 @@ ], "description": "Provides functionality to recursively process PHP variables", "homepage": "http://www.github.com/sebastianbergmann/recursion-context", - "time": "2017-03-03T06:23:57+00:00" + "support": { + "issues": "https://github.com/sebastianbergmann/recursion-context/issues", + "source": "https://github.com/sebastianbergmann/recursion-context/tree/3.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-11-30T07:34:24+00:00" }, { "name": "sebastian/resource-operations", - "version": "2.0.1", + "version": "2.0.2", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/resource-operations.git", - "reference": "4d7a795d35b889bf80a0cc04e08d77cedfa917a9" + "reference": "31d35ca87926450c44eae7e2611d45a7a65ea8b3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/resource-operations/zipball/4d7a795d35b889bf80a0cc04e08d77cedfa917a9", - "reference": "4d7a795d35b889bf80a0cc04e08d77cedfa917a9", + "url": "https://api.github.com/repos/sebastianbergmann/resource-operations/zipball/31d35ca87926450c44eae7e2611d45a7a65ea8b3", + "reference": "31d35ca87926450c44eae7e2611d45a7a65ea8b3", "shasum": "" }, "require": { - "php": "^7.1" + "php": ">=7.1" }, "type": "library", "extra": { @@ -2848,24 +3349,34 @@ ], "description": "Provides a list of PHP built-in functions that operate on resources", "homepage": "https://www.github.com/sebastianbergmann/resource-operations", - "time": "2018-10-04T04:07:39+00:00" + "support": { + "issues": "https://github.com/sebastianbergmann/resource-operations/issues", + "source": "https://github.com/sebastianbergmann/resource-operations/tree/2.0.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-11-30T07:30:19+00:00" }, { "name": "sebastian/type", - "version": "1.1.3", + "version": "1.1.4", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/type.git", - "reference": "3aaaa15fa71d27650d62a948be022fe3b48541a3" + "reference": "0150cfbc4495ed2df3872fb31b26781e4e077eb4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/3aaaa15fa71d27650d62a948be022fe3b48541a3", - "reference": "3aaaa15fa71d27650d62a948be022fe3b48541a3", + "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/0150cfbc4495ed2df3872fb31b26781e4e077eb4", + "reference": "0150cfbc4495ed2df3872fb31b26781e4e077eb4", "shasum": "" }, "require": { - "php": "^7.2" + "php": ">=7.2" }, "require-dev": { "phpunit/phpunit": "^8.2" @@ -2894,7 +3405,17 @@ ], "description": "Collection of value objects that represent the types of the PHP type system", "homepage": "https://github.com/sebastianbergmann/type", - "time": "2019-07-02T08:10:15+00:00" + "support": { + "issues": "https://github.com/sebastianbergmann/type/issues", + "source": "https://github.com/sebastianbergmann/type/tree/1.1.4" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-11-30T07:25:11+00:00" }, { "name": "sebastian/version", @@ -2937,25 +3458,29 @@ ], "description": "Library that helps with managing the version number of Git-hosted PHP projects", "homepage": "https://github.com/sebastianbergmann/version", + "support": { + "issues": "https://github.com/sebastianbergmann/version/issues", + "source": "https://github.com/sebastianbergmann/version/tree/master" + }, "time": "2016-10-03T07:35:21+00:00" }, { "name": "setasign/fpdi", - "version": "v2.3.4", + "version": "v2.3.6", "source": { "type": "git", "url": "https://github.com/Setasign/FPDI.git", - "reference": "2b5fb811c04f937ef257ef3f798cebeded33c136" + "reference": "6231e315f73e4f62d72b73f3d6d78ff0eed93c31" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Setasign/FPDI/zipball/2b5fb811c04f937ef257ef3f798cebeded33c136", - "reference": "2b5fb811c04f937ef257ef3f798cebeded33c136", + "url": "https://api.github.com/repos/Setasign/FPDI/zipball/6231e315f73e4f62d72b73f3d6d78ff0eed93c31", + "reference": "6231e315f73e4f62d72b73f3d6d78ff0eed93c31", "shasum": "" }, "require": { "ext-zlib": "*", - "php": "^5.6 || ^7.0" + "php": "^5.6 || ^7.0 || ^8.0" }, "conflict": { "setasign/tfpdf": "<1.31" @@ -2999,26 +3524,30 @@ "fpdi", "pdf" ], + "support": { + "issues": "https://github.com/Setasign/FPDI/issues", + "source": "https://github.com/Setasign/FPDI/tree/v2.3.6" + }, "funding": [ { "url": "https://tidelift.com/funding/github/packagist/setasign/fpdi", "type": "tidelift" } ], - "time": "2020-08-27T06:55:47+00:00" + "time": "2021-02-11T11:37:01+00:00" }, { "name": "squizlabs/php_codesniffer", - "version": "3.5.6", + "version": "3.6.1", "source": { "type": "git", "url": "https://github.com/squizlabs/PHP_CodeSniffer.git", - "reference": "e97627871a7eab2f70e59166072a6b767d5834e0" + "reference": "f268ca40d54617c6e06757f83f699775c9b3ff2e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/e97627871a7eab2f70e59166072a6b767d5834e0", - "reference": "e97627871a7eab2f70e59166072a6b767d5834e0", + "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/f268ca40d54617c6e06757f83f699775c9b3ff2e", + "reference": "f268ca40d54617c6e06757f83f699775c9b3ff2e", "shasum": "" }, "require": { @@ -3056,31 +3585,38 @@ "phpcs", "standards" ], - "time": "2020-08-10T04:50:15+00:00" + "support": { + "issues": "https://github.com/squizlabs/PHP_CodeSniffer/issues", + "source": "https://github.com/squizlabs/PHP_CodeSniffer", + "wiki": "https://github.com/squizlabs/PHP_CodeSniffer/wiki" + }, + "time": "2021-10-11T04:00:11+00:00" }, { "name": "symfony/console", - "version": "v5.1.7", + "version": "v5.3.10", "source": { "type": "git", "url": "https://github.com/symfony/console.git", - "reference": "ae789a8a2ad189ce7e8216942cdb9b77319f5eb8" + "reference": "d4e409d9fbcfbf71af0e5a940abb7b0b4bad0bd3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/ae789a8a2ad189ce7e8216942cdb9b77319f5eb8", - "reference": "ae789a8a2ad189ce7e8216942cdb9b77319f5eb8", + "url": "https://api.github.com/repos/symfony/console/zipball/d4e409d9fbcfbf71af0e5a940abb7b0b4bad0bd3", + "reference": "d4e409d9fbcfbf71af0e5a940abb7b0b4bad0bd3", "shasum": "" }, "require": { "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1", "symfony/polyfill-mbstring": "~1.0", "symfony/polyfill-php73": "^1.8", - "symfony/polyfill-php80": "^1.15", + "symfony/polyfill-php80": "^1.16", "symfony/service-contracts": "^1.1|^2", "symfony/string": "^5.1" }, "conflict": { + "psr/log": ">=3", "symfony/dependency-injection": "<4.4", "symfony/dotenv": "<5.1", "symfony/event-dispatcher": "<4.4", @@ -3088,10 +3624,10 @@ "symfony/process": "<4.4" }, "provide": { - "psr/log-implementation": "1.0" + "psr/log-implementation": "1.0|2.0" }, "require-dev": { - "psr/log": "~1.0", + "psr/log": "^1|^2", "symfony/config": "^4.4|^5.0", "symfony/dependency-injection": "^4.4|^5.0", "symfony/event-dispatcher": "^4.4|^5.0", @@ -3106,11 +3642,6 @@ "symfony/process": "" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "5.1-dev" - } - }, "autoload": { "psr-4": { "Symfony\\Component\\Console\\": "" @@ -3133,8 +3664,17 @@ "homepage": "https://symfony.com/contributors" } ], - "description": "Symfony Console Component", + "description": "Eases the creation of beautiful and testable command line interfaces", "homepage": "https://symfony.com", + "keywords": [ + "cli", + "command line", + "console", + "terminal" + ], + "support": { + "source": "https://github.com/symfony/console/tree/v5.3.10" + }, "funding": [ { "url": "https://symfony.com/sponsor", @@ -3149,20 +3689,20 @@ "type": "tidelift" } ], - "time": "2020-10-07T15:23:00+00:00" + "time": "2021-10-26T09:30:15+00:00" }, { "name": "symfony/deprecation-contracts", - "version": "v2.2.0", + "version": "v2.4.0", "source": { "type": "git", "url": "https://github.com/symfony/deprecation-contracts.git", - "reference": "5fa56b4074d1ae755beb55617ddafe6f5d78f665" + "reference": "5f38c8804a9e97d23e0c8d63341088cd8a22d627" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/5fa56b4074d1ae755beb55617ddafe6f5d78f665", - "reference": "5fa56b4074d1ae755beb55617ddafe6f5d78f665", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/5f38c8804a9e97d23e0c8d63341088cd8a22d627", + "reference": "5f38c8804a9e97d23e0c8d63341088cd8a22d627", "shasum": "" }, "require": { @@ -3171,7 +3711,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "2.2-dev" + "dev-main": "2.4-dev" }, "thanks": { "name": "symfony/contracts", @@ -3199,6 +3739,9 @@ ], "description": "A generic function and convention to trigger deprecation notices", "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/deprecation-contracts/tree/v2.4.0" + }, "funding": [ { "url": "https://symfony.com/sponsor", @@ -3213,27 +3756,27 @@ "type": "tidelift" } ], - "time": "2020-09-07T11:33:47+00:00" + "time": "2021-03-23T23:28:01+00:00" }, { "name": "symfony/event-dispatcher", - "version": "v5.1.7", + "version": "v5.3.7", "source": { "type": "git", "url": "https://github.com/symfony/event-dispatcher.git", - "reference": "d5de97d6af175a9e8131c546db054ca32842dd0f" + "reference": "ce7b20d69c66a20939d8952b617506a44d102130" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/d5de97d6af175a9e8131c546db054ca32842dd0f", - "reference": "d5de97d6af175a9e8131c546db054ca32842dd0f", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/ce7b20d69c66a20939d8952b617506a44d102130", + "reference": "ce7b20d69c66a20939d8952b617506a44d102130", "shasum": "" }, "require": { "php": ">=7.2.5", "symfony/deprecation-contracts": "^2.1", "symfony/event-dispatcher-contracts": "^2", - "symfony/polyfill-php80": "^1.15" + "symfony/polyfill-php80": "^1.16" }, "conflict": { "symfony/dependency-injection": "<4.4" @@ -3243,7 +3786,7 @@ "symfony/event-dispatcher-implementation": "2.0" }, "require-dev": { - "psr/log": "~1.0", + "psr/log": "^1|^2|^3", "symfony/config": "^4.4|^5.0", "symfony/dependency-injection": "^4.4|^5.0", "symfony/error-handler": "^4.4|^5.0", @@ -3257,11 +3800,6 @@ "symfony/http-kernel": "" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "5.1-dev" - } - }, "autoload": { "psr-4": { "Symfony\\Component\\EventDispatcher\\": "" @@ -3284,8 +3822,11 @@ "homepage": "https://symfony.com/contributors" } ], - "description": "Symfony EventDispatcher Component", + "description": "Provides tools that allow your application components to communicate with each other by dispatching events and listening to them", "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/event-dispatcher/tree/v5.3.7" + }, "funding": [ { "url": "https://symfony.com/sponsor", @@ -3300,20 +3841,20 @@ "type": "tidelift" } ], - "time": "2020-09-18T14:27:32+00:00" + "time": "2021-08-04T21:20:46+00:00" }, { "name": "symfony/event-dispatcher-contracts", - "version": "v2.2.0", + "version": "v2.4.0", "source": { "type": "git", "url": "https://github.com/symfony/event-dispatcher-contracts.git", - "reference": "0ba7d54483095a198fa51781bc608d17e84dffa2" + "reference": "69fee1ad2332a7cbab3aca13591953da9cdb7a11" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/0ba7d54483095a198fa51781bc608d17e84dffa2", - "reference": "0ba7d54483095a198fa51781bc608d17e84dffa2", + "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/69fee1ad2332a7cbab3aca13591953da9cdb7a11", + "reference": "69fee1ad2332a7cbab3aca13591953da9cdb7a11", "shasum": "" }, "require": { @@ -3326,7 +3867,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "2.2-dev" + "dev-main": "2.4-dev" }, "thanks": { "name": "symfony/contracts", @@ -3362,6 +3903,9 @@ "interoperability", "standards" ], + "support": { + "source": "https://github.com/symfony/event-dispatcher-contracts/tree/v2.4.0" + }, "funding": [ { "url": "https://symfony.com/sponsor", @@ -3376,32 +3920,28 @@ "type": "tidelift" } ], - "time": "2020-09-07T11:33:47+00:00" + "time": "2021-03-23T23:28:01+00:00" }, { "name": "symfony/filesystem", - "version": "v5.1.7", + "version": "v5.3.4", "source": { "type": "git", "url": "https://github.com/symfony/filesystem.git", - "reference": "1a8697545a8d87b9f2f6b1d32414199cc5e20aae" + "reference": "343f4fe324383ca46792cae728a3b6e2f708fb32" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/filesystem/zipball/1a8697545a8d87b9f2f6b1d32414199cc5e20aae", - "reference": "1a8697545a8d87b9f2f6b1d32414199cc5e20aae", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/343f4fe324383ca46792cae728a3b6e2f708fb32", + "reference": "343f4fe324383ca46792cae728a3b6e2f708fb32", "shasum": "" }, "require": { "php": ">=7.2.5", - "symfony/polyfill-ctype": "~1.8" + "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-php80": "^1.16" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "5.1-dev" - } - }, "autoload": { "psr-4": { "Symfony\\Component\\Filesystem\\": "" @@ -3424,8 +3964,11 @@ "homepage": "https://symfony.com/contributors" } ], - "description": "Symfony Filesystem Component", + "description": "Provides basic utilities for the filesystem", "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/filesystem/tree/v5.3.4" + }, "funding": [ { "url": "https://symfony.com/sponsor", @@ -3440,31 +3983,27 @@ "type": "tidelift" } ], - "time": "2020-09-27T14:02:37+00:00" + "time": "2021-07-21T12:40:44+00:00" }, { "name": "symfony/finder", - "version": "v5.1.7", + "version": "v5.3.7", "source": { "type": "git", "url": "https://github.com/symfony/finder.git", - "reference": "2c3ba7ad6884e6c4451ce2340e2dc23f6fa3e0d8" + "reference": "a10000ada1e600d109a6c7632e9ac42e8bf2fb93" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/finder/zipball/2c3ba7ad6884e6c4451ce2340e2dc23f6fa3e0d8", - "reference": "2c3ba7ad6884e6c4451ce2340e2dc23f6fa3e0d8", + "url": "https://api.github.com/repos/symfony/finder/zipball/a10000ada1e600d109a6c7632e9ac42e8bf2fb93", + "reference": "a10000ada1e600d109a6c7632e9ac42e8bf2fb93", "shasum": "" }, "require": { - "php": ">=7.2.5" + "php": ">=7.2.5", + "symfony/polyfill-php80": "^1.16" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "5.1-dev" - } - }, "autoload": { "psr-4": { "Symfony\\Component\\Finder\\": "" @@ -3487,8 +4026,11 @@ "homepage": "https://symfony.com/contributors" } ], - "description": "Symfony Finder Component", + "description": "Finds files and directories via an intuitive fluent interface", "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/finder/tree/v5.3.7" + }, "funding": [ { "url": "https://symfony.com/sponsor", @@ -3503,33 +4045,29 @@ "type": "tidelift" } ], - "time": "2020-09-02T16:23:27+00:00" + "time": "2021-08-04T21:20:46+00:00" }, { "name": "symfony/options-resolver", - "version": "v5.1.7", + "version": "v5.3.7", "source": { "type": "git", "url": "https://github.com/symfony/options-resolver.git", - "reference": "4c7e155bf7d93ea4ba3824d5a14476694a5278dd" + "reference": "4b78e55b179003a42523a362cc0e8327f7a69b5e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/options-resolver/zipball/4c7e155bf7d93ea4ba3824d5a14476694a5278dd", - "reference": "4c7e155bf7d93ea4ba3824d5a14476694a5278dd", + "url": "https://api.github.com/repos/symfony/options-resolver/zipball/4b78e55b179003a42523a362cc0e8327f7a69b5e", + "reference": "4b78e55b179003a42523a362cc0e8327f7a69b5e", "shasum": "" }, "require": { "php": ">=7.2.5", "symfony/deprecation-contracts": "^2.1", - "symfony/polyfill-php80": "^1.15" + "symfony/polyfill-php73": "~1.0", + "symfony/polyfill-php80": "^1.16" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "5.1-dev" - } - }, "autoload": { "psr-4": { "Symfony\\Component\\OptionsResolver\\": "" @@ -3552,13 +4090,16 @@ "homepage": "https://symfony.com/contributors" } ], - "description": "Symfony OptionsResolver Component", + "description": "Provides an improved replacement for the array_replace PHP function", "homepage": "https://symfony.com", "keywords": [ "config", "configuration", "options" ], + "support": { + "source": "https://github.com/symfony/options-resolver/tree/v5.3.7" + }, "funding": [ { "url": "https://symfony.com/sponsor", @@ -3573,24 +4114,24 @@ "type": "tidelift" } ], - "time": "2020-09-27T03:44:28+00:00" + "time": "2021-08-04T21:20:46+00:00" }, { "name": "symfony/polyfill-ctype", - "version": "v1.18.1", + "version": "v1.23.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-ctype.git", - "reference": "1c302646f6efc070cd46856e600e5e0684d6b454" + "reference": "46cd95797e9df938fdd2b03693b5fca5e64b01ce" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/1c302646f6efc070cd46856e600e5e0684d6b454", - "reference": "1c302646f6efc070cd46856e600e5e0684d6b454", + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/46cd95797e9df938fdd2b03693b5fca5e64b01ce", + "reference": "46cd95797e9df938fdd2b03693b5fca5e64b01ce", "shasum": "" }, "require": { - "php": ">=5.3.3" + "php": ">=7.1" }, "suggest": { "ext-ctype": "For best performance" @@ -3598,7 +4139,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.18-dev" + "dev-main": "1.23-dev" }, "thanks": { "name": "symfony/polyfill", @@ -3635,6 +4176,9 @@ "polyfill", "portable" ], + "support": { + "source": "https://github.com/symfony/polyfill-ctype/tree/v1.23.0" + }, "funding": [ { "url": "https://symfony.com/sponsor", @@ -3649,24 +4193,24 @@ "type": "tidelift" } ], - "time": "2020-07-14T12:35:20+00:00" + "time": "2021-02-19T12:13:01+00:00" }, { "name": "symfony/polyfill-intl-grapheme", - "version": "v1.18.1", + "version": "v1.23.1", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-intl-grapheme.git", - "reference": "b740103edbdcc39602239ee8860f0f45a8eb9aa5" + "reference": "16880ba9c5ebe3642d1995ab866db29270b36535" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/b740103edbdcc39602239ee8860f0f45a8eb9aa5", - "reference": "b740103edbdcc39602239ee8860f0f45a8eb9aa5", + "url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/16880ba9c5ebe3642d1995ab866db29270b36535", + "reference": "16880ba9c5ebe3642d1995ab866db29270b36535", "shasum": "" }, "require": { - "php": ">=5.3.3" + "php": ">=7.1" }, "suggest": { "ext-intl": "For best performance" @@ -3674,7 +4218,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.18-dev" + "dev-main": "1.23-dev" }, "thanks": { "name": "symfony/polyfill", @@ -3713,6 +4257,9 @@ "portable", "shim" ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.23.1" + }, "funding": [ { "url": "https://symfony.com/sponsor", @@ -3727,24 +4274,24 @@ "type": "tidelift" } ], - "time": "2020-07-14T12:35:20+00:00" + "time": "2021-05-27T12:26:48+00:00" }, { "name": "symfony/polyfill-intl-normalizer", - "version": "v1.18.1", + "version": "v1.23.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-intl-normalizer.git", - "reference": "37078a8dd4a2a1e9ab0231af7c6cb671b2ed5a7e" + "reference": "8590a5f561694770bdcd3f9b5c69dde6945028e8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-intl-normalizer/zipball/37078a8dd4a2a1e9ab0231af7c6cb671b2ed5a7e", - "reference": "37078a8dd4a2a1e9ab0231af7c6cb671b2ed5a7e", + "url": "https://api.github.com/repos/symfony/polyfill-intl-normalizer/zipball/8590a5f561694770bdcd3f9b5c69dde6945028e8", + "reference": "8590a5f561694770bdcd3f9b5c69dde6945028e8", "shasum": "" }, "require": { - "php": ">=5.3.3" + "php": ">=7.1" }, "suggest": { "ext-intl": "For best performance" @@ -3752,7 +4299,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.18-dev" + "dev-main": "1.23-dev" }, "thanks": { "name": "symfony/polyfill", @@ -3794,6 +4341,9 @@ "portable", "shim" ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.23.0" + }, "funding": [ { "url": "https://symfony.com/sponsor", @@ -3808,47 +4358,35 @@ "type": "tidelift" } ], - "time": "2020-07-14T12:35:20+00:00" + "time": "2021-02-19T12:13:01+00:00" }, { "name": "symfony/polyfill-php70", - "version": "v1.18.1", + "version": "v1.20.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php70.git", - "reference": "0dd93f2c578bdc9c72697eaa5f1dd25644e618d3" + "reference": "5f03a781d984aae42cebd18e7912fa80f02ee644" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php70/zipball/0dd93f2c578bdc9c72697eaa5f1dd25644e618d3", - "reference": "0dd93f2c578bdc9c72697eaa5f1dd25644e618d3", + "url": "https://api.github.com/repos/symfony/polyfill-php70/zipball/5f03a781d984aae42cebd18e7912fa80f02ee644", + "reference": "5f03a781d984aae42cebd18e7912fa80f02ee644", "shasum": "" }, "require": { - "paragonie/random_compat": "~1.0|~2.0|~9.99", - "php": ">=5.3.3" + "php": ">=7.1" }, - "type": "library", + "type": "metapackage", "extra": { "branch-alias": { - "dev-master": "1.18-dev" + "dev-main": "1.20-dev" }, "thanks": { "name": "symfony/polyfill", "url": "https://github.com/symfony/polyfill" } }, - "autoload": { - "psr-4": { - "Symfony\\Polyfill\\Php70\\": "" - }, - "files": [ - "bootstrap.php" - ], - "classmap": [ - "Resources/stubs" - ] - }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" @@ -3871,6 +4409,9 @@ "portable", "shim" ], + "support": { + "source": "https://github.com/symfony/polyfill-php70/tree/v1.20.0" + }, "funding": [ { "url": "https://symfony.com/sponsor", @@ -3885,29 +4426,29 @@ "type": "tidelift" } ], - "time": "2020-07-14T12:35:20+00:00" + "time": "2020-10-23T14:02:19+00:00" }, { "name": "symfony/polyfill-php72", - "version": "v1.18.1", + "version": "v1.23.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php72.git", - "reference": "639447d008615574653fb3bc60d1986d7172eaae" + "reference": "9a142215a36a3888e30d0a9eeea9766764e96976" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php72/zipball/639447d008615574653fb3bc60d1986d7172eaae", - "reference": "639447d008615574653fb3bc60d1986d7172eaae", + "url": "https://api.github.com/repos/symfony/polyfill-php72/zipball/9a142215a36a3888e30d0a9eeea9766764e96976", + "reference": "9a142215a36a3888e30d0a9eeea9766764e96976", "shasum": "" }, "require": { - "php": ">=5.3.3" + "php": ">=7.1" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.18-dev" + "dev-main": "1.23-dev" }, "thanks": { "name": "symfony/polyfill", @@ -3944,6 +4485,9 @@ "portable", "shim" ], + "support": { + "source": "https://github.com/symfony/polyfill-php72/tree/v1.23.0" + }, "funding": [ { "url": "https://symfony.com/sponsor", @@ -3958,29 +4502,29 @@ "type": "tidelift" } ], - "time": "2020-07-14T12:35:20+00:00" + "time": "2021-05-27T09:17:38+00:00" }, { "name": "symfony/polyfill-php73", - "version": "v1.18.1", + "version": "v1.23.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php73.git", - "reference": "fffa1a52a023e782cdcc221d781fe1ec8f87fcca" + "reference": "fba8933c384d6476ab14fb7b8526e5287ca7e010" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php73/zipball/fffa1a52a023e782cdcc221d781fe1ec8f87fcca", - "reference": "fffa1a52a023e782cdcc221d781fe1ec8f87fcca", + "url": "https://api.github.com/repos/symfony/polyfill-php73/zipball/fba8933c384d6476ab14fb7b8526e5287ca7e010", + "reference": "fba8933c384d6476ab14fb7b8526e5287ca7e010", "shasum": "" }, "require": { - "php": ">=5.3.3" + "php": ">=7.1" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.18-dev" + "dev-main": "1.23-dev" }, "thanks": { "name": "symfony/polyfill", @@ -4020,6 +4564,9 @@ "portable", "shim" ], + "support": { + "source": "https://github.com/symfony/polyfill-php73/tree/v1.23.0" + }, "funding": [ { "url": "https://symfony.com/sponsor", @@ -4034,29 +4581,29 @@ "type": "tidelift" } ], - "time": "2020-07-14T12:35:20+00:00" + "time": "2021-02-19T12:13:01+00:00" }, { "name": "symfony/polyfill-php80", - "version": "v1.18.1", + "version": "v1.23.1", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php80.git", - "reference": "d87d5766cbf48d72388a9f6b85f280c8ad51f981" + "reference": "1100343ed1a92e3a38f9ae122fc0eb21602547be" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/d87d5766cbf48d72388a9f6b85f280c8ad51f981", - "reference": "d87d5766cbf48d72388a9f6b85f280c8ad51f981", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/1100343ed1a92e3a38f9ae122fc0eb21602547be", + "reference": "1100343ed1a92e3a38f9ae122fc0eb21602547be", "shasum": "" }, "require": { - "php": ">=7.0.8" + "php": ">=7.1" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.18-dev" + "dev-main": "1.23-dev" }, "thanks": { "name": "symfony/polyfill", @@ -4100,6 +4647,9 @@ "portable", "shim" ], + "support": { + "source": "https://github.com/symfony/polyfill-php80/tree/v1.23.1" + }, "funding": [ { "url": "https://symfony.com/sponsor", @@ -4114,32 +4664,27 @@ "type": "tidelift" } ], - "time": "2020-07-14T12:35:20+00:00" + "time": "2021-07-28T13:41:28+00:00" }, { "name": "symfony/process", - "version": "v5.1.7", + "version": "v5.3.7", "source": { "type": "git", "url": "https://github.com/symfony/process.git", - "reference": "d3a2e64866169586502f0cd9cab69135ad12cee9" + "reference": "38f26c7d6ed535217ea393e05634cb0b244a1967" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/process/zipball/d3a2e64866169586502f0cd9cab69135ad12cee9", - "reference": "d3a2e64866169586502f0cd9cab69135ad12cee9", + "url": "https://api.github.com/repos/symfony/process/zipball/38f26c7d6ed535217ea393e05634cb0b244a1967", + "reference": "38f26c7d6ed535217ea393e05634cb0b244a1967", "shasum": "" }, "require": { "php": ">=7.2.5", - "symfony/polyfill-php80": "^1.15" + "symfony/polyfill-php80": "^1.16" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "5.1-dev" - } - }, "autoload": { "psr-4": { "Symfony\\Component\\Process\\": "" @@ -4162,8 +4707,11 @@ "homepage": "https://symfony.com/contributors" } ], - "description": "Symfony Process Component", + "description": "Executes commands in sub-processes", "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/process/tree/v5.3.7" + }, "funding": [ { "url": "https://symfony.com/sponsor", @@ -4178,25 +4726,25 @@ "type": "tidelift" } ], - "time": "2020-09-02T16:23:27+00:00" + "time": "2021-08-04T21:20:46+00:00" }, { "name": "symfony/service-contracts", - "version": "v2.2.0", + "version": "v2.4.0", "source": { "type": "git", "url": "https://github.com/symfony/service-contracts.git", - "reference": "d15da7ba4957ffb8f1747218be9e1a121fd298a1" + "reference": "f040a30e04b57fbcc9c6cbcf4dbaa96bd318b9bb" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/service-contracts/zipball/d15da7ba4957ffb8f1747218be9e1a121fd298a1", - "reference": "d15da7ba4957ffb8f1747218be9e1a121fd298a1", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/f040a30e04b57fbcc9c6cbcf4dbaa96bd318b9bb", + "reference": "f040a30e04b57fbcc9c6cbcf4dbaa96bd318b9bb", "shasum": "" }, "require": { "php": ">=7.2.5", - "psr/container": "^1.0" + "psr/container": "^1.1" }, "suggest": { "symfony/service-implementation": "" @@ -4204,7 +4752,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "2.2-dev" + "dev-main": "2.4-dev" }, "thanks": { "name": "symfony/contracts", @@ -4240,6 +4788,9 @@ "interoperability", "standards" ], + "support": { + "source": "https://github.com/symfony/service-contracts/tree/v2.4.0" + }, "funding": [ { "url": "https://symfony.com/sponsor", @@ -4254,20 +4805,20 @@ "type": "tidelift" } ], - "time": "2020-09-07T11:33:47+00:00" + "time": "2021-04-01T10:43:52+00:00" }, { "name": "symfony/stopwatch", - "version": "v5.1.7", + "version": "v5.3.4", "source": { "type": "git", "url": "https://github.com/symfony/stopwatch.git", - "reference": "0f7c58cf81dbb5dd67d423a89d577524a2ec0323" + "reference": "b24c6a92c6db316fee69e38c80591e080e41536c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/stopwatch/zipball/0f7c58cf81dbb5dd67d423a89d577524a2ec0323", - "reference": "0f7c58cf81dbb5dd67d423a89d577524a2ec0323", + "url": "https://api.github.com/repos/symfony/stopwatch/zipball/b24c6a92c6db316fee69e38c80591e080e41536c", + "reference": "b24c6a92c6db316fee69e38c80591e080e41536c", "shasum": "" }, "require": { @@ -4275,11 +4826,6 @@ "symfony/service-contracts": "^1.0|^2" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "5.1-dev" - } - }, "autoload": { "psr-4": { "Symfony\\Component\\Stopwatch\\": "" @@ -4302,8 +4848,11 @@ "homepage": "https://symfony.com/contributors" } ], - "description": "Symfony Stopwatch Component", + "description": "Provides a way to profile code", "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/stopwatch/tree/v5.3.4" + }, "funding": [ { "url": "https://symfony.com/sponsor", @@ -4318,20 +4867,20 @@ "type": "tidelift" } ], - "time": "2020-05-20T17:43:50+00:00" + "time": "2021-07-10T08:58:57+00:00" }, { "name": "symfony/string", - "version": "v5.1.7", + "version": "v5.3.10", "source": { "type": "git", "url": "https://github.com/symfony/string.git", - "reference": "4a9afe9d07bac506f75bcee8ed3ce76da5a9343e" + "reference": "d70c35bb20bbca71fc4ab7921e3c6bda1a82a60c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/string/zipball/4a9afe9d07bac506f75bcee8ed3ce76da5a9343e", - "reference": "4a9afe9d07bac506f75bcee8ed3ce76da5a9343e", + "url": "https://api.github.com/repos/symfony/string/zipball/d70c35bb20bbca71fc4ab7921e3c6bda1a82a60c", + "reference": "d70c35bb20bbca71fc4ab7921e3c6bda1a82a60c", "shasum": "" }, "require": { @@ -4349,11 +4898,6 @@ "symfony/var-exporter": "^4.4|^5.0" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "5.1-dev" - } - }, "autoload": { "psr-4": { "Symfony\\Component\\String\\": "" @@ -4379,7 +4923,7 @@ "homepage": "https://symfony.com/contributors" } ], - "description": "Symfony String component", + "description": "Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way", "homepage": "https://symfony.com", "keywords": [ "grapheme", @@ -4389,6 +4933,9 @@ "utf-8", "utf8" ], + "support": { + "source": "https://github.com/symfony/string/tree/v5.3.10" + }, "funding": [ { "url": "https://symfony.com/sponsor", @@ -4403,20 +4950,20 @@ "type": "tidelift" } ], - "time": "2020-09-15T12:23:47+00:00" + "time": "2021-10-27T18:21:46+00:00" }, { "name": "tecnickcom/tcpdf", - "version": "6.3.5", + "version": "6.4.2", "source": { "type": "git", "url": "https://github.com/tecnickcom/TCPDF.git", - "reference": "19a535eaa7fb1c1cac499109deeb1a7a201b4549" + "reference": "172540dcbfdf8dc983bc2fe78feff48ff7ec1c76" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/tecnickcom/TCPDF/zipball/19a535eaa7fb1c1cac499109deeb1a7a201b4549", - "reference": "19a535eaa7fb1c1cac499109deeb1a7a201b4549", + "url": "https://api.github.com/repos/tecnickcom/TCPDF/zipball/172540dcbfdf8dc983bc2fe78feff48ff7ec1c76", + "reference": "172540dcbfdf8dc983bc2fe78feff48ff7ec1c76", "shasum": "" }, "require": { @@ -4465,20 +5012,30 @@ "pdf417", "qrcode" ], - "time": "2020-02-14T14:20:12+00:00" + "support": { + "issues": "https://github.com/tecnickcom/TCPDF/issues", + "source": "https://github.com/tecnickcom/TCPDF/tree/6.4.2" + }, + "funding": [ + { + "url": "https://www.paypal.com/cgi-bin/webscr?cmd=_donations¤cy_code=GBP&business=paypal@tecnick.com&item_name=donation%20for%20tcpdf%20project", + "type": "custom" + } + ], + "time": "2021-07-20T14:43:20+00:00" }, { "name": "theseer/tokenizer", - "version": "1.2.0", + "version": "1.2.1", "source": { "type": "git", "url": "https://github.com/theseer/tokenizer.git", - "reference": "75a63c33a8577608444246075ea0af0d052e452a" + "reference": "34a41e998c2183e22995f158c581e7b5e755ab9e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/theseer/tokenizer/zipball/75a63c33a8577608444246075ea0af0d052e452a", - "reference": "75a63c33a8577608444246075ea0af0d052e452a", + "url": "https://api.github.com/repos/theseer/tokenizer/zipball/34a41e998c2183e22995f158c581e7b5e755ab9e", + "reference": "34a41e998c2183e22995f158c581e7b5e755ab9e", "shasum": "" }, "require": { @@ -4505,40 +5062,49 @@ } ], "description": "A small library for converting tokenized PHP source code into XML and potentially other formats", + "support": { + "issues": "https://github.com/theseer/tokenizer/issues", + "source": "https://github.com/theseer/tokenizer/tree/1.2.1" + }, "funding": [ { "url": "https://github.com/theseer", "type": "github" } ], - "time": "2020-07-12T23:59:07+00:00" + "time": "2021-07-28T10:34:58+00:00" }, { "name": "webmozart/assert", - "version": "1.9.1", + "version": "1.10.0", "source": { "type": "git", - "url": "https://github.com/webmozart/assert.git", - "reference": "bafc69caeb4d49c39fd0779086c03a3738cbb389" + "url": "https://github.com/webmozarts/assert.git", + "reference": "6964c76c7804814a842473e0c8fd15bab0f18e25" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/webmozart/assert/zipball/bafc69caeb4d49c39fd0779086c03a3738cbb389", - "reference": "bafc69caeb4d49c39fd0779086c03a3738cbb389", + "url": "https://api.github.com/repos/webmozarts/assert/zipball/6964c76c7804814a842473e0c8fd15bab0f18e25", + "reference": "6964c76c7804814a842473e0c8fd15bab0f18e25", "shasum": "" }, "require": { - "php": "^5.3.3 || ^7.0 || ^8.0", + "php": "^7.2 || ^8.0", "symfony/polyfill-ctype": "^1.8" }, "conflict": { "phpstan/phpstan": "<0.12.20", - "vimeo/psalm": "<3.9.1" + "vimeo/psalm": "<4.6.1 || 4.6.2" }, "require-dev": { - "phpunit/phpunit": "^4.8.36 || ^7.5.13" + "phpunit/phpunit": "^8.5.13" }, "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.10-dev" + } + }, "autoload": { "psr-4": { "Webmozart\\Assert\\": "src/" @@ -4560,21 +5126,27 @@ "check", "validate" ], - "time": "2020-07-08T17:02:28+00:00" + "support": { + "issues": "https://github.com/webmozarts/assert/issues", + "source": "https://github.com/webmozarts/assert/tree/1.10.0" + }, + "time": "2021-03-09T10:59:23+00:00" } ], "aliases": [], "minimum-stability": "stable", - "stability-flags": [], + "stability-flags": { + "dealerdirect/phpcodesniffer-composer-installer": 20 + }, "prefer-stable": false, "prefer-lowest": false, "platform": { - "php": "^7.2||^8.0", + "php": "^7.2 || ^8.0", "ext-ctype": "*", "ext-dom": "*", + "ext-fileinfo": "*", "ext-gd": "*", "ext-iconv": "*", - "ext-fileinfo": "*", "ext-libxml": "*", "ext-mbstring": "*", "ext-simplexml": "*", @@ -4585,5 +5157,5 @@ "ext-zlib": "*" }, "platform-dev": [], - "plugin-api-version": "2.0.0" + "plugin-api-version": "2.1.0" } diff --git a/docs/extra/extrajs.js b/docs/extra/extrajs.js new file mode 100644 index 00000000..9ad135e8 --- /dev/null +++ b/docs/extra/extrajs.js @@ -0,0 +1,5 @@ +document.addEventListener("DOMContentLoaded", function() { + document.querySelectorAll("table").forEach(function(table) { + table.classList.add("docutils"); + }); +}); \ No newline at end of file diff --git a/docs/index.md b/docs/index.md index b1207d53..42acedf9 100644 --- a/docs/index.md +++ b/docs/index.md @@ -89,7 +89,7 @@ php vendor/phpoffice/phpspreadsheet/samples/Basic/01_Simple.php ## Learn by documentation -For more in-depth documentation, you may read about an [overview of the +For more documentation in depth, you may read about an [overview of the architecture](./topics/architecture.md), [creating a spreadsheet](./topics/creating-spreadsheet.md), [worksheets](./topics/worksheets.md), diff --git a/docs/references/features-cross-reference.md b/docs/references/features-cross-reference.md index 716a3787..c836a99a 100644 --- a/docs/references/features-cross-reference.md +++ b/docs/references/features-cross-reference.md @@ -1220,13 +1220,13 @@ Merged Cells - - - - + ✔ ✔ - + ✔ + ✔ + N/A + N/A @@ -1313,13 +1313,13 @@ ● ● - - + ● + ● ● ● - + ● diff --git a/docs/references/function-list-by-category.md b/docs/references/function-list-by-category.md index 6ac54cb7..0ce7340e 100644 --- a/docs/references/function-list-by-category.md +++ b/docs/references/function-list-by-category.md @@ -2,543 +2,545 @@ ## CATEGORY_CUBE -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- -CUBEKPIMEMBER | **Not yet Implemented** -CUBEMEMBER | **Not yet Implemented** -CUBEMEMBERPROPERTY | **Not yet Implemented** -CUBERANKEDMEMBER | **Not yet Implemented** -CUBESET | **Not yet Implemented** -CUBESETCOUNT | **Not yet Implemented** -CUBEVALUE | **Not yet Implemented** +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- +CUBEKPIMEMBER | **Not yet Implemented** +CUBEMEMBER | **Not yet Implemented** +CUBEMEMBERPROPERTY | **Not yet Implemented** +CUBERANKEDMEMBER | **Not yet Implemented** +CUBESET | **Not yet Implemented** +CUBESETCOUNT | **Not yet Implemented** +CUBEVALUE | **Not yet Implemented** ## CATEGORY_DATABASE -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- -DAVERAGE | \PhpOffice\PhpSpreadsheet\Calculation\Database::DAVERAGE -DCOUNT | \PhpOffice\PhpSpreadsheet\Calculation\Database::DCOUNT -DCOUNTA | \PhpOffice\PhpSpreadsheet\Calculation\Database::DCOUNTA -DGET | \PhpOffice\PhpSpreadsheet\Calculation\Database::DGET -DMAX | \PhpOffice\PhpSpreadsheet\Calculation\Database::DMAX -DMIN | \PhpOffice\PhpSpreadsheet\Calculation\Database::DMIN -DPRODUCT | \PhpOffice\PhpSpreadsheet\Calculation\Database::DPRODUCT -DSTDEV | \PhpOffice\PhpSpreadsheet\Calculation\Database::DSTDEV -DSTDEVP | \PhpOffice\PhpSpreadsheet\Calculation\Database::DSTDEVP -DSUM | \PhpOffice\PhpSpreadsheet\Calculation\Database::DSUM -DVAR | \PhpOffice\PhpSpreadsheet\Calculation\Database::DVAR -DVARP | \PhpOffice\PhpSpreadsheet\Calculation\Database::DVARP +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- +DAVERAGE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DAverage::evaluate +DCOUNT | \PhpOffice\PhpSpreadsheet\Calculation\Database\DCount::evaluate +DCOUNTA | \PhpOffice\PhpSpreadsheet\Calculation\Database\DCountA::evaluate +DGET | \PhpOffice\PhpSpreadsheet\Calculation\Database\DGet::evaluate +DMAX | \PhpOffice\PhpSpreadsheet\Calculation\Database\DMax::evaluate +DMIN | \PhpOffice\PhpSpreadsheet\Calculation\Database\DMin::evaluate +DPRODUCT | \PhpOffice\PhpSpreadsheet\Calculation\Database\DProduct::evaluate +DSTDEV | \PhpOffice\PhpSpreadsheet\Calculation\Database\DStDev::evaluate +DSTDEVP | \PhpOffice\PhpSpreadsheet\Calculation\Database\DStDevP::evaluate +DSUM | \PhpOffice\PhpSpreadsheet\Calculation\Database\DSum::evaluate +DVAR | \PhpOffice\PhpSpreadsheet\Calculation\Database\DVar::evaluate +DVARP | \PhpOffice\PhpSpreadsheet\Calculation\Database\DVarP::evaluate ## CATEGORY_DATE_AND_TIME -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- -DATE | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::DATE -DATEDIF | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::DATEDIF -DATEVALUE | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::DATEVALUE -DAY | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::DAYOFMONTH -DAYS | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::DAYS -DAYS360 | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::DAYS360 -EDATE | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::EDATE -EOMONTH | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::EOMONTH -HOUR | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::HOUROFDAY -ISOWEEKNUM | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::ISOWEEKNUM -MINUTE | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::MINUTE -MONTH | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::MONTHOFYEAR -NETWORKDAYS | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::NETWORKDAYS -NETWORKDAYS.INTL | **Not yet Implemented** -NOW | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::DATETIMENOW -SECOND | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::SECOND -TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::TIME -TIMEVALUE | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::TIMEVALUE -TODAY | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::DATENOW -WEEKDAY | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::WEEKDAY -WEEKNUM | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::WEEKNUM -WORKDAY | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::WORKDAY -WORKDAY.INTL | **Not yet Implemented** -YEAR | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::YEAR -YEARFRAC | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::YEARFRAC +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- +DATE | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Date::fromYMD +DATEDIF | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Difference::interval +DATEVALUE | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\DateValue::fromString +DAY | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\DateParts::day +DAYS | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Days::between +DAYS360 | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Days360::between +EDATE | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Month::adjust +EOMONTH | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Month::lastDay +HOUR | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\TimeParts::hour +ISOWEEKNUM | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Week::isoWeekNumber +MINUTE | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\TimeParts::minute +MONTH | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\DateParts::month +NETWORKDAYS | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\NetworkDays::count +NETWORKDAYS.INTL | **Not yet Implemented** +NOW | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Current::now +SECOND | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\TimeParts::second +TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Time::fromHMS +TIMEVALUE | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\TimeValue::fromString +TODAY | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Current::today +WEEKDAY | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Week::day +WEEKNUM | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Week::number +WORKDAY | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\WorkDay::date +WORKDAY.INTL | **Not yet Implemented** +YEAR | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\DateParts::year +YEARFRAC | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\YearFrac::fraction ## CATEGORY_ENGINEERING -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- -BESSELI | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BESSELI -BESSELJ | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BESSELJ -BESSELK | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BESSELK -BESSELY | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BESSELY -BIN2DEC | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BINTODEC -BIN2HEX | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BINTOHEX -BIN2OCT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BINTOOCT -BITAND | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BITAND -BITLSHIFT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BITLSHIFT -BITOR | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BITOR -BITRSHIFT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BITRSHIFT -BITXOR | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BITOR -COMPLEX | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::COMPLEX -CONVERT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::CONVERTUOM -DEC2BIN | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::DECTOBIN -DEC2HEX | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::DECTOHEX -DEC2OCT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::DECTOOCT -DELTA | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::DELTA -ERF | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::ERF -ERF.PRECISE | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::ERFPRECISE -ERFC | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::ERFC -ERFC.PRECISE | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::ERFC -GESTEP | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::GESTEP -HEX2BIN | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::HEXTOBIN -HEX2DEC | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::HEXTODEC -HEX2OCT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::HEXTOOCT -IMABS | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMABS -IMAGINARY | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMAGINARY -IMARGUMENT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMARGUMENT -IMCONJUGATE | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMCONJUGATE -IMCOS | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMCOS -IMCOSH | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMCOSH -IMCOT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMCOT -IMCSC | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMCSC -IMCSCH | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMCSCH -IMDIV | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMDIV -IMEXP | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMEXP -IMLN | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMLN -IMLOG10 | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMLOG10 -IMLOG2 | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMLOG2 -IMPOWER | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMPOWER -IMPRODUCT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMPRODUCT -IMREAL | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMREAL -IMSEC | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMSEC -IMSECH | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMSECH -IMSIN | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMSIN -IMSINH | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMSINH -IMSQRT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMSQRT -IMSUB | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMSUB -IMSUM | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMSUM -IMTAN | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMTAN -OCT2BIN | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::OCTTOBIN -OCT2DEC | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::OCTTODEC -OCT2HEX | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::OCTTOHEX +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- +BESSELI | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BesselI::BESSELI +BESSELJ | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BesselJ::BESSELJ +BESSELK | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BesselK::BESSELK +BESSELY | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BesselY::BESSELY +BIN2DEC | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertBinary::toDecimal +BIN2HEX | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertBinary::toHex +BIN2OCT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertBinary::toOctal +BITAND | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BitWise::BITAND +BITLSHIFT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BitWise::BITLSHIFT +BITOR | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BitWise::BITOR +BITRSHIFT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BitWise::BITRSHIFT +BITXOR | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BitWise::BITXOR +COMPLEX | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Complex::COMPLEX +CONVERT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertUOM::CONVERT +DEC2BIN | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertDecimal::toBinary +DEC2HEX | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertDecimal::toHex +DEC2OCT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertDecimal::toOctal +DELTA | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Compare::DELTA +ERF | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Erf::ERF +ERF.PRECISE | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Erf::ERFPRECISE +ERFC | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ErfC::ERFC +ERFC.PRECISE | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ErfC::ERFC +GESTEP | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Compare::GESTEP +HEX2BIN | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertHex::toBinary +HEX2DEC | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertHex::toDecimal +HEX2OCT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertHex::toOctal +IMABS | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMABS +IMAGINARY | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Complex::IMAGINARY +IMARGUMENT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMARGUMENT +IMCONJUGATE | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCONJUGATE +IMCOS | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCOS +IMCOSH | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCOSH +IMCOT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCOT +IMCSC | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCSC +IMCSCH | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCSCH +IMDIV | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexOperations::IMDIV +IMEXP | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMEXP +IMLN | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMLN +IMLOG10 | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMLOG10 +IMLOG2 | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMLOG2 +IMPOWER | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMPOWER +IMPRODUCT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexOperations::IMPRODUCT +IMREAL | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Complex::IMREAL +IMSEC | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMSEC +IMSECH | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMSECH +IMSIN | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMSIN +IMSINH | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMSINH +IMSQRT | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMSQRT +IMSUB | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexOperations::IMSUB +IMSUM | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexOperations::IMSUM +IMTAN | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMTAN +OCT2BIN | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertOctal::toBinary +OCT2DEC | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertOctal::toDecimal +OCT2HEX | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertOctal::toHex ## CATEGORY_FINANCIAL -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- -ACCRINT | \PhpOffice\PhpSpreadsheet\Calculation\Financial::ACCRINT -ACCRINTM | \PhpOffice\PhpSpreadsheet\Calculation\Financial::ACCRINTM -AMORDEGRC | \PhpOffice\PhpSpreadsheet\Calculation\Financial::AMORDEGRC -AMORLINC | \PhpOffice\PhpSpreadsheet\Calculation\Financial::AMORLINC -COUPDAYBS | \PhpOffice\PhpSpreadsheet\Calculation\Financial::COUPDAYBS -COUPDAYS | \PhpOffice\PhpSpreadsheet\Calculation\Financial::COUPDAYS -COUPDAYSNC | \PhpOffice\PhpSpreadsheet\Calculation\Financial::COUPDAYSNC -COUPNCD | \PhpOffice\PhpSpreadsheet\Calculation\Financial::COUPNCD -COUPNUM | \PhpOffice\PhpSpreadsheet\Calculation\Financial::COUPNUM -COUPPCD | \PhpOffice\PhpSpreadsheet\Calculation\Financial::COUPPCD -CUMIPMT | \PhpOffice\PhpSpreadsheet\Calculation\Financial::CUMIPMT -CUMPRINC | \PhpOffice\PhpSpreadsheet\Calculation\Financial::CUMPRINC -DB | \PhpOffice\PhpSpreadsheet\Calculation\Financial::DB -DDB | \PhpOffice\PhpSpreadsheet\Calculation\Financial::DDB -DISC | \PhpOffice\PhpSpreadsheet\Calculation\Financial::DISC -DOLLARDE | \PhpOffice\PhpSpreadsheet\Calculation\Financial::DOLLARDE -DOLLARFR | \PhpOffice\PhpSpreadsheet\Calculation\Financial::DOLLARFR -DURATION | **Not yet Implemented** -EFFECT | \PhpOffice\PhpSpreadsheet\Calculation\Financial::EFFECT -FV | \PhpOffice\PhpSpreadsheet\Calculation\Financial::FV -FVSCHEDULE | \PhpOffice\PhpSpreadsheet\Calculation\Financial::FVSCHEDULE -INTRATE | \PhpOffice\PhpSpreadsheet\Calculation\Financial::INTRATE -IPMT | \PhpOffice\PhpSpreadsheet\Calculation\Financial::IPMT -IRR | \PhpOffice\PhpSpreadsheet\Calculation\Financial::IRR -ISPMT | \PhpOffice\PhpSpreadsheet\Calculation\Financial::ISPMT -MDURATION | **Not yet Implemented** -MIRR | \PhpOffice\PhpSpreadsheet\Calculation\Financial::MIRR -NOMINAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::NOMINAL -NPER | \PhpOffice\PhpSpreadsheet\Calculation\Financial::NPER -NPV | \PhpOffice\PhpSpreadsheet\Calculation\Financial::NPV -ODDFPRICE | **Not yet Implemented** -ODDFYIELD | **Not yet Implemented** -ODDLPRICE | **Not yet Implemented** -ODDLYIELD | **Not yet Implemented** -PDURATION | \PhpOffice\PhpSpreadsheet\Calculation\Financial::PDURATION -PMT | \PhpOffice\PhpSpreadsheet\Calculation\Financial::PMT -PPMT | \PhpOffice\PhpSpreadsheet\Calculation\Financial::PPMT -PRICE | \PhpOffice\PhpSpreadsheet\Calculation\Financial::PRICE -PRICEDISC | \PhpOffice\PhpSpreadsheet\Calculation\Financial::PRICEDISC -PRICEMAT | \PhpOffice\PhpSpreadsheet\Calculation\Financial::PRICEMAT -PV | \PhpOffice\PhpSpreadsheet\Calculation\Financial::PV -RATE | \PhpOffice\PhpSpreadsheet\Calculation\Financial::RATE -RECEIVED | \PhpOffice\PhpSpreadsheet\Calculation\Financial::RECEIVED -RRI | \PhpOffice\PhpSpreadsheet\Calculation\Financial::RRI -SLN | \PhpOffice\PhpSpreadsheet\Calculation\Financial::SLN -SYD | \PhpOffice\PhpSpreadsheet\Calculation\Financial::SYD -TBILLEQ | \PhpOffice\PhpSpreadsheet\Calculation\Financial::TBILLEQ -TBILLPRICE | \PhpOffice\PhpSpreadsheet\Calculation\Financial::TBILLPRICE -TBILLYIELD | \PhpOffice\PhpSpreadsheet\Calculation\Financial::TBILLYIELD -USDOLLAR | **Not yet Implemented** -VDB | **Not yet Implemented** -XIRR | \PhpOffice\PhpSpreadsheet\Calculation\Financial::XIRR -XNPV | \PhpOffice\PhpSpreadsheet\Calculation\Financial::XNPV -YIELD | **Not yet Implemented** -YIELDDISC | \PhpOffice\PhpSpreadsheet\Calculation\Financial::YIELDDISC -YIELDMAT | \PhpOffice\PhpSpreadsheet\Calculation\Financial::YIELDMAT +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- +ACCRINT | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\AccruedInterest::periodic +ACCRINTM | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\AccruedInterest::atMaturity +AMORDEGRC | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Amortization::AMORDEGRC +AMORLINC | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Amortization::AMORLINC +COUPDAYBS | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPDAYBS +COUPDAYS | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPDAYS +COUPDAYSNC | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPDAYSNC +COUPNCD | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPNCD +COUPNUM | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPNUM +COUPPCD | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPPCD +CUMIPMT | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Cumulative::interest +CUMPRINC | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Cumulative::principal +DB | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Depreciation::DB +DDB | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Depreciation::DDB +DISC | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Rates::discount +DOLLARDE | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Dollar::decimal +DOLLARFR | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Dollar::fractional +DURATION | **Not yet Implemented** +EFFECT | \PhpOffice\PhpSpreadsheet\Calculation\Financial\InterestRate::effective +FV | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic::futureValue +FVSCHEDULE | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Single::futureValue +INTRATE | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Rates::interest +IPMT | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Interest::payment +IRR | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable\Periodic::rate +ISPMT | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Interest::schedulePayment +MDURATION | **Not yet Implemented** +MIRR | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable\Periodic::modifiedRate +NOMINAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\InterestRate::nominal +NPER | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic::periods +NPV | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable\Periodic::presentValue +ODDFPRICE | **Not yet Implemented** +ODDFYIELD | **Not yet Implemented** +ODDLPRICE | **Not yet Implemented** +ODDLYIELD | **Not yet Implemented** +PDURATION | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Single::periods +PMT | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Payments::annuity +PPMT | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Payments::interestPayment +PRICE | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Price::price +PRICEDISC | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Price::priceDiscounted +PRICEMAT | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Price::priceAtMaturity +PV | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic::presentValue +RATE | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Interest::rate +RECEIVED | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Price::received +RRI | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Single::interestRate +SLN | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Depreciation::SLN +SYD | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Depreciation::SYD +TBILLEQ | \PhpOffice\PhpSpreadsheet\Calculation\Financial\TreasuryBill::bondEquivalentYield +TBILLPRICE | \PhpOffice\PhpSpreadsheet\Calculation\Financial\TreasuryBill::price +TBILLYIELD | \PhpOffice\PhpSpreadsheet\Calculation\Financial\TreasuryBill::yield +USDOLLAR | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Dollar::format +VDB | **Not yet Implemented** +XIRR | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable\NonPeriodic::rate +XNPV | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable\NonPeriodic::presentValue +YIELD | **Not yet Implemented** +YIELDDISC | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Yields::yieldDiscounted +YIELDMAT | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Yields::yieldAtMaturity ## CATEGORY_INFORMATION -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- -CELL | **Not yet Implemented** -ERROR.TYPE | \PhpOffice\PhpSpreadsheet\Calculation\Functions::errorType -INFO | **Not yet Implemented** -ISBLANK | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isBlank -ISERR | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isErr -ISERROR | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isError -ISEVEN | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isEven -ISFORMULA | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isFormula -ISLOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isLogical -ISNA | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isNa -ISNONTEXT | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isNonText -ISNUMBER | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isNumber -ISODD | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isOdd -ISREF | **Not yet Implemented** -ISTEXT | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isText -N | \PhpOffice\PhpSpreadsheet\Calculation\Functions::n -NA | \PhpOffice\PhpSpreadsheet\Calculation\Functions::NA -SHEET | **Not yet Implemented** -SHEETS | **Not yet Implemented** -TYPE | \PhpOffice\PhpSpreadsheet\Calculation\Functions::TYPE +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- +CELL | **Not yet Implemented** +ERROR.TYPE | \PhpOffice\PhpSpreadsheet\Calculation\Functions::errorType +INFO | **Not yet Implemented** +ISBLANK | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isBlank +ISERR | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isErr +ISERROR | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isError +ISEVEN | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isEven +ISFORMULA | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isFormula +ISLOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isLogical +ISNA | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isNa +ISNONTEXT | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isNonText +ISNUMBER | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isNumber +ISODD | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isOdd +ISREF | **Not yet Implemented** +ISTEXT | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isText +N | \PhpOffice\PhpSpreadsheet\Calculation\Functions::n +NA | \PhpOffice\PhpSpreadsheet\Calculation\Functions::NA +SHEET | **Not yet Implemented** +SHEETS | **Not yet Implemented** +TYPE | \PhpOffice\PhpSpreadsheet\Calculation\Functions::TYPE ## CATEGORY_LOGICAL -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- -AND | \PhpOffice\PhpSpreadsheet\Calculation\Logical::logicalAnd -FALSE | \PhpOffice\PhpSpreadsheet\Calculation\Logical::FALSE -IF | \PhpOffice\PhpSpreadsheet\Calculation\Logical::statementIf -IFERROR | \PhpOffice\PhpSpreadsheet\Calculation\Logical::IFERROR -IFNA | \PhpOffice\PhpSpreadsheet\Calculation\Logical::IFNA -IFS | \PhpOffice\PhpSpreadsheet\Calculation\Logical::IFS -NOT | \PhpOffice\PhpSpreadsheet\Calculation\Logical::NOT -OR | \PhpOffice\PhpSpreadsheet\Calculation\Logical::logicalOr -SWITCH | \PhpOffice\PhpSpreadsheet\Calculation\Logical::statementSwitch -TRUE | \PhpOffice\PhpSpreadsheet\Calculation\Logical::TRUE -XOR | \PhpOffice\PhpSpreadsheet\Calculation\Logical::logicalXor +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- +AND | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Operations::logicalAnd +FALSE | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Boolean::FALSE +IF | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Conditional::statementIf +IFERROR | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Conditional::IFERROR +IFNA | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Conditional::IFNA +IFS | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Conditional::IFS +NOT | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Operations::NOT +OR | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Operations::logicalOr +SWITCH | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Conditional::statementSwitch +TRUE | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Boolean::TRUE +XOR | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Operations::logicalXor ## CATEGORY_LOOKUP_AND_REFERENCE -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- -ADDRESS | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::cellAddress -AREAS | **Not yet Implemented** -CHOOSE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::CHOOSE -COLUMN | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::COLUMN -COLUMNS | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::COLUMNS -FILTER | **Not yet Implemented** -FORMULATEXT | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::FORMULATEXT -GETPIVOTDATA | **Not yet Implemented** -HLOOKUP | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::HLOOKUP -HYPERLINK | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::HYPERLINK -INDEX | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::INDEX -INDIRECT | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::INDIRECT -LOOKUP | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::LOOKUP -MATCH | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::MATCH -OFFSET | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::OFFSET -ROW | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::ROW -ROWS | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::ROWS -RTD | **Not yet Implemented** -SORT | **Not yet Implemented** -SORTBY | **Not yet Implemented** -TRANSPOSE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::TRANSPOSE -UNIQUE | **Not yet Implemented** -VLOOKUP | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::VLOOKUP -XLOOKUP | **Not yet Implemented** -XMATCH | **Not yet Implemented** +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- +ADDRESS | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Address::cell +AREAS | **Not yet Implemented** +CHOOSE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Selection::CHOOSE +COLUMN | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\RowColumnInformation::COLUMN +COLUMNS | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\RowColumnInformation::COLUMNS +FILTER | **Not yet Implemented** +FORMULATEXT | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Formula::text +GETPIVOTDATA | **Not yet Implemented** +HLOOKUP | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\HLookup::lookup +HYPERLINK | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Hyperlink::set +INDEX | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Matrix::index +INDIRECT | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Indirect::INDIRECT +LOOKUP | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Lookup::lookup +MATCH | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\ExcelMatch::MATCH +OFFSET | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Offset::OFFSET +ROW | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\RowColumnInformation::ROW +ROWS | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\RowColumnInformation::ROWS +RTD | **Not yet Implemented** +SORT | **Not yet Implemented** +SORTBY | **Not yet Implemented** +TRANSPOSE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Matrix::transpose +UNIQUE | **Not yet Implemented** +VLOOKUP | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\VLookup::lookup +XLOOKUP | **Not yet Implemented** +XMATCH | **Not yet Implemented** ## CATEGORY_MATH_AND_TRIG -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- -ABS | abs -ACOS | acos -ACOSH | acosh -ACOT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::ACOT -ACOTH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::ACOTH -AGGREGATE | **Not yet Implemented** -ARABIC | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::ARABIC -ASIN | asin -ASINH | asinh -ATAN | atan -ATAN2 | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::ATAN2 -ATANH | atanh -BASE | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::BASE -CEILING | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::CEILING -CEILING.MATH | **Not yet Implemented** -CEILING.PRECISE | **Not yet Implemented** -COMBIN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::COMBIN -COMBINA | **Not yet Implemented** -COS | cos -COSH | cosh -COT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::COT -COTH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::COTH -CSC | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::CSC -CSCH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::CSCH -DECIMAL | **Not yet Implemented** -DEGREES | rad2deg -EVEN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::EVEN -EXP | exp -FACT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::FACT -FACTDOUBLE | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::FACTDOUBLE -FLOOR | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::FLOOR -FLOOR.MATH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::FLOORMATH -FLOOR.PRECISE | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::FLOORPRECISE -GCD | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::GCD -INT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::INT -ISO.CEILING | **Not yet Implemented** -LCM | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::LCM -LN | log -LOG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::logBase -LOG10 | log10 -MDETERM | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::MDETERM -MINVERSE | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::MINVERSE -MMULT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::MMULT -MOD | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::MOD -MROUND | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::MROUND -MULTINOMIAL | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::MULTINOMIAL -MUNIT | **Not yet Implemented** -ODD | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::ODD -PI | pi -POWER | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::POWER -PRODUCT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::PRODUCT -QUOTIENT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::QUOTIENT -RADIANS | deg2rad -RAND | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::RAND -RANDARRAY | **Not yet Implemented** -RANDBETWEEN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::RAND -ROMAN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::ROMAN -ROUND | round -ROUNDDOWN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::ROUNDDOWN -ROUNDUP | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::ROUNDUP -SEC | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SEC -SECH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SECH -SERIESSUM | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SERIESSUM -SEQUENCE | **Not yet Implemented** -SIGN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SIGN -SIN | sin -SINH | sinh -SQRT | sqrt -SQRTPI | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SQRTPI -SUBTOTAL | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SUBTOTAL -SUM | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SUM -SUMIF | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SUMIF -SUMIFS | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SUMIFS -SUMPRODUCT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SUMPRODUCT -SUMSQ | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SUMSQ -SUMX2MY2 | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SUMX2MY2 -SUMX2PY2 | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SUMX2PY2 -SUMXMY2 | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SUMXMY2 -TAN | tan -TANH | tanh -TRUNC | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::TRUNC +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- +ABS | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Absolute::evaluate +ACOS | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosine::acos +ACOSH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosine::acosh +ACOT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cotangent::acot +ACOTH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cotangent::acoth +AGGREGATE | **Not yet Implemented** +ARABIC | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Arabic::evaluate +ASIN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Sine::asin +ASINH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Sine::asinh +ATAN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Tangent::atan +ATAN2 | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Tangent::atan2 +ATANH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Tangent::atanh +BASE | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Base::evaluate +CEILING | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Ceiling::ceiling +CEILING.MATH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Ceiling::math +CEILING.PRECISE | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Ceiling::precise +COMBIN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Combinations::withoutRepetition +COMBINA | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Combinations::withRepetition +COS | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosine::cos +COSH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosine::cosh +COT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cotangent::cot +COTH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cotangent::coth +CSC | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosecant::csc +CSCH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosecant::csch +DECIMAL | **Not yet Implemented** +DEGREES | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Angle::toDegrees +ECMA.CEILING | **Not yet Implemented** +EVEN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::even +EXP | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Exp::evaluate +FACT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Factorial::fact +FACTDOUBLE | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Factorial::factDouble +FLOOR | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Floor::floor +FLOOR.MATH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Floor::math +FLOOR.PRECISE | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Floor::precise +GCD | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Gcd::evaluate +INT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\IntClass::evaluate +ISO.CEILING | **Not yet Implemented** +LCM | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Lcm::evaluate +LN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Logarithms::natural +LOG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Logarithms::withBase +LOG10 | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Logarithms::base10 +MDETERM | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\MatrixFunctions::determinant +MINVERSE | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\MatrixFunctions::inverse +MMULT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\MatrixFunctions::multiply +MOD | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Operations::mod +MROUND | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::multiple +MULTINOMIAL | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Factorial::multinomial +MUNIT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\MatrixFunctions::identity +ODD | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::odd +PI | pi +POWER | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Operations::power +PRODUCT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Operations::product +QUOTIENT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Operations::quotient +RADIANS | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Angle::toRadians +RAND | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Random::rand +RANDARRAY | **Not yet Implemented** +RANDBETWEEN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Random::randBetween +ROMAN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Roman::evaluate +ROUND | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::round +ROUNDDOWN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::down +ROUNDUP | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::up +SEC | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Secant::sec +SECH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Secant::sech +SEQUENCE | **Not yet Implemented** +SERIESSUM | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\SeriesSum::evaluate +SIGN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sign::evaluate +SIN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Sine::sin +SINH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Sine::sinh +SQRT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sqrt::sqrt +SQRTPI | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sqrt::pi +SUBTOTAL | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Subtotal::evaluate +SUM | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sum::sumErroringStrings +SUMIF | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::SUMIF +SUMIFS | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::SUMIFS +SUMPRODUCT | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sum::product +SUMSQ | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\SumSquares::sumSquare +SUMX2MY2 | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\SumSquares::sumXSquaredMinusYSquared +SUMX2PY2 | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\SumSquares::sumXSquaredPlusYSquared +SUMXMY2 | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\SumSquares::sumXMinusYSquared +TAN | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Tangent::tan +TANH | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Tangent::tanh +TRUNC | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trunc::evaluate ## CATEGORY_STATISTICAL Excel Function | PhpSpreadsheet Function --------------------------|------------------------------------------- -AVEDEV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::AVEDEV -AVERAGE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::AVERAGE -AVERAGEA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::AVERAGEA -AVERAGEIF | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::AVERAGEIF -AVERAGEIFS | **Not yet Implemented** -BETADIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::BETADIST -BETA.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::BETADIST -BETAINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::BETAINV -BETA.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::BETAINV -BINOMDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::BINOMDIST -BINOM.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::BINOMDIST -BINOM.DIST.RANGE | **Not yet Implemented** -BINOM.INV | **Not yet Implemented** -CHIDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::CHIDIST -CHISQ.DIST | **Not yet Implemented** -CHISQ.DIST.RT | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::CHIDIST -CHIINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::CHIINV -CHISQ.INV | **Not yet Implemented** -CHISQ.INV.RT | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::CHIINV -CHITEST | **Not yet Implemented** -CHISQ.TEST | **Not yet Implemented** -CONFIDENCE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::CONFIDENCE -CONFIDENCE.NORM | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::CONFIDENCE +-------------------------|-------------------------------------- +AVEDEV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::averageDeviations +AVERAGE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::average +AVERAGEA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::averageA +AVERAGEIF | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::AVERAGEIF +AVERAGEIFS | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::AVERAGEIFS +BETA.DIST | **Not yet Implemented** +BETA.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Beta::inverse +BETADIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Beta::distribution +BETAINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Beta::inverse +BINOM.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::distribution +BINOM.DIST.RANGE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::range +BINOM.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::inverse +BINOMDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::distribution +CHIDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::distributionRightTail +CHIINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::inverseRightTail +CHISQ.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::distributionLeftTail +CHISQ.DIST.RT | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::distributionRightTail +CHISQ.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::inverseLeftTail +CHISQ.INV.RT | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::inverseRightTail +CHISQ.TEST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::test +CHITEST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::test +CONFIDENCE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Confidence::CONFIDENCE +CONFIDENCE.NORM | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Confidence::CONFIDENCE CONFIDENCE.T | **Not yet Implemented** -CORREL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::CORREL -COUNT | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::COUNT -COUNTA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::COUNTA -COUNTBLANK | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::COUNTBLANK -COUNTIF | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::COUNTIF -COUNTIFS | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::COUNTIFS -COVAR | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::COVAR -COVARIANCE.P | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::COVAR +CORREL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::CORREL +COUNT | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts::COUNT +COUNTA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts::COUNTA +COUNTBLANK | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts::COUNTBLANK +COUNTIF | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::COUNTIF +COUNTIFS | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::COUNTIFS +COVAR | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::COVAR +COVARIANCE.P | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::COVAR COVARIANCE.S | **Not yet Implemented** -CRITBINOM | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::CRITBINOM -DEVSQ | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::DEVSQ -EXPONDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::EXPONDIST -EXPON.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::EXPONDIST -FDIST | **Not yet Implemented** -F.DIST | **Not yet Implemented** +CRITBINOM | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::inverse +DEVSQ | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Deviations::sumSquares +EXPON.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Exponential::distribution +EXPONDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Exponential::distribution +F.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\F::distribution F.DIST.RT | **Not yet Implemented** -FINV | **Not yet Implemented** F.INV | **Not yet Implemented** F.INV.RT | **Not yet Implemented** F.TEST | **Not yet Implemented** -FISHER | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::FISHER -FISHERINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::FISHERINV -FORECAST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::FORECAST +FDIST | **Not yet Implemented** +FINV | **Not yet Implemented** +FISHER | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Fisher::distribution +FISHERINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Fisher::inverse +FORECAST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::FORECAST FORECAST.ETS | **Not yet Implemented** FORECAST.ETS.CONFINT | **Not yet Implemented** FORECAST.ETS.SEASONALITY | **Not yet Implemented** FORECAST.ETS.STAT | **Not yet Implemented** -FORECAST.LINEAR | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::FORECAST +FORECAST.LINEAR | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::FORECAST FREQUENCY | **Not yet Implemented** FTEST | **Not yet Implemented** -GAMMA | **Not yet Implemented** -GAMMADIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::GAMMADIST -GAMMA.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::GAMMADIST -GAMMAINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::GAMMAINV -GAMMA.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::GAMMAINV -GAMMALN | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::GAMMALN -GAMMALN.PRECISE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::GAMMALN -GAUSS | **Not yet Implemented** -GEOMEAN | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::GEOMEAN -GROWTH | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::GROWTH -HARMEAN | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::HARMEAN -HYPGEOMDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::HYPGEOMDIST -INTERCEPT | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::INTERCEPT -KURT | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::KURT -LARGE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::LARGE -LINEST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::LINEST -LOGEST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::LOGEST -LOGINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::LOGINV -LOGNORMDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::LOGNORMDIST -LOGNORM.DIST | **Not yet Implemented** -LOGNORM.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::LOGINV -MAX | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::MAX -MAXA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::MAXA -MAXIFS | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::MAXIFS -MEDIAN | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::MEDIAN +GAMMA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::gamma +GAMMA.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::distribution +GAMMA.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::inverse +GAMMADIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::distribution +GAMMAINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::inverse +GAMMALN | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::ln +GAMMALN.PRECISE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::ln +GAUSS | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::gauss +GEOMEAN | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages\Mean::geometric +GROWTH | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::GROWTH +HARMEAN | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages\Mean::harmonic +HYPGEOM.DIST | **Not yet Implemented** +HYPGEOMDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\HyperGeometric::distribution +INTERCEPT | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::INTERCEPT +KURT | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Deviations::kurtosis +LARGE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Size::large +LINEST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::LINEST +LOGEST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::LOGEST +LOGINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\LogNormal::inverse +LOGNORM.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\LogNormal::distribution +LOGNORM.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\LogNormal::inverse +LOGNORMDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\LogNormal::cumulative +MAX | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Maximum::max +MAXA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Maximum::maxA +MAXIFS | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::MAXIFS +MEDIAN | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::median MEDIANIF | **Not yet Implemented** -MIN | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::MIN -MINA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::MINA -MINIFS | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::MINIFS -MODE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::MODE +MIN | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Minimum::min +MINA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Minimum::minA +MINIFS | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::MINIFS +MODE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::mode MODE.MULT | **Not yet Implemented** -MODE.SNGL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::MODE -NEGBINOMDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::NEGBINOMDIST +MODE.SNGL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::mode NEGBINOM.DIST | **Not yet Implemented** -NORMDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::NORMDIST -NORM.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::NORMDIST -NORMINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::NORMINV -NORM.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::NORMINV -NORMSDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::NORMSDIST -NORM.S.DIST | **Not yet Implemented** -NORMSINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::NORMSINV -NORM.S.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::NORMSINV -PEARSON | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::CORREL -PERCENTILE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::PERCENTILE +NEGBINOMDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::negative +NORM.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Normal::distribution +NORM.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Normal::inverse +NORM.S.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::distribution +NORM.S.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::inverse +NORMDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Normal::distribution +NORMINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Normal::inverse +NORMSDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::cumulative +NORMSINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::inverse +PEARSON | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::CORREL +PERCENTILE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::PERCENTILE PERCENTILE.EXC | **Not yet Implemented** -PERCENTILE.INC | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::PERCENTILE -PERCENTRANK | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::PERCENTRANK +PERCENTILE.INC | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::PERCENTILE +PERCENTRANK | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::PERCENTRANK PERCENTRANK.EXC | **Not yet Implemented** -PERCENTRANK.INC | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::PERCENTRANK -PERMUT | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::PERMUT -PERMUTATIONA | **Not yet Implemented** +PERCENTRANK.INC | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::PERCENTRANK +PERMUT | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Permutations::PERMUT +PERMUTATIONA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Permutations::PERMUTATIONA PHI | **Not yet Implemented** -POISSON | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::POISSON -POISSON.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::POISSON +POISSON | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Poisson::distribution +POISSON.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Poisson::distribution PROB | **Not yet Implemented** -QUARTILE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::QUARTILE +QUARTILE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::QUARTILE QUARTILE.EXC | **Not yet Implemented** -QUARTILE.INC | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::QUARTILE -RANK | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::RANK +QUARTILE.INC | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::QUARTILE +RANK | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::RANK RANK.AVG | **Not yet Implemented** -RANK.EQ | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::RANK -RSQ | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::RSQ -SKEW | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::SKEW +RANK.EQ | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::RANK +RSQ | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::RSQ +SKEW | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Deviations::skew SKEW.P | **Not yet Implemented** -SLOPE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::SLOPE -SMALL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::SMALL -STANDARDIZE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::STANDARDIZE -STDEV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::STDEV -STDEV.P | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::STDEVP -STDEV.S | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::STDEV -STDEVA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::STDEVA -STDEVP | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::STDEVP -STDEVPA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::STDEVPA -STEYX | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::STEYX -TDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::TDIST +SLOPE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::SLOPE +SMALL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Size::small +STANDARDIZE | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Standardize::execute +STDEV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEV +STDEV.P | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEVP +STDEV.S | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEV +STDEVA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEVA +STDEVP | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEVP +STDEVPA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEVPA +STEYX | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::STEYX T.DIST | **Not yet Implemented** T.DIST.2T | **Not yet Implemented** T.DIST.RT | **Not yet Implemented** -TINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::TINV -T.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::TINV +T.INV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StudentT::inverse T.INV.2T | **Not yet Implemented** -TREND | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::TREND -TRIMMEAN | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::TRIMMEAN -TTEST | **Not yet Implemented** T.TEST | **Not yet Implemented** -VAR | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::VARFunc -VAR.P | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::VARP -VAR.S | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::VARFunc -VARA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::VARA -VARP | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::VARP -VARPA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::VARPA -WEIBULL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::WEIBULL -WEIBULL.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::WEIBULL -ZTEST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::ZTEST -Z.TEST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::ZTEST +TDIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StudentT::distribution +TINV | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StudentT::inverse +TREND | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::TREND +TRIMMEAN | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages\Mean::trim +TTEST | **Not yet Implemented** +VAR | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VAR +VAR.P | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VARP +VAR.S | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VAR +VARA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VARA +VARP | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VARP +VARPA | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VARPA +WEIBULL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Weibull::distribution +WEIBULL.DIST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Weibull::distribution +Z.TEST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::zTest +ZTEST | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::zTest ## CATEGORY_TEXT_AND_DATA -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- -ASC | **Not yet Implemented** -BAHTTEXT | **Not yet Implemented** -CHAR | \PhpOffice\PhpSpreadsheet\Calculation\TextData::CHARACTER -CLEAN | \PhpOffice\PhpSpreadsheet\Calculation\TextData::TRIMNONPRINTABLE -CODE | \PhpOffice\PhpSpreadsheet\Calculation\TextData::ASCIICODE -CONCAT | \PhpOffice\PhpSpreadsheet\Calculation\TextData::CONCATENATE -CONCATENATE | \PhpOffice\PhpSpreadsheet\Calculation\TextData::CONCATENATE -DBCS | **Not yet Implemented** -DOLLAR | \PhpOffice\PhpSpreadsheet\Calculation\TextData::DOLLAR -EXACT | \PhpOffice\PhpSpreadsheet\Calculation\TextData::EXACT -FIND | \PhpOffice\PhpSpreadsheet\Calculation\TextData::SEARCHSENSITIVE -FINDB | \PhpOffice\PhpSpreadsheet\Calculation\TextData::SEARCHSENSITIVE -FIXED | \PhpOffice\PhpSpreadsheet\Calculation\TextData::FIXEDFORMAT -JIS | **Not yet Implemented** -LEFT | \PhpOffice\PhpSpreadsheet\Calculation\TextData::LEFT -LEFTB | \PhpOffice\PhpSpreadsheet\Calculation\TextData::LEFT -LEN | \PhpOffice\PhpSpreadsheet\Calculation\TextData::STRINGLENGTH -LENB | \PhpOffice\PhpSpreadsheet\Calculation\TextData::STRINGLENGTH -LOWER | \PhpOffice\PhpSpreadsheet\Calculation\TextData::LOWERCASE -MID | \PhpOffice\PhpSpreadsheet\Calculation\TextData::MID -MIDB | \PhpOffice\PhpSpreadsheet\Calculation\TextData::MID -NUMBERVALUE | \PhpOffice\PhpSpreadsheet\Calculation\TextData::NUMBERVALUE -PHONETIC | **Not yet Implemented** -PROPER | \PhpOffice\PhpSpreadsheet\Calculation\TextData::PROPERCASE -REPLACE | \PhpOffice\PhpSpreadsheet\Calculation\TextData::REPLACE -REPLACEB | \PhpOffice\PhpSpreadsheet\Calculation\TextData::REPLACE -REPT | str_repeat -RIGHT | \PhpOffice\PhpSpreadsheet\Calculation\TextData::RIGHT -RIGHTB | \PhpOffice\PhpSpreadsheet\Calculation\TextData::RIGHT -SEARCH | \PhpOffice\PhpSpreadsheet\Calculation\TextData::SEARCHINSENSITIVE -SEARCHB | \PhpOffice\PhpSpreadsheet\Calculation\TextData::SEARCHINSENSITIVE -SUBSTITUTE | \PhpOffice\PhpSpreadsheet\Calculation\TextData::SUBSTITUTE -T | \PhpOffice\PhpSpreadsheet\Calculation\TextData::RETURNSTRING -TEXT | \PhpOffice\PhpSpreadsheet\Calculation\TextData::TEXTFORMAT -TEXTJOIN | \PhpOffice\PhpSpreadsheet\Calculation\TextData::TEXTJOIN -TRIM | \PhpOffice\PhpSpreadsheet\Calculation\TextData::TRIMSPACES -UNICHAR | \PhpOffice\PhpSpreadsheet\Calculation\TextData::CHARACTER -UNICODE | \PhpOffice\PhpSpreadsheet\Calculation\TextData::ASCIICODE -UPPER | \PhpOffice\PhpSpreadsheet\Calculation\TextData::UPPERCASE -VALUE | \PhpOffice\PhpSpreadsheet\Calculation\TextData::VALUE +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- +ASC | **Not yet Implemented** +BAHTTEXT | **Not yet Implemented** +CHAR | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CharacterConvert::character +CLEAN | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Trim::nonPrintable +CODE | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CharacterConvert::code +CONCAT | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Concatenate::CONCATENATE +CONCATENATE | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Concatenate::CONCATENATE +DBCS | **Not yet Implemented** +DOLLAR | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::DOLLAR +EXACT | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Text::exact +FIND | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Search::sensitive +FINDB | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Search::sensitive +FIXED | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::FIXEDFORMAT +JIS | **Not yet Implemented** +LEFT | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::left +LEFTB | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::left +LEN | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Text::length +LENB | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Text::length +LOWER | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CaseConvert::lower +MID | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::mid +MIDB | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::mid +NUMBERVALUE | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::NUMBERVALUE +PHONETIC | **Not yet Implemented** +PROPER | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CaseConvert::proper +REPLACE | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Replace::replace +REPLACEB | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Replace::replace +REPT | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Concatenate::builtinREPT +RIGHT | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::right +RIGHTB | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::right +SEARCH | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Search::insensitive +SEARCHB | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Search::insensitive +SUBSTITUTE | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Replace::substitute +T | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Text::test +TEXT | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::TEXTFORMAT +TEXTJOIN | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Concatenate::TEXTJOIN +TRIM | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Trim::spaces +UNICHAR | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CharacterConvert::character +UNICODE | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CharacterConvert::code +UPPER | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CaseConvert::upper +VALUE | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::VALUE ## CATEGORY_WEB -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- -ENCODEURL | **Not yet Implemented** -FILTERXML | **Not yet Implemented** -WEBSERVICE | \PhpOffice\PhpSpreadsheet\Calculation\Web::WEBSERVICE +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- +ENCODEURL | \PhpOffice\PhpSpreadsheet\Calculation\Web\Service::urlEncode +FILTERXML | **Not yet Implemented** +WEBSERVICE | \PhpOffice\PhpSpreadsheet\Calculation\Web\Service::webService diff --git a/docs/references/function-list-by-name.md b/docs/references/function-list-by-name.md index 2341ee5f..c5f733ea 100644 --- a/docs/references/function-list-by-name.md +++ b/docs/references/function-list-by-name.md @@ -2,613 +2,615 @@ ## A -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -ABS | CATEGORY_MATH_AND_TRIG | abs -ACCRINT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::ACCRINT -ACCRINTM | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::ACCRINTM -ACOS | CATEGORY_MATH_AND_TRIG | acos -ACOSH | CATEGORY_MATH_AND_TRIG | acosh -ACOT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::ACOT -ACOTH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::ACOTH -ADDRESS | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::cellAddress -AGGREGATE | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** -AMORDEGRC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::AMORDEGRC -AMORLINC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::AMORLINC -AND | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical::logicalAnd -ARABIC | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::ARABIC -AREAS | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** -ASC | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** -ASIN | CATEGORY_MATH_AND_TRIG | asin -ASINH | CATEGORY_MATH_AND_TRIG | asinh -ATAN | CATEGORY_MATH_AND_TRIG | atan -ATAN2 | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::ATAN2 -ATANH | CATEGORY_MATH_AND_TRIG | atanh -AVEDEV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::AVEDEV -AVERAGE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::AVERAGE -AVERAGEA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::AVERAGEA -AVERAGEIF | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::AVERAGEIF -AVERAGEIFS | CATEGORY_STATISTICAL | **Not yet Implemented** +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +ABS | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Absolute::evaluate +ACCRINT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\AccruedInterest::periodic +ACCRINTM | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\AccruedInterest::atMaturity +ACOS | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosine::acos +ACOSH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosine::acosh +ACOT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cotangent::acot +ACOTH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cotangent::acoth +ADDRESS | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Address::cell +AGGREGATE | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** +AMORDEGRC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Amortization::AMORDEGRC +AMORLINC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Amortization::AMORLINC +AND | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Operations::logicalAnd +ARABIC | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Arabic::evaluate +AREAS | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** +ASC | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** +ASIN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Sine::asin +ASINH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Sine::asinh +ATAN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Tangent::atan +ATAN2 | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Tangent::atan2 +ATANH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Tangent::atanh +AVEDEV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::averageDeviations +AVERAGE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::average +AVERAGEA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::averageA +AVERAGEIF | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::AVERAGEIF +AVERAGEIFS | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::AVERAGEIFS ## B -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -BAHTTEXT | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** -BASE | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::BASE -BESSELI | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BESSELI -BESSELJ | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BESSELJ -BESSELK | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BESSELK -BESSELY | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BESSELY -BETADIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::BETADIST -BETA.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::BETADIST -BETAINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::BETAINV -BETA.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::BETAINV -BIN2DEC | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BINTODEC -BIN2HEX | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BINTOHEX -BIN2OCT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BINTOOCT -BINOMDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::BINOMDIST -BINOM.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::BINOMDIST -BINOM.DIST.RANGE | CATEGORY_STATISTICAL | **Not yet Implemented** -BINOM.INV | CATEGORY_STATISTICAL | **Not yet Implemented** -BITAND | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BITAND -BITLSHIFT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BITLSHIFT -BITOR | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BITOR -BITRSHIFT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BITRSHIFT -BITXOR | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::BITOR +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +BAHTTEXT | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** +BASE | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Base::evaluate +BESSELI | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BesselI::BESSELI +BESSELJ | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BesselJ::BESSELJ +BESSELK | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BesselK::BESSELK +BESSELY | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BesselY::BESSELY +BETA.DIST | CATEGORY_STATISTICAL | **Not yet Implemented** +BETA.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Beta::inverse +BETADIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Beta::distribution +BETAINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Beta::inverse +BIN2DEC | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertBinary::toDecimal +BIN2HEX | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertBinary::toHex +BIN2OCT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertBinary::toOctal +BINOM.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::distribution +BINOM.DIST.RANGE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::range +BINOM.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::inverse +BINOMDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::distribution +BITAND | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BitWise::BITAND +BITLSHIFT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BitWise::BITLSHIFT +BITOR | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BitWise::BITOR +BITRSHIFT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BitWise::BITRSHIFT +BITXOR | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\BitWise::BITXOR ## C -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -CEILING | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::CEILING -CEILING.MATH | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** -CEILING.PRECISE | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** -CELL | CATEGORY_INFORMATION | **Not yet Implemented** -CHAR | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::CHARACTER -CHIDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::CHIDIST -CHIINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::CHIINV -CHISQ.DIST | CATEGORY_STATISTICAL | **Not yet Implemented** -CHISQ.DIST.RT | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::CHIDIST -CHISQ.INV | CATEGORY_STATISTICAL | **Not yet Implemented** -CHISQ.INV.RT | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::CHIINV -CHISQ.TEST | CATEGORY_STATISTICAL | **Not yet Implemented** -CHITEST | CATEGORY_STATISTICAL | **Not yet Implemented** -CHOOSE | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::CHOOSE -CLEAN | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::TRIMNONPRINTABLE -CODE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::ASCIICODE -COLUMN | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::COLUMN -COLUMNS | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::COLUMNS -COMBIN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::COMBIN -COMBINA | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** -COMPLEX | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::COMPLEX -CONCAT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::CONCATENATE -CONCATENATE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::CONCATENATE -CONFIDENCE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::CONFIDENCE -CONFIDENCE.NORM | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::CONFIDENCE -CONFIDENCE.T | CATEGORY_STATISTICAL | **Not yet Implemented** -CONVERT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::CONVERTUOM -CORREL | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::CORREL -COS | CATEGORY_MATH_AND_TRIG | cos -COSH | CATEGORY_MATH_AND_TRIG | cosh -COT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::COT -COTH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::COTH -COUNT | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::COUNT -COUNTA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::COUNTA -COUNTBLANK | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::COUNTBLANK -COUNTIF | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::COUNTIF -COUNTIFS | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::COUNTIFS -COUPDAYBS | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::COUPDAYBS -COUPDAYS | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::COUPDAYS -COUPDAYSNC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::COUPDAYSNC -COUPNCD | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::COUPNCD -COUPNUM | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::COUPNUM -COUPPCD | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::COUPPCD -COVAR | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::COVAR -COVARIANCE.P | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::COVAR -COVARIANCE.S | CATEGORY_STATISTICAL | **Not yet Implemented** -CRITBINOM | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::CRITBINOM -CSC | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::CSC -CSCH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::CSCH -CUBEKPIMEMBER | CATEGORY_CUBE | **Not yet Implemented** -CUBEMEMBER | CATEGORY_CUBE | **Not yet Implemented** -CUBEMEMBERPROPERTY | CATEGORY_CUBE | **Not yet Implemented** -CUBERANKEDMEMBER | CATEGORY_CUBE | **Not yet Implemented** -CUBESET | CATEGORY_CUBE | **Not yet Implemented** -CUBESETCOUNT | CATEGORY_CUBE | **Not yet Implemented** -CUBEVALUE | CATEGORY_CUBE | **Not yet Implemented** -CUMIPMT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::CUMIPMT -CUMPRINC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::CUMPRINC +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +CEILING | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Ceiling::ceiling +CEILING.MATH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Ceiling::math +CEILING.PRECISE | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Ceiling::precise +CELL | CATEGORY_INFORMATION | **Not yet Implemented** +CHAR | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CharacterConvert::character +CHIDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::distributionRightTail +CHIINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::inverseRightTail +CHISQ.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::distributionLeftTail +CHISQ.DIST.RT | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::distributionRightTail +CHISQ.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::inverseLeftTail +CHISQ.INV.RT | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::inverseRightTail +CHISQ.TEST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::test +CHITEST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\ChiSquared::test +CHOOSE | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Selection::CHOOSE +CLEAN | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Trim::nonPrintable +CODE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CharacterConvert::code +COLUMN | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\RowColumnInformation::COLUMN +COLUMNS | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\RowColumnInformation::COLUMNS +COMBIN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Combinations::withoutRepetition +COMBINA | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Combinations::withRepetition +COMPLEX | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Complex::COMPLEX +CONCAT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Concatenate::CONCATENATE +CONCATENATE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Concatenate::CONCATENATE +CONFIDENCE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Confidence::CONFIDENCE +CONFIDENCE.NORM | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Confidence::CONFIDENCE +CONFIDENCE.T | CATEGORY_STATISTICAL | **Not yet Implemented** +CONVERT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertUOM::CONVERT +CORREL | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::CORREL +COS | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosine::cos +COSH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosine::cosh +COT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cotangent::cot +COTH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cotangent::coth +COUNT | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts::COUNT +COUNTA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts::COUNTA +COUNTBLANK | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts::COUNTBLANK +COUNTIF | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::COUNTIF +COUNTIFS | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::COUNTIFS +COUPDAYBS | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPDAYBS +COUPDAYS | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPDAYS +COUPDAYSNC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPDAYSNC +COUPNCD | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPNCD +COUPNUM | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPNUM +COUPPCD | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons::COUPPCD +COVAR | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::COVAR +COVARIANCE.P | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::COVAR +COVARIANCE.S | CATEGORY_STATISTICAL | **Not yet Implemented** +CRITBINOM | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::inverse +CSC | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosecant::csc +CSCH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Cosecant::csch +CUBEKPIMEMBER | CATEGORY_CUBE | **Not yet Implemented** +CUBEMEMBER | CATEGORY_CUBE | **Not yet Implemented** +CUBEMEMBERPROPERTY | CATEGORY_CUBE | **Not yet Implemented** +CUBERANKEDMEMBER | CATEGORY_CUBE | **Not yet Implemented** +CUBESET | CATEGORY_CUBE | **Not yet Implemented** +CUBESETCOUNT | CATEGORY_CUBE | **Not yet Implemented** +CUBEVALUE | CATEGORY_CUBE | **Not yet Implemented** +CUMIPMT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Cumulative::interest +CUMPRINC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Cumulative::principal ## D -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -DATE | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::DATE -DATEDIF | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::DATEDIF -DATEVALUE | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::DATEVALUE -DAVERAGE | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database::DAVERAGE -DAY | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::DAYOFMONTH -DAYS | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::DAYS -DAYS360 | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::DAYS360 -DB | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::DB -DBCS | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** -DCOUNT | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database::DCOUNT -DCOUNTA | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database::DCOUNTA -DDB | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::DDB -DEC2BIN | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::DECTOBIN -DEC2HEX | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::DECTOHEX -DEC2OCT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::DECTOOCT -DECIMAL | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** -DEGREES | CATEGORY_MATH_AND_TRIG | rad2deg -DELTA | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::DELTA -DEVSQ | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::DEVSQ -DGET | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database::DGET -DISC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::DISC -DMAX | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database::DMAX -DMIN | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database::DMIN -DOLLAR | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::DOLLAR -DOLLARDE | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::DOLLARDE -DOLLARFR | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::DOLLARFR -DPRODUCT | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database::DPRODUCT -DSTDEV | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database::DSTDEV -DSTDEVP | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database::DSTDEVP -DSUM | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database::DSUM -DURATION | CATEGORY_FINANCIAL | **Not yet Implemented** -DVAR | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database::DVAR -DVARP | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database::DVARP +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +DATE | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Date::fromYMD +DATEDIF | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Difference::interval +DATEVALUE | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\DateValue::fromString +DAVERAGE | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DAverage::evaluate +DAY | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\DateParts::day +DAYS | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Days::between +DAYS360 | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Days360::between +DB | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Depreciation::DB +DBCS | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** +DCOUNT | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DCount::evaluate +DCOUNTA | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DCountA::evaluate +DDB | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Depreciation::DDB +DEC2BIN | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertDecimal::toBinary +DEC2HEX | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertDecimal::toHex +DEC2OCT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertDecimal::toOctal +DECIMAL | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** +DEGREES | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Angle::toDegrees +DELTA | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Compare::DELTA +DEVSQ | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Deviations::sumSquares +DGET | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DGet::evaluate +DISC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Rates::discount +DMAX | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DMax::evaluate +DMIN | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DMin::evaluate +DOLLAR | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::DOLLAR +DOLLARDE | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Dollar::decimal +DOLLARFR | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Dollar::fractional +DPRODUCT | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DProduct::evaluate +DSTDEV | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DStDev::evaluate +DSTDEVP | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DStDevP::evaluate +DSUM | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DSum::evaluate +DURATION | CATEGORY_FINANCIAL | **Not yet Implemented** +DVAR | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DVar::evaluate +DVARP | CATEGORY_DATABASE | \PhpOffice\PhpSpreadsheet\Calculation\Database\DVarP::evaluate ## E -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -EDATE | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::EDATE -EFFECT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::EFFECT -ENCODEURL | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** -EOMONTH | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::EOMONTH -ERF | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::ERF -ERFC | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::ERFC -ERFC.PRECISE | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::ERFC -ERF.PRECISE | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::ERFPRECISE -ERROR.TYPE | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::errorType -EVEN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::EVEN -EXACT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::EXACT -EXP | CATEGORY_MATH_AND_TRIG | exp -EXPONDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::EXPONDIST -EXPON.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::EXPONDIST +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +ECMA.CEILING | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** +EDATE | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Month::adjust +EFFECT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\InterestRate::effective +ENCODEURL | CATEGORY_WEB | \PhpOffice\PhpSpreadsheet\Calculation\Web\Service::urlEncode +EOMONTH | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Month::lastDay +ERF | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Erf::ERF +ERF.PRECISE | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Erf::ERFPRECISE +ERFC | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ErfC::ERFC +ERFC.PRECISE | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ErfC::ERFC +ERROR.TYPE | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::errorType +EVEN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::even +EXACT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Text::exact +EXP | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Exp::evaluate +EXPON.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Exponential::distribution +EXPONDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Exponential::distribution ## F -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -FACT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::FACT -FACTDOUBLE | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::FACTDOUBLE -FALSE | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical::FALSE -FDIST | CATEGORY_STATISTICAL | **Not yet Implemented** -F.DIST | CATEGORY_STATISTICAL | **Not yet Implemented** -F.DIST.RT | CATEGORY_STATISTICAL | **Not yet Implemented** -FILTER | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** -FILTERXML | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** -FIND | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::SEARCHSENSITIVE -FINDB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::SEARCHSENSITIVE -FINV | CATEGORY_STATISTICAL | **Not yet Implemented** -F.INV | CATEGORY_STATISTICAL | **Not yet Implemented** -F.INV.RT | CATEGORY_STATISTICAL | **Not yet Implemented** -FISHER | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::FISHER -FISHERINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::FISHERINV -FIXED | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::FIXEDFORMAT -FLOOR | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::FLOOR -FLOOR.MATH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::FLOORMATH -FLOOR.PRECISE | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::FLOORPRECISE -FORECAST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::FORECAST -FORECAST.ETS | CATEGORY_STATISTICAL | **Not yet Implemented** -FORECAST.ETS.CONFINT | CATEGORY_STATISTICAL | **Not yet Implemented** -FORECAST.ETS.SEASONALITY | CATEGORY_STATISTICAL | **Not yet Implemented** -FORECAST.ETS.STAT | CATEGORY_STATISTICAL | **Not yet Implemented** -FORECAST.LINEAR | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::FORECAST -FORMULATEXT | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::FORMULATEXT -FREQUENCY | CATEGORY_STATISTICAL | **Not yet Implemented** -FTEST | CATEGORY_STATISTICAL | **Not yet Implemented** -F.TEST | CATEGORY_STATISTICAL | **Not yet Implemented** -FV | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::FV -FVSCHEDULE | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::FVSCHEDULE +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +F.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\F::distribution +F.DIST.RT | CATEGORY_STATISTICAL | **Not yet Implemented** +F.INV | CATEGORY_STATISTICAL | **Not yet Implemented** +F.INV.RT | CATEGORY_STATISTICAL | **Not yet Implemented** +F.TEST | CATEGORY_STATISTICAL | **Not yet Implemented** +FACT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Factorial::fact +FACTDOUBLE | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Factorial::factDouble +FALSE | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Boolean::FALSE +FDIST | CATEGORY_STATISTICAL | **Not yet Implemented** +FILTER | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** +FILTERXML | CATEGORY_WEB | **Not yet Implemented** +FIND | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Search::sensitive +FINDB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Search::sensitive +FINV | CATEGORY_STATISTICAL | **Not yet Implemented** +FISHER | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Fisher::distribution +FISHERINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Fisher::inverse +FIXED | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::FIXEDFORMAT +FLOOR | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Floor::floor +FLOOR.MATH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Floor::math +FLOOR.PRECISE | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Floor::precise +FORECAST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::FORECAST +FORECAST.ETS | CATEGORY_STATISTICAL | **Not yet Implemented** +FORECAST.ETS.CONFINT | CATEGORY_STATISTICAL | **Not yet Implemented** +FORECAST.ETS.SEASONALITY | CATEGORY_STATISTICAL | **Not yet Implemented** +FORECAST.ETS.STAT | CATEGORY_STATISTICAL | **Not yet Implemented** +FORECAST.LINEAR | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::FORECAST +FORMULATEXT | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Formula::text +FREQUENCY | CATEGORY_STATISTICAL | **Not yet Implemented** +FTEST | CATEGORY_STATISTICAL | **Not yet Implemented** +FV | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic::futureValue +FVSCHEDULE | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Single::futureValue ## G -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -GAMMA | CATEGORY_STATISTICAL | **Not yet Implemented** -GAMMADIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::GAMMADIST -GAMMA.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::GAMMADIST -GAMMAINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::GAMMAINV -GAMMA.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::GAMMAINV -GAMMALN | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::GAMMALN -GAMMALN.PRECISE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::GAMMALN -GAUSS | CATEGORY_STATISTICAL | **Not yet Implemented** -GCD | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::GCD -GEOMEAN | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::GEOMEAN -GESTEP | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::GESTEP -GETPIVOTDATA | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** -GROWTH | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::GROWTH +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +GAMMA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::gamma +GAMMA.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::distribution +GAMMA.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::inverse +GAMMADIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::distribution +GAMMAINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::inverse +GAMMALN | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::ln +GAMMALN.PRECISE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Gamma::ln +GAUSS | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::gauss +GCD | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Gcd::evaluate +GEOMEAN | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages\Mean::geometric +GESTEP | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Compare::GESTEP +GETPIVOTDATA | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** +GROWTH | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::GROWTH ## H -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -HARMEAN | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::HARMEAN -HEX2BIN | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::HEXTOBIN -HEX2DEC | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::HEXTODEC -HEX2OCT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::HEXTOOCT -HLOOKUP | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::HLOOKUP -HOUR | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::HOUROFDAY -HYPERLINK | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::HYPERLINK -HYPGEOMDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::HYPGEOMDIST +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +HARMEAN | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages\Mean::harmonic +HEX2BIN | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertHex::toBinary +HEX2DEC | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertHex::toDecimal +HEX2OCT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertHex::toOctal +HLOOKUP | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\HLookup::lookup +HOUR | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\TimeParts::hour +HYPERLINK | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Hyperlink::set +HYPGEOM.DIST | CATEGORY_STATISTICAL | **Not yet Implemented** +HYPGEOMDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\HyperGeometric::distribution ## I -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -IF | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical::statementIf -IFERROR | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical::IFERROR -IFNA | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical::IFNA -IFS | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical::IFS -IMABS | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMABS -IMAGINARY | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMAGINARY -IMARGUMENT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMARGUMENT -IMCONJUGATE | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMCONJUGATE -IMCOS | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMCOS -IMCOSH | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMCOSH -IMCOT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMCOT -IMCSC | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMCSC -IMCSCH | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMCSCH -IMDIV | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMDIV -IMEXP | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMEXP -IMLN | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMLN -IMLOG10 | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMLOG10 -IMLOG2 | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMLOG2 -IMPOWER | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMPOWER -IMPRODUCT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMPRODUCT -IMREAL | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMREAL -IMSEC | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMSEC -IMSECH | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMSECH -IMSIN | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMSIN -IMSINH | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMSINH -IMSQRT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMSQRT -IMSUB | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMSUB -IMSUM | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMSUM -IMTAN | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::IMTAN -INDEX | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::INDEX -INDIRECT | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::INDIRECT -INFO | CATEGORY_INFORMATION | **Not yet Implemented** -INT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::INT -INTERCEPT | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::INTERCEPT -INTRATE | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::INTRATE -IPMT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::IPMT -IRR | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::IRR -ISBLANK | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isBlank -ISERR | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isErr -ISERROR | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isError -ISEVEN | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isEven -ISFORMULA | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isFormula -ISLOGICAL | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isLogical -ISNA | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isNa -ISNONTEXT | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isNonText -ISNUMBER | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isNumber -ISO.CEILING | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** -ISODD | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isOdd -ISOWEEKNUM | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::ISOWEEKNUM -ISPMT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::ISPMT -ISREF | CATEGORY_INFORMATION | **Not yet Implemented** -ISTEXT | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isText +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +IF | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Conditional::statementIf +IFERROR | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Conditional::IFERROR +IFNA | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Conditional::IFNA +IFS | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Conditional::IFS +IMABS | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMABS +IMAGINARY | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Complex::IMAGINARY +IMARGUMENT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMARGUMENT +IMCONJUGATE | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCONJUGATE +IMCOS | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCOS +IMCOSH | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCOSH +IMCOT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCOT +IMCSC | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCSC +IMCSCH | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMCSCH +IMDIV | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexOperations::IMDIV +IMEXP | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMEXP +IMLN | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMLN +IMLOG10 | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMLOG10 +IMLOG2 | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMLOG2 +IMPOWER | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMPOWER +IMPRODUCT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexOperations::IMPRODUCT +IMREAL | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\Complex::IMREAL +IMSEC | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMSEC +IMSECH | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMSECH +IMSIN | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMSIN +IMSINH | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMSINH +IMSQRT | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMSQRT +IMSUB | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexOperations::IMSUB +IMSUM | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexOperations::IMSUM +IMTAN | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions::IMTAN +INDEX | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Matrix::index +INDIRECT | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Indirect::INDIRECT +INFO | CATEGORY_INFORMATION | **Not yet Implemented** +INT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\IntClass::evaluate +INTERCEPT | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::INTERCEPT +INTRATE | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Rates::interest +IPMT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Interest::payment +IRR | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable\Periodic::rate +ISBLANK | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isBlank +ISERR | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isErr +ISERROR | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isError +ISEVEN | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isEven +ISFORMULA | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isFormula +ISLOGICAL | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isLogical +ISNA | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isNa +ISNONTEXT | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isNonText +ISNUMBER | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isNumber +ISO.CEILING | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** +ISODD | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isOdd +ISOWEEKNUM | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Week::isoWeekNumber +ISPMT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Interest::schedulePayment +ISREF | CATEGORY_INFORMATION | **Not yet Implemented** +ISTEXT | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::isText ## J -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -JIS | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +JIS | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** ## K -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -KURT | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::KURT +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +KURT | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Deviations::kurtosis ## L -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -LARGE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::LARGE -LCM | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::LCM -LEFT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::LEFT -LEFTB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::LEFT -LEN | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::STRINGLENGTH -LENB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::STRINGLENGTH -LINEST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::LINEST -LN | CATEGORY_MATH_AND_TRIG | log -LOG | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::logBase -LOG10 | CATEGORY_MATH_AND_TRIG | log10 -LOGEST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::LOGEST -LOGINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::LOGINV -LOGNORMDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::LOGNORMDIST -LOGNORM.DIST | CATEGORY_STATISTICAL | **Not yet Implemented** -LOGNORM.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::LOGINV -LOOKUP | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::LOOKUP -LOWER | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::LOWERCASE +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +LARGE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Size::large +LCM | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Lcm::evaluate +LEFT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::left +LEFTB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::left +LEN | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Text::length +LENB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Text::length +LINEST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::LINEST +LN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Logarithms::natural +LOG | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Logarithms::withBase +LOG10 | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Logarithms::base10 +LOGEST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::LOGEST +LOGINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\LogNormal::inverse +LOGNORM.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\LogNormal::distribution +LOGNORM.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\LogNormal::inverse +LOGNORMDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\LogNormal::cumulative +LOOKUP | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Lookup::lookup +LOWER | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CaseConvert::lower ## M -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -MATCH | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::MATCH -MAX | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::MAX -MAXA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::MAXA -MAXIFS | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::MAXIFS -MDETERM | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::MDETERM -MDURATION | CATEGORY_FINANCIAL | **Not yet Implemented** -MEDIAN | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::MEDIAN -MEDIANIF | CATEGORY_STATISTICAL | **Not yet Implemented** -MID | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::MID -MIDB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::MID -MIN | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::MIN -MINA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::MINA -MINIFS | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::MINIFS -MINUTE | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::MINUTE -MINVERSE | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::MINVERSE -MIRR | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::MIRR -MMULT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::MMULT -MOD | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::MOD -MODE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::MODE -MODE.MULT | CATEGORY_STATISTICAL | **Not yet Implemented** -MODE.SNGL | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::MODE -MONTH | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::MONTHOFYEAR -MROUND | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::MROUND -MULTINOMIAL | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::MULTINOMIAL -MUNIT | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +MATCH | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\ExcelMatch::MATCH +MAX | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Maximum::max +MAXA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Maximum::maxA +MAXIFS | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::MAXIFS +MDETERM | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\MatrixFunctions::determinant +MDURATION | CATEGORY_FINANCIAL | **Not yet Implemented** +MEDIAN | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::median +MEDIANIF | CATEGORY_STATISTICAL | **Not yet Implemented** +MID | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::mid +MIDB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::mid +MIN | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Minimum::min +MINA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Minimum::minA +MINIFS | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::MINIFS +MINUTE | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\TimeParts::minute +MINVERSE | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\MatrixFunctions::inverse +MIRR | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable\Periodic::modifiedRate +MMULT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\MatrixFunctions::multiply +MOD | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Operations::mod +MODE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::mode +MODE.MULT | CATEGORY_STATISTICAL | **Not yet Implemented** +MODE.SNGL | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages::mode +MONTH | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\DateParts::month +MROUND | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::multiple +MULTINOMIAL | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Factorial::multinomial +MUNIT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\MatrixFunctions::identity ## N -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -N | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::n -NA | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::NA -NEGBINOMDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::NEGBINOMDIST -NEGBINOM.DIST | CATEGORY_STATISTICAL | **Not yet Implemented** -NETWORKDAYS | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::NETWORKDAYS -NETWORKDAYS.INTL | CATEGORY_DATE_AND_TIME | **Not yet Implemented** -NOMINAL | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::NOMINAL -NORMDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::NORMDIST -NORM.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::NORMDIST -NORMINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::NORMINV -NORM.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::NORMINV -NORMSDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::NORMSDIST -NORM.S.DIST | CATEGORY_STATISTICAL | **Not yet Implemented** -NORMSINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::NORMSINV -NORM.S.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::NORMSINV -NOT | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical::NOT -NOW | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::DATETIMENOW -NPER | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::NPER -NPV | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::NPV -NUMBERVALUE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::NUMBERVALUE +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +N | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::n +NA | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::NA +NEGBINOM.DIST | CATEGORY_STATISTICAL | **Not yet Implemented** +NEGBINOMDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::negative +NETWORKDAYS | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\NetworkDays::count +NETWORKDAYS.INTL | CATEGORY_DATE_AND_TIME | **Not yet Implemented** +NOMINAL | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\InterestRate::nominal +NORM.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Normal::distribution +NORM.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Normal::inverse +NORM.S.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::distribution +NORM.S.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::inverse +NORMDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Normal::distribution +NORMINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Normal::inverse +NORMSDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::cumulative +NORMSINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::inverse +NOT | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Operations::NOT +NOW | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Current::now +NPER | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic::periods +NPV | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable\Periodic::presentValue +NUMBERVALUE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::NUMBERVALUE ## O -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -OCT2BIN | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::OCTTOBIN -OCT2DEC | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::OCTTODEC -OCT2HEX | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering::OCTTOHEX -ODD | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::ODD -ODDFPRICE | CATEGORY_FINANCIAL | **Not yet Implemented** -ODDFYIELD | CATEGORY_FINANCIAL | **Not yet Implemented** -ODDLPRICE | CATEGORY_FINANCIAL | **Not yet Implemented** -ODDLYIELD | CATEGORY_FINANCIAL | **Not yet Implemented** -OFFSET | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::OFFSET -OR | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical::logicalOr +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +OCT2BIN | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertOctal::toBinary +OCT2DEC | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertOctal::toDecimal +OCT2HEX | CATEGORY_ENGINEERING | \PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertOctal::toHex +ODD | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::odd +ODDFPRICE | CATEGORY_FINANCIAL | **Not yet Implemented** +ODDFYIELD | CATEGORY_FINANCIAL | **Not yet Implemented** +ODDLPRICE | CATEGORY_FINANCIAL | **Not yet Implemented** +ODDLYIELD | CATEGORY_FINANCIAL | **Not yet Implemented** +OFFSET | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Offset::OFFSET +OR | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Operations::logicalOr ## P -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -PDURATION | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::PDURATION -PEARSON | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::CORREL -PERCENTILE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::PERCENTILE -PERCENTILE.EXC | CATEGORY_STATISTICAL | **Not yet Implemented** -PERCENTILE.INC | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::PERCENTILE -PERCENTRANK | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::PERCENTRANK -PERCENTRANK.EXC | CATEGORY_STATISTICAL | **Not yet Implemented** -PERCENTRANK.INC | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::PERCENTRANK -PERMUT | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::PERMUT -PERMUTATIONA | CATEGORY_STATISTICAL | **Not yet Implemented** -PHI | CATEGORY_STATISTICAL | **Not yet Implemented** -PHONETIC | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** -PI | CATEGORY_MATH_AND_TRIG | pi -PMT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::PMT -POISSON | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::POISSON -POISSON.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::POISSON -POWER | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::POWER -PPMT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::PPMT -PRICE | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::PRICE -PRICEDISC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::PRICEDISC -PRICEMAT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::PRICEMAT -PROB | CATEGORY_STATISTICAL | **Not yet Implemented** -PRODUCT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::PRODUCT -PROPER | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::PROPERCASE -PV | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::PV +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +PDURATION | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Single::periods +PEARSON | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::CORREL +PERCENTILE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::PERCENTILE +PERCENTILE.EXC | CATEGORY_STATISTICAL | **Not yet Implemented** +PERCENTILE.INC | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::PERCENTILE +PERCENTRANK | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::PERCENTRANK +PERCENTRANK.EXC | CATEGORY_STATISTICAL | **Not yet Implemented** +PERCENTRANK.INC | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::PERCENTRANK +PERMUT | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Permutations::PERMUT +PERMUTATIONA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Permutations::PERMUTATIONA +PHI | CATEGORY_STATISTICAL | **Not yet Implemented** +PHONETIC | CATEGORY_TEXT_AND_DATA | **Not yet Implemented** +PI | CATEGORY_MATH_AND_TRIG | pi +PMT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Payments::annuity +POISSON | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Poisson::distribution +POISSON.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Poisson::distribution +POWER | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Operations::power +PPMT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Payments::interestPayment +PRICE | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Price::price +PRICEDISC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Price::priceDiscounted +PRICEMAT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Price::priceAtMaturity +PROB | CATEGORY_STATISTICAL | **Not yet Implemented** +PRODUCT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Operations::product +PROPER | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CaseConvert::proper +PV | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic::presentValue ## Q -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -QUARTILE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::QUARTILE -QUARTILE.EXC | CATEGORY_STATISTICAL | **Not yet Implemented** -QUARTILE.INC | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::QUARTILE -QUOTIENT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::QUOTIENT +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +QUARTILE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::QUARTILE +QUARTILE.EXC | CATEGORY_STATISTICAL | **Not yet Implemented** +QUARTILE.INC | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::QUARTILE +QUOTIENT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Operations::quotient ## R -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -RADIANS | CATEGORY_MATH_AND_TRIG | deg2rad -RAND | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::RAND -RANDARRAY | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** -RANDBETWEEN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::RAND -RANK | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::RANK -RANK.AVG | CATEGORY_STATISTICAL | **Not yet Implemented** -RANK.EQ | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::RANK -RATE | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::RATE -RECEIVED | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::RECEIVED -REPLACE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::REPLACE -REPLACEB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::REPLACE -REPT | CATEGORY_TEXT_AND_DATA | str_repeat -RIGHT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::RIGHT -RIGHTB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::RIGHT -ROMAN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::ROMAN -ROUND | CATEGORY_MATH_AND_TRIG | round -ROUNDDOWN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::ROUNDDOWN -ROUNDUP | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::ROUNDUP -ROW | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::ROW -ROWS | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::ROWS -RRI | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::RRI -RSQ | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::RSQ -RTD | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +RADIANS | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Angle::toRadians +RAND | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Random::rand +RANDARRAY | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** +RANDBETWEEN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Random::randBetween +RANK | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::RANK +RANK.AVG | CATEGORY_STATISTICAL | **Not yet Implemented** +RANK.EQ | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles::RANK +RATE | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic\Interest::rate +RECEIVED | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Price::received +REPLACE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Replace::replace +REPLACEB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Replace::replace +REPT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Concatenate::builtinREPT +RIGHT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::right +RIGHTB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::right +ROMAN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Roman::evaluate +ROUND | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::round +ROUNDDOWN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::down +ROUNDUP | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round::up +ROW | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\RowColumnInformation::ROW +ROWS | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\RowColumnInformation::ROWS +RRI | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Single::interestRate +RSQ | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::RSQ +RTD | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** ## S -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -SEARCH | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::SEARCHINSENSITIVE -SEARCHB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::SEARCHINSENSITIVE -SEC | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SEC -SECH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SECH -SECOND | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::SECOND -SEQUENCE | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** -SERIESSUM | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SERIESSUM -SHEET | CATEGORY_INFORMATION | **Not yet Implemented** -SHEETS | CATEGORY_INFORMATION | **Not yet Implemented** -SIGN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SIGN -SIN | CATEGORY_MATH_AND_TRIG | sin -SINH | CATEGORY_MATH_AND_TRIG | sinh -SKEW | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::SKEW -SKEW.P | CATEGORY_STATISTICAL | **Not yet Implemented** -SLN | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::SLN -SLOPE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::SLOPE -SMALL | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::SMALL -SORT | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** -SORTBY | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** -SQRT | CATEGORY_MATH_AND_TRIG | sqrt -SQRTPI | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SQRTPI -STANDARDIZE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::STANDARDIZE -STDEV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::STDEV -STDEVA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::STDEVA -STDEVP | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::STDEVP -STDEV.P | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::STDEVP -STDEVPA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::STDEVPA -STDEV.S | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::STDEV -STEYX | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::STEYX -SUBSTITUTE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::SUBSTITUTE -SUBTOTAL | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SUBTOTAL -SUM | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SUM -SUMIF | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SUMIF -SUMIFS | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SUMIFS -SUMPRODUCT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SUMPRODUCT -SUMSQ | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SUMSQ -SUMX2MY2 | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SUMX2MY2 -SUMX2PY2 | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SUMX2PY2 -SUMXMY2 | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::SUMXMY2 -SWITCH | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical::statementSwitch -SYD | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::SYD +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +SEARCH | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Search::insensitive +SEARCHB | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Search::insensitive +SEC | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Secant::sec +SECH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Secant::sech +SECOND | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\TimeParts::second +SEQUENCE | CATEGORY_MATH_AND_TRIG | **Not yet Implemented** +SERIESSUM | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\SeriesSum::evaluate +SHEET | CATEGORY_INFORMATION | **Not yet Implemented** +SHEETS | CATEGORY_INFORMATION | **Not yet Implemented** +SIGN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sign::evaluate +SIN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Sine::sin +SINH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Sine::sinh +SKEW | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Deviations::skew +SKEW.P | CATEGORY_STATISTICAL | **Not yet Implemented** +SLN | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Depreciation::SLN +SLOPE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::SLOPE +SMALL | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Size::small +SORT | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** +SORTBY | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** +SQRT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sqrt::sqrt +SQRTPI | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sqrt::pi +STANDARDIZE | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Standardize::execute +STDEV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEV +STDEV.P | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEVP +STDEV.S | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEV +STDEVA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEVA +STDEVP | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEVP +STDEVPA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations::STDEVPA +STEYX | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::STEYX +SUBSTITUTE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Replace::substitute +SUBTOTAL | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Subtotal::evaluate +SUM | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sum::sumErroringStrings +SUMIF | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::SUMIF +SUMIFS | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional::SUMIFS +SUMPRODUCT | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sum::product +SUMSQ | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\SumSquares::sumSquare +SUMX2MY2 | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\SumSquares::sumXSquaredMinusYSquared +SUMX2PY2 | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\SumSquares::sumXSquaredPlusYSquared +SUMXMY2 | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\SumSquares::sumXMinusYSquared +SWITCH | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Conditional::statementSwitch +SYD | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Depreciation::SYD ## T -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -T | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::RETURNSTRING -TAN | CATEGORY_MATH_AND_TRIG | tan -TANH | CATEGORY_MATH_AND_TRIG | tanh -TBILLEQ | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::TBILLEQ -TBILLPRICE | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::TBILLPRICE -TBILLYIELD | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::TBILLYIELD -TDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::TDIST -T.DIST | CATEGORY_STATISTICAL | **Not yet Implemented** -T.DIST.2T | CATEGORY_STATISTICAL | **Not yet Implemented** -T.DIST.RT | CATEGORY_STATISTICAL | **Not yet Implemented** -TEXT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::TEXTFORMAT -TEXTJOIN | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::TEXTJOIN -TIME | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::TIME -TIMEVALUE | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::TIMEVALUE -TINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::TINV -T.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::TINV -T.INV.2T | CATEGORY_STATISTICAL | **Not yet Implemented** -TODAY | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::DATENOW -TRANSPOSE | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::TRANSPOSE -TREND | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::TREND -TRIM | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::TRIMSPACES -TRIMMEAN | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::TRIMMEAN -TRUE | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical::TRUE -TRUNC | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::TRUNC -TTEST | CATEGORY_STATISTICAL | **Not yet Implemented** -T.TEST | CATEGORY_STATISTICAL | **Not yet Implemented** -TYPE | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::TYPE +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +T | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Text::test +T.DIST | CATEGORY_STATISTICAL | **Not yet Implemented** +T.DIST.2T | CATEGORY_STATISTICAL | **Not yet Implemented** +T.DIST.RT | CATEGORY_STATISTICAL | **Not yet Implemented** +T.INV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StudentT::inverse +T.INV.2T | CATEGORY_STATISTICAL | **Not yet Implemented** +T.TEST | CATEGORY_STATISTICAL | **Not yet Implemented** +TAN | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Tangent::tan +TANH | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig\Tangent::tanh +TBILLEQ | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\TreasuryBill::bondEquivalentYield +TBILLPRICE | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\TreasuryBill::price +TBILLYIELD | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\TreasuryBill::yield +TDIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StudentT::distribution +TEXT | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::TEXTFORMAT +TEXTJOIN | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Concatenate::TEXTJOIN +TIME | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Time::fromHMS +TIMEVALUE | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\TimeValue::fromString +TINV | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StudentT::inverse +TODAY | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Current::today +TRANSPOSE | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Matrix::transpose +TREND | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends::TREND +TRIM | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Trim::spaces +TRIMMEAN | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages\Mean::trim +TRUE | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Boolean::TRUE +TRUNC | CATEGORY_MATH_AND_TRIG | \PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trunc::evaluate +TTEST | CATEGORY_STATISTICAL | **Not yet Implemented** +TYPE | CATEGORY_INFORMATION | \PhpOffice\PhpSpreadsheet\Calculation\Functions::TYPE ## U -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -UNICHAR | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::CHARACTER -UNICODE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::ASCIICODE -UNIQUE | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** -UPPER | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::UPPERCASE -USDOLLAR | CATEGORY_FINANCIAL | **Not yet Implemented** +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +UNICHAR | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CharacterConvert::character +UNICODE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CharacterConvert::code +UNIQUE | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** +UPPER | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\CaseConvert::upper +USDOLLAR | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Dollar::format ## V -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -VALUE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData::VALUE -VAR | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::VARFunc -VARA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::VARA -VARP | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::VARP -VAR.P | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::VARP -VARPA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::VARPA -VAR.S | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::VARFunc -VDB | CATEGORY_FINANCIAL | **Not yet Implemented** -VLOOKUP | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::VLOOKUP +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +VALUE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\TextData\Format::VALUE +VAR | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VAR +VAR.P | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VARP +VAR.S | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VAR +VARA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VARA +VARP | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VARP +VARPA | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances::VARPA +VDB | CATEGORY_FINANCIAL | **Not yet Implemented** +VLOOKUP | CATEGORY_LOOKUP_AND_REFERENCE | \PhpOffice\PhpSpreadsheet\Calculation\LookupRef\VLookup::lookup ## W -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -WEBSERVICE | CATEGORY_TEXT_AND_DATA | \PhpOffice\PhpSpreadsheet\Calculation\Web::WEBSERVICE -WEEKDAY | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::WEEKDAY -WEEKNUM | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::WEEKNUM -WEIBULL | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::WEIBULL -WEIBULL.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::WEIBULL -WORKDAY | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::WORKDAY -WORKDAY.INTL | CATEGORY_DATE_AND_TIME | **Not yet Implemented** +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +WEBSERVICE | CATEGORY_WEB | \PhpOffice\PhpSpreadsheet\Calculation\Web\Service::webService +WEEKDAY | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Week::day +WEEKNUM | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Week::number +WEIBULL | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Weibull::distribution +WEIBULL.DIST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Weibull::distribution +WORKDAY | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\WorkDay::date +WORKDAY.INTL | CATEGORY_DATE_AND_TIME | **Not yet Implemented** ## X -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -XIRR | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::XIRR -XLOOKUP | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** -XMATCH | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** -XNPV | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::XNPV -XOR | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical::logicalXor +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +XIRR | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable\NonPeriodic::rate +XLOOKUP | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** +XMATCH | CATEGORY_LOOKUP_AND_REFERENCE | **Not yet Implemented** +XNPV | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable\NonPeriodic::presentValue +XOR | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Operations::logicalXor ## Y -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -YEAR | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::YEAR -YEARFRAC | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTime::YEARFRAC -YIELD | CATEGORY_FINANCIAL | **Not yet Implemented** -YIELDDISC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::YIELDDISC -YIELDMAT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial::YIELDMAT +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +YEAR | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\DateParts::year +YEARFRAC | CATEGORY_DATE_AND_TIME | \PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\YearFrac::fraction +YIELD | CATEGORY_FINANCIAL | **Not yet Implemented** +YIELDDISC | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Yields::yieldDiscounted +YIELDMAT | CATEGORY_FINANCIAL | \PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Yields::yieldAtMaturity ## Z -Excel Function | Category | PhpSpreadsheet Function --------------------------|-------------------------------|------------------------- -ZTEST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::ZTEST -Z.TEST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical::ZTEST +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +Z.TEST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::zTest +ZTEST | CATEGORY_STATISTICAL | \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\StandardNormal::zTest diff --git a/docs/topics/accessing-cells.md b/docs/topics/accessing-cells.md index a777afc1..346e5858 100644 --- a/docs/topics/accessing-cells.md +++ b/docs/topics/accessing-cells.md @@ -110,6 +110,11 @@ values beginning with `=` will be converted to a formula. Strings that aren't numeric, or that don't begin with a leading `=` will be treated as genuine string values. +Note that a numeric string that begins with a leading zero (that isn't +immediately followed by a decimal separator) will not be converted to a +numeric, so values like phone numbers (e.g. `01615991375``will remain as +strings). + This "conversion" is handled by a cell "value binder", and you can write custom "value binders" to change the behaviour of these "conversions". The standard PhpSpreadsheet package also provides an "advanced value @@ -138,8 +143,10 @@ Formats handled by the advanced value binder include: - When strings contain a newline character (`\n`), then the cell styling is set to wrap. -You can read more about value binders later in this section of the -documentation. +Basically, it attempts to mimic the behaviour of the MS Excel GUI. + +You can read more about value binders [later in this section of the +documentation](#using-value-binders-to-facilitate-data-entry). ### Setting a formula in a Cell @@ -551,8 +558,27 @@ $spreadsheet->getActiveSheet()->setCellValue('A5', 'Date/time value:'); $spreadsheet->getActiveSheet()->setCellValue('B5', '21 December 1983'); ``` -**Creating your own value binder is easy.** When advanced value binding -is required, you can implement the -`\PhpOffice\PhpSpreadsheet\Cell\IValueBinder` interface or extend the +Alternatively, a `\PhpOffice\PhpSpreadsheet\Cell\StringValueBinder` class is available +if you want to preserve all content as strings. This might be appropriate if you +were loading a file containing values that could be interpreted as numbers (e.g. numbers +with leading sign such as international phone numbers like `+441615579382`), but that +should be retained as strings (non-international phone numbers with leading zeroes are +already maintained as strings). + +By default, the StringValueBinder will cast any datatype passed to it into a string. However, there are a number of settings which allow you to specify that certain datatypes shouldn't be cast to strings, but left "as is": + +```php +// Set value binder +$stringValueBinder = new \PhpOffice\PhpSpreadsheet\Cell\StringValueBinder(); +$stringValueBinder->setNumericConversion(false) + ->setBooleanConversion(false) + ->setNullConversion(false) + ->setFormulaConversion(false); +\PhpOffice\PhpSpreadsheet\Cell\Cell::setValueBinder( $stringValueBinder ); +``` + +**Creating your own value binder is relatively straightforward.** When more specialised +value binding is required, you can implement the +`\PhpOffice\PhpSpreadsheet\Cell\IValueBinder` interface or extend the existing `\PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder` or `\PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder` classes. diff --git a/docs/topics/autofilters.md b/docs/topics/autofilters.md index d5a07f8b..cd4291f4 100644 --- a/docs/topics/autofilters.md +++ b/docs/topics/autofilters.md @@ -251,16 +251,16 @@ $columnFilter->createRule() ); ``` -MS Excel uses \* as a wildcard to match any number of characters, and ? -as a wildcard to match a single character. 'U\*' equates to "begins with -a 'U'"; '\*U' equates to "ends with a 'U'"; and '\*U\*' equates to -"contains a 'U'" +MS Excel uses `*` as a wildcard to match any number of characters, and `?` +as a wildcard to match a single character. `U*` equates to "begins with +a 'U'"; `*U` equates to "ends with a 'U'"; and `*U*` equates to +"contains a 'U'". -If you want to match explicitly against a \* or a ? character, you can -escape it with a tilde (\~), so ?\~\*\* would explicitly match for a \* -character as the second character in the cell value, followed by any +If you want to match explicitly against `*` or `?`, you can +escape it with a tilde `~`, so `?~**` would explicitly match for `*` +as the second character in the cell value, followed by any number of other characters. The only other character that needs escaping -is the \~ itself. +is the `~` itself. To create a "between" condition, we need to define two rules: @@ -327,14 +327,14 @@ $columnFilter->setFilterType( ``` When defining the rule for a dynamic filter, we don't define a value (we -can simply set that to NULL) but we do specify the dynamic filter +can simply set that to null string) but we do specify the dynamic filter category. ```php $columnFilter->createRule() ->setRule( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL, - NULL, + '', \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE ) ->setRuleType( diff --git a/docs/topics/file-formats.md b/docs/topics/file-formats.md index 7f4e6b7e..6f8783e6 100644 --- a/docs/topics/file-formats.md +++ b/docs/topics/file-formats.md @@ -71,7 +71,7 @@ library. ### Csv Comma Separated Value (CSV) file format is a common structuring strategy -for text format files. In CSV flies, each line in the file represents a +for text format files. In CSV files, each line in the file represents a row of data and (within each line of the file) the different data fields (or columns) are separated from one another using a comma (`,`). If a data field contains a comma, then it should be enclosed (typically in diff --git a/docs/topics/images/10-databar-of-conditional-formatting.png b/docs/topics/images/10-databar-of-conditional-formatting.png new file mode 100644 index 00000000..10c88f9f Binary files /dev/null and b/docs/topics/images/10-databar-of-conditional-formatting.png differ diff --git a/docs/topics/memory_saving.md b/docs/topics/memory_saving.md index 157bb704..e52a83e4 100644 --- a/docs/topics/memory_saving.md +++ b/docs/topics/memory_saving.md @@ -1,6 +1,6 @@ # Memory saving -PhpSpreadsheet uses an average of about 1k per cell in your worksheets, so +PhpSpreadsheet uses an average of about 1k per cell (1.6k on 64-bit PHP) in your worksheets, so large workbooks can quickly use up available memory. Cell caching provides a mechanism that allows PhpSpreadsheet to maintain the cell objects in a smaller size of memory, or off-memory (eg: on disk, in APCu, diff --git a/docs/topics/reading-and-writing-to-file.md b/docs/topics/reading-and-writing-to-file.md index b319de0f..8bb48cc5 100644 --- a/docs/topics/reading-and-writing-to-file.md +++ b/docs/topics/reading-and-writing-to-file.md @@ -1,8 +1,7 @@ # Reading and writing to file As you already know from the [architecture](./architecture.md#readers-and-writers), -reading and writing to a -persisted storage is not possible using the base PhpSpreadsheet classes. +reading and writing to a persisted storage is not possible using the base PhpSpreadsheet classes. For this purpose, PhpSpreadsheet provides readers and writers, which are implementations of `\PhpOffice\PhpSpreadsheet\Reader\IReader` and `\PhpOffice\PhpSpreadsheet\Writer\IWriter`. @@ -139,6 +138,11 @@ $reader->setReadFilter( new MyReadFilter() ); $spreadsheet = $reader->load("06largescale.xlsx"); ``` +Read Filtering does not renumber cell rows and columns. If you filter to read only rows 100-200, cells that you read will still be numbered A100-A200, not A1-A101. Cells A1-A99 will not be loaded, but if you then try to call `getCell()` for a cell outside your loaded range, then PHPSpreadsheet will create a new cell with a null value. + +Methods such as `toArray()` assume that all cells in a spreadsheet has been loaded from A1, so will return null values for rows and columns that fall outside your filter range: it is recommended that you keep track of the range that your filter has requested, and use `rangeToArray()` instead. + + ### \PhpOffice\PhpSpreadsheet\Writer\Xlsx #### Writing a spreadsheet @@ -162,6 +166,9 @@ $writer->setPreCalculateFormulas(false); $writer->save("05featuredemo.xlsx"); ``` +**Note** Formulas will still be calculated in any column set to be autosized +even if pre-calculated is set to false + #### Office 2003 compatibility pack Because of a bug in the Office2003 compatibility pack, there can be some @@ -477,6 +484,41 @@ $reader->setSheetIndex(0); $spreadsheet = $reader->load('sample.csv'); ``` +You can also set the reader to guess the encoding +rather than calling guessEncoding directly. In this case, +the user-settable fallback encoding is used if nothing else works. + +```php +$reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv(); +$reader->setInputEncoding(\PhpOffice\PhpSpreadsheet\Reader\Csv::GUESS_ENCODING); +$reader->setFallbackEncoding('ISO-8859-2'); // default CP1252 without this statement +$reader->setDelimiter(';'); +$reader->setEnclosure(''); +$reader->setSheetIndex(0); + +$spreadsheet = $reader->load('sample.csv'); +``` + +Finally, you can set a callback to be invoked when the constructor is executed, +either through `new Csv()` or `IOFactory::load`, +and have that callback set the customizable attributes to whatever +defaults are appropriate for your environment. + +```php +function constructorCallback(\PhpOffice\PhpSpreadsheet\Reader\Csv $reader): void +{ + $reader->setInputEncoding(\PhpOffice\PhpSpreadsheet\Reader\Csv::GUESS_ENCODING); + $reader->setFallbackEncoding('ISO-8859-2'); + $reader->setDelimiter(','); + $reader->setEnclosure('"'); + // Following represents how Excel behaves better than the default escape character + $reader->setEscapeCharacter((version_compare(PHP_VERSION, '7.4') < 0) ? "\x0" : ''); +} + +\PhpOffice\PhpSpreadsheet\Reader\Csv::setConstructorCallback('constructorCallback'); +$spreadsheet = \PhpSpreadsheet\IOFactory::load('sample.csv'); +``` + #### Read a specific worksheet CSV files can only contain one worksheet. Therefore, you can specify @@ -580,6 +622,18 @@ $writer->setUseBOM(true); $writer->save("05featuredemo.csv"); ``` +#### Writing CSV files with desired encoding + +It can be set to output with the encoding that can be specified by PHP's mb_convert_encoding. +This looks like the following code: + +```php +$writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet); +$writer->setUseBOM(false); +$writer->setOutputEncoding('SJIS-WIN'); +$writer->save("05featuredemo.csv"); +``` + #### Decimal and thousands separators If the worksheet you are exporting contains numbers with decimal or @@ -837,8 +891,7 @@ class My_Custom_TCPDF_Writer extends \PhpOffice\PhpSpreadsheet\Writer\Pdf\Tcpdf #### Writing a spreadsheet -Once you have identified the Renderer that you wish to use for PDF -generation, you can write a .pdf file using the following code: +Once you have identified the Renderer that you wish to use for PDF generation, you can write a .pdf file using the following code: ```php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet); @@ -850,8 +903,7 @@ first worksheet by default. #### Write all worksheets -PDF files can contain one or more worksheets. If you want to write all -sheets into a single PDF file, use the following code: +PDF files can contain one or more worksheets. If you want to write all sheets into a single PDF file, use the following code: ```php $writer->writeAllSheets(); @@ -965,3 +1017,64 @@ $spreadhseet = $reader->loadFromString($secondHtmlString, $spreadsheet); $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls'); $writer->save('write.xls'); ``` + +## Reader/Writer Flags + +Some Readers and Writers support special "Feature Flags" that need to be explicitly enabled. +An example of this is Charts in a spreadsheet. By default, when you load a spreadsheet that contains Charts, the charts will not be loaded. If all you want to do is read the data in the spreadsheet, then loading charts is an overhead for both speed of loading and memory usage. +However, there are times when you may want to load any charts in the spreadsheet as well as the data. To do so, you need to tell the Reader explicitly to include Charts. + +```php +$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile("05featuredemo.xlsx"); +$reader->setIncludeCharts(true); +$reader->load("spreadsheetWithCharts.xlsx"); +``` +Alternatively, you can specify this in the call to load the spreadsheet: +```php +$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile("spreadsheetWithCharts.xlsx"); +$reader->load("spreadsheetWithCharts.xlsx", $reader::LOAD_WITH_CHARTS); +``` + +If you wish to use the IOFactory `load()` method rather than instantiating a specific Reader, then you can still pass these flags. + +```php +$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load("spreadsheetWithCharts.xlsx", \PhpOffice\PhpSpreadsheet\Reader\IReader::LOAD_WITH_CHARTS); +``` + +Likewise, when saving a file using a Writer, loaded charts wil not be saved unless you explicitly tell the Writer to include them: + +```php +$writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); +$writer->setIncludeCharts(true); +$writer->save('mySavedFileWithCharts.xlsx'); +``` + +As with the `load()` method, you can also pass flags in the `save()` method: +```php +$writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); +$writer->save('mySavedFileWithCharts.xlsx', \PhpOffice\PhpSpreadsheet\Writer\IWriter::SAVE_WITH_CHARTS); +``` + +Currently, the only special "Feature Flag" that is supported in this way is the inclusion of Charts, and only for certain formats. + +Readers | LOAD_WITH_CHARTS | +---------|------------------| +Xlsx | YES | +Xls | NO | +Xml | NO | +Ods | NO | +Gnumeric | NO | +Html | N/A | +Slk | N/A | +Csv | N/A | + + +Writers | SAVE_WITH_CHARTS | +--------|------------------| +Xlsx | YES | +Xls | NO | +Ods | NO | +Html | YES | +Pdf | YES | +Csv | N/A | + diff --git a/docs/topics/reading-files.md b/docs/topics/reading-files.md index b46908a6..6c30f266 100644 --- a/docs/topics/reading-files.md +++ b/docs/topics/reading-files.md @@ -324,6 +324,10 @@ to read and process a large workbook in "chunks": an example of this usage might be when transferring data from an Excel worksheet to a database. +Read Filtering does not renumber cell rows and columns. If you filter to read only rows 100-200, cells that you read will still be numbered A100-A200, not A1-A101. Cells A1-A99 will not be loaded, but if you then try to call `getCell()` for a cell outside your loaded range, then PHPSpreadsheet will create a new cell with a null value. + +Methods such as `toArray()` assume that all cells in a spreadsheet has been loaded from A1, so will return null values for rows and columns that fall outside your filter range: it is recommended that you keep track of the range that your filter has requested, and use `rangeToArray()` instead. + ```php $inputFileType = 'Xls'; $inputFileName = './sampleData/example2.xls'; diff --git a/docs/topics/recipes.md b/docs/topics/recipes.md index db09642d..25d4bb50 100644 --- a/docs/topics/recipes.md +++ b/docs/topics/recipes.md @@ -201,7 +201,7 @@ $spreadsheet->getActiveSheet()->setCellValue('B8',$internalFormula); ``` Currently, formula translation only translates the function names, the -constants TRUE and FALSE, and the function argument separators. +constants TRUE and FALSE, and the function argument separators. Cell addressing using R1C1 formatting is not supported. At present, the following locale settings are supported: @@ -216,7 +216,7 @@ French | Français | fr Hungarian | Magyar | hu Italian | Italiano | it Dutch | Nederlands | nl -Norwegian | Norsk | no +Norwegian | Norsk Bokmål | nb Polish | Jezyk polski | pl Portuguese | Português | pt Brazilian Portuguese | Português Brasileiro | pt_br @@ -475,7 +475,7 @@ $spreadsheet->getActiveSheet()->setBreak('D10', \PhpOffice\PhpSpreadsheet\Worksh To show/hide gridlines when printing, use the following code: ```php -$spreadsheet->getActiveSheet()->setShowGridlines(true); +$spreadsheet->getActiveSheet()->setPrintGridlines(true); ``` ### Setting rows/columns to repeat at top/left @@ -884,6 +884,44 @@ $spreadsheet->getActiveSheet() ); ``` +### DataBar of Conditional formatting +The basics are the same as conditional formatting. +Additional DataBar object to conditional formatting. + +For example, the following code will result in the conditional formatting shown in the image. +```php +$conditional = new Conditional(); +$conditional->setConditionType(Conditional::CONDITION_DATABAR); +$conditional->setDataBar(new ConditionalDataBar()); +$conditional->getDataBar() + ->setMinimumConditionalFormatValueObject(new ConditionalFormatValueObject('num', '2')) + ->setMaximumConditionalFormatValueObject(new ConditionalFormatValueObject('max')) + ->setColor('FFFF555A'); +$ext = $conditional + ->getDataBar() + ->setConditionalFormattingRuleExt(new ConditionalFormattingRuleExtension()) + ->getConditionalFormattingRuleExt(); + +$ext->setCfRule('dataBar'); +$ext->setSqref('A1:A5'); // target CellCoordinates +$ext->setDataBarExt(new ConditionalDataBarExtension()); +$ext->getDataBarExt() + ->setMinimumConditionalFormatValueObject(new ConditionalFormatValueObject('num', '2')) + ->setMaximumConditionalFormatValueObject(new ConditionalFormatValueObject('autoMax')) + ->setMinLength(0) + ->setMaxLength(100) + ->setBorder(true) + ->setDirection('rightToLeft') + ->setNegativeBarBorderColorSameAsPositive(false) + ->setBorderColor('FFFF555A') + ->setNegativeFillColor('FFFF0000') + ->setNegativeBorderColor('FFFF0000') + ->setAxisColor('FF000000'); + +``` + +![10-databar-of-conditional-formatting.png](./images/10-databar-of-conditional-formatting.png) + ## Add a comment to a cell To add a comment to a cell, use the following code. The example below @@ -950,6 +988,9 @@ $security->setLockStructure(true); $security->setWorkbookPassword("PhpSpreadsheet"); ``` +Note that there are additional methods setLockRevision and setRevisionsPassword +which apply only to change tracking and history for shared workbooks. + ### Worksheet An example on setting worksheet security: @@ -1063,7 +1104,7 @@ formula is allowed to be maximum 255 characters (not bytes). This sets a limit on how many items you can have in the string "Item A,Item B,Item C". Therefore it is normally a better idea to type the item values directly in some cell range, say A1:A3, and instead use, say, -`$validation->setFormula1('Sheet!$A$1:$A$3')`. Another benefit is that +`$validation->setFormula1('\'Sheet title\'!$A$1:$A$3')`. Another benefit is that the item values themselves can contain the comma `,` character itself. If you need data validation on multiple cells, one can clone the @@ -1073,6 +1114,11 @@ ruleset: $spreadsheet->getActiveSheet()->getCell('B8')->setDataValidation(clone $validation); ``` +Alternatively, one can apply the validation to a range of cells: +```php +$validation->setSqref('B5:B1048576'); +``` + ## Setting a column's width A column's width can be set using the following code: @@ -1081,6 +1127,16 @@ A column's width can be set using the following code: $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(12); ``` +If you want to set a column width using a different unit of measure, +then you can do so by telling PhpSpreadsheet what UoM the width value +that you are setting is measured in. +Valid units are `pt` (points), `px` (pixels), `pc` (pica), `in` (inches), +`cm` (centimeters) and `mm` (millimeters). + +```php +$spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(120, 'pt'); +``` + If you want PhpSpreadsheet to perform an automatic width calculation, use the following code. PhpSpreadsheet will approximate the column with to the width of the widest column value. @@ -1166,6 +1222,16 @@ Excel measures row height in points, where 1 pt is 1/72 of an inch (or about 0.35mm). The default value is 12.75 pts; and the permitted range of values is between 0 and 409 pts, where 0 pts is a hidden row. +If you want to set a row height using a different unit of measure, +then you can do so by telling PhpSpreadsheet what UoM the height value +that you are setting is measured in. +Valid units are `pt` (points), `px` (pixels), `pc` (pica), `in` (inches), +`cm` (centimeters) and `mm` (millimeters). + +```php +$spreadsheet->getActiveSheet()->getRowDimension('10')->setRowHeight(100, 'pt'); +``` + ## Show/hide a row To set a worksheet''s row visibility, you can use the following code. @@ -1311,9 +1377,11 @@ The following code extracts images from the current active worksheet, and writes each as a separate file. ```php +use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; $i = 0; + foreach ($spreadsheet->getActiveSheet()->getDrawingCollection() as $drawing) { - if ($drawing instanceof \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing) { + if ($drawing instanceof MemoryDrawing) { ob_start(); call_user_func( $drawing->getRenderingFunction(), @@ -1322,24 +1390,39 @@ foreach ($spreadsheet->getActiveSheet()->getDrawingCollection() as $drawing) { $imageContents = ob_get_contents(); ob_end_clean(); switch ($drawing->getMimeType()) { - case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_PNG : + case MemoryDrawing::MIMETYPE_PNG : $extension = 'png'; break; - case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_GIF: + case MemoryDrawing::MIMETYPE_GIF: $extension = 'gif'; break; - case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_JPEG : + case MemoryDrawing::MIMETYPE_JPEG : $extension = 'jpg'; break; } } else { - $zipReader = fopen($drawing->getPath(),'r'); - $imageContents = ''; - while (!feof($zipReader)) { - $imageContents .= fread($zipReader,1024); + if ($drawing->getPath()) { + // Check if the source is a URL or a file path + if ($drawing->getIsURL()) { + $imageContents = file_get_contents($drawing->getPath()); + $filePath = tempnam(sys_get_temp_dir(), 'Drawing'); + file_put_contents($filePath , $imageContents); + $mimeType = mime_content_type($filePath); + // You could use the below to find the extension from mime type. + // https://gist.github.com/alexcorvi/df8faecb59e86bee93411f6a7967df2c#gistcomment-2722664 + $extension = File::mime2ext($mimeType); + unlink($filePath); + } + else { + $zipReader = fopen($drawing->getPath(),'r'); + $imageContents = ''; + while (!feof($zipReader)) { + $imageContents .= fread($zipReader,1024); + } + fclose($zipReader); + $extension = $drawing->getExtension(); + } } - fclose($zipReader); - $extension = $drawing->getExtension(); } $myFileName = '00_Image_'.++$i.'.'.$extension; file_put_contents($myFileName,$imageContents); @@ -1519,6 +1602,20 @@ Default column width can be set using the following code: $spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(12); ``` +Excel measures column width in its own proprietary units, based on the number +of characters that will be displayed in the default font. + +If you want to set the default column width using a different unit of measure, +then you can do so by telling PhpSpreadsheet what UoM the width value +that you are setting is measured in. +Valid units are `pt` (points), `px` (pixels), `pc` (pica), `in` (inches), +`cm` (centimeters) and `mm` (millimeters). + +```php +$spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(400, 'pt'); +``` +and PhpSpreadsheet will handle the internal conversion. + ## Setting the default row height Default row height can be set using the following code: @@ -1527,6 +1624,21 @@ Default row height can be set using the following code: $spreadsheet->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15); ``` +Excel measures row height in points, where 1 pt is 1/72 of an inch (or +about 0.35mm). The default value is 12.75 pts; and the permitted range +of values is between 0 and 409 pts, where 0 pts is a hidden row. + +If you want to set a row height using a different unit of measure, +then you can do so by telling PhpSpreadsheet what UoM the height value +that you are setting is measured in. +Valid units are `pt` (points), `px` (pixels), `pc` (pica), `in` (inches), +`cm` (centimeters) and `mm` (millimeters). + +```php +$spreadsheet->getActiveSheet()->getDefaultRowDimension()->setRowHeight(100, 'pt'); +``` + + ## Add a GD drawing to a worksheet There might be a situation where you want to generate an in-memory image diff --git a/src/PhpSpreadsheet/DocumentGenerator.php b/infra/DocumentGenerator.php similarity index 95% rename from src/PhpSpreadsheet/DocumentGenerator.php rename to infra/DocumentGenerator.php index 5e06af97..e2c3c86c 100644 --- a/src/PhpSpreadsheet/DocumentGenerator.php +++ b/infra/DocumentGenerator.php @@ -1,6 +1,6 @@ $functionInfo) { @@ -78,7 +78,8 @@ class DocumentGenerator $result = "# Function list by name\n"; $lastAlphabet = null; foreach ($phpSpreadsheetFunctions as $excelFunction => $functionInfo) { - $lengths = [20, 31, 42]; + /** @var string $excelFunction */ + $lengths = [25, 31, 37]; if ($lastAlphabet !== $excelFunction[0]) { $lastAlphabet = $excelFunction[0]; $result .= "\n"; diff --git a/infra/LocaleGenerator.php b/infra/LocaleGenerator.php new file mode 100644 index 00000000..bb97754d --- /dev/null +++ b/infra/LocaleGenerator.php @@ -0,0 +1,345 @@ +translationBaseFolder = $translationBaseFolder; + $this->translationSpreadsheetName = $translationSpreadsheetName; + $this->phpSpreadsheetFunctions = $phpSpreadsheetFunctions; + $this->verbose = $verbose; + } + + public function generateLocales(): void + { + $this->openTranslationWorkbook(); + + $this->localeTranslations = $this->getTranslationSheet(self::EXCEL_LOCALISATION_WORKSHEET); + $this->localeLanguageMap = $this->mapLanguageColumns($this->localeTranslations); + $this->mapErrorCodeRows(); + + $this->functionNameTranslations = $this->getTranslationSheet(self::EXCEL_FUNCTIONS_WORKSHEET); + $this->functionNameLanguageMap = $this->mapLanguageColumns($this->functionNameTranslations); + $this->mapFunctionNameRows(); + + foreach ($this->localeLanguageMap as $column => $locale) { + $this->buildConfigFileForLocale($column, $locale); + } + + foreach ($this->functionNameLanguageMap as $column => $locale) { + $this->buildFunctionsFileForLocale($column, $locale); + } + } + + protected function buildConfigFileForLocale($column, $locale): void + { + $language = $this->localeTranslations->getCell($column . self::ENGLISH_LANGUAGE_NAME_ROW)->getValue(); + $localeLanguage = $this->localeTranslations->getCell($column . self::LOCALE_LANGUAGE_NAME_ROW)->getValue(); + $configFile = $this->openConfigFile($locale, $language, $localeLanguage); + + $this->writeConfigArgumentSeparator($configFile, $column); + $this->writeFileSectionHeader($configFile, 'Error Codes'); + + foreach ($this->errorCodeMap as $errorCode => $row) { + $translationCell = $this->localeTranslations->getCell($column . $row); + $translationValue = $translationCell->getValue(); + if (!empty($translationValue)) { + $errorCodeTranslation = "{$errorCode} = {$translationValue}" . self::EOL; + fwrite($configFile, $errorCodeTranslation); + } else { + $errorCodeTranslation = "{$errorCode}" . self::EOL; + fwrite($configFile, $errorCodeTranslation); + $this->log("No {$language} translation available for error code {$errorCode}"); + } + } + + fclose($configFile); + } + + protected function writeConfigArgumentSeparator($configFile, $column): void + { + $translationCell = $this->localeTranslations->getCell($column . self::ARGUMENT_SEPARATOR_ROW); + $localeValue = $translationCell->getValue(); + if (!empty($localeValue)) { + $functionTranslation = "ArgumentSeparator = {$localeValue}" . self::EOL; + fwrite($configFile, $functionTranslation); + } else { + $this->log('No Argument Separator defined'); + } + } + + protected function buildFunctionsFileForLocale($column, $locale): void + { + $language = $this->functionNameTranslations->getCell($column . self::ENGLISH_LANGUAGE_NAME_ROW)->getValue(); + $localeLanguage = $this->functionNameTranslations->getCell($column . self::LOCALE_LANGUAGE_NAME_ROW) + ->getValue(); + $functionFile = $this->openFunctionNameFile($locale, $language, $localeLanguage); + + foreach ($this->functionNameMap as $functionName => $row) { + $translationCell = $this->functionNameTranslations->getCell($column . $row); + $translationValue = $translationCell->getValue(); + if ($this->isFunctionCategoryEntry($translationCell)) { + $this->writeFileSectionHeader($functionFile, "{$translationValue} ({$functionName})"); + } elseif (!array_key_exists($functionName, $this->phpSpreadsheetFunctions)) { + $this->log("Function {$functionName} is not defined in PhpSpreadsheet"); + } elseif (!empty($translationValue)) { + $functionTranslation = "{$functionName} = {$translationValue}" . self::EOL; + fwrite($functionFile, $functionTranslation); + } else { + $this->log("No {$language} translation available for function {$functionName}"); + } + } + + fclose($functionFile); + } + + protected function openConfigFile(string $locale, string $language, string $localeLanguage) + { + $this->log("Building locale {$locale} ($language) configuration"); + $localeFolder = $this->getLocaleFolder($locale); + + $configFileName = realpath($localeFolder . DIRECTORY_SEPARATOR . 'config'); + $this->log("Writing locale configuration to {$configFileName}"); + + $configFile = fopen($configFileName, 'wb'); + $this->writeFileHeader($configFile, $localeLanguage, $language, 'locale settings'); + + return $configFile; + } + + protected function openFunctionNameFile(string $locale, string $language, string $localeLanguage) + { + $this->log("Building locale {$locale} ($language) function names"); + $localeFolder = $this->getLocaleFolder($locale); + + $functionFileName = realpath($localeFolder . DIRECTORY_SEPARATOR . 'functions'); + $this->log("Writing local function names to {$functionFileName}"); + + $functionFile = fopen($functionFileName, 'wb'); + $this->writeFileHeader($functionFile, $localeLanguage, $language, 'function name translations'); + + return $functionFile; + } + + protected function getLocaleFolder(string $locale): string + { + $localeFolder = $this->translationBaseFolder . + DIRECTORY_SEPARATOR . + str_replace('_', DIRECTORY_SEPARATOR, $locale); + if (!file_exists($localeFolder) || !is_dir($localeFolder)) { + mkdir($localeFolder, 0777, true); + } + + return $localeFolder; + } + + protected function writeFileHeader($localeFile, string $localeLanguage, string $language, string $title): void + { + fwrite($localeFile, str_repeat('#', 60) . self::EOL); + fwrite($localeFile, '##' . self::EOL); + fwrite($localeFile, "## PhpSpreadsheet - {$title}" . self::EOL); + fwrite($localeFile, '##' . self::EOL); + fwrite($localeFile, "## {$localeLanguage} ({$language})" . self::EOL); + fwrite($localeFile, '##' . self::EOL); + fwrite($localeFile, str_repeat('#', 60) . self::EOL . self::EOL); + } + + protected function writeFileSectionHeader($localeFile, string $header): void + { + fwrite($localeFile, self::EOL . '##' . self::EOL); + fwrite($localeFile, "## {$header}" . self::EOL); + fwrite($localeFile, '##' . self::EOL); + } + + protected function openTranslationWorkbook(): void + { + $filepathName = $this->translationBaseFolder . '/' . $this->translationSpreadsheetName; + $this->translationSpreadsheet = IOFactory::load($filepathName); + } + + protected function getTranslationSheet(string $sheetName): Worksheet + { + $worksheet = $this->translationSpreadsheet->setActiveSheetIndexByName($sheetName); + if ($worksheet === null) { + throw new Exception("{$sheetName} Worksheet not found"); + } + + return $worksheet; + } + + protected function mapLanguageColumns(Worksheet $translationWorksheet): array + { + $sheetName = $translationWorksheet->getTitle(); + $this->log("Mapping Languages for {$sheetName}:"); + + $baseColumn = self::ENGLISH_REFERENCE_COLUMN; + $languagesList = $translationWorksheet->getColumnIterator(++$baseColumn); + + $languageNameMap = []; + foreach ($languagesList as $languageColumn) { + /** @var Column $languageColumn */ + $cells = $languageColumn->getCellIterator(self::LOCALE_NAME_ROW, self::LOCALE_NAME_ROW); + $cells->setIterateOnlyExistingCells(true); + foreach ($cells as $cell) { + /** @var Cell $cell */ + if ($this->localeCanBeSupported($translationWorksheet, $cell)) { + $languageNameMap[$cell->getColumn()] = $cell->getValue(); + $this->log($cell->getColumn() . ' -> ' . $cell->getValue()); + } + } + } + + return $languageNameMap; + } + + protected function localeCanBeSupported(Worksheet $worksheet, Cell $cell): bool + { + if ($worksheet->getTitle() === self::EXCEL_LOCALISATION_WORKSHEET) { + // Only provide support for languages that have a function argument separator defined + // in the localisation worksheet + return !empty( + $worksheet->getCell($cell->getColumn() . self::ARGUMENT_SEPARATOR_ROW)->getValue() + ); + } + + // If we're processing other worksheets, then language support is determined by whether we included the + // language in the map when we were processing the localisation worksheet (which is always processed first) + return in_array($cell->getValue(), $this->localeLanguageMap, true); + } + + protected function mapErrorCodeRows(): void + { + $this->log('Mapping Error Codes:'); + $errorList = $this->localeTranslations->getRowIterator(self::ERROR_CODES_FIRST_ROW); + + foreach ($errorList as $errorRow) { + /** @var Row $errorList */ + $cells = $errorRow->getCellIterator(self::ENGLISH_REFERENCE_COLUMN, self::ENGLISH_REFERENCE_COLUMN); + $cells->setIterateOnlyExistingCells(true); + foreach ($cells as $cell) { + /** @var Cell $cell */ + if ($cell->getValue() != '') { + $this->log($cell->getRow() . ' -> ' . $cell->getValue()); + $this->errorCodeMap[$cell->getValue()] = $cell->getRow(); + } + } + } + } + + protected function mapFunctionNameRows(): void + { + $this->log('Mapping Functions:'); + $functionList = $this->functionNameTranslations->getRowIterator(self::FUNCTION_NAME_LIST_FIRST_ROW); + + foreach ($functionList as $functionRow) { + /** @var Row $functionRow */ + $cells = $functionRow->getCellIterator(self::ENGLISH_REFERENCE_COLUMN, self::ENGLISH_REFERENCE_COLUMN); + $cells->setIterateOnlyExistingCells(true); + foreach ($cells as $cell) { + /** @var Cell $cell */ + if ($this->isFunctionCategoryEntry($cell)) { + if (!empty($cell->getValue())) { + $this->log('CATEGORY: ' . $cell->getValue()); + $this->functionNameMap[$cell->getValue()] = $cell->getRow(); + } + + continue; + } + if ($cell->getValue() != '') { + if (is_bool($cell->getValue())) { + $this->log($cell->getRow() . ' -> ' . ($cell->getValue() ? 'TRUE' : 'FALSE')); + $this->functionNameMap[($cell->getValue() ? 'TRUE' : 'FALSE')] = $cell->getRow(); + } else { + $this->log($cell->getRow() . ' -> ' . $cell->getValue()); + $this->functionNameMap[$cell->getValue()] = $cell->getRow(); + } + } + } + } + } + + private function isFunctionCategoryEntry(Cell $cell): bool + { + $categoryCheckCell = self::ENGLISH_FUNCTION_CATEGORIES_COLUMN . $cell->getRow(); + if ($this->functionNameTranslations->getCell($categoryCheckCell)->getValue() != '') { + return true; + } + + return false; + } + + private function log(string $message): void + { + if ($this->verbose === false) { + return; + } + + echo $message, self::EOL; + } +} diff --git a/mkdocs.yml b/mkdocs.yml index cf87a142..f79acb69 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -5,3 +5,5 @@ edit_uri: edit/master/docs/ theme: readthedocs extra_css: - extra/extra.css +extra_javascript: + - extra/extrajs.js diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon new file mode 100644 index 00000000..0fca9ef3 --- /dev/null +++ b/phpstan-baseline.neon @@ -0,0 +1,6292 @@ +parameters: + ignoreErrors: + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$returnArrayAsType has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$branchPruningEnabled has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$cellStack has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$cyclicFormulaCell has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$localeFunctions has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$phpSpreadsheetFunctions has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$controlFunctions has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$spreadsheet \\(PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Argument of an invalid type array\\\\|false supplied for foreach, only iterables are supported\\.$#" + count: 3 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Parameter \\#3 \\$formula of static method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:translateSeparator\\(\\) expects string, string\\|null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$functionReplaceFromExcel has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$functionReplaceToLocale has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:_translateFormulaToLocale\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:_translateFormulaToLocale\\(\\) has parameter \\$formula with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Parameter \\#1 \\$str of function preg_quote expects string, int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$functionReplaceFromLocale has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$functionReplaceToExcel has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:_translateFormulaToEnglish\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:_translateFormulaToEnglish\\(\\) has parameter \\$formula with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Parameter \\#1 \\$str of function trim expects string, int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:localeFunc\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:localeFunc\\(\\) has parameter \\$function with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Cannot call method getCell\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 6 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$operatorAssociativity has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$comparisonOperators has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$operatorPrecedence has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Strict comparison using \\=\\=\\= between mixed and null will always evaluate to false\\.$#" + count: 2 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Parameter \\#1 \\$haystack of function stripos expects string, float\\|int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Parameter \\#1 \\$haystack of function strpos expects string, float\\|int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:dataTestReference\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:dataTestReference\\(\\) has parameter \\$operandData with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Cannot call method getTitle\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Cannot call method getColumn\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Parameter \\#1 \\$str of function trim expects string, null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Cannot call method getCoordinate\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Cannot call method getRow\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Cannot call method has\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Collection\\\\Cells\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Parameter \\#1 \\$parent of method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\:\\:attach\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Collection\\\\Cells, PhpOffice\\\\PhpSpreadsheet\\\\Collection\\\\Cells\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Cannot call method attach\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:validateBinaryOperand\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:validateBinaryOperand\\(\\) has parameter \\$operand with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:validateBinaryOperand\\(\\) has parameter \\$stack with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Parameter \\#1 \\$textValue of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:strCaseReverse\\(\\) expects string, string\\|null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:raiseFormulaError\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:raiseFormulaError\\(\\) has parameter \\$errorMessage with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Cannot call method cellExists\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 4 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Parameter \\#2 \\$worksheet of static method PhpOffice\\\\PhpSpreadsheet\\\\DefinedName\\:\\:resolveName\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet, PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Cannot call method getHighestRow\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Cannot call method getHighestColumn\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:getUnusedBranchStoreKey\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:getTokensAsString\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:getTokensAsString\\(\\) has parameter \\$tokens with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Parameter \\#2 \\$field of static method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\\\DCountA\\:\\:evaluate\\(\\) expects int\\|string, int\\|string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\:\\:DMAX\\(\\) should return float but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\:\\:DMIN\\(\\) should return float but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\:\\:DPRODUCT\\(\\) should return float\\|string but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\:\\:DSTDEV\\(\\) should return float\\|string but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\:\\:DSTDEVP\\(\\) should return float\\|string but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\:\\:DSUM\\(\\) should return float\\|string but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\:\\:DVAR\\(\\) should return float\\|string but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\:\\:DVARP\\(\\) should return float\\|string but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\\\DatabaseAbstract\\:\\:evaluate\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database/DatabaseAbstract.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\\\DatabaseAbstract\\:\\:evaluate\\(\\) has parameter \\$criteria with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database/DatabaseAbstract.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\\\DatabaseAbstract\\:\\:evaluate\\(\\) has parameter \\$database with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database/DatabaseAbstract.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\\\DatabaseAbstract\\:\\:evaluate\\(\\) has parameter \\$field with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database/DatabaseAbstract.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\\\DatabaseAbstract\\:\\:buildCondition\\(\\) has parameter \\$criterion with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database/DatabaseAbstract.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\\\DatabaseAbstract\\:\\:processCondition\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database/DatabaseAbstract.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engine\\\\Logger\\:\\:writeDebugLog\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engine/Logger.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\:\\:BITLSHIFT\\(\\) should return int\\|string but returns float\\|int\\|string\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\:\\:BITRSHIFT\\(\\) should return int\\|string but returns float\\|int\\|string\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\BesselJ\\:\\:besselj2a\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/BesselJ.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\BesselJ\\:\\:besselj2b\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/BesselJ.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\BesselK\\:\\:besselK2\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/BesselK.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\BitWise\\:\\:validateBitwiseArgument\\(\\) never returns int so it can be removed from the return typehint\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/BitWise.php + + - + message: "#^Parameter \\#1 \\$number of function floor expects float, float\\|int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/BitWise.php + + - + message: "#^Parameter \\#1 \\$number of function floor expects float, float\\|int\\<0, 281474976710655\\>\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/BitWise.php + + - + message: "#^Parameter \\#1 \\$power of method Complex\\\\Complex\\:\\:pow\\(\\) expects float\\|int, float\\|int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/ComplexFunctions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\ConvertBase\\:\\:validateValue\\(\\) has parameter \\$value with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/ConvertBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\ConvertBase\\:\\:validatePlaces\\(\\) has parameter \\$places with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/ConvertBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\ConvertUOM\\:\\:getUOMDetails\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/ConvertUOM.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\ConvertUOM\\:\\:resolveTemperatureSynonyms\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/ConvertUOM.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\Erf\\:\\:\\$twoSqrtPi has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/Erf.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\Erf\\:\\:erfValue\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/Erf.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\Erf\\:\\:erfValue\\(\\) has parameter \\$value with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/Erf.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\ErfC\\:\\:\\$oneSqrtPi has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/ErfC.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\ErfC\\:\\:erfcValue\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/ErfC.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\ErfC\\:\\:erfcValue\\(\\) has parameter \\$value with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/ErfC.php + + - + message: "#^Parameter \\#1 \\$callback of function set_error_handler expects \\(callable\\(int, string, string, int, array\\)\\: bool\\)\\|null, array\\('PhpOffice\\\\\\\\PhpSpreadsheet\\\\\\\\Calculation\\\\\\\\Exception', 'errorHandlerCallback'\\) given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/ExceptionHandler.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\:\\:ISPMT\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\:\\:ISPMT\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\:\\:NPV\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Constant\\\\Periodic\\\\Interest\\:\\:schedulePayment\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Constant\\\\Periodic\\\\Interest\\:\\:rateNextGuess\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Constant\\\\Periodic\\\\Interest\\:\\:rateNextGuess\\(\\) has parameter \\$futureValue with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Constant\\\\Periodic\\\\Interest\\:\\:rateNextGuess\\(\\) has parameter \\$numberOfPeriods with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Constant\\\\Periodic\\\\Interest\\:\\:rateNextGuess\\(\\) has parameter \\$payment with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Constant\\\\Periodic\\\\Interest\\:\\:rateNextGuess\\(\\) has parameter \\$presentValue with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Constant\\\\Periodic\\\\Interest\\:\\:rateNextGuess\\(\\) has parameter \\$rate with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Constant\\\\Periodic\\\\Interest\\:\\:rateNextGuess\\(\\) has parameter \\$type with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Constant\\\\Periodic\\\\InterestAndPrincipal\\:\\:\\$interest has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/InterestAndPrincipal.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Constant\\\\Periodic\\\\InterestAndPrincipal\\:\\:\\$principal has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/InterestAndPrincipal.php + + - + message: "#^Binary operation \"\\-\" between float\\|string and 0\\|float results in an error\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/InterestAndPrincipal.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Variable\\\\Periodic\\:\\:presentValue\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/Periodic.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\Depreciation\\:\\:validateCost\\(\\) has parameter \\$cost with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/Depreciation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\Depreciation\\:\\:validateSalvage\\(\\) has parameter \\$salvage with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/Depreciation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\Depreciation\\:\\:validateLife\\(\\) has parameter \\$life with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/Depreciation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\Depreciation\\:\\:validatePeriod\\(\\) has parameter \\$period with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/Depreciation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\Depreciation\\:\\:validateMonth\\(\\) has parameter \\$month with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/Depreciation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\Depreciation\\:\\:validateFactor\\(\\) has parameter \\$factor with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/Depreciation.php + + - + message: "#^Strict comparison using \\=\\=\\= between string and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/FormulaParser.php + + - + message: "#^Cannot call method setValue\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\FormulaToken\\|null\\.$#" + count: 5 + path: src/PhpSpreadsheet/Calculation/FormulaParser.php + + - + message: "#^Cannot call method setTokenSubType\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\FormulaToken\\|null\\.$#" + count: 5 + path: src/PhpSpreadsheet/Calculation/FormulaParser.php + + - + message: "#^Cannot call method getTokenType\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\FormulaToken\\|null\\.$#" + count: 9 + path: src/PhpSpreadsheet/Calculation/FormulaParser.php + + - + message: "#^Strict comparison using \\=\\=\\= between PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\FormulaToken and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/FormulaParser.php + + - + message: "#^Cannot call method getTokenSubType\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\FormulaToken\\|null\\.$#" + count: 4 + path: src/PhpSpreadsheet/Calculation/FormulaParser.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Functions\\:\\:isMatrixValue\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Functions\\:\\:isMatrixValue\\(\\) has parameter \\$idx with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Functions\\:\\:isValue\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Functions\\:\\:isValue\\(\\) has parameter \\$idx with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Functions\\:\\:isCellValue\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Functions\\:\\:isCellValue\\(\\) has parameter \\$idx with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Functions\\:\\:ifCondition\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Functions\\:\\:ifCondition\\(\\) has parameter \\$condition with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Functions\\:\\:operandSpecialHandling\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Functions\\:\\:operandSpecialHandling\\(\\) has parameter \\$operand with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Cannot call method getCell\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Internal\\\\MakeMatrix\\:\\:make\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Internal/MakeMatrix.php + + - + message: "#^Call to function is_string\\(\\) with null will always evaluate to false\\.$#" + count: 3 + path: src/PhpSpreadsheet/Calculation/Logical/Operations.php + + - + message: "#^Result of && is always false\\.$#" + count: 3 + path: src/PhpSpreadsheet/Calculation/Logical/Operations.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\:\\:OFFSET\\(\\) should return array\\|string but returns array\\|int\\|string\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\:\\:CHOOSE\\(\\) has parameter \\$chooseArgs with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Address\\:\\:sheetName\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Address.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:matchFirstValue\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:matchFirstValue\\(\\) has parameter \\$lookupArray with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:matchFirstValue\\(\\) has parameter \\$lookupValue with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:matchLargestValue\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:matchLargestValue\\(\\) has parameter \\$keySet with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:matchLargestValue\\(\\) has parameter \\$lookupArray with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:matchLargestValue\\(\\) has parameter \\$lookupValue with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:matchSmallestValue\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:matchSmallestValue\\(\\) has parameter \\$lookupArray with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:matchSmallestValue\\(\\) has parameter \\$lookupValue with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:validateLookupValue\\(\\) has parameter \\$lookupValue with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:validateMatchType\\(\\) has parameter \\$matchType with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:validateLookupArray\\(\\) has parameter \\$lookupArray with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:prepareLookupArray\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:prepareLookupArray\\(\\) has parameter \\$lookupArray with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:prepareLookupArray\\(\\) has parameter \\$matchType with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Lookup\\:\\:verifyResultVector\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Lookup.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Lookup\\:\\:verifyResultVector\\(\\) has parameter \\$resultVector with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Lookup.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\LookupBase\\:\\:validateIndexLookup\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/LookupBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\LookupBase\\:\\:validateIndexLookup\\(\\) has parameter \\$index_number with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/LookupBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\LookupBase\\:\\:validateIndexLookup\\(\\) has parameter \\$lookup_array with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/LookupBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\LookupBase\\:\\:checkMatch\\(\\) has parameter \\$notExactMatch with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/LookupBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Matrix\\:\\:extractRowValue\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Offset\\:\\:extractRequiredCells\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Offset.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Offset\\:\\:extractWorksheet\\(\\) has parameter \\$cellAddress with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Offset.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Offset\\:\\:adjustEndCellColumnForWidth\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Offset.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Offset\\:\\:adjustEndCellColumnForWidth\\(\\) has parameter \\$columns with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Offset.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Offset\\:\\:adjustEndCellColumnForWidth\\(\\) has parameter \\$width with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Offset.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Offset\\:\\:adustEndCellRowForHeight\\(\\) has parameter \\$endCellRow with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Offset.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Offset\\:\\:adustEndCellRowForHeight\\(\\) has parameter \\$height with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Offset.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Offset\\:\\:adustEndCellRowForHeight\\(\\) has parameter \\$rows with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Offset.php + + - + message: "#^Parameter \\#1 \\$columnAddress of static method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Coordinate\\:\\:columnIndexFromString\\(\\) expects string, string\\|null given\\.$#" + count: 3 + path: src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php + + - + message: "#^Parameter \\#1 \\$low of function range expects float\\|int\\|string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php + + - + message: "#^Parameter \\#2 \\$high of function range expects float\\|int\\|string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php + + - + message: "#^Parameter \\#2 \\$cmp_function of function uasort expects callable\\(mixed, mixed\\)\\: int, array\\('self', 'vlookupSort'\\) given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\VLookup\\:\\:vlookupSort\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\VLookup\\:\\:vlookupSort\\(\\) has parameter \\$a with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\VLookup\\:\\:vlookupSort\\(\\) has parameter \\$b with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\VLookup\\:\\:vLookupSearch\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\VLookup\\:\\:vLookupSearch\\(\\) has parameter \\$column with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\VLookup\\:\\:vLookupSearch\\(\\) has parameter \\$lookupArray with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\VLookup\\:\\:vLookupSearch\\(\\) has parameter \\$lookupValue with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\VLookup\\:\\:vLookupSearch\\(\\) has parameter \\$notExactMatch with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\:\\:MAXIFS\\(\\) should return float but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\:\\:MINIFS\\(\\) should return float but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Averages\\:\\:filterArguments\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Averages.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Averages\\:\\:filterArguments\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Averages.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Averages\\:\\:modeCalc\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Averages.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Averages\\:\\:modeCalc\\(\\) has parameter \\$data with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Averages.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Percentiles\\:\\:percentileFilterValues\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Percentiles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Percentiles\\:\\:rankFilterValues\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Percentiles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Trends\\:\\:checkTrendArrays\\(\\) has parameter \\$array1 with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Trends.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Trends\\:\\:checkTrendArrays\\(\\) has parameter \\$array2 with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Trends.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Trends\\:\\:GROWTH\\(\\) should return array\\ but returns array\\\\>\\>\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Trends.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Trends\\:\\:TREND\\(\\) should return array\\ but returns array\\\\>\\>\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Trends.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Conditional\\:\\:SUMIF\\(\\) should return float\\|string but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Conditional.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Conditional\\:\\:buildConditionSet\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Conditional.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Conditional\\:\\:buildConditionSetForValueRange\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Conditional.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Conditional\\:\\:buildConditions\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Conditional.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Conditional\\:\\:buildDatabase\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Conditional.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Conditional\\:\\:buildDatabaseWithValueRange\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Conditional.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Conditional\\:\\:buildDataSet\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Conditional.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\Beta\\:\\:\\$logBetaCacheP has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/Beta.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\Beta\\:\\:\\$logBetaCacheQ has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/Beta.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\Beta\\:\\:\\$logBetaCacheResult has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/Beta.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:pchisq\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:pchisq\\(\\) has parameter \\$chi2 with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:pchisq\\(\\) has parameter \\$degrees with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:gammp\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:gammp\\(\\) has parameter \\$n with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:gammp\\(\\) has parameter \\$x with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:gser\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:gser\\(\\) has parameter \\$n with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:gser\\(\\) has parameter \\$x with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:gcf\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:gcf\\(\\) has parameter \\$n with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:gcf\\(\\) has parameter \\$x with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\Normal\\:\\:inverseNcdf\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/Normal.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\Normal\\:\\:inverseNcdf\\(\\) has parameter \\$p with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/Normal.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\GammaBase\\:\\:calculateDistribution\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\GammaBase\\:\\:calculateInverse\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\GammaBase\\:\\:\\$logGammaCacheResult has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\GammaBase\\:\\:\\$logGammaCacheX has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\GammaBase\\:\\:logGamma1\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\GammaBase\\:\\:logGamma2\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\GammaBase\\:\\:logGamma3\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\GammaBase\\:\\:logGamma4\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\NewtonRaphson\\:\\:\\$callback has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/NewtonRaphson.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\NewtonRaphson\\:\\:execute\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/NewtonRaphson.php + + - + message: "#^Binary operation \"\\-\" between float\\|string and float\\|int\\|\\(string&numeric\\) results in an error\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/StandardNormal.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\MaxMinBase\\:\\:datatypeAdjustmentAllowStrings\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\MaxMinBase\\:\\:datatypeAdjustmentAllowStrings\\(\\) has parameter \\$value with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\VarianceBase\\:\\:datatypeAdjustmentAllowStrings\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\VarianceBase\\:\\:datatypeAdjustmentAllowStrings\\(\\) has parameter \\$value with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\VarianceBase\\:\\:datatypeAdjustmentBooleans\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\VarianceBase\\:\\:datatypeAdjustmentBooleans\\(\\) has parameter \\$value with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\TextData\\:\\:TRIMNONPRINTABLE\\(\\) should return string but returns string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/TextData.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\TextData\\:\\:CONCATENATE\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/TextData.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\TextData\\:\\:SEARCHSENSITIVE\\(\\) should return string but returns int\\|string\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/TextData.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\TextData\\:\\:SEARCHINSENSITIVE\\(\\) should return string but returns int\\|string\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/TextData.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Token\\\\Stack\\:\\:getStackItem\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Token/Stack.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Token\\\\Stack\\:\\:getStackItem\\(\\) has parameter \\$onlyIf with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Token/Stack.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Token\\\\Stack\\:\\:getStackItem\\(\\) has parameter \\$onlyIfNot with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Token/Stack.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Token\\\\Stack\\:\\:getStackItem\\(\\) has parameter \\$reference with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Token/Stack.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Token\\\\Stack\\:\\:getStackItem\\(\\) has parameter \\$storeKey with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Token/Stack.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Token\\\\Stack\\:\\:getStackItem\\(\\) has parameter \\$type with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Token/Stack.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Token\\\\Stack\\:\\:getStackItem\\(\\) has parameter \\$value with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Token/Stack.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\:\\:\\$formulaAttributes has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Cell/Cell.php + + - + message: "#^Elseif branch is unreachable because previous condition is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Cell/Cell.php + + - + message: "#^Parameter \\#2 \\$format of static method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\:\\:toFormattedString\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Cell/Cell.php + + - + message: "#^Unreachable statement \\- code above always terminates\\.$#" + count: 1 + path: src/PhpSpreadsheet/Cell/Cell.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\:\\:getFormulaAttributes\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Cell/Cell.php + + - + message: "#^Parameter \\#2 \\$str of function explode expects string, array\\\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Cell/Coordinate.php + + - + message: "#^Parameter \\#4 \\$currentRow of static method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Coordinate\\:\\:validateRange\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Cell/Coordinate.php + + - + message: "#^Parameter \\#5 \\$endRow of static method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Coordinate\\:\\:validateRange\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Cell/Coordinate.php + + - + message: "#^Call to an undefined method object\\:\\:getHashCode\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Cell/Coordinate.php + + - + message: "#^Parameter \\#1 \\$input of function array_chunk expects array, array\\\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Cell/Coordinate.php + + - + message: "#^Parameter \\#1 \\$textValue of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:substring\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Cell/DataType.php + + - + message: "#^Parameter \\#2 \\$alpha of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis\\:\\:setShadowColor\\(\\) expects int, int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Axis.php + + - + message: "#^Parameter \\#1 \\$blur of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis\\:\\:setShadowBlur\\(\\) expects float, float\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Axis.php + + - + message: "#^Parameter \\#1 \\$angle of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis\\:\\:setShadowAngle\\(\\) expects int, int\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Axis.php + + - + message: "#^Parameter \\#1 \\$distance of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis\\:\\:setShadowDistance\\(\\) expects float, float\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Axis.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:\\$title \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Title\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Title\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:\\$legend \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Legend\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Legend\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:\\$xAxisLabel \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Title\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Title\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:\\$yAxisLabel \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Title\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Title\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:\\$plotArea \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\PlotArea\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\PlotArea\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:\\$xAxis \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:\\$yAxis \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:\\$majorGridlines \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:\\$minorGridlines \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:\\$worksheet \\(PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:setTopLeftXOffset\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:setTopLeftXOffset\\(\\) has parameter \\$xOffset with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:getTopLeftXOffset\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:setTopLeftYOffset\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:setTopLeftYOffset\\(\\) has parameter \\$yOffset with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:getTopLeftYOffset\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:setBottomRightCell\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:setBottomRightCell\\(\\) has parameter \\$cell with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:setBottomRightXOffset\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:setBottomRightXOffset\\(\\) has parameter \\$xOffset with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:getBottomRightXOffset\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:setBottomRightYOffset\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:setBottomRightYOffset\\(\\) has parameter \\$yOffset with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:getBottomRightYOffset\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Strict comparison using \\=\\=\\= between PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues and null will always evaluate to false\\.$#" + count: 2 + path: src/PhpSpreadsheet/Chart/DataSeries.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues\\:\\:\\$dataTypeValues has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/DataSeriesValues.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues\\:\\:\\$dataSource \\(string\\) does not accept string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/DataSeriesValues.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues\\:\\:\\$fillColor \\(array\\\\|string\\) does not accept array\\\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/DataSeriesValues.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues\\:\\:refresh\\(\\) has parameter \\$flatten with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/DataSeriesValues.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:\\$objectState has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/GridLines.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:\\$lineProperties has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/GridLines.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:\\$shadowProperties has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/GridLines.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:\\$glowProperties has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/GridLines.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:\\$softEdges has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/GridLines.php + + - + message: "#^Parameter \\#1 \\$color of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:setGlowColor\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/GridLines.php + + - + message: "#^Parameter \\#2 \\$alpha of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:setGlowColor\\(\\) expects int, int\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/GridLines.php + + - + message: "#^Parameter \\#3 \\$colorType of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:setGlowColor\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/GridLines.php + + - + message: "#^Parameter \\#1 \\$angle of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:setShadowAngle\\(\\) expects int, int\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/GridLines.php + + - + message: "#^Parameter \\#1 \\$distance of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:setShadowDistance\\(\\) expects float, float\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/GridLines.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Legend\\:\\:\\$positionXLref has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Legend.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Legend\\:\\:\\$layout \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Layout\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Layout\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Legend.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\PlotArea\\:\\:\\$layout \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Layout\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Layout\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/PlotArea.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getTrueAlpha\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getTrueAlpha\\(\\) has parameter \\$alpha with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:setColorProperties\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:setColorProperties\\(\\) has parameter \\$alpha with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:setColorProperties\\(\\) has parameter \\$color with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:setColorProperties\\(\\) has parameter \\$colorType with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getLineStyleArrowSize\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getLineStyleArrowSize\\(\\) has parameter \\$arrayKaySelector with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getLineStyleArrowSize\\(\\) has parameter \\$arraySelector with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getShadowPresetsMap\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getShadowPresetsMap\\(\\) has parameter \\$presetsOption with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getArrayElementsValue\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getArrayElementsValue\\(\\) has parameter \\$elements with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getArrayElementsValue\\(\\) has parameter \\$properties with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:\\$width has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:\\$height has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:\\$colourSet has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:\\$markSet has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:\\$chart has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:\\$graph has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:\\$plotColour has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:\\$plotMark has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:formatPointMarker\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:formatPointMarker\\(\\) has parameter \\$markerID with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:formatPointMarker\\(\\) has parameter \\$seriesPlot with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:formatDataSetLabels\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:formatDataSetLabels\\(\\) has parameter \\$datasetLabels with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:formatDataSetLabels\\(\\) has parameter \\$groupID with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:formatDataSetLabels\\(\\) has parameter \\$labelCount with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:formatDataSetLabels\\(\\) has parameter \\$rotation with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:percentageSumCalculation\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:percentageSumCalculation\\(\\) has parameter \\$groupID with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:percentageSumCalculation\\(\\) has parameter \\$seriesCount with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:percentageAdjustValues\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:percentageAdjustValues\\(\\) has parameter \\$dataValues with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:percentageAdjustValues\\(\\) has parameter \\$sumValues with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:getCaption\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:getCaption\\(\\) has parameter \\$captionElement with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderCartesianPlotArea\\(\\) has parameter \\$type with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotLine\\(\\) has parameter \\$combination with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotLine\\(\\) has parameter \\$dimensions with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotLine\\(\\) has parameter \\$filled with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotLine\\(\\) has parameter \\$groupID with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotBar\\(\\) has parameter \\$dimensions with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotBar\\(\\) has parameter \\$groupID with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotScatter\\(\\) has parameter \\$bubble with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotScatter\\(\\) has parameter \\$groupID with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotRadar\\(\\) has parameter \\$groupID with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotContour\\(\\) has parameter \\$groupID with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotStock\\(\\) has parameter \\$groupID with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderAreaChart\\(\\) has parameter \\$dimensions with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderAreaChart\\(\\) has parameter \\$groupCount with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderLineChart\\(\\) has parameter \\$dimensions with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderLineChart\\(\\) has parameter \\$groupCount with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderBarChart\\(\\) has parameter \\$dimensions with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderBarChart\\(\\) has parameter \\$groupCount with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderScatterChart\\(\\) has parameter \\$groupCount with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderBubbleChart\\(\\) has parameter \\$groupCount with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPieChart\\(\\) has parameter \\$dimensions with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPieChart\\(\\) has parameter \\$doughnut with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPieChart\\(\\) has parameter \\$groupCount with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPieChart\\(\\) has parameter \\$multiplePlots with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderRadarChart\\(\\) has parameter \\$groupCount with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderStockChart\\(\\) has parameter \\$groupCount with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderContourChart\\(\\) has parameter \\$dimensions with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderContourChart\\(\\) has parameter \\$groupCount with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderCombinationChart\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderCombinationChart\\(\\) has parameter \\$dimensions with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderCombinationChart\\(\\) has parameter \\$groupCount with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderCombinationChart\\(\\) has parameter \\$outputDestination with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Title\\:\\:\\$layout \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Layout\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Layout\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Title.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Collection\\\\Cells\\:\\:getParent\\(\\) should return PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet but returns PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Collection/Cells.php + + - + message: "#^Parameter \\#1 \\$string of function substr expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Collection/Cells.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Collection\\\\Cells\\:\\:getCurrentCoordinate\\(\\) should return string but returns string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Collection/Cells.php + + - + message: "#^Parameter \\#1 \\$str of function sscanf expects string, string\\|null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Collection/Cells.php + + - + message: "#^Parameter \\#1 \\$columnIndex of static method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Coordinate\\:\\:stringFromColumnIndex\\(\\) expects int, int\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Collection/Cells.php + + - + message: "#^Possibly invalid array key type \\(array\\|string\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Collection/Cells.php + + - + message: "#^Cannot call method detach\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Collection/Cells.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Collection\\\\Memory\\:\\:\\$cache has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Collection/Memory.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\DefinedName\\:\\:\\$worksheet \\(PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/DefinedName.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\DefinedName\\:\\:\\$scope \\(PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 3 + path: src/PhpSpreadsheet/DefinedName.php + + - + message: "#^Parameter \\#1 \\$namedRange of method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\:\\:addNamedRange\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\NamedRange, \\$this\\(PhpOffice\\\\PhpSpreadsheet\\\\DefinedName\\) given\\.$#" + count: 1 + path: src/PhpSpreadsheet/DefinedName.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$colourMap has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$face has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$size has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$color has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$bold has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$italic has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$underline has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$superscript has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$subscript has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$strikethrough has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$startTagCallbacks has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$endTagCallbacks has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$stack has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$stringData has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Parameter \\#1 \\$text of method PhpOffice\\\\PhpSpreadsheet\\\\RichText\\\\ITextElement\\:\\:setText\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Cannot call method setName\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Cannot call method setSize\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Cannot call method setColor\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Cannot call method setBold\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Cannot call method setItalic\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Cannot call method setUnderline\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Cannot call method setSuperscript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Cannot call method setSubscript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Cannot call method setStrikethrough\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:startFontTag\\(\\) has parameter \\$tag with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Parameter \\#1 \\$function of function call_user_func expects callable\\(\\)\\: mixed, array\\(\\$this\\(PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\), mixed\\) given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Parameter \\#1 \\$directory of class RecursiveDirectoryIterator constructor expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Sample.php + + - + message: "#^Parameter \\#3 \\$subject of function str_replace expects array\\|string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Sample.php + + - + message: "#^Parameter \\#1 \\$path of function pathinfo expects string, array\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Sample.php + + - + message: "#^Parameter \\#3 \\$subject of function str_replace expects array\\|string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Sample.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Sample\\:\\:getSamples\\(\\) should return array\\\\> but returns array\\\\>\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Sample.php + + - + message: "#^Parameter \\#1 \\$filename of function unlink expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Sample.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Sample\\:\\:log\\(\\) has parameter \\$message with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Sample.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\IOFactory\\:\\:\\$readers has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/IOFactory.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\IOFactory\\:\\:\\$writers has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/IOFactory.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\BaseReader\\:\\:\\$fileHandle has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/BaseReader.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\BaseReader\\:\\:getSecurityScanner\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/BaseReader.php + + - + message: "#^Cannot call method getNamespaces\\(\\) on SimpleXMLElement\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^Cannot call method children\\(\\) on SimpleXMLElement\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\:\\:listWorksheetNames\\(\\) should return array\\ but returns array\\\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^Cannot call method getElementsByTagNameNS\\(\\) on DOMElement\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^Parameter \\#1 \\$element of method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\:\\:scanElementForText\\(\\) expects DOMNode, DOMElement\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^Cannot call method getAttributeNS\\(\\) on DOMElement\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^Parameter \\#1 \\$settings of method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\:\\:lookForActiveSheet\\(\\) expects DOMElement, DOMElement\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^Parameter \\#1 \\$settings of method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\:\\:lookForSelectedCells\\(\\) expects DOMElement, DOMElement\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^Cannot call method setSelectedCellByColumnAndRow\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^Cannot call method getNamedItem\\(\\) on DOMNamedNodeMap\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^If condition is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\PageSettings\\:\\:\\$officeNs has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/PageSettings.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\PageSettings\\:\\:\\$stylesNs has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/PageSettings.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\PageSettings\\:\\:\\$stylesFo has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/PageSettings.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\PageSettings\\:\\:\\$pageLayoutStyles has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/PageSettings.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\PageSettings\\:\\:\\$masterStylesCrossReference has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/PageSettings.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\PageSettings\\:\\:\\$masterPrintStylesCrossReference has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/PageSettings.php + + - + message: "#^Cannot call method getElementsByTagNameNS\\(\\) on DOMElement\\|null\\.$#" + count: 3 + path: src/PhpSpreadsheet/Reader/Ods/PageSettings.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\Properties\\:\\:\\$spreadsheet has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\Properties\\:\\:load\\(\\) has parameter \\$namespacesMeta with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\Properties\\:\\:setMetaProperties\\(\\) has parameter \\$namespacesMeta with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\Properties\\:\\:setMetaProperties\\(\\) has parameter \\$propertyName with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\Properties\\:\\:setUserDefinedProperty\\(\\) has parameter \\$propertyValue with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\Properties\\:\\:setUserDefinedProperty\\(\\) has parameter \\$propertyValueAttributes with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/Properties.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Security\\\\XmlScanner\\:\\:\\$callback has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Security/XmlScanner.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Security\\\\XmlScanner\\:\\:\\$libxmlDisableEntityLoaderValue has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Security/XmlScanner.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Security\\\\XmlScanner\\:\\:__construct\\(\\) has parameter \\$pattern with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Security/XmlScanner.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Security\\\\XmlScanner\\:\\:getInstance\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Security/XmlScanner.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Security\\\\XmlScanner\\:\\:threadSafeLibxmlDisableEntityLoaderAvailability\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Security/XmlScanner.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Security\\\\XmlScanner\\:\\:toUtf8\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Security/XmlScanner.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Security\\\\XmlScanner\\:\\:toUtf8\\(\\) has parameter \\$xml with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Security/XmlScanner.php + + - + message: "#^Parameter \\#2 \\$subject of function preg_match expects string, array\\\\|string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Security/XmlScanner.php + + - + message: "#^Call to an undefined method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\\\SpgrContainer\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\\\SpgrContainer\\\\SpContainer\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DggContainer\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DggContainer\\\\BstoreContainer\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DggContainer\\\\BstoreContainer\\\\BSE\\:\\:getDgContainer\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Call to an undefined method object\\:\\:getNestingLevel\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Call to an undefined method object\\:\\:getStartCoordinates\\(\\)\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Call to an undefined method object\\:\\:getEndCoordinates\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Call to an undefined method object\\:\\:getStartOffsetX\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Call to an undefined method object\\:\\:getStartOffsetY\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Call to an undefined method object\\:\\:getEndOffsetX\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Call to an undefined method object\\:\\:getEndOffsetY\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Parameter \\#2 \\$startRow of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Xls\\:\\:getDistanceY\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Parameter \\#4 \\$endRow of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Xls\\:\\:getDistanceY\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Parameter \\#2 \\$row of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Xls\\:\\:sizeRow\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Call to an undefined method object\\:\\:getOPT\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Call to an undefined method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\\\SpgrContainer\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\\\SpgrContainer\\\\SpContainer\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DggContainer\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DggContainer\\\\BstoreContainer\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DggContainer\\\\BstoreContainer\\\\BSE\\:\\:getDggContainer\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^If condition is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Parameter \\#2 \\$row of method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\IReadFilter\\:\\:readCell\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Negated boolean expression is always false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Parameter \\#1 \\$block of method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\:\\:makeKey\\(\\) expects int, float given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\:\\:\\$data \\(string\\) does not accept string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\:\\:\\$summaryInformation \\(string\\) does not accept string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\:\\:\\$documentSummaryInformation \\(string\\) does not accept string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Parameter \\#3 \\$subject of function str_replace expects array\\|string, int\\|string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Parameter \\#1 \\$pValue of method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\:\\:setShowSummaryBelow\\(\\) expects bool, int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Parameter \\#1 \\$pValue of method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\:\\:setShowSummaryRight\\(\\) expects bool, int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\:\\:includeCellRangeFiltered\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\:\\:includeCellRangeFiltered\\(\\) has parameter \\$cellRangeAddress with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Parameter \\#1 \\$type of method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\DataValidation\\:\\:setType\\(\\) expects string, int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Parameter \\#1 \\$errorStyle of method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\DataValidation\\:\\:setErrorStyle\\(\\) expects string, int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Parameter \\#1 \\$operator of method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\DataValidation\\:\\:setOperator\\(\\) expects string, int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Unreachable statement \\- code above always terminates\\.$#" + count: 8 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Cannot access offset 1 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\:\\:parseRichText\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\:\\:parseRichText\\(\\) has parameter \\$is with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\Color\\\\BIFF5\\:\\:\\$map has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/Color/BIFF5.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\Color\\\\BIFF8\\:\\:\\$map has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/Color/BIFF8.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\Color\\\\BuiltIn\\:\\:\\$map has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/Color/BuiltIn.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\ErrorCode\\:\\:\\$map has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/ErrorCode.php + + - + message: "#^Parameter \\#1 \\$input of function array_values expects array, array\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/MD5.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\MD5\\:\\:f\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/MD5.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\MD5\\:\\:g\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/MD5.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\MD5\\:\\:h\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/MD5.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\MD5\\:\\:i\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/MD5.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\MD5\\:\\:step\\(\\) has parameter \\$func with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/MD5.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\MD5\\:\\:rotate\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/MD5.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\RC4\\:\\:\\$s has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/RC4.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\RC4\\:\\:\\$i has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/RC4.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\RC4\\:\\:\\$j has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/RC4.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToBoolean\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToBoolean\\(\\) has parameter \\$c with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToError\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToError\\(\\) has parameter \\$c with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToString\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToString\\(\\) has parameter \\$c with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToFormula\\(\\) has parameter \\$c with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToFormula\\(\\) has parameter \\$calculatedValue with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToFormula\\(\\) has parameter \\$castBaseType with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToFormula\\(\\) has parameter \\$cellDataType with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToFormula\\(\\) has parameter \\$r with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToFormula\\(\\) has parameter \\$sharedFormulas with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToFormula\\(\\) has parameter \\$value with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:getFromZipArchive\\(\\) should return string but returns string\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Negated boolean expression is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Argument of an invalid type array\\\\|false supplied for foreach, only iterables are supported\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Parameter \\#1 \\$worksheetName of method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\:\\:getSheetByName\\(\\) expects string, array\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot access offset 0 on array\\\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot call method addChart\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot access property \\$r on SimpleXMLElement\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot call method setName\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot call method setSize\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot call method setColor\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot call method setBold\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot call method setItalic\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot call method setSuperscript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot call method setSubscript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot call method setUnderline\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot call method setStrikethrough\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:getArrayItem\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:getArrayItem\\(\\) has parameter \\$array with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:getArrayItem\\(\\) has parameter \\$key with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:dirAdd\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:dirAdd\\(\\) has parameter \\$add with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:dirAdd\\(\\) has parameter \\$base with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:toCSSArray\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:toCSSArray\\(\\) has parameter \\$style with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Parameter \\#1 \\$fontSizeInPoints of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Font\\:\\:fontSizeToPixels\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Parameter \\#1 \\$haystack of function strpos expects string, int\\|string given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Parameter \\#3 \\$subject of function str_replace expects array\\|string, int\\|string given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Parameter \\#1 \\$sizeInInch of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Font\\:\\:inchSizeToPixels\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Parameter \\#1 \\$sizeInCm of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Font\\:\\:centimeterSizeToPixels\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:stripWhiteSpaceFromStyleString\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:stripWhiteSpaceFromStyleString\\(\\) has parameter \\$string with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:boolean\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:boolean\\(\\) has parameter \\$value with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:readFormControlProperties\\(\\) has parameter \\$dir with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:readFormControlProperties\\(\\) has parameter \\$docSheet with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:readFormControlProperties\\(\\) has parameter \\$fileWorksheet with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:readPrinterSettings\\(\\) has parameter \\$dir with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:readPrinterSettings\\(\\) has parameter \\$docSheet with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:readPrinterSettings\\(\\) has parameter \\$fileWorksheet with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\AutoFilter\\:\\:\\$worksheet has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\AutoFilter\\:\\:\\$worksheetXml has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\AutoFilter\\:\\:readAutoFilter\\(\\) has parameter \\$autoFilterRange with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\AutoFilter\\:\\:readAutoFilter\\(\\) has parameter \\$xmlSheet with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php + + - + message: "#^Parameter \\#1 \\$pOperator of method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\AutoFilter\\\\Column\\\\Rule\\:\\:setRule\\(\\) expects string, null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\BaseParserClass\\:\\:boolean\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/BaseParserClass.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\BaseParserClass\\:\\:boolean\\(\\) has parameter \\$value with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/BaseParserClass.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:readColor\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:readColor\\(\\) has parameter \\$background with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:readColor\\(\\) has parameter \\$color with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Parameter \\#1 \\$position of class PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Legend constructor expects string, bool\\|float\\|int\\|string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Parameter \\#3 \\$overlay of class PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Legend constructor expects bool, bool\\|float\\|int\\|string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Parameter \\#6 \\$displayBlanksAs of class PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart constructor expects string, bool\\|float\\|int\\|string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartTitle\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartLayoutDetails\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartLayoutDetails\\(\\) has parameter \\$chartDetail with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartLayoutDetails\\(\\) has parameter \\$namespacesChartMeta with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeries\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeries\\(\\) has parameter \\$chartDetail with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeries\\(\\) has parameter \\$namespacesChartMeta with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeries\\(\\) has parameter \\$plotType with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Parameter \\#3 \\$plotOrder of class PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeries constructor expects array\\, array\\ given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Parameter \\#7 \\$plotDirection of class PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeries constructor expects string\\|null, bool\\|float\\|int\\|string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeriesValueSet\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeriesValueSet\\(\\) has parameter \\$marker with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeriesValueSet\\(\\) has parameter \\$namespacesChartMeta with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeriesValueSet\\(\\) has parameter \\$seriesDetail with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Parameter \\#4 \\$pointCount of class PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues constructor expects int, null given\\.$#" + count: 4 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeriesValues\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeriesValues\\(\\) has parameter \\$dataType with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeriesValues\\(\\) has parameter \\$seriesValueSet with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeriesValuesMultiLevel\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeriesValuesMultiLevel\\(\\) has parameter \\$dataType with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeriesValuesMultiLevel\\(\\) has parameter \\$seriesValueSet with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:parseRichText\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Cannot call method getFont\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\RichText\\\\Run\\|null\\.$#" + count: 12 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Cannot call method setName\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Cannot call method setSize\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Cannot call method setColor\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Cannot call method setBold\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Cannot call method setItalic\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Cannot call method setSuperscript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Cannot call method setSubscript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Cannot call method setUnderline\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 3 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Cannot call method setStrikethrough\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:readChartAttributes\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:readChartAttributes\\(\\) has parameter \\$chartDetail with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:\\$worksheet has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:\\$worksheetXml has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:isFilteredColumn\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:isFilteredColumn\\(\\) has parameter \\$columnCoordinate with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:readColumnAttributes\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:readColumnAttributes\\(\\) has parameter \\$readDataOnly with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:readColumnRangeAttributes\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:readColumnRangeAttributes\\(\\) has parameter \\$readDataOnly with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:isFilteredRow\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:isFilteredRow\\(\\) has parameter \\$rowCoordinate with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:readRowAttributes\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:readRowAttributes\\(\\) has parameter \\$readDataOnly with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:\\$worksheet has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:\\$worksheetXml has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:\\$dxfs has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:readConditionalStyles\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:readConditionalStyles\\(\\) has parameter \\$xmlSheet with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:setConditionalStyles\\(\\) has parameter \\$xmlExtLst with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:readStyleRules\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:readStyleRules\\(\\) has parameter \\$cfRules with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:readStyleRules\\(\\) has parameter \\$extLst with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:readDataBarOfConditionalRule\\(\\) has parameter \\$cfRule with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:readDataBarOfConditionalRule\\(\\) has parameter \\$conditionalFormattingRuleExtensions with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:readDataBarExtLstOfConditionalRule\\(\\) has parameter \\$cfRule with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:readDataBarExtLstOfConditionalRule\\(\\) has parameter \\$conditionalFormattingRuleExtensions with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\DataValidations\\:\\:\\$worksheet has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\DataValidations\\:\\:\\$worksheetXml has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Hyperlinks\\:\\:\\$worksheet has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Hyperlinks\\:\\:\\$hyperlinks has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\PageSetup\\:\\:\\$worksheet has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/PageSetup.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\PageSetup\\:\\:\\$worksheetXml has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/PageSetup.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\PageSetup\\:\\:load\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/PageSetup.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\PageSetup\\:\\:pageSetup\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/PageSetup.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\SheetViewOptions\\:\\:\\$worksheet has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/SheetViewOptions.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\SheetViewOptions\\:\\:\\$worksheetXml has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/SheetViewOptions.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Styles\\:\\:\\$styles has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Styles\\:\\:\\$cellStyles has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Styles\\:\\:\\$styleXml has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Styles\\:\\:setStyleBaseData\\(\\) has parameter \\$cellStyles with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Styles\\:\\:setStyleBaseData\\(\\) has parameter \\$styles with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php + + - + message: "#^Static property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Styles\\:\\:\\$theme \\(PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Theme\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Theme\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Styles\\:\\:readStyle\\(\\) has parameter \\$style with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php + + - + message: "#^Parameter \\#2 \\$alignmentXml of static method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Styles\\:\\:readAlignmentStyle\\(\\) expects SimpleXMLElement, object given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Styles\\:\\:readProtectionLocked\\(\\) has parameter \\$style with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Styles\\:\\:readProtectionHidden\\(\\) has parameter \\$style with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Styles\\:\\:readColor\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Styles\\:\\:readColor\\(\\) has parameter \\$background with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Styles\\:\\:readColor\\(\\) has parameter \\$color with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php + + - + message: "#^Parameter \\#1 \\$hexColourValue of static method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Color\\:\\:changeBrightness\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Styles\\:\\:dxfs\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Styles\\:\\:dxfs\\(\\) has parameter \\$readDataOnly with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Styles\\:\\:styles\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Styles\\:\\:getArrayItem\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Styles\\:\\:getArrayItem\\(\\) has parameter \\$array with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Styles\\:\\:getArrayItem\\(\\) has parameter \\$key with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Styles.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xml\\:\\:\\$fileContents has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xml.php + + - + message: "#^Parameter \\#1 \\$haystack of function strpos expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xml.php + + - + message: "#^Parameter \\#2 \\$subject of function preg_match expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xml.php + + - + message: "#^Parameter \\#1 \\$textValue of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:convertEncoding\\(\\) expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xml.php + + - + message: "#^Parameter \\#2 \\$cmp_function of function uksort expects callable\\(\\(int\\|string\\), \\(int\\|string\\)\\)\\: int, array\\('self', 'cellReverseSort'\\) given\\.$#" + count: 4 + path: src/PhpSpreadsheet/ReferenceHelper.php + + - + message: "#^Parameter \\#2 \\$cmp_function of function uksort expects callable\\(\\(int\\|string\\), \\(int\\|string\\)\\)\\: int, array\\('self', 'cellSort'\\) given\\.$#" + count: 4 + path: src/PhpSpreadsheet/ReferenceHelper.php + + - + message: "#^Parameter \\#1 \\$index of method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\RowDimension\\:\\:setRowIndex\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/ReferenceHelper.php + + - + message: "#^Parameter \\#3 \\$subject of function str_replace expects array\\|string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/ReferenceHelper.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\RichText\\\\Run\\:\\:\\$font \\(PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/RichText/Run.php + + - + message: "#^Result of && is always false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Settings.php + + - + message: "#^Strict comparison using \\=\\=\\= between int and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Settings.php + + - + message: "#^Negated boolean expression is always false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Settings.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Settings\\:\\:getHttpClient\\(\\) should return Psr\\\\Http\\\\Client\\\\ClientInterface but returns Psr\\\\Http\\\\Client\\\\ClientInterface\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Settings.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Settings\\:\\:getRequestFactory\\(\\) should return Psr\\\\Http\\\\Message\\\\RequestFactoryInterface but returns Psr\\\\Http\\\\Message\\\\RequestFactoryInterface\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Settings.php + + - + message: "#^Parameter \\#1 \\$unixTimestamp of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Date\\:\\:timestampToExcel\\(\\) expects int, float\\|int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Date.php + + - + message: "#^Parameter \\#1 \\$string of function substr expects string, int given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Shared/Date.php + + - + message: "#^Parameter \\#1 \\$excelFormatCode of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Date\\:\\:isDateTimeFormatCode\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Date.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Date\\:\\:\\$possibleDateFormatCharacters has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Date.php + + - + message: "#^Parameter \\#1 \\$fp of function fread expects resource, resource\\|false given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Shared/Drawing.php + + - + message: "#^Parameter \\#1 \\$fp of function feof expects resource, resource\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Drawing.php + + - + message: "#^Parameter \\#2 \\$data of function unpack expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Drawing.php + + - + message: "#^Cannot access offset 1 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Drawing.php + + - + message: "#^Parameter \\#1 \\$x_size of function imagecreatetruecolor expects int, float\\|int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Drawing.php + + - + message: "#^Parameter \\#2 \\$y_size of function imagecreatetruecolor expects int, float\\|int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Drawing.php + + - + message: "#^Parameter \\#1 \\$im of function imagecolorallocate expects resource, resource\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Drawing.php + + - + message: "#^Parameter \\#2 \\$red of function imagecolorallocate expects int, float\\|int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Drawing.php + + - + message: "#^Parameter \\#3 \\$green of function imagecolorallocate expects int, float\\|int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Drawing.php + + - + message: "#^Parameter \\#4 \\$blue of function imagecolorallocate expects int, float\\|int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Drawing.php + + - + message: "#^Parameter \\#1 \\$im of function imagesetpixel expects resource, resource\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Drawing.php + + - + message: "#^Parameter \\#3 \\$y of function imagesetpixel expects int, float\\|int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Drawing.php + + - + message: "#^Parameter \\#4 \\$col of function imagesetpixel expects int, int\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Drawing.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Drawing\\:\\:imagecreatefrombmp\\(\\) should return GdImage\\|resource but returns resource\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Drawing.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\:\\:\\$spgrContainer has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Escher/DgContainer.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\:\\:getDgId\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Escher/DgContainer.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\:\\:setDgId\\(\\) has parameter \\$value with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Escher/DgContainer.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\:\\:getLastSpId\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Escher/DgContainer.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\:\\:setLastSpId\\(\\) has parameter \\$value with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Escher/DgContainer.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\:\\:getSpgrContainer\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Escher/DgContainer.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\:\\:setSpgrContainer\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Escher/DgContainer.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\:\\:setSpgrContainer\\(\\) has parameter \\$spgrContainer with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Escher/DgContainer.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\\\SpgrContainer\\:\\:getChildren\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Font\\:\\:\\$autoSizeMethods has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Font.php + + - + message: "#^Parameter \\#2 \\$defaultFont of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Drawing\\:\\:pixelsToCellDimension\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font, PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Font.php + + - + message: "#^Parameter \\#1 \\$size of function imagettfbbox expects float, float\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Font.php + + - + message: "#^Cannot access offset 0 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Font.php + + - + message: "#^Cannot access offset 2 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Font.php + + - + message: "#^Cannot access offset 4 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Font.php + + - + message: "#^Cannot access offset 6 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Font.php + + - + message: "#^Unreachable statement \\- code above always terminates\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Font.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\EigenvalueDecomposition\\:\\:\\$e has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/EigenvalueDecomposition.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\EigenvalueDecomposition\\:\\:\\$cdivi has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/EigenvalueDecomposition.php + + - + message: "#^Else branch is unreachable because previous condition is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/LUDecomposition.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\LUDecomposition\\:\\:getDoublePivot\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/LUDecomposition.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:__construct\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Unreachable statement \\- code above always terminates\\.$#" + count: 19 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:getMatrix\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:plus\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:plusEquals\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Call to function is_string\\(\\) with float\\|int will always evaluate to false\\.$#" + count: 5 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Result of && is always false\\.$#" + count: 10 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:minus\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:minusEquals\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:arrayTimes\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:arrayTimesEquals\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:arrayRightDivide\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Parameter \\#3 \\$c of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:set\\(\\) expects float\\|int\\|null, string given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:arrayRightDivideEquals\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:arrayLeftDivide\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:arrayLeftDivideEquals\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:times\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:power\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:concat\\(\\) has parameter \\$args with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Parameter \\#1 \\$str of function trim expects string, float\\|int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Left side of && is always true\\.$#" + count: 4 + path: src/PhpSpreadsheet/Shared/JAMA/SingularValueDecomposition.php + + - + message: "#^If condition is always true\\.$#" + count: 7 + path: src/PhpSpreadsheet/Shared/JAMA/SingularValueDecomposition.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\:\\:getStream\\(\\) should return resource but returns resource\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#2 \\$data of function unpack expects string, string\\|false given\\.$#" + count: 3 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#1 \\$string of function substr expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#1 \\$No of class PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS constructor expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#2 \\$name of class PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS constructor expects string, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#3 \\$type of class PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS constructor expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#4 \\$prev of class PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS constructor expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#5 \\$next of class PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS constructor expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#6 \\$dir of class PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS constructor expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#9 \\$data of class PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS constructor expects string, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#1 \\$oleTimestamp of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\:\\:OLE2LocalDate\\(\\) expects string, string\\|false given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\:\\:getData\\(\\) should return string but returns string\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Cannot access offset 3 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Cannot access offset 4 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Cannot access offset 1 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Cannot access offset 2 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#1 \\$var of function count expects array\\|Countable, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/ChainedBlockStream.php + + - + message: "#^Parameter \\#3 \\$length of function array_slice expects int\\|null, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS.php + + - + message: "#^Parameter \\#2 \\$offset of function array_slice expects int, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS.php + + - + message: "#^Parameter \\#1 \\$No of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\:\\:__construct\\(\\) expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/File.php + + - + message: "#^Parameter \\#4 \\$prev of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\:\\:__construct\\(\\) expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/File.php + + - + message: "#^Parameter \\#5 \\$next of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\:\\:__construct\\(\\) expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/File.php + + - + message: "#^Parameter \\#6 \\$dir of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\:\\:__construct\\(\\) expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/File.php + + - + message: "#^Parameter \\#1 \\$No of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\:\\:__construct\\(\\) expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#4 \\$prev of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\:\\:__construct\\(\\) expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#5 \\$next of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\:\\:__construct\\(\\) expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#6 \\$dir of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\:\\:__construct\\(\\) expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#9 \\$data of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\:\\:__construct\\(\\) expects string, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#1 \\$iSBDcnt of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\\\Root\\:\\:saveHeader\\(\\) expects int, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#2 \\$iBBcnt of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\\\Root\\:\\:saveHeader\\(\\) expects int, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#3 \\$iPPScnt of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\\\Root\\:\\:saveHeader\\(\\) expects int, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#1 \\$iStBlk of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\\\Root\\:\\:saveBigData\\(\\) expects int, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#1 \\$iSbdSize of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\\\Root\\:\\:saveBbd\\(\\) expects int, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#2 \\$iBsize of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\\\Root\\:\\:saveBbd\\(\\) expects int, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#3 \\$iPpsCnt of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\\\Root\\:\\:saveBbd\\(\\) expects int, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLERead\\:\\:\\$data has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLERead.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLERead\\:\\:\\$wrkbook has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLERead.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLERead\\:\\:\\$summaryInformation has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLERead.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLERead\\:\\:\\$documentSummaryInformation has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLERead.php + + - + message: "#^Parameter \\#1 \\$data of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLERead\\:\\:getInt4d\\(\\) expects string, string\\|false given\\.$#" + count: 8 + path: src/PhpSpreadsheet/Shared/OLERead.php + + - + message: "#^Parameter \\#1 \\$string of function substr expects string, string\\|false given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Shared/OLERead.php + + - + message: "#^Strict comparison using \\=\\=\\= between int and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLERead.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:sanitizeUTF8\\(\\) should return string but returns string\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/StringHelper.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:formatNumber\\(\\) should return string but returns array\\|string\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/StringHelper.php + + - + message: "#^Parameter \\#3 \\$subject of function str_replace expects array\\|string, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/StringHelper.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:countCharacters\\(\\) should return int but returns int\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/StringHelper.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:mbIsUpper\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/StringHelper.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:mbIsUpper\\(\\) has parameter \\$character with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/StringHelper.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:mbStrSplit\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/StringHelper.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:mbStrSplit\\(\\) has parameter \\$string with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/StringHelper.php + + - + message: "#^Parameter \\#1 \\$string of function strlen expects string, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/StringHelper.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$goodnessOfFit has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$stdevOfResiduals has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$covariance has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$correlation has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$SSRegression has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$SSResiduals has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$DFResiduals has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$f has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$slope has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$slopeSE has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$intersect has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$intersectSE has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$xOffset has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$yOffset has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:getError\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:getBestFitType\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:calculateGoodnessOfFit\\(\\) has parameter \\$const with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:calculateGoodnessOfFit\\(\\) has parameter \\$meanX with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:calculateGoodnessOfFit\\(\\) has parameter \\$meanY with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:calculateGoodnessOfFit\\(\\) has parameter \\$sumX with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:calculateGoodnessOfFit\\(\\) has parameter \\$sumX2 with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:calculateGoodnessOfFit\\(\\) has parameter \\$sumXY with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:calculateGoodnessOfFit\\(\\) has parameter \\$sumY with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:calculateGoodnessOfFit\\(\\) has parameter \\$sumY2 with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:sumSquares\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\PolynomialBestFit\\:\\:getCoefficients\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\PolynomialBestFit\\:\\:getCoefficients\\(\\) has parameter \\$dp with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php + + - + message: "#^Parameter \\#2 \\.\\.\\.\\$args of function array_merge expects array, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\Trend\\:\\:calculate\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/Trend.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\Trend\\:\\:calculate\\(\\) has parameter \\$const with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/Trend.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\Trend\\:\\:calculate\\(\\) has parameter \\$trendType with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/Trend.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\Trend\\:\\:calculate\\(\\) has parameter \\$xValues with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/Trend.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\Trend\\:\\:calculate\\(\\) has parameter \\$yValues with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/Trend.php + + - + message: "#^Parameter \\#1 \\$order of class PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\PolynomialBestFit constructor expects int, string given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Shared/Trend/Trend.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\XMLWriter\\:\\:\\$debugEnabled has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/XMLWriter.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\XMLWriter\\:\\:\\$tempFileName \\(string\\) does not accept string\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/XMLWriter.php + + - + message: "#^Parameter \\#1 \\$uri of method XMLWriter\\:\\:openUri\\(\\) expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/XMLWriter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\XMLWriter\\:\\:getData\\(\\) should return string but returns string\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/XMLWriter.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\:\\:\\$workbookViewVisibilityValues has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Spreadsheet.php + + - + message: "#^Call to function is_array\\(\\) with string will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Spreadsheet.php + + - + message: "#^Unreachable statement \\- code above always terminates\\.$#" + count: 1 + path: src/PhpSpreadsheet/Spreadsheet.php + + - + message: "#^Strict comparison using \\=\\=\\= between PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Spreadsheet.php + + - + message: "#^Parameter \\#1 \\$worksheet of method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\:\\:getIndex\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet, PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Spreadsheet.php + + - + message: "#^Cannot call method getTitle\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Spreadsheet.php + + - + message: "#^Strict comparison using \\=\\=\\= between string and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Spreadsheet.php + + - + message: "#^Comparison operation \"\\<\\=\" between int\\ and 1000 is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Spreadsheet.php + + - + message: "#^Result of \\|\\| is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Spreadsheet.php + + - + message: "#^Call to an undefined method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style\\:\\:getSharedComponent\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/Alignment.php + + - + message: "#^Parameter \\#1 \\$parent of method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Supervisor\\:\\:bindParent\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style, \\$this\\(PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Border\\) given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/Border.php + + - + message: "#^Call to an undefined method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style\\:\\:getSharedComponent\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/Border.php + + - + message: "#^Call to an undefined method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style\\:\\:getStyleArray\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/Border.php + + - + message: "#^Parameter \\#1 \\$parent of method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Supervisor\\:\\:bindParent\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style, \\$this\\(PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Borders\\) given\\.$#" + count: 10 + path: src/PhpSpreadsheet/Style/Borders.php + + - + message: "#^Call to an undefined method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style\\:\\:getSharedComponent\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/Borders.php + + - + message: "#^Call to an undefined method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style\\:\\:getSharedComponent\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/Color.php + + - + message: "#^Call to an undefined method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Border\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Fill\\:\\:getEndColor\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/Color.php + + - + message: "#^Call to an undefined method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Border\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Fill\\:\\:getStartColor\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/Color.php + + - + message: "#^Call to an undefined method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Border\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Fill\\:\\:getColor\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/Color.php + + - + message: "#^Call to an undefined method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style\\:\\:getStyleArray\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/Color.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Color\\:\\:getColourComponent\\(\\) should return int\\|string but returns float\\|int\\|string\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/Color.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Conditional\\:\\:\\$condition \\(array\\\\) does not accept array\\\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/Conditional.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Conditional\\:\\:\\$style \\(PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/Conditional.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBar\\:\\:setShowValue\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBar\\:\\:setMinimumConditionalFormatValueObject\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBar\\:\\:setMaximumConditionalFormatValueObject\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBar\\:\\:setConditionalFormattingRuleExt\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBarExtension\\:\\:getXmlAttributes\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBarExtension\\:\\:getXmlElements\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBarExtension\\:\\:setMaximumConditionalFormatValueObject\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBarExtension\\:\\:setMinimumConditionalFormatValueObject\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormatValueObject\\:\\:\\$type has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormatValueObject\\:\\:\\$value has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormatValueObject\\:\\:\\$cellFormula has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormatValueObject\\:\\:__construct\\(\\) has parameter \\$type with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormatValueObject\\:\\:__construct\\(\\) has parameter \\$value with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormatValueObject\\:\\:setType\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormatValueObject\\:\\:setValue\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormatValueObject\\:\\:setCellFormula\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormattingRuleExtension\\:\\:\\$id has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormattingRuleExtension\\:\\:__construct\\(\\) has parameter \\$id with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormattingRuleExtension\\:\\:generateUuid\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormattingRuleExtension\\:\\:parseExtLstXml\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormattingRuleExtension\\:\\:parseExtLstXml\\(\\) has parameter \\$extLstXml with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Cannot access property \\$minLength on SimpleXMLElement\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Cannot access property \\$maxLength on SimpleXMLElement\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Cannot access property \\$border on SimpleXMLElement\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Cannot access property \\$gradient on SimpleXMLElement\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Cannot access property \\$direction on SimpleXMLElement\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Cannot access property \\$negativeBarBorderColorSameAsPositive on SimpleXMLElement\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Cannot access property \\$axisPosition on SimpleXMLElement\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormattingRuleExtension\\:\\:parseExtDataBarElementChildrenFromXml\\(\\) has parameter \\$ns with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Offset 'rgb' does not exist on SimpleXMLElement\\|null\\.$#" + count: 4 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Offset 'theme' does not exist on SimpleXMLElement\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Offset 'tint' does not exist on SimpleXMLElement\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Parameter \\#1 \\$parent of method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Supervisor\\:\\:bindParent\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style, \\$this\\(PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Fill\\) given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Style/Fill.php + + - + message: "#^Call to an undefined method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style\\:\\:getSharedComponent\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/Fill.php + + - + message: "#^Parameter \\#1 \\$parent of method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Supervisor\\:\\:bindParent\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style, \\$this\\(PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\) given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/Font.php + + - + message: "#^Call to an undefined method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style\\:\\:getSharedComponent\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/Font.php + + - + message: "#^Call to an undefined method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style\\:\\:getSharedComponent\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\:\\:\\$builtInFormatCode \\(int\\|false\\) does not accept bool\\|int\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\DateFormatter\\:\\:format\\(\\) has parameter \\$value with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/DateFormatter.php + + - + message: "#^Parameter \\#2 \\$callback of function preg_replace_callback expects callable\\(\\)\\: mixed, array\\('self', 'setLowercaseCallback'\\) given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/DateFormatter.php + + - + message: "#^Parameter \\#3 \\$subject of function preg_replace_callback expects array\\|string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/DateFormatter.php + + - + message: "#^Parameter \\#2 \\$str of function explode expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/DateFormatter.php + + - + message: "#^Parameter \\#2 \\$replace of function str_replace expects array\\|string, int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/DateFormatter.php + + - + message: "#^Parameter \\#2 \\$callback of function preg_replace_callback expects callable\\(\\)\\: mixed, array\\('self', 'escapeQuotesCallback'\\) given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/DateFormatter.php + + - + message: "#^Parameter \\#3 \\$subject of function preg_replace expects array\\|string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/DateFormatter.php + + - + message: "#^Parameter \\#1 \\$format of method DateTime\\:\\:format\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/DateFormatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\DateFormatter\\:\\:setLowercaseCallback\\(\\) has parameter \\$matches with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/DateFormatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\DateFormatter\\:\\:escapeQuotesCallback\\(\\) has parameter \\$matches with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/DateFormatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\Formatter\\:\\:splitFormatCompare\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\Formatter\\:\\:splitFormatCompare\\(\\) has parameter \\$cond with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\Formatter\\:\\:splitFormatCompare\\(\\) has parameter \\$dfcond with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\Formatter\\:\\:splitFormatCompare\\(\\) has parameter \\$dfval with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\Formatter\\:\\:splitFormatCompare\\(\\) has parameter \\$val with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\Formatter\\:\\:splitFormatCompare\\(\\) has parameter \\$value with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\Formatter\\:\\:splitFormat\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\Formatter\\:\\:splitFormat\\(\\) has parameter \\$sections with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\Formatter\\:\\:splitFormat\\(\\) has parameter \\$value with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\Formatter\\:\\:toFormattedString\\(\\) should return string but returns float\\|int\\|string\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Parameter \\#3 \\$subject of function preg_replace expects array\\|string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Parameter \\#2 \\$subject of function preg_split expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\PercentageFormatter\\:\\:format\\(\\) has parameter \\$value with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/PercentageFormatter.php + + - + message: "#^Parameter \\#1 \\$format of function sprintf expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/PercentageFormatter.php + + - + message: "#^Call to an undefined method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style\\:\\:getSharedComponent\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/Protection.php + + - + message: "#^Call to an undefined method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style\\:\\:getCellXfByIndex\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/Style.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style\\:\\:getParent\\(\\) should return PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet but returns PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Style\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/Style.php + + - + message: "#^Cannot call method getCell\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/BaseDrawing.php + + - + message: "#^Cannot call method getDrawingCollection\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/BaseDrawing.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\BaseDrawing\\:\\:\\$shadow \\(PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Drawing\\\\Shadow\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Drawing\\\\Shadow\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/BaseDrawing.php + + - + message: "#^Cannot call method getHashCode\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/BaseDrawing.php + + - + message: "#^Class PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\CellIterator implements generic interface Iterator but does not specify its types\\: TKey, TValue$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/CellIterator.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\CellIterator\\:\\:adjustForExistingOnlyRange\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/CellIterator.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Column\\:\\:\\$parent \\(PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Column.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\CellIterator\\:\\:\\$worksheet \\(PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php + + - + message: "#^Class PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\ColumnIterator implements generic interface Iterator but does not specify its types\\: TKey, TValue$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/ColumnIterator.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Drawing\\\\Shadow\\:\\:\\$color \\(PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Color\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Color\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php + + - + message: "#^Class PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Iterator implements generic interface Iterator but does not specify its types\\: TKey, TValue$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Iterator.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\PageSetup\\:\\:\\$pageOrder has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/PageSetup.php + + - + message: "#^Strict comparison using \\=\\=\\= between int\\ and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/PageSetup.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\PageSetup\\:\\:getPrintArea\\(\\) should return string but returns string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/PageSetup.php + + - + message: "#^Parameter \\#2 \\$str of function explode expects string, string\\|null given\\.$#" + count: 5 + path: src/PhpSpreadsheet/Worksheet/PageSetup.php + + - + message: "#^Parameter \\#1 \\$value of method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\PageSetup\\:\\:setFirstPageNumber\\(\\) expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/PageSetup.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Row\\:\\:\\$worksheet \\(PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Row.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\CellIterator\\:\\:\\$worksheet \\(PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/RowCellIterator.php + + - + message: "#^Class PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\RowIterator implements generic interface Iterator but does not specify its types\\: TKey, TValue$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/RowIterator.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\SheetView\\:\\:\\$sheetViewTypes has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/SheetView.php + + - + message: "#^Strict comparison using \\=\\=\\= between int\\ and null will always evaluate to false\\.$#" + count: 2 + path: src/PhpSpreadsheet/Worksheet/SheetView.php + + - + message: "#^Strict comparison using \\=\\=\\= between string and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/SheetView.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\:\\:\\$drawingCollection with generic class ArrayObject does not specify its types\\: TKey, TValue$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\:\\:\\$chartCollection with generic class ArrayObject does not specify its types\\: TKey, TValue$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\:\\:\\$parent \\(PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Parameter \\#1 \\$pIndex of class PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\RowDimension constructor expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Parameter \\#1 \\$pIndex of class PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\ColumnDimension constructor expects string, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Parameter \\#1 \\$pRange of class PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\AutoFilter constructor expects string, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\:\\:getDrawingCollection\\(\\) return type with generic class ArrayObject does not specify its types\\: TKey, TValue$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\:\\:getChartCollection\\(\\) return type with generic class ArrayObject does not specify its types\\: TKey, TValue$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Parameter \\#1 \\$input of function array_splice expects array, ArrayObject&iterable\\ given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Strict comparison using \\=\\=\\= between string and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Parameter \\#1 \\$range of static method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Coordinate\\:\\:rangeDimension\\(\\) expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Parameter \\#2 \\$format of static method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\:\\:toFormattedString\\(\\) expects string, string\\|null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Parameter \\#3 \\$rotation of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Font\\:\\:calculateColumnWidth\\(\\) expects int, int\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^If condition is always true\\.$#" + count: 2 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Left side of && is always true\\.$#" + count: 2 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Cannot call method renameCalculationCacheForWorksheet\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Parameter \\#2 \\$start of function substr expects int, int\\<0, max\\>\\|false given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Result of && is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Parameter \\#1 \\$pRange of method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\AutoFilter\\:\\:setRange\\(\\) expects string, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Parameter \\#1 \\$row of method PhpOffice\\\\PhpSpreadsheet\\\\Collection\\\\Cells\\:\\:removeRow\\(\\) expects string, int given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Cannot call method getValue\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\|null\\.$#" + count: 4 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Cannot call method getCalculatedValue\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Cannot call method getXfIndex\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Right side of && is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Cannot call method getHashCode\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Cannot call method getWorksheet\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\DefinedName\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Cannot call method getValue\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\DefinedName\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Cannot call method rangeToArray\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Call to function array_key_exists\\(\\) with int and array\\('none' \\=\\> 'none', 'dashDot' \\=\\> '1px dashed', 'dashDotDot' \\=\\> '1px dotted', 'dashed' \\=\\> '1px dashed', 'dotted' \\=\\> '1px dotted', 'double' \\=\\> '3px double', 'hair' \\=\\> '1px solid', 'medium' \\=\\> '2px solid', \\.\\.\\.\\) will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:getSheetIndex\\(\\) should return int but returns int\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateMeta\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateMeta\\(\\) has parameter \\$desc with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateMeta\\(\\) has parameter \\$val with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateSheetPrep\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateSheetStarts\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateSheetStarts\\(\\) has parameter \\$rowMin with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateSheetStarts\\(\\) has parameter \\$sheet with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateSheetTags\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateSheetTags\\(\\) has parameter \\$row with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateSheetTags\\(\\) has parameter \\$tbodyStart with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateSheetTags\\(\\) has parameter \\$theadEnd with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateSheetTags\\(\\) has parameter \\$theadStart with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Parameter \\#1 \\$string of function htmlspecialchars expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Cannot access offset 'mime' on array\\|false\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Parameter \\#1 \\$im of function imagepng expects resource, GdImage\\|resource given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Parameter \\#1 \\$str of function base64_encode expects string, string\\|false given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Ternary operator condition is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Parameter \\#3 \\$use_include_path of function fopen expects bool, int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Parameter \\#2 \\$length of function fread expects int, int\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Cannot access offset 0 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Cannot access offset 1 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Parameter \\#1 \\$vAlign of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:mapVAlign\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Parameter \\#1 \\$hAlign of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:mapHAlign\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Parameter \\#1 \\$borderStyle of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:mapBorderStyle\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateHTMLFooter\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateTableTagInline\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateTableTagInline\\(\\) has parameter \\$id with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateTableTag\\(\\) has parameter \\$html with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateTableTag\\(\\) has parameter \\$id with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateTableTag\\(\\) has parameter \\$sheetIndex with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateTableFooter\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellCss\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellCss\\(\\) has parameter \\$cellAddress with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellCss\\(\\) has parameter \\$colNum with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellCss\\(\\) has parameter \\$pRow with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellDataValueRich\\(\\) has parameter \\$cell with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellDataValueRich\\(\\) has parameter \\$cellData with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Parameter \\#1 \\$pStyle of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:createCSSStyleFont\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font, PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Cannot call method getSuperscript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Cannot call method getSubscript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellDataValue\\(\\) has parameter \\$cell with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellDataValue\\(\\) has parameter \\$cellData with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellData\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellData\\(\\) has parameter \\$cell with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellData\\(\\) has parameter \\$cellType with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellData\\(\\) has parameter \\$cssClass with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowIncludeCharts\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowIncludeCharts\\(\\) has parameter \\$coordinate with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowSpans\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowSpans\\(\\) has parameter \\$colSpan with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowSpans\\(\\) has parameter \\$html with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowSpans\\(\\) has parameter \\$rowSpan with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$cellData with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$cellType with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$colNum with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$colSpan with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$coordinate with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$cssClass with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$html with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$pRow with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$rowSpan with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$sheetIndex with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:calculateSpansOmitRows\\(\\) has parameter \\$candidateSpannedRow with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:calculateSpansOmitRows\\(\\) has parameter \\$sheet with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:calculateSpansOmitRows\\(\\) has parameter \\$sheetIndex with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Negated boolean expression is always false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Ods.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Ods\\\\Cell\\\\Style\\:\\:\\$writer has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Ods/Cell/Style.php + + - + message: "#^If condition is always true\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Ods/Cell/Style.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Ods\\\\Content\\:\\:\\$formulaConvertor has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Ods/Content.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int given\\.$#" + count: 4 + path: src/PhpSpreadsheet/Writer/Ods/Content.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int\\<2, max\\> given\\.$#" + count: 3 + path: src/PhpSpreadsheet/Writer/Ods/Content.php + + - + message: "#^Parameter \\#1 \\$range of static method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Coordinate\\:\\:splitRange\\(\\) expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Ods/Content.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Ods\\\\Formula\\:\\:\\$definedNames has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Ods/Formula.php + + - + message: "#^Parameter \\#1 \\$content of method XMLWriter\\:\\:text\\(\\) expects string, int given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Ods/Settings.php + + - + message: "#^Strict comparison using \\=\\=\\= between int and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Pdf/Dompdf.php + + - + message: "#^Parameter \\#2 \\$str of function fwrite expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Pdf/Dompdf.php + + - + message: "#^Strict comparison using \\=\\=\\= between null and int will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Pdf/Mpdf.php + + - + message: "#^Strict comparison using \\=\\=\\= between int and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php + + - + message: "#^Cannot call method getHashCode\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Parameter \\#1 \\$font of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Workbook\\:\\:addFont\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font, PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Offset 'startCoordinates' does not exist on array\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Offset 'startOffsetX' does not exist on array\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Offset 'startOffsetY' does not exist on array\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Offset 'endCoordinates' does not exist on array\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Offset 'endOffsetX' does not exist on array\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Offset 'endOffsetY' does not exist on array\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Parameter \\#1 \\$data of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DggContainer\\\\BstoreContainer\\\\BSE\\\\Blip\\:\\:setData\\(\\) expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Parameter \\#1 \\$im of function imagepng expects resource, resource\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Parameter \\#1 \\$im of function imagepng expects resource, GdImage\\|resource given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Parameter \\#1 \\$blipType of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DggContainer\\\\BstoreContainer\\\\BSE\\:\\:setBlipType\\(\\) expects int, int\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\BIFFwriter\\:\\:writeEof\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/BIFFwriter.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Escher\\:\\:\\$object has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Escher.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Escher\\:\\:\\$data has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Escher.php + + - + message: "#^If condition is always true\\.$#" + count: 3 + path: src/PhpSpreadsheet/Writer/Xls/Escher.php + + - + message: "#^Elseif condition is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Escher.php + + - + message: "#^Parameter \\#1 \\$fontName of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Font\\:\\:getCharsetFromFontName\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Font.php + + - + message: "#^If condition is always false\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xls/Font.php + + - + message: "#^Parameter \\#1 \\$bold of static method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Font\\:\\:mapBold\\(\\) expects bool, bool\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Font.php + + - + message: "#^Parameter \\#1 \\$underline of static method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Font\\:\\:mapUnderline\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Font.php + + - + message: "#^Parameter \\#1 \\$textValue of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:UTF8toBIFF8UnicodeShort\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Font.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Parser\\:\\:\\$spreadsheet has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Parser.php + + - + message: "#^Unreachable statement \\- code above always terminates\\.$#" + count: 5 + path: src/PhpSpreadsheet/Writer/Xls/Parser.php + + - + message: "#^Parameter \\#3 \\$subject of function preg_replace expects array\\|string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Parser.php + + - + message: "#^Parameter \\#3 \\$subject of function str_replace expects array\\|string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Parser.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Parser\\:\\:advance\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Parser.php + + - + message: "#^Offset 'left' does not exist on \\(array&nonEmpty\\)\\|string\\.$#" + count: 6 + path: src/PhpSpreadsheet/Writer/Xls/Parser.php + + - + message: "#^Offset 'right' does not exist on \\(array&nonEmpty\\)\\|string\\.$#" + count: 5 + path: src/PhpSpreadsheet/Writer/Xls/Parser.php + + - + message: "#^Offset 'value' does not exist on \\(array&nonEmpty\\)\\|string\\.$#" + count: 7 + path: src/PhpSpreadsheet/Writer/Xls/Parser.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Workbook\\:\\:\\$colors has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Workbook.php + + - + message: "#^Cannot call method getTitle\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Workbook.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Workbook\\:\\:writeAllDefinedNamesBiff8\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Workbook.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Workbook\\:\\:writeSupbookInternal\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Workbook.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Workbook\\:\\:writeExternalsheetBiff8\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Workbook.php + + - + message: "#^Cannot access offset 'encoding' on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Workbook.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Workbook\\:\\:writeMsoDrawingGroup\\(\\) has no return typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Workbook.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Workbook\\:\\:\\$escher \\(PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Workbook.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Worksheet\\:\\:\\$colors has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Cannot call method getHashCode\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#4 \\$isError of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Worksheet\\:\\:writeBoolErr\\(\\) expects bool, int given\\.$#" + count: 3 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#2 \\$pieces of function implode expects array, array\\\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#3 \\$subject of function preg_replace expects array\\|string, string\\|null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#2 \\$subject of function preg_match expects string, string\\|null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#2 \\$subject of function preg_match_all expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#1 \\$coordinates of static method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Coordinate\\:\\:indexesFromString\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Worksheet\\:\\:\\$activePane \\(int\\) does not accept int\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#5 \\$width of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Worksheet\\:\\:positionImage\\(\\) expects int, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#6 \\$height of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Worksheet\\:\\:positionImage\\(\\) expects int, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#1 \\$im of function imagesx expects resource, GdImage\\|resource given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#1 \\$im of function imagesy expects resource, GdImage\\|resource given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#1 \\$im of function imagecolorat expects resource, GdImage\\|resource given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#1 \\$im of function imagecolorsforindex expects resource, GdImage\\|resource given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#2 \\$col of function imagecolorsforindex expects int, int\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#1 \\$ascii of function chr expects int, float given\\.$#" + count: 3 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#2 \\$length of function fread expects int, int\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#1 \\$string of function strlen expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#2 \\$data of function unpack expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Cannot access offset 'ident' on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#1 \\$string of function substr expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Cannot access offset 'sa' on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Cannot access offset 1 on array\\|false\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Cannot access offset 2 on array\\|false\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Cannot access offset 'comp' on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Worksheet\\:\\:\\$escher \\(PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#1 \\$textRotation of static method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Xf\\:\\:mapTextRotation\\(\\) expects int, int\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Xf.php + + - + message: "#^Possibly invalid array key type array\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx.php + + - + message: "#^Parameter \\#1 \\$path of function dirname expects string, array\\|string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx.php + + - + message: "#^Argument of an invalid type array\\|null supplied for foreach, only iterables are supported\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx.php + + - + message: "#^Parameter \\#1 \\$path of function basename expects string, array\\|string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx.php + + - + message: "#^Parameter \\#1 \\$function of function call_user_func expects callable\\(\\)\\: mixed, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\:\\:\\$pathNames has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:\\$calculateCellValues has no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int given\\.$#" + count: 45 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Strict comparison using \\=\\=\\= between PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\PlotArea and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Argument of an invalid type array\\|string supplied for foreach, only iterables are supported\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, string\\|null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#2 \\$yAxisLabel of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:writeValueAxis\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Title, PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Title\\|null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#4 \\$id1 of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:writeValueAxis\\(\\) expects string, int\\|string given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#5 \\$id2 of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:writeValueAxis\\(\\) expects string, int\\|string given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#7 \\$xAxis of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:writeValueAxis\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis, PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis\\|null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#8 \\$majorGridlines of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:writeValueAxis\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines, PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\|null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#9 \\$minorGridlines of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:writeValueAxis\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines, PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\|null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#2 \\$xAxisLabel of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:writeCategoryAxis\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Title, PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Title\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#3 \\$id1 of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:writeCategoryAxis\\(\\) expects string, int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#4 \\$id2 of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:writeCategoryAxis\\(\\) expects string, int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#6 \\$yAxis of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:writeCategoryAxis\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis, PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Part \\$xAxis\\-\\>getShadowProperty\\('effect'\\) \\(array\\|int\\|string\\|null\\) of encapsed string cannot be cast to string\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, array\\|int\\|string given\\.$#" + count: 8 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Part \\$xAxis\\-\\>getShadowProperty\\(\\['color', 'type'\\]\\) \\(array\\|int\\|string\\|null\\) of encapsed string cannot be cast to string\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, array\\|int\\|string\\|null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Else branch is unreachable because previous condition is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:getChartType\\(\\) never returns string so it can be removed from the return typehint\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Strict comparison using \\=\\=\\= between PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeries and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Cannot call method getFillColor\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Cannot call method getDataValues\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#1 \\$plotSeriesValues of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:writeBubbles\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues, PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Strict comparison using \\=\\=\\= between PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues and null will always evaluate to false\\.$#" + count: 3 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#1 \\$rawTextData of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\XMLWriter\\:\\:writeRawData\\(\\) expects array\\\\|string, int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, float\\|int given\\.$#" + count: 4 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, float given\\.$#" + count: 6 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#1 \\$string of function substr expects string, int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Comments.php + + - + message: "#^Parameter \\#2 \\$content of method XMLWriter\\:\\:writeElement\\(\\) expects string\\|null, int given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Comments.php + + - + message: "#^Parameter \\#1 \\$arr1 of function array_diff expects array, array\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/ContentTypes.php + + - + message: "#^Cannot access offset 2 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/ContentTypes.php + + - + message: "#^Parameter \\#2 \\$content of method XMLWriter\\:\\:writeElement\\(\\) expects string\\|null, int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/DocProps.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/DocProps.php + + - + message: "#^Parameter \\#1 \\$index of method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\:\\:getChartByIndex\\(\\) expects string, int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Drawing.php + + - + message: "#^Parameter \\#2 \\$pChart of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Drawing\\:\\:writeChart\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart, PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Drawing.php + + - + message: "#^Parameter \\#2 \\$content of method XMLWriter\\:\\:writeElement\\(\\) expects string\\|null, int given\\.$#" + count: 12 + path: src/PhpSpreadsheet/Writer/Xlsx/Drawing.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int given\\.$#" + count: 8 + path: src/PhpSpreadsheet/Writer/Xlsx/Drawing.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int\\<0, max\\> given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Drawing.php + + - + message: "#^Parameter \\#4 \\$pTarget of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Rels\\:\\:writeRelationship\\(\\) expects string, array\\|string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Rels.php + + - + message: "#^Parameter \\#2 \\$pId of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Rels\\:\\:writeRelationship\\(\\) expects int, string given\\.$#" + count: 4 + path: src/PhpSpreadsheet/Writer/Xlsx/Rels.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Rels\\:\\:writeUnparsedRelationship\\(\\) has parameter \\$relationship with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Rels.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Rels\\:\\:writeUnparsedRelationship\\(\\) has parameter \\$type with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Rels.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Rels\\:\\:writeDrawingHyperLink\\(\\) has parameter \\$i with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Rels.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Rels\\:\\:writeDrawingHyperLink\\(\\) has parameter \\$objWriter with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Rels.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int\\<0, max\\> given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Instanceof between string and PhpOffice\\\\PhpSpreadsheet\\\\RichText\\\\RichText will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Instanceof between \\*NEVER\\* and PhpOffice\\\\PhpSpreadsheet\\\\RichText\\\\RichText will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Cannot call method getName\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, string\\|null given\\.$#" + count: 4 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Cannot call method getBold\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Cannot call method getItalic\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Cannot call method getSubscript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Cannot call method getSuperscript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Cannot call method getStrikethrough\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Cannot call method getColor\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Cannot call method getSize\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, float\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Cannot call method getUnderline\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Parameter \\#1 \\$text of method PhpOffice\\\\PhpSpreadsheet\\\\RichText\\\\RichText\\:\\:createTextRun\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int given\\.$#" + count: 22 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$pNumberFormat of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Style\\:\\:writeNumFmt\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat, PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$pFont of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Style\\:\\:writeFont\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font, PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$pFill of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Style\\:\\:writeFill\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Fill, PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Fill\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$pBorders of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Style\\:\\:writeBorder\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Borders, PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Borders\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int\\<0, max\\> given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Cannot call method getStyle\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Conditional\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, string\\|null given\\.$#" + count: 4 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Comparison operation \"\\<\" between int\\ and 0 is always true\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int\\<1, max\\> given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Result of \\|\\| is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int given\\.$#" + count: 7 + path: src/PhpSpreadsheet/Writer/Xlsx/Workbook.php + + - + message: "#^Parameter \\#3 \\$pStringTable of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Worksheet\\:\\:writeSheetData\\(\\) expects array\\, array\\\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int given\\.$#" + count: 19 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int\\<1, max\\> given\\.$#" + count: 7 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int\\<0, max\\> given\\.$#" + count: 3 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Worksheet\\:\\:writeAttributeIf\\(\\) has parameter \\$condition with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Worksheet\\:\\:writeElementIf\\(\\) has parameter \\$condition with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Parameter \\#3 \\$namespace of method XMLWriter\\:\\:startElementNs\\(\\) expects string, null given\\.$#" + count: 8 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^If condition is always true\\.$#" + count: 6 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Worksheet\\:\\:writeDataBarElements\\(\\) has parameter \\$dataBar with no typehint specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Parameter \\#4 \\$val of static method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Worksheet\\:\\:writeAttributeIf\\(\\) expects string, int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Parameter \\#2 \\$content of method XMLWriter\\:\\:writeElement\\(\\) expects string\\|null, int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Xlfn\\:\\:addXlfn\\(\\) should return string but returns string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Xlfn.php + + - + message: "#^Unreachable statement \\- code above always terminates\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Calculation/Engine/RangeTest.php + + - + message: "#^Call to static method PHPUnit\\\\Framework\\\\Assert\\:\\:assertSame\\(\\) with arguments PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell, null and 'should get exact…' will always evaluate to false\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Collection/CellsTest.php + + - + message: "#^Cannot call method getParent\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\|null\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Collection/CellsTest.php + + - + message: "#^Cannot call method getCoordinate\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\|null\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Collection/CellsTest.php + + - + message: "#^Parameter \\#1 \\$row of method PhpOffice\\\\PhpSpreadsheet\\\\Collection\\\\Cells\\:\\:getHighestColumn\\(\\) expects string\\|null, int given\\.$#" + count: 3 + path: tests/PhpSpreadsheetTests/Collection/CellsTest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheetTests\\\\Functional\\\\ColumnWidthTest\\:\\:testReadColumnWidth\\(\\) has parameter \\$format with no typehint specified\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Functional/ColumnWidthTest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheetTests\\\\Functional\\\\CommentsTest\\:\\:testComments\\(\\) has parameter \\$format with no typehint specified\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Functional/CommentsTest.php + + - + message: "#^Parameter \\#1 \\$condition of method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Conditional\\:\\:addCondition\\(\\) expects string, float given\\.$#" + count: 2 + path: tests/PhpSpreadsheetTests/Functional/ConditionalStopIfTrueTest.php + + - + message: "#^Parameter \\#1 \\$im of function imagecolorallocate expects resource, resource\\|false given\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Functional/DrawingImageHyperlinkTest.php + + - + message: "#^Parameter \\#1 \\$im of function imagestring expects resource, resource\\|false given\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Functional/DrawingImageHyperlinkTest.php + + - + message: "#^Parameter \\#6 \\$col of function imagestring expects int, int\\|false given\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Functional/DrawingImageHyperlinkTest.php + + - + message: "#^Parameter \\#1 \\$value of method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\MemoryDrawing\\:\\:setImageResource\\(\\) expects GdImage\\|resource, resource\\|false given\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Functional/DrawingImageHyperlinkTest.php + + - + message: "#^Cannot call method getUrl\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Hyperlink\\|null\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Functional/DrawingImageHyperlinkTest.php + + - + message: "#^Cannot call method getPageSetup\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 5 + path: tests/PhpSpreadsheetTests/Functional/PrintAreaTest.php + + - + message: "#^Cannot access offset 'size' on array\\(0 \\=\\> int, 1 \\=\\> int, 2 \\=\\> int, 3 \\=\\> int, 4 \\=\\> int, 5 \\=\\> int, 6 \\=\\> int, 7 \\=\\> int, \\.\\.\\.\\)\\|false\\.$#" + count: 2 + path: tests/PhpSpreadsheetTests/Functional/StreamTest.php + + - + message: "#^Parameter \\#1 \\$fp of function fstat expects resource, resource\\|false given\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Functional/StreamTest.php + + - + message: "#^Parameter \\#1 \\$filename of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\IWriter\\:\\:save\\(\\) expects resource\\|string, resource\\|false given\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Functional/StreamTest.php + + - + message: "#^Parameter \\#1 \\$expected of static method PHPUnit\\\\Framework\\\\Assert\\:\\:assertInstanceOf\\(\\) expects class\\-string\\, string given\\.$#" + count: 3 + path: tests/PhpSpreadsheetTests/IOFactoryTest.php + + - + message: "#^Cannot call method getValue\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\NamedFormula\\|null\\.$#" + count: 5 + path: tests/PhpSpreadsheetTests/NamedFormulaTest.php + + - + message: "#^Cannot call method getValue\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\NamedRange\\|null\\.$#" + count: 5 + path: tests/PhpSpreadsheetTests/NamedRangeTest.php + + - + message: "#^Unreachable statement \\- code above always terminates\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Reader/Ods/OdsTest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheetTests\\\\Reader\\\\Security\\\\XmlScannerTest\\:\\:testValidXML\\(\\) has parameter \\$libxmlDisableEntityLoader with no typehint specified\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Reader/Security/XmlScannerTest.php + + - + message: "#^Argument of an invalid type array\\\\|false supplied for foreach, only iterables are supported\\.$#" + count: 3 + path: tests/PhpSpreadsheetTests/Reader/Security/XmlScannerTest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheetTests\\\\Reader\\\\Security\\\\XmlScannerTest\\:\\:testInvalidXML\\(\\) has parameter \\$libxmlDisableEntityLoader with no typehint specified\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Reader/Security/XmlScannerTest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheetTests\\\\Reader\\\\Xlsx\\\\AutoFilterTest\\:\\:getWorksheetInstance\\(\\) has no return typehint specified\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Reader/Xlsx/AutoFilterTest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheetTests\\\\Reader\\\\Xlsx\\\\AutoFilterTest\\:\\:getXMLInstance\\(\\) has no return typehint specified\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Reader/Xlsx/AutoFilterTest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheetTests\\\\Reader\\\\Xlsx\\\\AutoFilterTest\\:\\:getXMLInstance\\(\\) has parameter \\$ref with no typehint specified\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Reader/Xlsx/AutoFilterTest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheetTests\\\\Reader\\\\Xlsx\\\\AutoFilterTest\\:\\:getAutoFilterInstance\\(\\) has no return typehint specified\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Reader/Xlsx/AutoFilterTest.php + + - + message: "#^Cannot call method setMinimumConditionalFormatValueObject\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBar\\|null\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Reader/Xlsx/ConditionalFormattingDataBarXlsxTest.php + + - + message: "#^Cannot call method getMinimumConditionalFormatValueObject\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBar\\|null\\.$#" + count: 13 + path: tests/PhpSpreadsheetTests/Reader/Xlsx/ConditionalFormattingDataBarXlsxTest.php + + - + message: "#^Cannot call method getMaximumConditionalFormatValueObject\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBar\\|null\\.$#" + count: 13 + path: tests/PhpSpreadsheetTests/Reader/Xlsx/ConditionalFormattingDataBarXlsxTest.php + + - + message: "#^Cannot call method getColor\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBar\\|null\\.$#" + count: 5 + path: tests/PhpSpreadsheetTests/Reader/Xlsx/ConditionalFormattingDataBarXlsxTest.php + + - + message: "#^Cannot call method getConditionalFormattingRuleExt\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBar\\|null\\.$#" + count: 8 + path: tests/PhpSpreadsheetTests/Reader/Xlsx/ConditionalFormattingDataBarXlsxTest.php + + - + message: "#^Cannot call method getShowValue\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBar\\|null\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Reader/Xlsx/ConditionalFormattingDataBarXlsxTest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheetTests\\\\Reader\\\\Xml\\\\XmlTest\\:\\:testInvalidSimpleXML\\(\\) has parameter \\$filename with no typehint specified\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Reader/Xml/XmlTest.php + + - + message: "#^Argument of an invalid type array\\\\|false supplied for foreach, only iterables are supported\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Reader/Xml/XmlTest.php + + - + message: "#^Parameter \\#1 \\$currencyCode of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:setCurrencyCode\\(\\) expects string, null given\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Shared/StringHelperTest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheetTests\\\\SpreadsheetTest\\:\\:testGetSheetByName\\(\\) has parameter \\$index with no typehint specified\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/SpreadsheetTest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheetTests\\\\SpreadsheetTest\\:\\:testGetSheetByName\\(\\) has parameter \\$sheetName with no typehint specified\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/SpreadsheetTest.php + + - + message: "#^Parameter \\#1 \\$condition of method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Conditional\\:\\:addCondition\\(\\) expects string, float given\\.$#" + count: 2 + path: tests/PhpSpreadsheetTests/Style/ConditionalTest.php + + - + message: "#^Parameter \\#1 \\$conditions of method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Conditional\\:\\:setConditions\\(\\) expects array\\\\|bool\\|float\\|int\\|string, array\\ given\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Style/ConditionalTest.php + + - + message: "#^Parameter \\#2 \\$pValue of method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\AutoFilter\\\\Column\\:\\:setAttribute\\(\\) expects string, int given\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Worksheet/AutoFilter/ColumnTest.php + + - + message: "#^Parameter \\#1 \\$im of function imagecolorallocate expects resource, resource\\|false given\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Worksheet/DrawingTest.php + + - + message: "#^Parameter \\#1 \\$im of function imagestring expects resource, resource\\|false given\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Worksheet/DrawingTest.php + + - + message: "#^Parameter \\#6 \\$col of function imagestring expects int, int\\|false given\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Worksheet/DrawingTest.php + + - + message: "#^Parameter \\#1 \\$value of method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\MemoryDrawing\\:\\:setImageResource\\(\\) expects GdImage\\|resource, resource\\|false given\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Worksheet/DrawingTest.php + + - + message: "#^Parameter \\#2 \\$rowIndex of class PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\RowCellIterator constructor expects int, string given\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Worksheet/RowCellIterator2Test.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheetTests\\\\Writer\\\\Html\\\\CallbackTest\\:\\:yellowBody\\(\\) should return string but returns string\\|null\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Writer/Html/CallbackTest.php + + - + message: "#^Parameter \\#1 \\$haystack of function strpos expects string, string\\|false given\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Writer/Html/CallbackTest.php + + - + message: "#^Cannot call method getColor\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 3 + path: tests/PhpSpreadsheetTests/Writer/Html/GridlinesTest.php + + - + message: "#^Cannot call method setSuperScript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Writer/Html/GridlinesTest.php + + - + message: "#^Cannot call method setSubScript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 3 + path: tests/PhpSpreadsheetTests/Writer/Html/GridlinesTest.php + + - + message: "#^Cannot call method setBold\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 3 + path: tests/PhpSpreadsheetTests/Writer/Html/HtmlCommentsTest.php + + - + message: "#^Cannot call method getDrawingCollection\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 4 + path: tests/PhpSpreadsheetTests/Writer/Xlsx/UnparsedDataCloneTest.php + + - + message: "#^Cannot call method getCell\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 4 + path: tests/PhpSpreadsheetTests/Writer/Xlsx/UnparsedDataCloneTest.php + + - + message: "#^Parameter \\#1 \\$data of function simplexml_load_string expects string, string\\|false given\\.$#" + count: 2 + path: tests/PhpSpreadsheetTests/Writer/Xlsx/UnparsedDataTest.php + + - + message: "#^Cannot access property \\$pageSetup on SimpleXMLElement\\|false\\.$#" + count: 1 + path: tests/PhpSpreadsheetTests/Writer/Xlsx/UnparsedDataTest.php + + - + message: "#^Cannot access property \\$sheetProtection on SimpleXMLElement\\|false\\.$#" + count: 5 + path: tests/PhpSpreadsheetTests/Writer/Xlsx/UnparsedDataTest.php + + - + message: "#^Argument of an invalid type SimpleXMLElement\\|null supplied for foreach, only iterables are supported\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xml/Properties.php + + - + message: "#^Argument of an invalid type SimpleXMLElement\\|null supplied for foreach, only iterables are supported\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xml/Style.php + + - + message: "#^Binary operation \"/\" between int\\|string and 360 results in an error\\.$#" + count: 3 + path: src/PhpSpreadsheet/Calculation/DateTimeExcel/YearFrac.php + + - + message: "#^Binary operation \"/\" between int\\|string and 365 results in an error\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/DateTimeExcel/YearFrac.php + + - + message: "#^Binary operation \"/\" between int\\|string and \\(float\\|int\\) results in an error\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/DateTimeExcel/YearFrac.php + + - + message: "#^Binary operation \"/\" between float\\|string and float\\|string results in an error\\.$#" + count: 2 + path: src/PhpSpreadsheet/Calculation/Financial/Securities/Price.php + + - + message: "#^Binary operation \"/\" between float\\|int\\|string and float\\|int\\|string results in an error\\.$#" + count: 2 + path: src/PhpSpreadsheet/Calculation/MathTrig/Combinations.php + + - + message: "#^Binary operation \"/\" between float\\|int\\|string and float\\|int results in an error\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/MathTrig/Factorial.php + + - + message: "#^Binary operation \"/\" between float\\|int\\|string and float\\|int\\|string results in an error\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Permutations.php + + - + message: "#^Offset '(percentage|value)' does not exist on SimpleXMLElement|null\\.$#" + count: 3 + path: src/PhpSpreadsheet/Reader/Gnumeric/PageSetup.php + diff --git a/phpstan.neon.dist b/phpstan.neon.dist new file mode 100644 index 00000000..b7a4fca8 --- /dev/null +++ b/phpstan.neon.dist @@ -0,0 +1,29 @@ +includes: + - phpstan-baseline.neon + - vendor/phpstan/phpstan-phpunit/extension.neon + - vendor/phpstan/phpstan-phpunit/rules.neon + +parameters: + level: max + paths: + - src/ + - tests/ + parallel: + processTimeout: 300.0 + checkMissingIterableValueType: false + ignoreErrors: + - '~^Class GdImage not found\.$~' + - '~^Return typehint of method .* has invalid type GdImage\.$~' + - '~^Property .* has unknown class GdImage as its type\.$~' + - '~^Parameter .* of method .* has invalid typehint type GdImage\.$~' + - '~^Parameter \#1 \$im of function (imagedestroy|imageistruecolor|imagealphablending|imagesavealpha|imagecolortransparent|imagecolorsforindex|imagesavealpha|imagesx|imagesy) expects resource, GdImage\|resource given\.$~' + - '~^Parameter \#2 \$src_im of function imagecopy expects resource, GdImage\|resource given\.$~' + # Accept a bit anything for assert methods + - '~^Parameter \#2 .* of static method PHPUnit\\Framework\\Assert\:\:assert\w+\(\) expects .*, .* given\.$~' + - '~^Method PhpOffice\\PhpSpreadsheetTests\\.*\:\:test.*\(\) has parameter \$args with no typehint specified\.$~' + + # Ignore all JpGraph issues + - '~^Constant (MARK_CIRCLE|MARK_CROSS|MARK_DIAMOND|MARK_DTRIANGLE|MARK_FILLEDCIRCLE|MARK_SQUARE|MARK_STAR|MARK_UTRIANGLE|MARK_X|SIDE_RIGHT) not found\.$~' + - '~^Instantiated class (AccBarPlot|AccLinePlot|BarPlot|ContourPlot|Graph|GroupBarPlot|GroupBarPlot|LinePlot|LinePlot|PieGraph|PiePlot|PiePlot3D|PiePlotC|RadarGraph|RadarPlot|ScatterPlot|Spline|StockPlot) not found\.$~' + - '~^Call to method .*\(\) on an unknown class (AccBarPlot|AccLinePlot|BarPlot|ContourPlot|Graph|GroupBarPlot|GroupBarPlot|LinePlot|LinePlot|PieGraph|PiePlot|PiePlot3D|PiePlotC|RadarGraph|RadarPlot|ScatterPlot|Spline|StockPlot)\.$~' + - '~^Access to property .* on an unknown class (AccBarPlot|AccLinePlot|BarPlot|ContourPlot|Graph|GroupBarPlot|GroupBarPlot|LinePlot|LinePlot|PieGraph|PiePlot|PiePlot3D|PiePlotC|RadarGraph|RadarPlot|ScatterPlot|Spline|StockPlot)\.$~' diff --git a/samples/Autofilter/10_Autofilter_dynamic_dates.php b/samples/Autofilter/10_Autofilter_dynamic_dates.php new file mode 100644 index 00000000..959925c1 --- /dev/null +++ b/samples/Autofilter/10_Autofilter_dynamic_dates.php @@ -0,0 +1,100 @@ +createSheet(); + $sheet->setTitle($rule); + $sheet->getCell('A1')->setValue('Date'); + $row = 1; + $date = new DateTime(); + $year = (int) $date->format('Y'); + $month = (int) $date->format('m'); + $day = (int) $date->format('d'); + $yearMinus2 = $year - 2; + $sheet->getCell('B1')->setValue("=DATE($year, $month, $day)"); + // Each day for two weeks before today through 2 weeks after + for ($dayOffset = -14; $dayOffset < 14; ++$dayOffset) { + ++$row; + $sheet->getCell("A$row")->setValue("=B1+($dayOffset)"); + } + // First and last day of each month, starting with January 2 years before, + // through December 2 years after. + for ($monthOffset = 0; $monthOffset < 48; ++$monthOffset) { + ++$row; + $sheet->getCell("A$row")->setValue("=DATE($yearMinus2, $monthOffset, 1)"); + ++$row; + $sheet->getCell("A$row")->setValue("=DATE($yearMinus2, $monthOffset + 1, 0)"); + } + $sheet->getStyle("A2:A$row")->getNumberFormat()->setFormatCode('yyyy-mm-dd'); + $sheet->getStyle('B1')->getNumberFormat()->setFormatCode('yyyy-mm-dd'); + $sheet->getColumnDimension('A')->setAutoSize(true); + $sheet->getColumnDimension('B')->setAutoSize(true); + $autoFilter = $spreadsheet->getActiveSheet()->getAutoFilter(); + $autoFilter->setRange("A1:A$row"); + $columnFilter = $autoFilter->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + '', + $rule + ) + ->setRuleType(Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER); + $sheet->setSelectedCell('B1'); +} + +// Create new Spreadsheet object +$helper->log('Create new Spreadsheet object'); +$spreadsheet = new Spreadsheet(); + +// Set document properties +$helper->log('Set document properties'); +$spreadsheet->getProperties()->setCreator('Owen Leibman') + ->setLastModifiedBy('Owen Leibman') + ->setTitle('PhpSpreadsheet Test Document') + ->setSubject('PhpSpreadsheet Test Document') + ->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.') + ->setKeywords('office PhpSpreadsheet php') + ->setCategory('Test result file'); + +$ruleNames = [ + Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH, + Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER, + Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK, + Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR, + Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH, + Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER, + Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK, + Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR, + Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH, + Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER, + Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK, + Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR, + Rule::AUTOFILTER_RULETYPE_DYNAMIC_TODAY, + Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW, + Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE, + Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY, + Rule::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2, + Rule::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3, +]; + +// Create the worksheets +foreach ($ruleNames as $ruleName) { + $helper->log("Add data and filter for $ruleName"); + createSheet($spreadsheet, $ruleName); +} +$spreadsheet->removeSheetByIndex(0); +$spreadsheet->setActiveSheetIndex(0); +// Save +$helper->write($spreadsheet, __FILE__); diff --git a/samples/Autofilter/10_Autofilter_selection_1.php b/samples/Autofilter/10_Autofilter_selection_1.php index 556ef61c..511417f0 100644 --- a/samples/Autofilter/10_Autofilter_selection_1.php +++ b/samples/Autofilter/10_Autofilter_selection_1.php @@ -31,7 +31,8 @@ $spreadsheet->getActiveSheet()->setCellValue('A1', 'Financial Year') ->setCellValue('D1', 'Date') ->setCellValue('E1', 'Sales Value') ->setCellValue('F1', 'Expenditure'); -$startYear = $endYear = $currentYear = date('Y'); +$dateTime = new DateTime(); +$startYear = $endYear = $currentYear = (int) $dateTime->format('Y'); --$startYear; ++$endYear; @@ -52,7 +53,9 @@ $row = 2; foreach ($years as $year) { foreach ($periods as $period) { foreach ($countries as $country) { - $endDays = date('t', mktime(0, 0, 0, $period, 1, (int) $year)); + $dateString = sprintf('%04d-%02d-01T00:00:00', $year, $period); + $dateTime = new DateTime($dateString); + $endDays = (int) $dateTime->format('t'); for ($i = 1; $i <= $endDays; ++$i) { $eDate = Date::formattedPHPToExcel( $year, @@ -124,10 +127,12 @@ $autoFilter->getColumn('C') 'japan' ) ->setRuleType(Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER); -// Filter the Date column on a filter value of the first day of every period of the current year +// Filter the Date column on a filter value of the last day of every period of the current year // We us a dateGroup ruletype for this, although it is still a standard filter foreach ($periods as $period) { - $endDate = date('t', mktime(0, 0, 0, $period, 1, (int) $currentYear)); + $dateString = sprintf('%04d-%02d-01T00:00:00', $currentYear, $period); + $dateTime = new DateTime($dateString); + $endDate = (int) $dateTime->format('t'); $autoFilter->getColumn('D') ->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER) diff --git a/samples/Autofilter/10_Autofilter_selection_2.php b/samples/Autofilter/10_Autofilter_selection_2.php index 4bae0aba..9e0680fc 100644 --- a/samples/Autofilter/10_Autofilter_selection_2.php +++ b/samples/Autofilter/10_Autofilter_selection_2.php @@ -31,7 +31,8 @@ $spreadsheet->getActiveSheet()->setCellValue('A1', 'Financial Year') ->setCellValue('D1', 'Date') ->setCellValue('E1', 'Sales Value') ->setCellValue('F1', 'Expenditure'); -$startYear = $endYear = $currentYear = date('Y'); +$dateTime = new DateTime(); +$startYear = $endYear = $currentYear = (int) $dateTime->format('Y'); --$startYear; ++$endYear; @@ -52,7 +53,9 @@ $row = 2; foreach ($years as $year) { foreach ($periods as $period) { foreach ($countries as $country) { - $endDays = date('t', mktime(0, 0, 0, $period, 1, (int) $year)); + $dateString = sprintf('%04d-%02d-01T00:00:00', $year, $period); + $dateTime = new DateTime($dateString); + $endDays = (int) $dateTime->format('t'); for ($i = 1; $i <= $endDays; ++$i) { $eDate = Date::formattedPHPToExcel( $year, diff --git a/samples/Autofilter/10_Autofilter_selection_display.php b/samples/Autofilter/10_Autofilter_selection_display.php index 4810348c..b07266b9 100644 --- a/samples/Autofilter/10_Autofilter_selection_display.php +++ b/samples/Autofilter/10_Autofilter_selection_display.php @@ -31,7 +31,8 @@ $spreadsheet->getActiveSheet()->setCellValue('A1', 'Financial Year') ->setCellValue('D1', 'Date') ->setCellValue('E1', 'Sales Value') ->setCellValue('F1', 'Expenditure'); -$startYear = $endYear = $currentYear = date('Y'); +$dateTime = new DateTime(); +$startYear = $endYear = $currentYear = (int) $dateTime->format('Y'); --$startYear; ++$endYear; @@ -52,7 +53,9 @@ $row = 2; foreach ($years as $year) { foreach ($periods as $period) { foreach ($countries as $country) { - $endDays = date('t', mktime(0, 0, 0, $period, 1, (int) $year)); + $dateString = sprintf('%04d-%02d-01T00:00:00', $year, $period); + $dateTime = new DateTime($dateString); + $endDays = (int) $dateTime->format('t'); for ($i = 1; $i <= $endDays; ++$i) { $eDate = Date::formattedPHPToExcel( $year, @@ -124,10 +127,12 @@ $autoFilter->getColumn('C') 'japan' ) ->setRuleType(Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER); -// Filter the Date column on a filter value of the first day of every period of the current year +// Filter the Date column on a filter value of the last day of every period of the current year // We us a dateGroup ruletype for this, although it is still a standard filter foreach ($periods as $period) { - $endDate = date('t', mktime(0, 0, 0, $period, 1, (int) $currentYear)); + $dateString = sprintf('%04d-%02d-01T00:00:00', $currentYear, $period); + $dateTime = new DateTime($dateString); + $endDate = (int) $dateTime->format('t'); $autoFilter->getColumn('D') ->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER) diff --git a/samples/Basic/01_Simple.php b/samples/Basic/01_Simple.php index 69309794..1ab182e1 100644 --- a/samples/Basic/01_Simple.php +++ b/samples/Basic/01_Simple.php @@ -61,4 +61,4 @@ $spreadsheet->getActiveSheet() ->setTitle('Simple'); // Save -$helper->write($spreadsheet, __FILE__); +$helper->write($spreadsheet, __FILE__, ['Xlsx', 'Xls', 'Ods']); diff --git a/samples/Basic/16_Csv.php b/samples/Basic/16_Csv.php index 15bbf0d4..137f6469 100644 --- a/samples/Basic/16_Csv.php +++ b/samples/Basic/16_Csv.php @@ -38,7 +38,8 @@ $helper->write($spreadsheetFromCSV, __FILE__, ['Xlsx']); $filenameCSV = $helper->getFilename(__FILE__, 'csv'); /** @var \PhpOffice\PhpSpreadsheet\Writer\Csv $writerCSV */ $writerCSV = new CsvWriter($spreadsheetFromCSV); -$writerCSV->setExcelCompatibility(true); +//$writerCSV->setExcelCompatibility(true); +$writerCSV->setUseBom(true); // because of non-ASCII chars $callStartTime = microtime(true); $writerCSV->save($filenameCSV); diff --git a/samples/Basic/19_Namedrange.php b/samples/Basic/19_Namedrange.php index d89e1b04..6170fa28 100644 --- a/samples/Basic/19_Namedrange.php +++ b/samples/Basic/19_Namedrange.php @@ -31,8 +31,8 @@ $spreadsheet->getActiveSheet()->setCellValue('A1', 'Firstname:') // Define named ranges $helper->log('Define named ranges'); -$spreadsheet->addNamedRange(new NamedRange('PersonName', $spreadsheet->getActiveSheet(), 'B1')); -$spreadsheet->addNamedRange(new NamedRange('PersonLN', $spreadsheet->getActiveSheet(), 'B2')); +$spreadsheet->addNamedRange(new NamedRange('PersonName', $spreadsheet->getActiveSheet(), '$B$1')); +$spreadsheet->addNamedRange(new NamedRange('PersonLN', $spreadsheet->getActiveSheet(), '$B$2')); // Rename named ranges $helper->log('Rename named ranges'); diff --git a/samples/Basic/30_Templatebiff5.php b/samples/Basic/30_Templatebiff5.php new file mode 100644 index 00000000..53c4c2a8 --- /dev/null +++ b/samples/Basic/30_Templatebiff5.php @@ -0,0 +1,43 @@ +log('Load from Xls template'); +$reader = IOFactory::createReader('Xls'); +$spreadsheet = $reader->load(__DIR__ . '/../templates/30templatebiff5.xls'); + +$helper->log('Add new data to the template'); +$data = [['title' => 'Excel for dummies', + 'price' => 17.99, + 'quantity' => 2, +], + ['title' => 'PHP for dummies', + 'price' => 15.99, + 'quantity' => 1, + ], + ['title' => 'Inside OOP', + 'price' => 12.95, + 'quantity' => 1, + ], +]; + +$spreadsheet->getActiveSheet()->setCellValue('D1', Date::PHPToExcel(time())); + +$baseRow = 5; +foreach ($data as $r => $dataRow) { + $row = $baseRow + $r; + $spreadsheet->getActiveSheet()->insertNewRowBefore($row, 1); + + $spreadsheet->getActiveSheet()->setCellValue('A' . $row, $r + 1) + ->setCellValue('B' . $row, $dataRow['title']) + ->setCellValue('C' . $row, $dataRow['price']) + ->setCellValue('D' . $row, $dataRow['quantity']) + ->setCellValue('E' . $row, '=C' . $row . '*D' . $row); +} +$spreadsheet->getActiveSheet()->removeRow($baseRow - 1, 1); + +// Save +$helper->write($spreadsheet, __FILE__); diff --git a/samples/Basic/40_Duplicate_style.php b/samples/Basic/40_Duplicate_style.php index 0366703d..38f7fb49 100644 --- a/samples/Basic/40_Duplicate_style.php +++ b/samples/Basic/40_Duplicate_style.php @@ -30,7 +30,7 @@ for ($col = 1; $col <= 50; ++$col) { } } $d = microtime(true) - $t; -$helper->log('Add data (end) . time: ' . round((string) ($d . 2)) . ' s'); +$helper->log('Add data (end) . time: ' . (string) round($d, 2) . ' s'); // Save $helper->write($spreadsheet, __FILE__); diff --git a/samples/Basic/43_Merge_workbooks.php b/samples/Basic/43_Merge_workbooks.php index 86314b3b..28353cc6 100644 --- a/samples/Basic/43_Merge_workbooks.php +++ b/samples/Basic/43_Merge_workbooks.php @@ -18,6 +18,10 @@ $helper->logRead('Xlsx', $filename2, $callStartTime); foreach ($spreadsheet2->getSheetNames() as $sheetName) { $sheet = $spreadsheet2->getSheetByName($sheetName); + if ($sheet === null) { + continue; + } + $sheet->setTitle($sheet->getTitle() . ' copied'); $spreadsheet1->addExternalSheet($sheet); } diff --git a/samples/Basic/45_Quadratic_equation_solver.php b/samples/Basic/45_Quadratic_equation_solver.php index 84c126aa..83a2000f 100644 --- a/samples/Basic/45_Quadratic_equation_solver.php +++ b/samples/Basic/45_Quadratic_equation_solver.php @@ -1,20 +1,35 @@
Enter the coefficients for the Ax2 + Bx + C = 0 - - + + + - - + + + - - + + +
+ + + +
+ + + +
+ + +

diff --git a/samples/Calculations/Financial/ACCRINT.php b/samples/Calculations/Financial/ACCRINT.php new file mode 100644 index 00000000..6f24f651 --- /dev/null +++ b/samples/Calculations/Financial/ACCRINT.php @@ -0,0 +1,35 @@ +log('Returns the accrued interest for a security that pays periodic interest.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Issue Date', DateHelper::getDateValue('01-Jan-2012')], + ['First Interest Date', DateHelper::getDateValue('01-Apr-2012')], + ['Settlement Date', DateHelper::getDateValue('31-Dec-2013')], + ['Annual Coupon Rate', 0.08], + ['Par Value', 10000], + ['Frequency', 4], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1:B3')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); +$worksheet->getStyle('B4')->getNumberFormat()->setFormatCode('0.00%'); +$worksheet->getStyle('B5')->getNumberFormat()->setFormatCode('$#,##0.00'); + +// Now the formula +$worksheet->setCellValue('B10', '=ACCRINT(B1, B2, B3, B4, B5, B6)'); +$worksheet->getStyle('B10')->getNumberFormat()->setFormatCode('$#,##0.00'); + +$helper->log($worksheet->getCell('B10')->getValue()); +$helper->log('ACCRINT() Result is ' . $worksheet->getCell('B10')->getFormattedValue()); diff --git a/samples/Calculations/Financial/ACCRINTM.php b/samples/Calculations/Financial/ACCRINTM.php new file mode 100644 index 00000000..8cc73899 --- /dev/null +++ b/samples/Calculations/Financial/ACCRINTM.php @@ -0,0 +1,33 @@ +log('Returns the accrued interest for a security that pays interest at maturity.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Issue Date', DateHelper::getDateValue('01-Jan-2012')], + ['Settlement Date', DateHelper::getDateValue('31-Dec-2012')], + ['Annual Coupon Rate', 0.08], + ['Par Value', 10000], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); +$worksheet->getStyle('B3')->getNumberFormat()->setFormatCode('0.00%'); +$worksheet->getStyle('B4')->getNumberFormat()->setFormatCode('$#,##0.00'); + +// Now the formula +$worksheet->setCellValue('B6', '=ACCRINTM(B1, B2, B3, B4)'); +$worksheet->getStyle('B6')->getNumberFormat()->setFormatCode('$#,##0.00'); + +$helper->log($worksheet->getCell('B6')->getValue()); +$helper->log('ACCRINTM() Result is ' . $worksheet->getCell('B6')->getFormattedValue()); diff --git a/samples/Calculations/Financial/AMORDEGRC.php b/samples/Calculations/Financial/AMORDEGRC.php new file mode 100644 index 00000000..c9e0c4c9 --- /dev/null +++ b/samples/Calculations/Financial/AMORDEGRC.php @@ -0,0 +1,38 @@ +log('Returns the prorated linear depreciation of an asset for a specified accounting period.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Cost', 150.00], + ['Date Purchased', DateHelper::getDateValue('01-Jan-2015')], + ['First Period Date', DateHelper::getDateValue('30-Sep-2015')], + ['Salvage Value', 20.00], + ['Number of Periods', 1], + ['Depreciation Rate', 0.20], + ['Basis', FinancialConstants::BASIS_DAYS_PER_YEAR_360_EUROPEAN], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1')->getNumberFormat()->setFormatCode('$#,##0.00'); +$worksheet->getStyle('B2:B3')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); +$worksheet->getStyle('B4')->getNumberFormat()->setFormatCode('$#,##0.00'); +$worksheet->getStyle('B6')->getNumberFormat()->setFormatCode('0.00%'); + +// Now the formula +$worksheet->setCellValue('B10', '=AMORDEGRC(B1, B2, B3, B4, B5, B6, B7)'); +$worksheet->getStyle('B10')->getNumberFormat()->setFormatCode('$#,##0.00'); + +$helper->log($worksheet->getCell('B10')->getValue()); +$helper->log('AMORDEGRC() Result is ' . $worksheet->getCell('B10')->getFormattedValue()); diff --git a/samples/Calculations/Financial/AMORLINC.php b/samples/Calculations/Financial/AMORLINC.php new file mode 100644 index 00000000..3491eae0 --- /dev/null +++ b/samples/Calculations/Financial/AMORLINC.php @@ -0,0 +1,38 @@ +log('Returns the prorated linear depreciation of an asset for a specified accounting period.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Cost', 150.00], + ['Date Purchased', DateHelper::getDateValue('01-Jan-2015')], + ['First Period Date', DateHelper::getDateValue('30-Sep-2015')], + ['Salvage Value', 20.00], + ['Period', 1], + ['Depreciation Rate', 0.20], + ['Basis', FinancialConstants::BASIS_DAYS_PER_YEAR_360_EUROPEAN], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1')->getNumberFormat()->setFormatCode('$#,##0.00'); +$worksheet->getStyle('B2:B3')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); +$worksheet->getStyle('B4')->getNumberFormat()->setFormatCode('$#,##0.00'); +$worksheet->getStyle('B6')->getNumberFormat()->setFormatCode('0.00%'); + +// Now the formula +$worksheet->setCellValue('B10', '=AMORLINC(B1, B2, B3, B4, B5, B6, B7)'); +$worksheet->getStyle('B10')->getNumberFormat()->setFormatCode('$#,##0.00'); + +$helper->log($worksheet->getCell('B10')->getValue()); +$helper->log('AMORLINC() Result is ' . $worksheet->getCell('B10')->getFormattedValue()); diff --git a/samples/Calculations/Financial/COUPDAYBS.php b/samples/Calculations/Financial/COUPDAYBS.php new file mode 100644 index 00000000..727d17d9 --- /dev/null +++ b/samples/Calculations/Financial/COUPDAYBS.php @@ -0,0 +1,29 @@ +log('Returns the number of days from the beginning of a coupon\'s period to the settlement date.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Settlement Date', DateHelper::getDateValue('01-Jan-2011')], + ['Maturity Date', DateHelper::getDateValue('25-Oct-2012')], + ['Frequency', 4], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); + +// Now the formula +$worksheet->setCellValue('B6', '=COUPDAYBS(B1, B2, B3)'); + +$helper->log($worksheet->getCell('B6')->getValue()); +$helper->log('COUPDAYBS() Result is ' . $worksheet->getCell('B6')->getFormattedValue()); diff --git a/samples/Calculations/Financial/COUPDAYS.php b/samples/Calculations/Financial/COUPDAYS.php new file mode 100644 index 00000000..f6e148cc --- /dev/null +++ b/samples/Calculations/Financial/COUPDAYS.php @@ -0,0 +1,29 @@ +log('Returns the number of days in the coupon period that contains the settlement date.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Settlement Date', DateHelper::getDateValue('01-Jan-2011')], + ['Maturity Date', DateHelper::getDateValue('25-Oct-2012')], + ['Frequency', 4], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); + +// Now the formula +$worksheet->setCellValue('B6', '=COUPDAYS(B1, B2, B3)'); + +$helper->log($worksheet->getCell('B6')->getValue()); +$helper->log('COUPDAYS() Result is ' . $worksheet->getCell('B6')->getFormattedValue()); diff --git a/samples/Calculations/Financial/COUPDAYSNC.php b/samples/Calculations/Financial/COUPDAYSNC.php new file mode 100644 index 00000000..dfb21dd7 --- /dev/null +++ b/samples/Calculations/Financial/COUPDAYSNC.php @@ -0,0 +1,29 @@ +log('Returns the number of days from the settlement date to the next coupon date.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Settlement Date', DateHelper::getDateValue('01-Jan-2011')], + ['Maturity Date', DateHelper::getDateValue('25-Oct-2012')], + ['Frequency', 4], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); + +// Now the formula +$worksheet->setCellValue('B6', '=COUPDAYSNC(B1, B2, B3)'); + +$helper->log($worksheet->getCell('B6')->getValue()); +$helper->log('COUPDAYSNC() Result is ' . $worksheet->getCell('B6')->getFormattedValue()); diff --git a/samples/Calculations/Financial/COUPNCD.php b/samples/Calculations/Financial/COUPNCD.php new file mode 100644 index 00000000..b38faf03 --- /dev/null +++ b/samples/Calculations/Financial/COUPNCD.php @@ -0,0 +1,30 @@ +log('Returns the next coupon date, after the settlement date.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Settlement Date', DateHelper::getDateValue('01-Jan-2011')], + ['Maturity Date', DateHelper::getDateValue('25-Oct-2012')], + ['Frequency', 4], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); + +// Now the formula +$worksheet->setCellValue('B6', '=COUPNCD(B1, B2, B3)'); +$worksheet->getStyle('B6')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); + +$helper->log($worksheet->getCell('B6')->getValue()); +$helper->log('COUPNCD() Result is ' . $worksheet->getCell('B6')->getFormattedValue()); diff --git a/samples/Calculations/Financial/COUPNUM.php b/samples/Calculations/Financial/COUPNUM.php new file mode 100644 index 00000000..b1bd0d52 --- /dev/null +++ b/samples/Calculations/Financial/COUPNUM.php @@ -0,0 +1,30 @@ +log('Returns the number of coupons payable, between a security\'s settlement date and maturity date,'); +$helper->log('rounded up to the nearest whole coupon.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Settlement Date', DateHelper::getDateValue('01-Jan-2011')], + ['Maturity Date', DateHelper::getDateValue('25-Oct-2012')], + ['Frequency', 4], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); + +// Now the formula +$worksheet->setCellValue('B6', '=COUPNUM(B1, B2, B3)'); + +$helper->log($worksheet->getCell('B6')->getValue()); +$helper->log('COUPNUM() Result is ' . $worksheet->getCell('B6')->getFormattedValue()); diff --git a/samples/Calculations/Financial/COUPPCD.php b/samples/Calculations/Financial/COUPPCD.php new file mode 100644 index 00000000..8ac78606 --- /dev/null +++ b/samples/Calculations/Financial/COUPPCD.php @@ -0,0 +1,30 @@ +log('Returns the previous coupon date, before the settlement date for a security.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Settlement Date', DateHelper::getDateValue('01-Jan-2011')], + ['Maturity Date', DateHelper::getDateValue('25-Oct-2012')], + ['Frequency', 4], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); + +// Now the formula +$worksheet->setCellValue('B6', '=COUPPCD(B1, B2, B3)'); +$worksheet->getStyle('B6')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); + +$helper->log($worksheet->getCell('B6')->getValue()); +$helper->log('COUPPCD() Result is ' . $worksheet->getCell('B6')->getFormattedValue()); diff --git a/samples/Calculations/Financial/CUMIPMT.php b/samples/Calculations/Financial/CUMIPMT.php new file mode 100644 index 00000000..f97caec8 --- /dev/null +++ b/samples/Calculations/Financial/CUMIPMT.php @@ -0,0 +1,38 @@ +log('Returns the cumulative interest paid on a loan or investment, between two specified periods.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Interest Rate (per period)', 0.05 / 12], + ['Number of Periods', 5 * 12], + ['Present Value', 50000], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1')->getNumberFormat()->setFormatCode('0.00%'); +$worksheet->getStyle('B3')->getNumberFormat()->setFormatCode('$#,##0.00'); + +// Now the formula +$baseRow = 5; +for ($year = 1; $year <= 5; ++$year) { + $row = (string) ($baseRow + $year); + $yearStartPeriod = (int) $year * 12 - 11; + $yearEndPeriod = (int) $year * 12; + + $worksheet->setCellValue("A{$row}", "Yr {$year}"); + $worksheet->setCellValue("B{$row}", "=CUMIPMT(\$B\$1, \$B\$2, \$B\$3, {$yearStartPeriod}, {$yearEndPeriod}, 0)"); + $worksheet->getStyle("B{$row}")->getNumberFormat()->setFormatCode('$#,##0.00;-$#,##0.00'); + + $helper->log($worksheet->getCell("B{$row}")->getValue()); + $helper->log("CUMIPMT() Year {$year} Result is " . $worksheet->getCell("B{$row}")->getFormattedValue()); +} diff --git a/samples/Calculations/Financial/CUMPRINC.php b/samples/Calculations/Financial/CUMPRINC.php new file mode 100644 index 00000000..86de3070 --- /dev/null +++ b/samples/Calculations/Financial/CUMPRINC.php @@ -0,0 +1,38 @@ +log('Returns the cumulative payment on the principal of a loan or investment, between two specified periods.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Interest Rate (per period)', 0.05 / 12], + ['Number of Periods', 5 * 12], + ['Present Value', 50000], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1')->getNumberFormat()->setFormatCode('0.00%'); +$worksheet->getStyle('B3')->getNumberFormat()->setFormatCode('$#,##0.00'); + +// Now the formula +$baseRow = 5; +for ($year = 1; $year <= 5; ++$year) { + $row = (string) ($baseRow + $year); + $yearStartPeriod = (int) $year * 12 - 11; + $yearEndPeriod = (int) $year * 12; + + $worksheet->setCellValue("A{$row}", "Yr {$year}"); + $worksheet->setCellValue("B{$row}", "=CUMPRINC(\$B\$1, \$B\$2, \$B\$3, {$yearStartPeriod}, {$yearEndPeriod}, 0)"); + $worksheet->getStyle("B{$row}")->getNumberFormat()->setFormatCode('$#,##0.00;-$#,##0.00'); + + $helper->log($worksheet->getCell("B{$row}")->getValue()); + $helper->log("CUMPRINC() Year {$year} Result is " . $worksheet->getCell("B{$row}")->getFormattedValue()); +} diff --git a/samples/Calculations/Financial/DB.php b/samples/Calculations/Financial/DB.php new file mode 100644 index 00000000..0759c0aa --- /dev/null +++ b/samples/Calculations/Financial/DB.php @@ -0,0 +1,50 @@ +log('Returns the depreciation of an asset, using the Fixed Declining Balance Method,'); +$helper->log('for each period of the asset\'s lifetime.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Cost Value', 10000], + ['Salvage', 1000], + ['Life', 5, 'Years'], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('$#,##0.00'); + +// Now the formula +$baseRow = 5; +for ($year = 1; $year <= 5; ++$year) { + $row = (string) ($baseRow + $year); + + $worksheet->setCellValue("A{$row}", "Depreciation after Yr {$year}"); + $worksheet->setCellValue("B{$row}", "=DB(\$B\$1, \$B\$2, \$B\$3, {$year})"); + $worksheet->getStyle("B{$row}")->getNumberFormat()->setFormatCode('$#,##0.00;-$#,##0.00'); + + $helper->log($worksheet->getCell("B{$row}")->getValue()); + $helper->log("DB() Year {$year} Result is " . $worksheet->getCell("B{$row}")->getFormattedValue()); +} + +$helper->log('And with depreciation only starting after 6 months.'); + +$baseRow = 12; +for ($year = 1; $year <= 6; ++$year) { + $row = (string) ($baseRow + $year); + + $worksheet->setCellValue("A{$row}", "Depreciation after Yr {$year}"); + $worksheet->setCellValue("B{$row}", "=DB(\$B\$1, \$B\$2, \$B\$3, {$year}, 6)"); + $worksheet->getStyle("B{$row}")->getNumberFormat()->setFormatCode('$#,##0.00;-$#,##0.00'); + + $helper->log($worksheet->getCell("B{$row}")->getValue()); + $helper->log("DB() Year {$year} Result is " . $worksheet->getCell("B{$row}")->getFormattedValue()); +} diff --git a/samples/Calculations/Financial/DDB.php b/samples/Calculations/Financial/DDB.php new file mode 100644 index 00000000..d261d4bd --- /dev/null +++ b/samples/Calculations/Financial/DDB.php @@ -0,0 +1,36 @@ +log('Returns the depreciation of an asset, using the Double Declining Balance Method,'); +$helper->log('for each period of the asset\'s lifetime.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Cost Value', 10000], + ['Salvage', 1000], + ['Life', 5, 'Years'], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('$#,##0.00'); + +// Now the formula +$baseRow = 5; +for ($year = 1; $year <= 5; ++$year) { + $row = (string) ($baseRow + $year); + + $worksheet->setCellValue("A{$row}", "Depreciation after Yr {$year}"); + $worksheet->setCellValue("B{$row}", "=DDB(\$B\$1, \$B\$2, \$B\$3, {$year})"); + $worksheet->getStyle("B{$row}")->getNumberFormat()->setFormatCode('$#,##0.00;-$#,##0.00'); + + $helper->log($worksheet->getCell("B{$row}")->getValue()); + $helper->log("DDB() Year {$year} Result is " . $worksheet->getCell("B{$row}")->getFormattedValue()); +} diff --git a/samples/Calculations/Financial/DISC.php b/samples/Calculations/Financial/DISC.php new file mode 100644 index 00000000..389d75e0 --- /dev/null +++ b/samples/Calculations/Financial/DISC.php @@ -0,0 +1,32 @@ +log('Returns the the Discount Rate for a security.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Settlement Date', DateHelper::getDateValue('01-Apr-2016')], + ['Maturity Date', DateHelper::getDateValue('31-Mar-2021')], + ['Par Value', 95.00], + ['Redemption Value', 100.00], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); +$worksheet->getStyle('B3:B4')->getNumberFormat()->setFormatCode('$#,##0.00'); + +// Now the formula +$worksheet->setCellValue('B7', '=DISC(B1, B2, B3, B4)'); +$worksheet->getStyle('B7')->getNumberFormat()->setFormatCode('0.00%'); + +$helper->log($worksheet->getCell('B7')->getValue()); +$helper->log('DISC() Result is ' . $worksheet->getCell('B7')->getFormattedValue()); diff --git a/samples/Calculations/Financial/DOLLARDE.php b/samples/Calculations/Financial/DOLLARDE.php new file mode 100644 index 00000000..d7187401 --- /dev/null +++ b/samples/Calculations/Financial/DOLLARDE.php @@ -0,0 +1,30 @@ +log('Returns the dollar value in fractional notation, into a dollar value expressed as a decimal.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + [1.01, 16], + [1.1, 16], + [1.03, 32], + [1.3, 32], + [1.12, 32], +]; + +$worksheet->fromArray($arguments, null, 'A1'); + +// Now the formula +for ($row = 1; $row <= 5; ++$row) { + $worksheet->setCellValue("C{$row}", "=DOLLARDE(A{$row}, B{$row})"); + + $helper->log($worksheet->getCell("C{$row}")->getValue()); + $helper->log('DOLLARDE() Result is ' . $worksheet->getCell("C{$row}")->getFormattedValue()); +} diff --git a/samples/Calculations/Financial/DOLLARFR.php b/samples/Calculations/Financial/DOLLARFR.php new file mode 100644 index 00000000..75424be0 --- /dev/null +++ b/samples/Calculations/Financial/DOLLARFR.php @@ -0,0 +1,30 @@ +log('Returns the dollar value expressed as a decimal number, into a dollar price, expressed as a fraction.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + [1.0625, 16], + [1.625, 16], + [1.09375, 32], + [1.9375, 32], + [1.375, 32], +]; + +$worksheet->fromArray($arguments, null, 'A1'); + +// Now the formula +for ($row = 1; $row <= 5; ++$row) { + $worksheet->setCellValue("C{$row}", "=DOLLARFR(A{$row}, B{$row})"); + + $helper->log($worksheet->getCell("C{$row}")->getValue()); + $helper->log('DOLLARFR() Result is ' . $worksheet->getCell("C{$row}")->getFormattedValue()); +} diff --git a/samples/Calculations/Financial/EFFECT.php b/samples/Calculations/Financial/EFFECT.php new file mode 100644 index 00000000..a74f4500 --- /dev/null +++ b/samples/Calculations/Financial/EFFECT.php @@ -0,0 +1,31 @@ +log('Returns the effective annual interest rate for a given nominal interest rate and number of'); +$helper->log('compounding periods per year.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + [0.10, 4], + [0.10, 2], + [0.025, 2], +]; + +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1:B3')->getNumberFormat()->setFormatCode('0.00%'); + +// Now the formula +for ($row = 1; $row <= 3; ++$row) { + $worksheet->setCellValue("C{$row}", "=EFFECT(A{$row}, B{$row})"); + $worksheet->getStyle("C{$row}")->getNumberFormat()->setFormatCode('0.00%'); + + $helper->log($worksheet->getCell("C{$row}")->getValue()); + $helper->log('EFFECT() Result is ' . $worksheet->getCell("C{$row}")->getFormattedValue()); +} diff --git a/samples/Calculations/Financial/FV.php b/samples/Calculations/Financial/FV.php new file mode 100644 index 00000000..31ddb630 --- /dev/null +++ b/samples/Calculations/Financial/FV.php @@ -0,0 +1,36 @@ +log('Returns the Future Value of an investment with periodic constant payments and a constant interest rate.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Interest Rate', 0.05, 0.10], + ['Pament Frequency', 12, 4], + ['Duration (Years)', 5, 4], + ['Investment', -1000.00, -2000.00], + ['Payment Type', 0, 1], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1:C1')->getNumberFormat()->setFormatCode('0.00%'); +$worksheet->getStyle('B4:C4')->getNumberFormat()->setFormatCode('$#,##0.00'); + +// Now the formula +$worksheet->setCellValue('B8', '=FV(B1/B2, B3*B2, B4)'); +$worksheet->setCellValue('C8', '=FV(C1/C2, C3*C2, C4, null, C5)'); +$worksheet->getStyle('B8:C8')->getNumberFormat()->setFormatCode('$#,##0.00'); + +$helper->log($worksheet->getCell('B8')->getValue()); +$helper->log('FV() Result is ' . $worksheet->getCell('B8')->getFormattedValue()); + +$helper->log($worksheet->getCell('C6')->getValue()); +$helper->log('FV() Result is ' . $worksheet->getCell('C8')->getFormattedValue()); diff --git a/samples/Calculations/Financial/FVSCHEDULE.php b/samples/Calculations/Financial/FVSCHEDULE.php new file mode 100644 index 00000000..dfd2abbc --- /dev/null +++ b/samples/Calculations/Financial/FVSCHEDULE.php @@ -0,0 +1,36 @@ +log('Returns the Future Value of an initial principal, after applying a series of compound interest rates.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Principal'], + [10000.00], + [null], + ['Schedule'], + [0.05], + [0.05], + [0.035], + [0.035], + [0.035], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('A2')->getNumberFormat()->setFormatCode('$#,##0.00'); +$worksheet->getStyle('A5:A9')->getNumberFormat()->setFormatCode('0.00%'); + +// Now the formula +$worksheet->setCellValue('B1', '=FVSCHEDULE(A2, A5:A9)'); +$worksheet->getStyle('B1')->getNumberFormat()->setFormatCode('$#,##0.00'); + +$helper->log($worksheet->getCell('B1')->getValue()); +$helper->log('FVSCHEDULE() Result is ' . $worksheet->getCell('B1')->getFormattedValue()); diff --git a/samples/Calculations/Financial/INTRATE.php b/samples/Calculations/Financial/INTRATE.php new file mode 100644 index 00000000..594fb6cb --- /dev/null +++ b/samples/Calculations/Financial/INTRATE.php @@ -0,0 +1,32 @@ +log('Returns the interest rate for a fully invested security.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Settlement Date', DateHelper::getDateValue('01-Apr-2005')], + ['Maturity Date', DateHelper::getDateValue('31-Mar-2010')], + ['Investment', 1000.00], + ['Investment', 2125.00], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1:B2')->getNumberFormat()->setFormatCode('dd-mmm-yyyy'); +$worksheet->getStyle('B3:B4')->getNumberFormat()->setFormatCode('$#,##0.00'); + +// Now the formula +$worksheet->setCellValue('B7', '=INTRATE(B1, B2, B3, B4)'); +$worksheet->getStyle('B7')->getNumberFormat()->setFormatCode('0.00%'); + +$helper->log($worksheet->getCell('B7')->getValue()); +$helper->log('INTRATE() Result is ' . $worksheet->getCell('B7')->getFormattedValue()); diff --git a/samples/Calculations/Financial/IPMT.php b/samples/Calculations/Financial/IPMT.php new file mode 100644 index 00000000..138ec378 --- /dev/null +++ b/samples/Calculations/Financial/IPMT.php @@ -0,0 +1,37 @@ +log('Returns the interest payment, during a specific period of a loan or investment that is paid in,'); +$helper->log('constant periodic payments, with a constant interest rate.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Interest Rate', 0.05], + ['Number of Years', 5], + ['Present Value', 50000.00], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1')->getNumberFormat()->setFormatCode('0.00%'); +$worksheet->getStyle('B3')->getNumberFormat()->setFormatCode('$#,##0.00'); + +// Now the formula +$baseRow = 6; +for ($month = 1; $month <= 12; ++$month) { + $row = (string) ($baseRow + $month); + + $worksheet->setCellValue("A{$row}", "Payment for Mth {$month}"); + $worksheet->setCellValue("B{$row}", "=IPMT(\$B\$1/12, {$month}, \$B\$2*12, \$B\$3)"); + $worksheet->getStyle("B{$row}")->getNumberFormat()->setFormatCode('$#,##0.00;-$#,##0.00'); + + $helper->log($worksheet->getCell("B{$row}")->getValue()); + $helper->log("IPMT() Month {$month} Result is " . $worksheet->getCell("B{$row}")->getFormattedValue()); +} diff --git a/samples/Calculations/Financial/IRR.php b/samples/Calculations/Financial/IRR.php new file mode 100644 index 00000000..e489af93 --- /dev/null +++ b/samples/Calculations/Financial/IRR.php @@ -0,0 +1,38 @@ +log('Returns the Internal Rate of Return for a supplied series of periodic cash flows.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Initial Investment', -100.00], + ['Year 1 Income', 20.00], + ['Year 2 Income', 24.00, 'IRR after 3 Years'], + ['Year 3 Income', 28.80], + ['Year 4 Income', 34.56, 'IRR after 5 Years'], + ['Year 5 Income', 41.47], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1:B6')->getNumberFormat()->setFormatCode('$#,##0.00;-$#,##0.00'); + +// Now the formula +$worksheet->setCellValue('C4', '=IRR(B1:B4)'); +$worksheet->getStyle('C4')->getNumberFormat()->setFormatCode('0.00%'); + +$helper->log($worksheet->getCell('C4')->getValue()); +$helper->log('IRR() Result is ' . $worksheet->getCell('C4')->getFormattedValue()); + +$worksheet->setCellValue('C6', '=IRR(B1:B6)'); +$worksheet->getStyle('C6')->getNumberFormat()->setFormatCode('0.00%'); + +$helper->log($worksheet->getCell('C6')->getValue()); +$helper->log('IRR() Result is ' . $worksheet->getCell('C6')->getFormattedValue()); diff --git a/samples/Calculations/Financial/ISPMT.php b/samples/Calculations/Financial/ISPMT.php new file mode 100644 index 00000000..cbede7ce --- /dev/null +++ b/samples/Calculations/Financial/ISPMT.php @@ -0,0 +1,36 @@ +log('Returns the interest paid during a specific period of a loan or investment.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Interest Rate', 0.05], + ['Number of Years', 5], + ['Present Value', 50000.00], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1')->getNumberFormat()->setFormatCode('0.00%'); +$worksheet->getStyle('B3')->getNumberFormat()->setFormatCode('$#,##0.00'); + +// Now the formula +$baseRow = 6; +for ($month = 1; $month <= 12; ++$month) { + $row = (string) ($baseRow + $month); + + $worksheet->setCellValue("A{$row}", "Payment for Mth {$month}"); + $worksheet->setCellValue("B{$row}", "=ISPMT(\$B\$1/12, {$month}, \$B\$2*12, \$B\$3)"); + $worksheet->getStyle("B{$row}")->getNumberFormat()->setFormatCode('$#,##0.00;-$#,##0.00'); + + $helper->log($worksheet->getCell("B{$row}")->getValue()); + $helper->log("ISPMT() Month {$month} Result is " . $worksheet->getCell("B{$row}")->getFormattedValue()); +} diff --git a/samples/Calculations/Financial/MIRR.php b/samples/Calculations/Financial/MIRR.php new file mode 100644 index 00000000..313e10bd --- /dev/null +++ b/samples/Calculations/Financial/MIRR.php @@ -0,0 +1,42 @@ +log('Returns the Modified Internal Rate of Return for a supplied series of periodic cash flows.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Initial Investment', -100.00], + ['Year 1 Income', 18.00], + ['Year 2 Income', 22.50, 'MIRR after 3 Years'], + ['Year 3 Income', 28.00], + ['Year 4 Income', 35.50, 'MIRR after 5 Years'], + ['Year 5 Income', 45.00], + [null], + ['Finance Rate', 0.055], + ['Re-invest Rate', 0.05], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1:B6')->getNumberFormat()->setFormatCode('$#,##0.00;-$#,##0.00'); +$worksheet->getStyle('B8:B9')->getNumberFormat()->setFormatCode('0.00%'); + +// Now the formula +$worksheet->setCellValue('C4', '=MIRR(B1:B4, B8, B9)'); +$worksheet->getStyle('C4')->getNumberFormat()->setFormatCode('0.00%'); + +$helper->log($worksheet->getCell('C4')->getValue()); +$helper->log('MIRR() Result is ' . $worksheet->getCell('C4')->getFormattedValue()); + +$worksheet->setCellValue('C6', '=MIRR(B1:B6, B8, B9)'); +$worksheet->getStyle('C6')->getNumberFormat()->setFormatCode('0.00%'); + +$helper->log($worksheet->getCell('C6')->getValue()); +$helper->log('MIRR() Result is ' . $worksheet->getCell('C6')->getFormattedValue()); diff --git a/samples/Calculations/Financial/NOMINAL.php b/samples/Calculations/Financial/NOMINAL.php new file mode 100644 index 00000000..6b7951a1 --- /dev/null +++ b/samples/Calculations/Financial/NOMINAL.php @@ -0,0 +1,31 @@ +log('Returns the nominal interest rate for a given effective interest rate and number of'); +$helper->log('compounding periods per year.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + [0.10, 4], + [0.10, 2], + [0.025, 12], +]; + +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1:B3')->getNumberFormat()->setFormatCode('0.00%'); + +// Now the formula +for ($row = 1; $row <= 3; ++$row) { + $worksheet->setCellValue("C{$row}", "=NOMINAL(A{$row}, B{$row})"); + $worksheet->getStyle("C{$row}")->getNumberFormat()->setFormatCode('0.00%'); + + $helper->log($worksheet->getCell("C{$row}")->getValue()); + $helper->log('NOMINAL() Result is ' . $worksheet->getCell("C{$row}")->getFormattedValue()); +} diff --git a/samples/Calculations/Financial/NPER.php b/samples/Calculations/Financial/NPER.php new file mode 100644 index 00000000..8acae473 --- /dev/null +++ b/samples/Calculations/Financial/NPER.php @@ -0,0 +1,39 @@ +log('Returns the number of periods required to pay off a loan, for a constant periodic payment'); +$helper->log('and a constant interest rate.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Interest Rate', 0.04, 0.06], + ['Payments per Year', 1, 4], + ['Payment Amount', -6000.00, -2000], + ['Present Value', 50000, 60000], + ['Future Value', null, 30000], + ['Payment Type', null, FinancialConstants::PAYMENT_BEGINNING_OF_PERIOD], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1:C1')->getNumberFormat()->setFormatCode('0.00%'); +$worksheet->getStyle('B3:C5')->getNumberFormat()->setFormatCode('$#,##0.00'); + +// Now the formula +$worksheet->setCellValue('B8', '=NPER(B1/B2, B3, B4)'); + +$helper->log($worksheet->getCell('B8')->getValue()); +$helper->log('NPER() Result is ' . $worksheet->getCell('B8')->getFormattedValue()); + +$worksheet->setCellValue('C8', '=NPER(C1/C2, C3, C4, C5, C6)'); + +$helper->log($worksheet->getCell('C8')->getValue()); +$helper->log('NPER() Result is ' . $worksheet->getCell('C8')->getFormattedValue()); diff --git a/samples/Calculations/Financial/NPV.php b/samples/Calculations/Financial/NPV.php new file mode 100644 index 00000000..fa76d542 --- /dev/null +++ b/samples/Calculations/Financial/NPV.php @@ -0,0 +1,43 @@ +log('Returns the Net Present Value of an investment, based on a supplied discount rate,'); +$helper->log('and a series of future payments and income.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +// Add some data +$arguments = [ + ['Annual Discount Rate', 0.02, 0.05], + ['Initial Investment Cost', -5000.00, -10000], + ['Return from Year 1', 800.00, 2000.00], + ['Return from Year 2', 950.00, 2400.00], + ['Return from Year 3', 1080.00, 2900.00], + ['Return from Year 4', 1220.00, 3500.00], + ['Return from Year 5', 1500.00, 4100.00], +]; + +// Some basic formatting for the data +$worksheet->fromArray($arguments, null, 'A1'); +$worksheet->getStyle('B1:C1')->getNumberFormat()->setFormatCode('0.00%'); +$worksheet->getStyle('B2:C7')->getNumberFormat()->setFormatCode('$#,##0.00'); + +// Now the formula +// When initial investment is made at the end of the first period +$worksheet->setCellValue('B10', '=NPV(B1, B2:B7)'); +$worksheet->getStyle('B10')->getNumberFormat()->setFormatCode('$#,##0.00'); + +$helper->log($worksheet->getCell('B10')->getValue()); +$helper->log('NPV() Result is ' . $worksheet->getCell('B10')->getFormattedValue()); + +// When initial investment is made at the start of the first period +$worksheet->setCellValue('C10', '=NPV(C1, C3:C7) + C2'); +$worksheet->getStyle('C10')->getNumberFormat()->setFormatCode('$#,##0.00'); + +$helper->log($worksheet->getCell('C10')->getValue()); +$helper->log('NPV() Result is ' . $worksheet->getCell('C10')->getFormattedValue()); diff --git a/samples/Calculations/LookupRef/ADDRESS.php b/samples/Calculations/LookupRef/ADDRESS.php new file mode 100644 index 00000000..2377541d --- /dev/null +++ b/samples/Calculations/LookupRef/ADDRESS.php @@ -0,0 +1,22 @@ +log('Returns a text reference to a single cell in a worksheet.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +$worksheet->getCell('A1')->setValue('=ADDRESS(2,3)'); +$worksheet->getCell('A2')->setValue('=ADDRESS(2,3,2)'); +$worksheet->getCell('A3')->setValue('=ADDRESS(2,3,2,FALSE)'); +$worksheet->getCell('A4')->setValue('=ADDRESS(2,3,1,FALSE,"[Book1]Sheet1")'); +$worksheet->getCell('A5')->setValue('=ADDRESS(2,3,1,FALSE,"EXCEL SHEET")'); + +for ($row = 1; $row <= 5; ++$row) { + $cell = $worksheet->getCell("A{$row}"); + $helper->log("A{$row}: {$cell->getValue()} => {$cell->getCalculatedValue()}"); +} diff --git a/samples/Calculations/LookupRef/COLUMN.php b/samples/Calculations/LookupRef/COLUMN.php new file mode 100644 index 00000000..e9e58466 --- /dev/null +++ b/samples/Calculations/LookupRef/COLUMN.php @@ -0,0 +1,23 @@ +log('Returns the column index of a cell.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +$worksheet->getCell('A1')->setValue('=COLUMN(C13)'); +$worksheet->getCell('A2')->setValue('=COLUMN(E13:G15)'); +$worksheet->getCell('F1')->setValue('=COLUMN()'); + +for ($row = 1; $row <= 2; ++$row) { + $cell = $worksheet->getCell("A{$row}"); + $helper->log("A{$row}: {$cell->getValue()} => {$cell->getCalculatedValue()}"); +} + +$cell = $worksheet->getCell('F1'); +$helper->log("F1: {$cell->getValue()} => {$cell->getCalculatedValue()}"); diff --git a/samples/Calculations/LookupRef/COLUMNS.php b/samples/Calculations/LookupRef/COLUMNS.php new file mode 100644 index 00000000..4d7f8d10 --- /dev/null +++ b/samples/Calculations/LookupRef/COLUMNS.php @@ -0,0 +1,21 @@ +log('Returns the number of columns in an array or reference.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +$worksheet->getCell('A1')->setValue('=COLUMNS(C1:G4)'); +$worksheet->getCell('A2')->setValue('=COLUMNS({1,2,3;4,5,6})'); +$worksheet->getCell('A3')->setValue('=ROWS(C1:E4 D3:G5)'); +$worksheet->getCell('A4')->setValue('=COLUMNS(1:1)'); + +for ($row = 1; $row <= 4; ++$row) { + $cell = $worksheet->getCell("A{$row}"); + $helper->log("A{$row}: {$cell->getValue()} => {$cell->getCalculatedValue()}"); +} diff --git a/samples/Calculations/LookupRef/INDEX.php b/samples/Calculations/LookupRef/INDEX.php new file mode 100644 index 00000000..9ef0b945 --- /dev/null +++ b/samples/Calculations/LookupRef/INDEX.php @@ -0,0 +1,39 @@ +log('Returns the row index of a cell.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +$data1 = [ + ['Apples', 'Lemons'], + ['Bananas', 'Pears'], +]; + +$data2 = [ + [4, 6], + [5, 3], + [6, 9], + [7, 5], + [8, 3], +]; + +$worksheet->fromArray($data1, null, 'A1'); +$worksheet->fromArray($data2, null, 'C1'); + +$worksheet->getCell('A11')->setValue('=INDEX(A1:B2, 2, 2)'); +$worksheet->getCell('A12')->setValue('=INDEX(A1:B2, 2, 1)'); +$worksheet->getCell('A13')->setValue('=INDEX({1,2;3,4}, 0, 2)'); +$worksheet->getCell('A14')->setValue('=INDEX(C1:C5, 5)'); +$worksheet->getCell('A15')->setValue('=INDEX(C1:D5, 5, 2)'); +$worksheet->getCell('A16')->setValue('=SUM(INDEX(C1:D5, 5, 0))'); + +for ($row = 11; $row <= 16; ++$row) { + $cell = $worksheet->getCell("A{$row}"); + $helper->log("A{$row}: {$cell->getValue()} => {$cell->getCalculatedValue()}"); +} diff --git a/samples/Calculations/LookupRef/INDIRECT.php b/samples/Calculations/LookupRef/INDIRECT.php new file mode 100644 index 00000000..ffbada9a --- /dev/null +++ b/samples/Calculations/LookupRef/INDIRECT.php @@ -0,0 +1,33 @@ +log('Returns the cell specified by a text string.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +$data = [ + [8, 9, 0], + [3, 4, 5], + [9, 1, 3], + [4, 6, 2], +]; +$worksheet->fromArray($data, null, 'C1'); + +$spreadsheet->addNamedRange(new NamedRange('NAMED_RANGE_FOR_CELL_D4', $worksheet, '="$D$4"')); + +$worksheet->getCell('A1')->setValue('=INDIRECT("C1")'); +$worksheet->getCell('A2')->setValue('=INDIRECT("D"&4)'); +$worksheet->getCell('A3')->setValue('=INDIRECT("E"&ROW())'); +$worksheet->getCell('A4')->setValue('=SUM(INDIRECT("$C$4:$E$4"))'); +$worksheet->getCell('A5')->setValue('=INDIRECT(NAMED_RANGE_FOR_CELL_D4)'); + +for ($row = 1; $row <= 5; ++$row) { + $cell = $worksheet->getCell("A{$row}"); + $helper->log("A{$row}: {$cell->getValue()} => {$cell->getCalculatedValue()}"); +} diff --git a/samples/Calculations/LookupRef/OFFSET.php b/samples/Calculations/LookupRef/OFFSET.php new file mode 100644 index 00000000..ae613ec5 --- /dev/null +++ b/samples/Calculations/LookupRef/OFFSET.php @@ -0,0 +1,33 @@ +log('Returns a cell range that is a specified number of rows and columns from a cell or range of cells.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +$data = [ + [null, 'Week 1', 'Week 2', 'Week 3', 'Week 4'], + ['Sunday', 4500, 2200, 3800, 1500], + ['Monday', 5500, 6100, 5200, 4800], + ['Tuesday', 7000, 6200, 5000, 7100], + ['Wednesday', 8000, 4000, 3900, 7600], + ['Thursday', 5900, 5500, 6900, 7100], + ['Friday', 4900, 6300, 6900, 5200], + ['Saturday', 3500, 3900, 5100, 4100], +]; +$worksheet->fromArray($data, null, 'A3'); + +$worksheet->getCell('H1')->setValue('=OFFSET(A3, 3, 1)'); +$worksheet->getCell('H2')->setValue('=SUM(OFFSET(A3, 3, 1, 1, 4))'); +$worksheet->getCell('H3')->setValue('=SUM(OFFSET(B3:E3, 3, 0))'); +$worksheet->getCell('H4')->setValue('=SUM(OFFSET(E3, 1, -3, 7))'); + +for ($row = 1; $row <= 4; ++$row) { + $cell = $worksheet->getCell("H{$row}"); + $helper->log("H{$row}: {$cell->getValue()} => {$cell->getCalculatedValue()}"); +} diff --git a/samples/Calculations/LookupRef/ROW.php b/samples/Calculations/LookupRef/ROW.php new file mode 100644 index 00000000..560639a5 --- /dev/null +++ b/samples/Calculations/LookupRef/ROW.php @@ -0,0 +1,20 @@ +log('Returns the row index of a cell.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +$worksheet->getCell('A1')->setValue('=ROW(C13)'); +$worksheet->getCell('A2')->setValue('=ROW(E19:G21)'); +$worksheet->getCell('A3')->setValue('=ROW()'); + +for ($row = 1; $row <= 3; ++$row) { + $cell = $worksheet->getCell("A{$row}"); + $helper->log("A{$row}: {$cell->getValue()} => {$cell->getCalculatedValue()}"); +} diff --git a/samples/Calculations/LookupRef/ROWS.php b/samples/Calculations/LookupRef/ROWS.php new file mode 100644 index 00000000..3cdf085b --- /dev/null +++ b/samples/Calculations/LookupRef/ROWS.php @@ -0,0 +1,20 @@ +log('Returns the row index of a cell.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +$worksheet->getCell('A1')->setValue('=ROWS(C1:E4)'); +$worksheet->getCell('A2')->setValue('=ROWS({1,2,3;4,5,6})'); +$worksheet->getCell('A3')->setValue('=ROWS(C1:E4 D3:G5)'); + +for ($row = 1; $row <= 3; ++$row) { + $cell = $worksheet->getCell("A{$row}"); + $helper->log("A{$row}: {$cell->getValue()} => {$cell->getCalculatedValue()}"); +} diff --git a/samples/Calculations/LookupRef/VLOOKUP.php b/samples/Calculations/LookupRef/VLOOKUP.php new file mode 100644 index 00000000..3e7eaa71 --- /dev/null +++ b/samples/Calculations/LookupRef/VLOOKUP.php @@ -0,0 +1,35 @@ +log('Searches for a value in the top row of a table or an array of values, + and then returns a value in the same column from a row you specify + in the table or array.'); + +// Create new PhpSpreadsheet object +$spreadsheet = new Spreadsheet(); +$worksheet = $spreadsheet->getActiveSheet(); + +$data = [ + ['ID', 'First Name', 'Last Name', 'Salary'], + [72, 'Emily', 'Smith', 64901, null, 'ID', 53, 66, 56], + [66, 'James', 'Anderson', 70855, null, 'Salary'], + [14, 'Mia', 'Clark', 188657], + [30, 'John', 'Lewis', 97566], + [53, 'Jessica', 'Walker', 58339], + [56, 'Mark', 'Reed', 125180], + [79, 'Richard', 'Lopez', 91632], +]; + +$worksheet->fromArray($data, null, 'B2'); + +$worksheet->getCell('H4')->setValue('=VLOOKUP(H3, B3:E9, 4, FALSE)'); +$worksheet->getCell('I4')->setValue('=VLOOKUP(I3, B3:E9, 4, FALSE)'); +$worksheet->getCell('J4')->setValue('=VLOOKUP(J3, B3:E9, 4, FALSE)'); + +for ($column = 'H'; $column !== 'K'; ++$column) { + $cell = $worksheet->getCell("{$column}4"); + $helper->log("{$column}4: {$cell->getValue()} => {$cell->getCalculatedValue()}"); +} diff --git a/samples/Chart/35_Chart_render.php b/samples/Chart/35_Chart_render.php index 9638c679..ebab16a7 100644 --- a/samples/Chart/35_Chart_render.php +++ b/samples/Chart/35_Chart_render.php @@ -5,6 +5,11 @@ use PhpOffice\PhpSpreadsheet\Settings; require __DIR__ . '/../Header.php'; +if (PHP_VERSION_ID >= 80000) { + $helper->log('Jpgraph no longer runs against PHP8'); + exit; +} + // Change these values to select the Rendering library that you wish to use Settings::setChartRenderer(\PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph::class); diff --git a/samples/Reader/16_Handling_loader_exceptions_using_TryCatch.php b/samples/Reader/16_Handling_loader_exceptions_using_TryCatch.php index 80bb371d..5b102967 100644 --- a/samples/Reader/16_Handling_loader_exceptions_using_TryCatch.php +++ b/samples/Reader/16_Handling_loader_exceptions_using_TryCatch.php @@ -1,6 +1,7 @@ log('Loading file ' . pathinfo($inputFileName, PATHINFO_BASENAME) . ' u try { $spreadsheet = IOFactory::load($inputFileName); -} catch (InvalidArgumentException $e) { +} catch (ReaderException $e) { $helper->log('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage()); } diff --git a/samples/Reader/20_Reader_worksheet_hyperlink_image.php b/samples/Reader/20_Reader_worksheet_hyperlink_image.php index 9dad4b6c..19d837a5 100644 --- a/samples/Reader/20_Reader_worksheet_hyperlink_image.php +++ b/samples/Reader/20_Reader_worksheet_hyperlink_image.php @@ -1,5 +1,6 @@ log('Write link: ' . $baseUrl); $drawing->setWorksheet($aSheet); -$filename = tempnam(\PhpOffice\PhpSpreadsheet\Shared\File::sysGetTempDir(), 'phpspreadsheet-test'); +$filename = File::temporaryFilename(); $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, $inputFileType); $writer->save($filename); diff --git a/samples/Reading_workbook_data/Properties.php b/samples/Reading_workbook_data/Properties.php index 5bf25b8e..8f7be375 100644 --- a/samples/Reading_workbook_data/Properties.php +++ b/samples/Reading_workbook_data/Properties.php @@ -1,6 +1,7 @@ log('Document Creator: ' . $creator); // Read the Date when the workbook was created (as a PHP timestamp value) $creationDatestamp = $spreadsheet->getProperties()->getCreated(); -// Format the date and time using the standard PHP date() function -$creationDate = date('l, d<\s\up>S F Y', $creationDatestamp); -$creationTime = date('g:i A', $creationDatestamp); +$creationDate = Date::formattedDateTimeFromTimestamp("$creationDatestamp", 'l, d<\s\up>S F Y'); +$creationTime = Date::formattedDateTimeFromTimestamp("$creationDatestamp", 'g:i A'); $helper->log('Created On: ' . $creationDate . ' at ' . $creationTime); // Read the name of the last person to modify this workbook @@ -30,8 +30,8 @@ $helper->log('Last Modified By: ' . $modifiedBy); // Read the Date when the workbook was last modified (as a PHP timestamp value) $modifiedDatestamp = $spreadsheet->getProperties()->getModified(); // Format the date and time using the standard PHP date() function -$modifiedDate = date('l, d<\s\up>S F Y', $modifiedDatestamp); -$modifiedTime = date('g:i A', $modifiedDatestamp); +$modifiedDate = Date::formattedDateTimeFromTimestamp("$modifiedDatestamp", 'l, d<\s\up>S F Y'); +$modifiedTime = Date::formattedDateTimeFromTimestamp("$modifiedDatestamp", 'g:i A'); $helper->log('Last Modified On: ' . $modifiedDate . ' at ' . $modifiedTime); // Read the workbook title property diff --git a/samples/templates/30template.xls b/samples/templates/30template.xls index af8de03b..58fe333d 100644 Binary files a/samples/templates/30template.xls and b/samples/templates/30template.xls differ diff --git a/samples/templates/30templatebiff5.xls b/samples/templates/30templatebiff5.xls new file mode 100644 index 00000000..0523e83d Binary files /dev/null and b/samples/templates/30templatebiff5.xls differ diff --git a/samples/templates/excel2003.xml b/samples/templates/excel2003.xml index cd1188a7..5e0268f9 100644 --- a/samples/templates/excel2003.xml +++ b/samples/templates/excel2003.xml @@ -14,7 +14,7 @@ Some comments about the PHPExcel Gnumeric Reader Owen Leibman 2010-09-02T20:48:39Z - 2010-09-02T20:48:39Z + 2010-09-03T21:48:39Z PHPExcel Xml Reader Test Category Maarten Balliauw PHPExcel diff --git a/samples/templates/sampleSpreadsheet.php b/samples/templates/sampleSpreadsheet.php index 6d9568be..b698ba89 100644 --- a/samples/templates/sampleSpreadsheet.php +++ b/samples/templates/sampleSpreadsheet.php @@ -31,7 +31,9 @@ $spreadsheet->getProperties()->setCreator('Maarten Balliauw') $helper->log('Add some data'); $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet()->setCellValue('B1', 'Invoice'); -$spreadsheet->getActiveSheet()->setCellValue('D1', Date::PHPToExcel(gmmktime(0, 0, 0, date('m'), date('d'), date('Y')))); +$date = new DateTime('now'); +$date->setTime(0, 0, 0); +$spreadsheet->getActiveSheet()->setCellValue('D1', Date::PHPToExcel($date)); $spreadsheet->getActiveSheet()->getStyle('D1')->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_XLSX15); $spreadsheet->getActiveSheet()->setCellValue('E1', '#12566'); diff --git a/src/PhpSpreadsheet/Calculation/Calculation.php b/src/PhpSpreadsheet/Calculation/Calculation.php index 99287721..f9c4fc0c 100644 --- a/src/PhpSpreadsheet/Calculation/Calculation.php +++ b/src/PhpSpreadsheet/Calculation/Calculation.php @@ -12,7 +12,9 @@ use PhpOffice\PhpSpreadsheet\ReferenceHelper; use PhpOffice\PhpSpreadsheet\Shared; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use ReflectionClassConstant; use ReflectionMethod; +use ReflectionParameter; class Calculation { @@ -30,6 +32,9 @@ class Calculation const CALCULATION_REGEXP_CELLREF = '((([^\s,!&%^\/\*\+<>=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?\$?\b([a-z]{1,3})\$?(\d{1,7})(?![\w.])'; // Cell reference (with or without a sheet reference) ensuring absolute/relative const CALCULATION_REGEXP_CELLREF_RELATIVE = '((([^\s\(,!&%^\/\*\+<>=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?(\$?\b[a-z]{1,3})(\$?\d{1,7})(?![\w.])'; + const CALCULATION_REGEXP_COLUMN_RANGE = '(((([^\s\(,!&%^\/\*\+<>=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?(\$?[a-z]{1,3})):(?![.*])'; + const CALCULATION_REGEXP_ROW_RANGE = '(((([^\s\(,!&%^\/\*\+<>=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?(\$?[1-9][0-9]{0,6})):(?![.*])'; + // Cell reference (with or without a sheet reference) ensuring absolute/relative // Cell ranges ensuring absolute/relative const CALCULATION_REGEXP_COLUMNRANGE_RELATIVE = '(\$?[a-z]{1,3}):(\$?[a-z]{1,3})'; const CALCULATION_REGEXP_ROWRANGE_RELATIVE = '(\$?\d{1,7}):(\$?\d{1,7})'; @@ -130,7 +135,7 @@ class Calculation /** * Error message for any error that was raised/thrown by the calculation engine. * - * @var string + * @var null|string */ public $formulaError; @@ -204,7 +209,7 @@ class Calculation /** * Locale-specific translations for Excel constants (True, False and Null). * - * @var string[] + * @var array */ public static $localeBoolean = [ 'TRUE' => 'TRUE', @@ -216,7 +221,7 @@ class Calculation * Excel constant string translations to their PHP equivalents * Constant conversion from text name/value to actual (datatyped) value. * - * @var string[] + * @var array */ private static $excelConstants = [ 'TRUE' => true, @@ -228,42 +233,42 @@ class Calculation private static $phpSpreadsheetFunctions = [ 'ABS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'abs', + 'functionCall' => [MathTrig\Absolute::class, 'evaluate'], 'argumentCount' => '1', ], 'ACCRINT' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'ACCRINT'], - 'argumentCount' => '4-7', + 'functionCall' => [Financial\Securities\AccruedInterest::class, 'periodic'], + 'argumentCount' => '4-8', ], 'ACCRINTM' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'ACCRINTM'], + 'functionCall' => [Financial\Securities\AccruedInterest::class, 'atMaturity'], 'argumentCount' => '3-5', ], 'ACOS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'acos', + 'functionCall' => [MathTrig\Trig\Cosine::class, 'acos'], 'argumentCount' => '1', ], 'ACOSH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'acosh', + 'functionCall' => [MathTrig\Trig\Cosine::class, 'acosh'], 'argumentCount' => '1', ], 'ACOT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'ACOT'], + 'functionCall' => [MathTrig\Trig\Cotangent::class, 'acot'], 'argumentCount' => '1', ], 'ACOTH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'ACOTH'], + 'functionCall' => [MathTrig\Trig\Cotangent::class, 'acoth'], 'argumentCount' => '1', ], 'ADDRESS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'cellAddress'], + 'functionCall' => [LookupRef\Address::class, 'cell'], 'argumentCount' => '2-5', ], 'AGGREGATE' => [ @@ -273,22 +278,22 @@ class Calculation ], 'AMORDEGRC' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'AMORDEGRC'], + 'functionCall' => [Financial\Amortization::class, 'AMORDEGRC'], 'argumentCount' => '6,7', ], 'AMORLINC' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'AMORLINC'], + 'functionCall' => [Financial\Amortization::class, 'AMORLINC'], 'argumentCount' => '6,7', ], 'AND' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'logicalAnd'], + 'functionCall' => [Logical\Operations::class, 'logicalAnd'], 'argumentCount' => '1+', ], 'ARABIC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'ARABIC'], + 'functionCall' => [MathTrig\Arabic::class, 'evaluate'], 'argumentCount' => '1', ], 'AREAS' => [ @@ -296,6 +301,11 @@ class Calculation 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], + 'ARRAYTOTEXT' => [ + 'category' => Category::CATEGORY_TEXT_AND_DATA, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], 'ASC' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], @@ -303,52 +313,52 @@ class Calculation ], 'ASIN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'asin', + 'functionCall' => [MathTrig\Trig\Sine::class, 'asin'], 'argumentCount' => '1', ], 'ASINH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'asinh', + 'functionCall' => [MathTrig\Trig\Sine::class, 'asinh'], 'argumentCount' => '1', ], 'ATAN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'atan', + 'functionCall' => [MathTrig\Trig\Tangent::class, 'atan'], 'argumentCount' => '1', ], 'ATAN2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'ATAN2'], + 'functionCall' => [MathTrig\Trig\Tangent::class, 'atan2'], 'argumentCount' => '2', ], 'ATANH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'atanh', + 'functionCall' => [MathTrig\Trig\Tangent::class, 'atanh'], 'argumentCount' => '1', ], 'AVEDEV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'AVEDEV'], + 'functionCall' => [Statistical\Averages::class, 'averageDeviations'], 'argumentCount' => '1+', ], 'AVERAGE' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'AVERAGE'], + 'functionCall' => [Statistical\Averages::class, 'average'], 'argumentCount' => '1+', ], 'AVERAGEA' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'AVERAGEA'], + 'functionCall' => [Statistical\Averages::class, 'averageA'], 'argumentCount' => '1+', ], 'AVERAGEIF' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'AVERAGEIF'], + 'functionCall' => [Statistical\Conditional::class, 'AVERAGEIF'], 'argumentCount' => '2,3', ], 'AVERAGEIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Functions::class, 'DUMMY'], + 'functionCall' => [Statistical\Conditional::class, 'AVERAGEIFS'], 'argumentCount' => '3+', ], 'BAHTTEXT' => [ @@ -358,32 +368,32 @@ class Calculation ], 'BASE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'BASE'], + 'functionCall' => [MathTrig\Base::class, 'evaluate'], 'argumentCount' => '2,3', ], 'BESSELI' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BESSELI'], + 'functionCall' => [Engineering\BesselI::class, 'BESSELI'], 'argumentCount' => '2', ], 'BESSELJ' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BESSELJ'], + 'functionCall' => [Engineering\BesselJ::class, 'BESSELJ'], 'argumentCount' => '2', ], 'BESSELK' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BESSELK'], + 'functionCall' => [Engineering\BesselK::class, 'BESSELK'], 'argumentCount' => '2', ], 'BESSELY' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BESSELY'], + 'functionCall' => [Engineering\BesselY::class, 'BESSELY'], 'argumentCount' => '2', ], 'BETADIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'BETADIST'], + 'functionCall' => [Statistical\Distributions\Beta::class, 'distribution'], 'argumentCount' => '3-5', ], 'BETA.DIST' => [ @@ -393,88 +403,88 @@ class Calculation ], 'BETAINV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'BETAINV'], + 'functionCall' => [Statistical\Distributions\Beta::class, 'inverse'], 'argumentCount' => '3-5', ], 'BETA.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'BETAINV'], + 'functionCall' => [Statistical\Distributions\Beta::class, 'inverse'], 'argumentCount' => '3-5', ], 'BIN2DEC' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BINTODEC'], + 'functionCall' => [Engineering\ConvertBinary::class, 'toDecimal'], 'argumentCount' => '1', ], 'BIN2HEX' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BINTOHEX'], + 'functionCall' => [Engineering\ConvertBinary::class, 'toHex'], 'argumentCount' => '1,2', ], 'BIN2OCT' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BINTOOCT'], + 'functionCall' => [Engineering\ConvertBinary::class, 'toOctal'], 'argumentCount' => '1,2', ], 'BINOMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'BINOMDIST'], + 'functionCall' => [Statistical\Distributions\Binomial::class, 'distribution'], 'argumentCount' => '4', ], 'BINOM.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'BINOMDIST'], + 'functionCall' => [Statistical\Distributions\Binomial::class, 'distribution'], 'argumentCount' => '4', ], 'BINOM.DIST.RANGE' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Functions::class, 'DUMMY'], + 'functionCall' => [Statistical\Distributions\Binomial::class, 'range'], 'argumentCount' => '3,4', ], 'BINOM.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Functions::class, 'DUMMY'], + 'functionCall' => [Statistical\Distributions\Binomial::class, 'inverse'], 'argumentCount' => '3', ], 'BITAND' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BITAND'], + 'functionCall' => [Engineering\BitWise::class, 'BITAND'], 'argumentCount' => '2', ], 'BITOR' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BITOR'], + 'functionCall' => [Engineering\BitWise::class, 'BITOR'], 'argumentCount' => '2', ], 'BITXOR' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BITOR'], + 'functionCall' => [Engineering\BitWise::class, 'BITXOR'], 'argumentCount' => '2', ], 'BITLSHIFT' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BITLSHIFT'], + 'functionCall' => [Engineering\BitWise::class, 'BITLSHIFT'], 'argumentCount' => '2', ], 'BITRSHIFT' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BITRSHIFT'], + 'functionCall' => [Engineering\BitWise::class, 'BITRSHIFT'], 'argumentCount' => '2', ], 'CEILING' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'CEILING'], - 'argumentCount' => '2', + 'functionCall' => [MathTrig\Ceiling::class, 'ceiling'], + 'argumentCount' => '1-2', // 2 for Excel, 1-2 for Ods/Gnumeric ], 'CEILING.MATH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [Functions::class, 'DUMMY'], - 'argumentCount' => '3', + 'functionCall' => [MathTrig\Ceiling::class, 'math'], + 'argumentCount' => '1-3', ], 'CEILING.PRECISE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [Functions::class, 'DUMMY'], - 'argumentCount' => '2', + 'functionCall' => [MathTrig\Ceiling::class, 'precise'], + 'argumentCount' => '1,2', ], 'CELL' => [ 'category' => Category::CATEGORY_INFORMATION, @@ -483,108 +493,109 @@ class Calculation ], 'CHAR' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'CHARACTER'], + 'functionCall' => [TextData\CharacterConvert::class, 'character'], 'argumentCount' => '1', ], 'CHIDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'CHIDIST'], + 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionRightTail'], 'argumentCount' => '2', ], 'CHISQ.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Functions::class, 'DUMMY'], + 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionLeftTail'], 'argumentCount' => '3', ], 'CHISQ.DIST.RT' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'CHIDIST'], + 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionRightTail'], 'argumentCount' => '2', ], 'CHIINV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'CHIINV'], + 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseRightTail'], 'argumentCount' => '2', ], 'CHISQ.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Functions::class, 'DUMMY'], + 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseLeftTail'], 'argumentCount' => '2', ], 'CHISQ.INV.RT' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'CHIINV'], + 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseRightTail'], 'argumentCount' => '2', ], 'CHITEST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Functions::class, 'DUMMY'], + 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'test'], 'argumentCount' => '2', ], 'CHISQ.TEST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Functions::class, 'DUMMY'], + 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'test'], 'argumentCount' => '2', ], 'CHOOSE' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'CHOOSE'], + 'functionCall' => [LookupRef\Selection::class, 'CHOOSE'], 'argumentCount' => '2+', ], 'CLEAN' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'TRIMNONPRINTABLE'], + 'functionCall' => [TextData\Trim::class, 'nonPrintable'], 'argumentCount' => '1', ], 'CODE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'ASCIICODE'], + 'functionCall' => [TextData\CharacterConvert::class, 'code'], 'argumentCount' => '1', ], 'COLUMN' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'COLUMN'], + 'functionCall' => [LookupRef\RowColumnInformation::class, 'COLUMN'], 'argumentCount' => '-1', + 'passCellReference' => true, 'passByReference' => [true], ], 'COLUMNS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'COLUMNS'], + 'functionCall' => [LookupRef\RowColumnInformation::class, 'COLUMNS'], 'argumentCount' => '1', ], 'COMBIN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'COMBIN'], + 'functionCall' => [MathTrig\Combinations::class, 'withoutRepetition'], 'argumentCount' => '2', ], 'COMBINA' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [Functions::class, 'DUMMY'], + 'functionCall' => [MathTrig\Combinations::class, 'withRepetition'], 'argumentCount' => '2', ], 'COMPLEX' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'COMPLEX'], + 'functionCall' => [Engineering\Complex::class, 'COMPLEX'], 'argumentCount' => '2,3', ], 'CONCAT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'CONCATENATE'], + 'functionCall' => [TextData\Concatenate::class, 'CONCATENATE'], 'argumentCount' => '1+', ], 'CONCATENATE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'CONCATENATE'], + 'functionCall' => [TextData\Concatenate::class, 'CONCATENATE'], 'argumentCount' => '1+', ], 'CONFIDENCE' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'CONFIDENCE'], + 'functionCall' => [Statistical\Confidence::class, 'CONFIDENCE'], 'argumentCount' => '3', ], 'CONFIDENCE.NORM' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'CONFIDENCE'], + 'functionCall' => [Statistical\Confidence::class, 'CONFIDENCE'], 'argumentCount' => '3', ], 'CONFIDENCE.T' => [ @@ -594,97 +605,97 @@ class Calculation ], 'CONVERT' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'CONVERTUOM'], + 'functionCall' => [Engineering\ConvertUOM::class, 'CONVERT'], 'argumentCount' => '3', ], 'CORREL' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'CORREL'], + 'functionCall' => [Statistical\Trends::class, 'CORREL'], 'argumentCount' => '2', ], 'COS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'cos', + 'functionCall' => [MathTrig\Trig\Cosine::class, 'cos'], 'argumentCount' => '1', ], 'COSH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'cosh', + 'functionCall' => [MathTrig\Trig\Cosine::class, 'cosh'], 'argumentCount' => '1', ], 'COT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'COT'], + 'functionCall' => [MathTrig\Trig\Cotangent::class, 'cot'], 'argumentCount' => '1', ], 'COTH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'COTH'], + 'functionCall' => [MathTrig\Trig\Cotangent::class, 'coth'], 'argumentCount' => '1', ], 'COUNT' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'COUNT'], + 'functionCall' => [Statistical\Counts::class, 'COUNT'], 'argumentCount' => '1+', ], 'COUNTA' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'COUNTA'], + 'functionCall' => [Statistical\Counts::class, 'COUNTA'], 'argumentCount' => '1+', ], 'COUNTBLANK' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'COUNTBLANK'], + 'functionCall' => [Statistical\Counts::class, 'COUNTBLANK'], 'argumentCount' => '1', ], 'COUNTIF' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'COUNTIF'], + 'functionCall' => [Statistical\Conditional::class, 'COUNTIF'], 'argumentCount' => '2', ], 'COUNTIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'COUNTIFS'], + 'functionCall' => [Statistical\Conditional::class, 'COUNTIFS'], 'argumentCount' => '2+', ], 'COUPDAYBS' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'COUPDAYBS'], + 'functionCall' => [Financial\Coupons::class, 'COUPDAYBS'], 'argumentCount' => '3,4', ], 'COUPDAYS' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'COUPDAYS'], + 'functionCall' => [Financial\Coupons::class, 'COUPDAYS'], 'argumentCount' => '3,4', ], 'COUPDAYSNC' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'COUPDAYSNC'], + 'functionCall' => [Financial\Coupons::class, 'COUPDAYSNC'], 'argumentCount' => '3,4', ], 'COUPNCD' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'COUPNCD'], + 'functionCall' => [Financial\Coupons::class, 'COUPNCD'], 'argumentCount' => '3,4', ], 'COUPNUM' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'COUPNUM'], + 'functionCall' => [Financial\Coupons::class, 'COUPNUM'], 'argumentCount' => '3,4', ], 'COUPPCD' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'COUPPCD'], + 'functionCall' => [Financial\Coupons::class, 'COUPPCD'], 'argumentCount' => '3,4', ], 'COVAR' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'COVAR'], + 'functionCall' => [Statistical\Trends::class, 'COVAR'], 'argumentCount' => '2', ], 'COVARIANCE.P' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'COVAR'], + 'functionCall' => [Statistical\Trends::class, 'COVAR'], 'argumentCount' => '2', ], 'COVARIANCE.S' => [ @@ -694,17 +705,17 @@ class Calculation ], 'CRITBINOM' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'CRITBINOM'], + 'functionCall' => [Statistical\Distributions\Binomial::class, 'inverse'], 'argumentCount' => '3', ], 'CSC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'CSC'], + 'functionCall' => [MathTrig\Trig\Cosecant::class, 'csc'], 'argumentCount' => '1', ], 'CSCH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'CSCH'], + 'functionCall' => [MathTrig\Trig\Cosecant::class, 'csch'], 'argumentCount' => '1', ], 'CUBEKPIMEMBER' => [ @@ -744,52 +755,57 @@ class Calculation ], 'CUMIPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'CUMIPMT'], + 'functionCall' => [Financial\CashFlow\Constant\Periodic\Cumulative::class, 'interest'], 'argumentCount' => '6', ], 'CUMPRINC' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'CUMPRINC'], + 'functionCall' => [Financial\CashFlow\Constant\Periodic\Cumulative::class, 'principal'], 'argumentCount' => '6', ], 'DATE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'DATE'], + 'functionCall' => [DateTimeExcel\Date::class, 'fromYMD'], 'argumentCount' => '3', ], 'DATEDIF' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'DATEDIF'], + 'functionCall' => [DateTimeExcel\Difference::class, 'interval'], 'argumentCount' => '2,3', ], + 'DATESTRING' => [ + 'category' => Category::CATEGORY_DATE_AND_TIME, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], 'DATEVALUE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'DATEVALUE'], + 'functionCall' => [DateTimeExcel\DateValue::class, 'fromString'], 'argumentCount' => '1', ], 'DAVERAGE' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DAVERAGE'], + 'functionCall' => [Database\DAverage::class, 'evaluate'], 'argumentCount' => '3', ], 'DAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'DAYOFMONTH'], + 'functionCall' => [DateTimeExcel\DateParts::class, 'day'], 'argumentCount' => '1', ], 'DAYS' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'DAYS'], + 'functionCall' => [DateTimeExcel\Days::class, 'between'], 'argumentCount' => '2', ], 'DAYS360' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'DAYS360'], + 'functionCall' => [DateTimeExcel\Days360::class, 'between'], 'argumentCount' => '2,3', ], 'DB' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'DB'], + 'functionCall' => [Financial\Depreciation::class, 'DB'], 'argumentCount' => '4,5', ], 'DBCS' => [ @@ -799,32 +815,32 @@ class Calculation ], 'DCOUNT' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DCOUNT'], + 'functionCall' => [Database\DCount::class, 'evaluate'], 'argumentCount' => '3', ], 'DCOUNTA' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DCOUNTA'], + 'functionCall' => [Database\DCountA::class, 'evaluate'], 'argumentCount' => '3', ], 'DDB' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'DDB'], + 'functionCall' => [Financial\Depreciation::class, 'DDB'], 'argumentCount' => '4,5', ], 'DEC2BIN' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'DECTOBIN'], + 'functionCall' => [Engineering\ConvertDecimal::class, 'toBinary'], 'argumentCount' => '1,2', ], 'DEC2HEX' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'DECTOHEX'], + 'functionCall' => [Engineering\ConvertDecimal::class, 'toHex'], 'argumentCount' => '1,2', ], 'DEC2OCT' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'DECTOOCT'], + 'functionCall' => [Engineering\ConvertDecimal::class, 'toOctal'], 'argumentCount' => '1,2', ], 'DECIMAL' => [ @@ -834,72 +850,72 @@ class Calculation ], 'DEGREES' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'rad2deg', + 'functionCall' => [MathTrig\Angle::class, 'toDegrees'], 'argumentCount' => '1', ], 'DELTA' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'DELTA'], + 'functionCall' => [Engineering\Compare::class, 'DELTA'], 'argumentCount' => '1,2', ], 'DEVSQ' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'DEVSQ'], + 'functionCall' => [Statistical\Deviations::class, 'sumSquares'], 'argumentCount' => '1+', ], 'DGET' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DGET'], + 'functionCall' => [Database\DGet::class, 'evaluate'], 'argumentCount' => '3', ], 'DISC' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'DISC'], + 'functionCall' => [Financial\Securities\Rates::class, 'discount'], 'argumentCount' => '4,5', ], 'DMAX' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DMAX'], + 'functionCall' => [Database\DMax::class, 'evaluate'], 'argumentCount' => '3', ], 'DMIN' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DMIN'], + 'functionCall' => [Database\DMin::class, 'evaluate'], 'argumentCount' => '3', ], 'DOLLAR' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'DOLLAR'], + 'functionCall' => [TextData\Format::class, 'DOLLAR'], 'argumentCount' => '1,2', ], 'DOLLARDE' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'DOLLARDE'], + 'functionCall' => [Financial\Dollar::class, 'decimal'], 'argumentCount' => '2', ], 'DOLLARFR' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'DOLLARFR'], + 'functionCall' => [Financial\Dollar::class, 'fractional'], 'argumentCount' => '2', ], 'DPRODUCT' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DPRODUCT'], + 'functionCall' => [Database\DProduct::class, 'evaluate'], 'argumentCount' => '3', ], 'DSTDEV' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DSTDEV'], + 'functionCall' => [Database\DStDev::class, 'evaluate'], 'argumentCount' => '3', ], 'DSTDEVP' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DSTDEVP'], + 'functionCall' => [Database\DStDevP::class, 'evaluate'], 'argumentCount' => '3', ], 'DSUM' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DSUM'], + 'functionCall' => [Database\DSum::class, 'evaluate'], 'argumentCount' => '3', ], 'DURATION' => [ @@ -909,52 +925,57 @@ class Calculation ], 'DVAR' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DVAR'], + 'functionCall' => [Database\DVar::class, 'evaluate'], 'argumentCount' => '3', ], 'DVARP' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DVARP'], + 'functionCall' => [Database\DVarP::class, 'evaluate'], 'argumentCount' => '3', ], + 'ECMA.CEILING' => [ + 'category' => Category::CATEGORY_MATH_AND_TRIG, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '1,2', + ], 'EDATE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'EDATE'], + 'functionCall' => [DateTimeExcel\Month::class, 'adjust'], 'argumentCount' => '2', ], 'EFFECT' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'EFFECT'], + 'functionCall' => [Financial\InterestRate::class, 'effective'], 'argumentCount' => '2', ], 'ENCODEURL' => [ 'category' => Category::CATEGORY_WEB, - 'functionCall' => [Functions::class, 'DUMMY'], + 'functionCall' => [Web\Service::class, 'urlEncode'], 'argumentCount' => '1', ], 'EOMONTH' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'EOMONTH'], + 'functionCall' => [DateTimeExcel\Month::class, 'lastDay'], 'argumentCount' => '2', ], 'ERF' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'ERF'], + 'functionCall' => [Engineering\Erf::class, 'ERF'], 'argumentCount' => '1,2', ], 'ERF.PRECISE' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'ERFPRECISE'], + 'functionCall' => [Engineering\Erf::class, 'ERFPRECISE'], 'argumentCount' => '1', ], 'ERFC' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'ERFC'], + 'functionCall' => [Engineering\ErfC::class, 'ERFC'], 'argumentCount' => '1', ], 'ERFC.PRECISE' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'ERFC'], + 'functionCall' => [Engineering\ErfC::class, 'ERFC'], 'argumentCount' => '1', ], 'ERROR.TYPE' => [ @@ -964,42 +985,42 @@ class Calculation ], 'EVEN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'EVEN'], + 'functionCall' => [MathTrig\Round::class, 'even'], 'argumentCount' => '1', ], 'EXACT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'EXACT'], + 'functionCall' => [TextData\Text::class, 'exact'], 'argumentCount' => '2', ], 'EXP' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'exp', + 'functionCall' => [MathTrig\Exp::class, 'evaluate'], 'argumentCount' => '1', ], 'EXPONDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'EXPONDIST'], + 'functionCall' => [Statistical\Distributions\Exponential::class, 'distribution'], 'argumentCount' => '3', ], 'EXPON.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'EXPONDIST'], + 'functionCall' => [Statistical\Distributions\Exponential::class, 'distribution'], 'argumentCount' => '3', ], 'FACT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'FACT'], + 'functionCall' => [MathTrig\Factorial::class, 'fact'], 'argumentCount' => '1', ], 'FACTDOUBLE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'FACTDOUBLE'], + 'functionCall' => [MathTrig\Factorial::class, 'factDouble'], 'argumentCount' => '1', ], 'FALSE' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'FALSE'], + 'functionCall' => [Logical\Boolean::class, 'FALSE'], 'argumentCount' => '0', ], 'FDIST' => [ @@ -1009,7 +1030,7 @@ class Calculation ], 'F.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'FDIST2'], + 'functionCall' => [Statistical\Distributions\F::class, 'distribution'], 'argumentCount' => '4', ], 'F.DIST.RT' => [ @@ -1029,12 +1050,12 @@ class Calculation ], 'FIND' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'SEARCHSENSITIVE'], + 'functionCall' => [TextData\Search::class, 'sensitive'], 'argumentCount' => '2,3', ], 'FINDB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'SEARCHSENSITIVE'], + 'functionCall' => [TextData\Search::class, 'sensitive'], 'argumentCount' => '2,3', ], 'FINV' => [ @@ -1054,37 +1075,37 @@ class Calculation ], 'FISHER' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'FISHER'], + 'functionCall' => [Statistical\Distributions\Fisher::class, 'distribution'], 'argumentCount' => '1', ], 'FISHERINV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'FISHERINV'], + 'functionCall' => [Statistical\Distributions\Fisher::class, 'inverse'], 'argumentCount' => '1', ], 'FIXED' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'FIXEDFORMAT'], + 'functionCall' => [TextData\Format::class, 'FIXEDFORMAT'], 'argumentCount' => '1-3', ], 'FLOOR' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'FLOOR'], - 'argumentCount' => '2', + 'functionCall' => [MathTrig\Floor::class, 'floor'], + 'argumentCount' => '1-2', // Excel requries 2, Ods/Gnumeric 1-2 ], 'FLOOR.MATH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'FLOORMATH'], - 'argumentCount' => '3', + 'functionCall' => [MathTrig\Floor::class, 'math'], + 'argumentCount' => '1-3', ], 'FLOOR.PRECISE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'FLOORPRECISE'], - 'argumentCount' => '2', + 'functionCall' => [MathTrig\Floor::class, 'precise'], + 'argumentCount' => '1-2', ], 'FORECAST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'FORECAST'], + 'functionCall' => [Statistical\Trends::class, 'FORECAST'], 'argumentCount' => '3', ], 'FORECAST.ETS' => [ @@ -1109,12 +1130,12 @@ class Calculation ], 'FORECAST.LINEAR' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'FORECAST'], + 'functionCall' => [Statistical\Trends::class, 'FORECAST'], 'argumentCount' => '3', ], 'FORMULATEXT' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'FORMULATEXT'], + 'functionCall' => [LookupRef\Formula::class, 'text'], 'argumentCount' => '1', 'passCellReference' => true, 'passByReference' => [true], @@ -1136,67 +1157,67 @@ class Calculation ], 'FV' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'FV'], + 'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'futureValue'], 'argumentCount' => '3-5', ], 'FVSCHEDULE' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'FVSCHEDULE'], + 'functionCall' => [Financial\CashFlow\Single::class, 'futureValue'], 'argumentCount' => '2', ], 'GAMMA' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'GAMMAFunction'], + 'functionCall' => [Statistical\Distributions\Gamma::class, 'gamma'], 'argumentCount' => '1', ], 'GAMMADIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'GAMMADIST'], + 'functionCall' => [Statistical\Distributions\Gamma::class, 'distribution'], 'argumentCount' => '4', ], 'GAMMA.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'GAMMADIST'], + 'functionCall' => [Statistical\Distributions\Gamma::class, 'distribution'], 'argumentCount' => '4', ], 'GAMMAINV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'GAMMAINV'], + 'functionCall' => [Statistical\Distributions\Gamma::class, 'inverse'], 'argumentCount' => '3', ], 'GAMMA.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'GAMMAINV'], + 'functionCall' => [Statistical\Distributions\Gamma::class, 'inverse'], 'argumentCount' => '3', ], 'GAMMALN' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'GAMMALN'], + 'functionCall' => [Statistical\Distributions\Gamma::class, 'ln'], 'argumentCount' => '1', ], 'GAMMALN.PRECISE' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'GAMMALN'], + 'functionCall' => [Statistical\Distributions\Gamma::class, 'ln'], 'argumentCount' => '1', ], 'GAUSS' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'GAUSS'], + 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'gauss'], 'argumentCount' => '1', ], 'GCD' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'GCD'], + 'functionCall' => [MathTrig\Gcd::class, 'evaluate'], 'argumentCount' => '1+', ], 'GEOMEAN' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'GEOMEAN'], + 'functionCall' => [Statistical\Averages\Mean::class, 'geometric'], 'argumentCount' => '1+', ], 'GESTEP' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'GESTEP'], + 'functionCall' => [Engineering\Compare::class, 'GESTEP'], 'argumentCount' => '1,2', ], 'GETPIVOTDATA' => [ @@ -1206,48 +1227,48 @@ class Calculation ], 'GROWTH' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'GROWTH'], + 'functionCall' => [Statistical\Trends::class, 'GROWTH'], 'argumentCount' => '1-4', ], 'HARMEAN' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'HARMEAN'], + 'functionCall' => [Statistical\Averages\Mean::class, 'harmonic'], 'argumentCount' => '1+', ], 'HEX2BIN' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'HEXTOBIN'], + 'functionCall' => [Engineering\ConvertHex::class, 'toBinary'], 'argumentCount' => '1,2', ], 'HEX2DEC' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'HEXTODEC'], + 'functionCall' => [Engineering\ConvertHex::class, 'toDecimal'], 'argumentCount' => '1', ], 'HEX2OCT' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'HEXTOOCT'], + 'functionCall' => [Engineering\ConvertHex::class, 'toOctal'], 'argumentCount' => '1,2', ], 'HLOOKUP' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'HLOOKUP'], + 'functionCall' => [LookupRef\HLookup::class, 'lookup'], 'argumentCount' => '3,4', ], 'HOUR' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'HOUROFDAY'], + 'functionCall' => [DateTimeExcel\TimeParts::class, 'hour'], 'argumentCount' => '1', ], 'HYPERLINK' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'HYPERLINK'], + 'functionCall' => [LookupRef\Hyperlink::class, 'set'], 'argumentCount' => '1,2', 'passCellReference' => true, ], 'HYPGEOMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'HYPGEOMDIST'], + 'functionCall' => [Statistical\Distributions\HyperGeometric::class, 'distribution'], 'argumentCount' => '4', ], 'HYPGEOM.DIST' => [ @@ -1257,157 +1278,157 @@ class Calculation ], 'IF' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'statementIf'], + 'functionCall' => [Logical\Conditional::class, 'statementIf'], 'argumentCount' => '1-3', ], 'IFERROR' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'IFERROR'], + 'functionCall' => [Logical\Conditional::class, 'IFERROR'], 'argumentCount' => '2', ], 'IFNA' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'IFNA'], + 'functionCall' => [Logical\Conditional::class, 'IFNA'], 'argumentCount' => '2', ], 'IFS' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'IFS'], + 'functionCall' => [Logical\Conditional::class, 'IFS'], 'argumentCount' => '2+', ], 'IMABS' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMABS'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMABS'], 'argumentCount' => '1', ], 'IMAGINARY' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMAGINARY'], + 'functionCall' => [Engineering\Complex::class, 'IMAGINARY'], 'argumentCount' => '1', ], 'IMARGUMENT' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMARGUMENT'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMARGUMENT'], 'argumentCount' => '1', ], 'IMCONJUGATE' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMCONJUGATE'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCONJUGATE'], 'argumentCount' => '1', ], 'IMCOS' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMCOS'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOS'], 'argumentCount' => '1', ], 'IMCOSH' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMCOSH'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOSH'], 'argumentCount' => '1', ], 'IMCOT' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMCOT'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOT'], 'argumentCount' => '1', ], 'IMCSC' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMCSC'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCSC'], 'argumentCount' => '1', ], 'IMCSCH' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMCSCH'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCSCH'], 'argumentCount' => '1', ], 'IMDIV' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMDIV'], + 'functionCall' => [Engineering\ComplexOperations::class, 'IMDIV'], 'argumentCount' => '2', ], 'IMEXP' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMEXP'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMEXP'], 'argumentCount' => '1', ], 'IMLN' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMLN'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMLN'], 'argumentCount' => '1', ], 'IMLOG10' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMLOG10'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMLOG10'], 'argumentCount' => '1', ], 'IMLOG2' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMLOG2'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMLOG2'], 'argumentCount' => '1', ], 'IMPOWER' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMPOWER'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMPOWER'], 'argumentCount' => '2', ], 'IMPRODUCT' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMPRODUCT'], + 'functionCall' => [Engineering\ComplexOperations::class, 'IMPRODUCT'], 'argumentCount' => '1+', ], 'IMREAL' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMREAL'], + 'functionCall' => [Engineering\Complex::class, 'IMREAL'], 'argumentCount' => '1', ], 'IMSEC' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMSEC'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSEC'], 'argumentCount' => '1', ], 'IMSECH' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMSECH'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSECH'], 'argumentCount' => '1', ], 'IMSIN' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMSIN'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSIN'], 'argumentCount' => '1', ], 'IMSINH' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMSINH'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSINH'], 'argumentCount' => '1', ], 'IMSQRT' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMSQRT'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSQRT'], 'argumentCount' => '1', ], 'IMSUB' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMSUB'], + 'functionCall' => [Engineering\ComplexOperations::class, 'IMSUB'], 'argumentCount' => '2', ], 'IMSUM' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMSUM'], + 'functionCall' => [Engineering\ComplexOperations::class, 'IMSUM'], 'argumentCount' => '1+', ], 'IMTAN' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMTAN'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMTAN'], 'argumentCount' => '1', ], 'INDEX' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'INDEX'], + 'functionCall' => [LookupRef\Matrix::class, 'index'], 'argumentCount' => '1-4', ], 'INDIRECT' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'INDIRECT'], + 'functionCall' => [LookupRef\Indirect::class, 'INDIRECT'], 'argumentCount' => '1,2', 'passCellReference' => true, ], @@ -1418,27 +1439,27 @@ class Calculation ], 'INT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'INT'], + 'functionCall' => [MathTrig\IntClass::class, 'evaluate'], 'argumentCount' => '1', ], 'INTERCEPT' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'INTERCEPT'], + 'functionCall' => [Statistical\Trends::class, 'INTERCEPT'], 'argumentCount' => '2', ], 'INTRATE' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'INTRATE'], + 'functionCall' => [Financial\Securities\Rates::class, 'interest'], 'argumentCount' => '4,5', ], 'IPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'IPMT'], + 'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'payment'], 'argumentCount' => '4-6', ], 'IRR' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'IRR'], + 'functionCall' => [Financial\CashFlow\Variable\Periodic::class, 'rate'], 'argumentCount' => '1,2', ], 'ISBLANK' => [ @@ -1500,12 +1521,12 @@ class Calculation ], 'ISOWEEKNUM' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'ISOWEEKNUM'], + 'functionCall' => [DateTimeExcel\Week::class, 'isoWeekNumber'], 'argumentCount' => '1', ], 'ISPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'ISPMT'], + 'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'schedulePayment'], 'argumentCount' => '4', ], 'ISREF' => [ @@ -1518,6 +1539,11 @@ class Calculation 'functionCall' => [Functions::class, 'isText'], 'argumentCount' => '1', ], + 'ISTHAIDIGIT' => [ + 'category' => Category::CATEGORY_TEXT_AND_DATA, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], 'JIS' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], @@ -1525,117 +1551,117 @@ class Calculation ], 'KURT' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'KURT'], + 'functionCall' => [Statistical\Deviations::class, 'kurtosis'], 'argumentCount' => '1+', ], 'LARGE' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'LARGE'], + 'functionCall' => [Statistical\Size::class, 'large'], 'argumentCount' => '2', ], 'LCM' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'LCM'], + 'functionCall' => [MathTrig\Lcm::class, 'evaluate'], 'argumentCount' => '1+', ], 'LEFT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'LEFT'], + 'functionCall' => [TextData\Extract::class, 'left'], 'argumentCount' => '1,2', ], 'LEFTB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'LEFT'], + 'functionCall' => [TextData\Extract::class, 'left'], 'argumentCount' => '1,2', ], 'LEN' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'STRINGLENGTH'], + 'functionCall' => [TextData\Text::class, 'length'], 'argumentCount' => '1', ], 'LENB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'STRINGLENGTH'], + 'functionCall' => [TextData\Text::class, 'length'], 'argumentCount' => '1', ], 'LINEST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'LINEST'], + 'functionCall' => [Statistical\Trends::class, 'LINEST'], 'argumentCount' => '1-4', ], 'LN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'log', + 'functionCall' => [MathTrig\Logarithms::class, 'natural'], 'argumentCount' => '1', ], 'LOG' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'logBase'], + 'functionCall' => [MathTrig\Logarithms::class, 'withBase'], 'argumentCount' => '1,2', ], 'LOG10' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'log10', + 'functionCall' => [MathTrig\Logarithms::class, 'base10'], 'argumentCount' => '1', ], 'LOGEST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'LOGEST'], + 'functionCall' => [Statistical\Trends::class, 'LOGEST'], 'argumentCount' => '1-4', ], 'LOGINV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'LOGINV'], + 'functionCall' => [Statistical\Distributions\LogNormal::class, 'inverse'], 'argumentCount' => '3', ], 'LOGNORMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'LOGNORMDIST'], + 'functionCall' => [Statistical\Distributions\LogNormal::class, 'cumulative'], 'argumentCount' => '3', ], 'LOGNORM.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'LOGNORMDIST2'], + 'functionCall' => [Statistical\Distributions\LogNormal::class, 'distribution'], 'argumentCount' => '4', ], 'LOGNORM.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'LOGINV'], + 'functionCall' => [Statistical\Distributions\LogNormal::class, 'inverse'], 'argumentCount' => '3', ], 'LOOKUP' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'LOOKUP'], + 'functionCall' => [LookupRef\Lookup::class, 'lookup'], 'argumentCount' => '2,3', ], 'LOWER' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'LOWERCASE'], + 'functionCall' => [TextData\CaseConvert::class, 'lower'], 'argumentCount' => '1', ], 'MATCH' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'MATCH'], + 'functionCall' => [LookupRef\ExcelMatch::class, 'MATCH'], 'argumentCount' => '2,3', ], 'MAX' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'MAX'], + 'functionCall' => [Statistical\Maximum::class, 'max'], 'argumentCount' => '1+', ], 'MAXA' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'MAXA'], + 'functionCall' => [Statistical\Maximum::class, 'maxA'], 'argumentCount' => '1+', ], 'MAXIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'MAXIFS'], + 'functionCall' => [Statistical\Conditional::class, 'MAXIFS'], 'argumentCount' => '3+', ], 'MDETERM' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'MDETERM'], + 'functionCall' => [MathTrig\MatrixFunctions::class, 'determinant'], 'argumentCount' => '1', ], 'MDURATION' => [ @@ -1645,7 +1671,7 @@ class Calculation ], 'MEDIAN' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'MEDIAN'], + 'functionCall' => [Statistical\Averages::class, 'median'], 'argumentCount' => '1+', ], 'MEDIANIF' => [ @@ -1655,57 +1681,57 @@ class Calculation ], 'MID' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'MID'], + 'functionCall' => [TextData\Extract::class, 'mid'], 'argumentCount' => '3', ], 'MIDB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'MID'], + 'functionCall' => [TextData\Extract::class, 'mid'], 'argumentCount' => '3', ], 'MIN' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'MIN'], + 'functionCall' => [Statistical\Minimum::class, 'min'], 'argumentCount' => '1+', ], 'MINA' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'MINA'], + 'functionCall' => [Statistical\Minimum::class, 'minA'], 'argumentCount' => '1+', ], 'MINIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'MINIFS'], + 'functionCall' => [Statistical\Conditional::class, 'MINIFS'], 'argumentCount' => '3+', ], 'MINUTE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'MINUTE'], + 'functionCall' => [DateTimeExcel\TimeParts::class, 'minute'], 'argumentCount' => '1', ], 'MINVERSE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'MINVERSE'], + 'functionCall' => [MathTrig\MatrixFunctions::class, 'inverse'], 'argumentCount' => '1', ], 'MIRR' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'MIRR'], + 'functionCall' => [Financial\CashFlow\Variable\Periodic::class, 'modifiedRate'], 'argumentCount' => '3', ], 'MMULT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'MMULT'], + 'functionCall' => [MathTrig\MatrixFunctions::class, 'multiply'], 'argumentCount' => '2', ], 'MOD' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'MOD'], + 'functionCall' => [MathTrig\Operations::class, 'mod'], 'argumentCount' => '2', ], 'MODE' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'MODE'], + 'functionCall' => [Statistical\Averages::class, 'mode'], 'argumentCount' => '1+', ], 'MODE.MULT' => [ @@ -1715,27 +1741,27 @@ class Calculation ], 'MODE.SNGL' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'MODE'], + 'functionCall' => [Statistical\Averages::class, 'mode'], 'argumentCount' => '1+', ], 'MONTH' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'MONTHOFYEAR'], + 'functionCall' => [DateTimeExcel\DateParts::class, 'month'], 'argumentCount' => '1', ], 'MROUND' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'MROUND'], + 'functionCall' => [MathTrig\Round::class, 'multiple'], 'argumentCount' => '2', ], 'MULTINOMIAL' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'MULTINOMIAL'], + 'functionCall' => [MathTrig\Factorial::class, 'multinomial'], 'argumentCount' => '1+', ], 'MUNIT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [Functions::class, 'DUMMY'], + 'functionCall' => [MathTrig\MatrixFunctions::class, 'identity'], 'argumentCount' => '1', ], 'N' => [ @@ -1750,7 +1776,7 @@ class Calculation ], 'NEGBINOMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'NEGBINOMDIST'], + 'functionCall' => [Statistical\Distributions\Binomial::class, 'negative'], 'argumentCount' => '3', ], 'NEGBINOM.DIST' => [ @@ -1760,7 +1786,7 @@ class Calculation ], 'NETWORKDAYS' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'NETWORKDAYS'], + 'functionCall' => [DateTimeExcel\NetworkDays::class, 'count'], 'argumentCount' => '2-3', ], 'NETWORKDAYS.INTL' => [ @@ -1770,92 +1796,97 @@ class Calculation ], 'NOMINAL' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'NOMINAL'], + 'functionCall' => [Financial\InterestRate::class, 'nominal'], 'argumentCount' => '2', ], 'NORMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'NORMDIST'], + 'functionCall' => [Statistical\Distributions\Normal::class, 'distribution'], 'argumentCount' => '4', ], 'NORM.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'NORMDIST'], + 'functionCall' => [Statistical\Distributions\Normal::class, 'distribution'], 'argumentCount' => '4', ], 'NORMINV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'NORMINV'], + 'functionCall' => [Statistical\Distributions\Normal::class, 'inverse'], 'argumentCount' => '3', ], 'NORM.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'NORMINV'], + 'functionCall' => [Statistical\Distributions\Normal::class, 'inverse'], 'argumentCount' => '3', ], 'NORMSDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'NORMSDIST'], + 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'cumulative'], 'argumentCount' => '1', ], 'NORM.S.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'NORMSDIST2'], + 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'distribution'], 'argumentCount' => '1,2', ], 'NORMSINV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'NORMSINV'], + 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'inverse'], 'argumentCount' => '1', ], 'NORM.S.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'NORMSINV'], + 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'inverse'], 'argumentCount' => '1', ], 'NOT' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'NOT'], + 'functionCall' => [Logical\Operations::class, 'NOT'], 'argumentCount' => '1', ], 'NOW' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'DATETIMENOW'], + 'functionCall' => [DateTimeExcel\Current::class, 'now'], 'argumentCount' => '0', ], 'NPER' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'NPER'], + 'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'periods'], 'argumentCount' => '3-5', ], 'NPV' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'NPV'], + 'functionCall' => [Financial\CashFlow\Variable\Periodic::class, 'presentValue'], 'argumentCount' => '2+', ], + 'NUMBERSTRING' => [ + 'category' => Category::CATEGORY_TEXT_AND_DATA, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], 'NUMBERVALUE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'NUMBERVALUE'], + 'functionCall' => [TextData\Format::class, 'NUMBERVALUE'], 'argumentCount' => '1+', ], 'OCT2BIN' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'OCTTOBIN'], + 'functionCall' => [Engineering\ConvertOctal::class, 'toBinary'], 'argumentCount' => '1,2', ], 'OCT2DEC' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'OCTTODEC'], + 'functionCall' => [Engineering\ConvertOctal::class, 'toDecimal'], 'argumentCount' => '1', ], 'OCT2HEX' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'OCTTOHEX'], + 'functionCall' => [Engineering\ConvertOctal::class, 'toHex'], 'argumentCount' => '1,2', ], 'ODD' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'ODD'], + 'functionCall' => [MathTrig\Round::class, 'odd'], 'argumentCount' => '1', ], 'ODDFPRICE' => [ @@ -1880,29 +1911,29 @@ class Calculation ], 'OFFSET' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'OFFSET'], + 'functionCall' => [LookupRef\Offset::class, 'OFFSET'], 'argumentCount' => '3-5', 'passCellReference' => true, 'passByReference' => [true], ], 'OR' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'logicalOr'], + 'functionCall' => [Logical\Operations::class, 'logicalOr'], 'argumentCount' => '1+', ], 'PDURATION' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'PDURATION'], + 'functionCall' => [Financial\CashFlow\Single::class, 'periods'], 'argumentCount' => '3', ], 'PEARSON' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'CORREL'], + 'functionCall' => [Statistical\Trends::class, 'CORREL'], 'argumentCount' => '2', ], 'PERCENTILE' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'PERCENTILE'], + 'functionCall' => [Statistical\Percentiles::class, 'PERCENTILE'], 'argumentCount' => '2', ], 'PERCENTILE.EXC' => [ @@ -1912,12 +1943,12 @@ class Calculation ], 'PERCENTILE.INC' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'PERCENTILE'], + 'functionCall' => [Statistical\Percentiles::class, 'PERCENTILE'], 'argumentCount' => '2', ], 'PERCENTRANK' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'PERCENTRANK'], + 'functionCall' => [Statistical\Percentiles::class, 'PERCENTRANK'], 'argumentCount' => '2,3', ], 'PERCENTRANK.EXC' => [ @@ -1927,17 +1958,17 @@ class Calculation ], 'PERCENTRANK.INC' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'PERCENTRANK'], + 'functionCall' => [Statistical\Percentiles::class, 'PERCENTRANK'], 'argumentCount' => '2,3', ], 'PERMUT' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'PERMUT'], + 'functionCall' => [Statistical\Permutations::class, 'PERMUT'], 'argumentCount' => '2', ], 'PERMUTATIONA' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Functions::class, 'DUMMY'], + 'functionCall' => [Statistical\Permutations::class, 'PERMUTATIONA'], 'argumentCount' => '2', ], 'PHONETIC' => [ @@ -1957,42 +1988,42 @@ class Calculation ], 'PMT' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'PMT'], + 'functionCall' => [Financial\CashFlow\Constant\Periodic\Payments::class, 'annuity'], 'argumentCount' => '3-5', ], 'POISSON' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'POISSON'], + 'functionCall' => [Statistical\Distributions\Poisson::class, 'distribution'], 'argumentCount' => '3', ], 'POISSON.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'POISSON'], + 'functionCall' => [Statistical\Distributions\Poisson::class, 'distribution'], 'argumentCount' => '3', ], 'POWER' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'POWER'], + 'functionCall' => [MathTrig\Operations::class, 'power'], 'argumentCount' => '2', ], 'PPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'PPMT'], + 'functionCall' => [Financial\CashFlow\Constant\Periodic\Payments::class, 'interestPayment'], 'argumentCount' => '4-6', ], 'PRICE' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'PRICE'], + 'functionCall' => [Financial\Securities\Price::class, 'price'], 'argumentCount' => '6,7', ], 'PRICEDISC' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'PRICEDISC'], + 'functionCall' => [Financial\Securities\Price::class, 'priceDiscounted'], 'argumentCount' => '4,5', ], 'PRICEMAT' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'PRICEMAT'], + 'functionCall' => [Financial\Securities\Price::class, 'priceAtMaturity'], 'argumentCount' => '5,6', ], 'PROB' => [ @@ -2002,22 +2033,22 @@ class Calculation ], 'PRODUCT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'PRODUCT'], + 'functionCall' => [MathTrig\Operations::class, 'product'], 'argumentCount' => '1+', ], 'PROPER' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'PROPERCASE'], + 'functionCall' => [TextData\CaseConvert::class, 'proper'], 'argumentCount' => '1', ], 'PV' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'PV'], + 'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'presentValue'], 'argumentCount' => '3-5', ], 'QUARTILE' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'QUARTILE'], + 'functionCall' => [Statistical\Percentiles::class, 'QUARTILE'], 'argumentCount' => '2', ], 'QUARTILE.EXC' => [ @@ -2027,22 +2058,22 @@ class Calculation ], 'QUARTILE.INC' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'QUARTILE'], + 'functionCall' => [Statistical\Percentiles::class, 'QUARTILE'], 'argumentCount' => '2', ], 'QUOTIENT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'QUOTIENT'], + 'functionCall' => [MathTrig\Operations::class, 'quotient'], 'argumentCount' => '2', ], 'RADIANS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'deg2rad', + 'functionCall' => [MathTrig\Angle::class, 'toRadians'], 'argumentCount' => '1', ], 'RAND' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'RAND'], + 'functionCall' => [MathTrig\Random::class, 'rand'], 'argumentCount' => '0', ], 'RANDARRAY' => [ @@ -2052,12 +2083,12 @@ class Calculation ], 'RANDBETWEEN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'RAND'], + 'functionCall' => [MathTrig\Random::class, 'randBetween'], 'argumentCount' => '2', ], 'RANK' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'RANK'], + 'functionCall' => [Statistical\Percentiles::class, 'RANK'], 'argumentCount' => '2,3', ], 'RANK.AVG' => [ @@ -2067,83 +2098,94 @@ class Calculation ], 'RANK.EQ' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'RANK'], + 'functionCall' => [Statistical\Percentiles::class, 'RANK'], 'argumentCount' => '2,3', ], 'RATE' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'RATE'], + 'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'rate'], 'argumentCount' => '3-6', ], 'RECEIVED' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'RECEIVED'], + 'functionCall' => [Financial\Securities\Price::class, 'received'], 'argumentCount' => '4-5', ], 'REPLACE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'REPLACE'], + 'functionCall' => [TextData\Replace::class, 'replace'], 'argumentCount' => '4', ], 'REPLACEB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'REPLACE'], + 'functionCall' => [TextData\Replace::class, 'replace'], 'argumentCount' => '4', ], 'REPT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => 'str_repeat', + 'functionCall' => [TextData\Concatenate::class, 'builtinREPT'], 'argumentCount' => '2', ], 'RIGHT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'RIGHT'], + 'functionCall' => [TextData\Extract::class, 'right'], 'argumentCount' => '1,2', ], 'RIGHTB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'RIGHT'], + 'functionCall' => [TextData\Extract::class, 'right'], 'argumentCount' => '1,2', ], 'ROMAN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'ROMAN'], + 'functionCall' => [MathTrig\Roman::class, 'evaluate'], 'argumentCount' => '1,2', ], 'ROUND' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'round', + 'functionCall' => [MathTrig\Round::class, 'round'], 'argumentCount' => '2', ], + 'ROUNDBAHTDOWN' => [ + 'category' => Category::CATEGORY_MATH_AND_TRIG, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], + 'ROUNDBAHTUP' => [ + 'category' => Category::CATEGORY_MATH_AND_TRIG, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], 'ROUNDDOWN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'ROUNDDOWN'], + 'functionCall' => [MathTrig\Round::class, 'down'], 'argumentCount' => '2', ], 'ROUNDUP' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'ROUNDUP'], + 'functionCall' => [MathTrig\Round::class, 'up'], 'argumentCount' => '2', ], 'ROW' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'ROW'], + 'functionCall' => [LookupRef\RowColumnInformation::class, 'ROW'], 'argumentCount' => '-1', + 'passCellReference' => true, 'passByReference' => [true], ], 'ROWS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'ROWS'], + 'functionCall' => [LookupRef\RowColumnInformation::class, 'ROWS'], 'argumentCount' => '1', ], 'RRI' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'RRI'], + 'functionCall' => [Financial\CashFlow\Single::class, 'interestRate'], 'argumentCount' => '3', ], 'RSQ' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'RSQ'], + 'functionCall' => [Statistical\Trends::class, 'RSQ'], 'argumentCount' => '2', ], 'RTD' => [ @@ -2153,27 +2195,27 @@ class Calculation ], 'SEARCH' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'SEARCHINSENSITIVE'], + 'functionCall' => [TextData\Search::class, 'insensitive'], 'argumentCount' => '2,3', ], 'SEARCHB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'SEARCHINSENSITIVE'], + 'functionCall' => [TextData\Search::class, 'insensitive'], 'argumentCount' => '2,3', ], 'SEC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SEC'], + 'functionCall' => [MathTrig\Trig\Secant::class, 'sec'], 'argumentCount' => '1', ], 'SECH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SECH'], + 'functionCall' => [MathTrig\Trig\Secant::class, 'sech'], 'argumentCount' => '1', ], 'SECOND' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'SECOND'], + 'functionCall' => [DateTimeExcel\TimeParts::class, 'second'], 'argumentCount' => '1', ], 'SEQUENCE' => [ @@ -2183,7 +2225,7 @@ class Calculation ], 'SERIESSUM' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SERIESSUM'], + 'functionCall' => [MathTrig\SeriesSum::class, 'evaluate'], 'argumentCount' => '4', ], 'SHEET' => [ @@ -2198,22 +2240,22 @@ class Calculation ], 'SIGN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SIGN'], + 'functionCall' => [MathTrig\Sign::class, 'evaluate'], 'argumentCount' => '1', ], 'SIN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'sin', + 'functionCall' => [MathTrig\Trig\Sine::class, 'sin'], 'argumentCount' => '1', ], 'SINH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'sinh', + 'functionCall' => [MathTrig\Trig\Sine::class, 'sinh'], 'argumentCount' => '1', ], 'SKEW' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'SKEW'], + 'functionCall' => [Statistical\Deviations::class, 'skew'], 'argumentCount' => '1+', ], 'SKEW.P' => [ @@ -2223,17 +2265,17 @@ class Calculation ], 'SLN' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'SLN'], + 'functionCall' => [Financial\Depreciation::class, 'SLN'], 'argumentCount' => '3', ], 'SLOPE' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'SLOPE'], + 'functionCall' => [Statistical\Trends::class, 'SLOPE'], 'argumentCount' => '2', ], 'SMALL' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'SMALL'], + 'functionCall' => [Statistical\Size::class, 'small'], 'argumentCount' => '2', ], 'SORT' => [ @@ -2248,148 +2290,148 @@ class Calculation ], 'SQRT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'sqrt', + 'functionCall' => [MathTrig\Sqrt::class, 'sqrt'], 'argumentCount' => '1', ], 'SQRTPI' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SQRTPI'], + 'functionCall' => [MathTrig\Sqrt::class, 'pi'], 'argumentCount' => '1', ], 'STANDARDIZE' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'STANDARDIZE'], + 'functionCall' => [Statistical\Standardize::class, 'execute'], 'argumentCount' => '3', ], 'STDEV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'STDEV'], + 'functionCall' => [Statistical\StandardDeviations::class, 'STDEV'], 'argumentCount' => '1+', ], 'STDEV.S' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'STDEV'], + 'functionCall' => [Statistical\StandardDeviations::class, 'STDEV'], 'argumentCount' => '1+', ], 'STDEV.P' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'STDEVP'], + 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVP'], 'argumentCount' => '1+', ], 'STDEVA' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'STDEVA'], + 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVA'], 'argumentCount' => '1+', ], 'STDEVP' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'STDEVP'], + 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVP'], 'argumentCount' => '1+', ], 'STDEVPA' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'STDEVPA'], + 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVPA'], 'argumentCount' => '1+', ], 'STEYX' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'STEYX'], + 'functionCall' => [Statistical\Trends::class, 'STEYX'], 'argumentCount' => '2', ], 'SUBSTITUTE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'SUBSTITUTE'], + 'functionCall' => [TextData\Replace::class, 'substitute'], 'argumentCount' => '3,4', ], 'SUBTOTAL' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SUBTOTAL'], + 'functionCall' => [MathTrig\Subtotal::class, 'evaluate'], 'argumentCount' => '2+', 'passCellReference' => true, ], 'SUM' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SUM'], + 'functionCall' => [MathTrig\Sum::class, 'sumErroringStrings'], 'argumentCount' => '1+', ], 'SUMIF' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SUMIF'], + 'functionCall' => [Statistical\Conditional::class, 'SUMIF'], 'argumentCount' => '2,3', ], 'SUMIFS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SUMIFS'], + 'functionCall' => [Statistical\Conditional::class, 'SUMIFS'], 'argumentCount' => '3+', ], 'SUMPRODUCT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SUMPRODUCT'], + 'functionCall' => [MathTrig\Sum::class, 'product'], 'argumentCount' => '1+', ], 'SUMSQ' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SUMSQ'], + 'functionCall' => [MathTrig\SumSquares::class, 'sumSquare'], 'argumentCount' => '1+', ], 'SUMX2MY2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SUMX2MY2'], + 'functionCall' => [MathTrig\SumSquares::class, 'sumXSquaredMinusYSquared'], 'argumentCount' => '2', ], 'SUMX2PY2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SUMX2PY2'], + 'functionCall' => [MathTrig\SumSquares::class, 'sumXSquaredPlusYSquared'], 'argumentCount' => '2', ], 'SUMXMY2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SUMXMY2'], + 'functionCall' => [MathTrig\SumSquares::class, 'sumXMinusYSquared'], 'argumentCount' => '2', ], 'SWITCH' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'statementSwitch'], + 'functionCall' => [Logical\Conditional::class, 'statementSwitch'], 'argumentCount' => '3+', ], 'SYD' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'SYD'], + 'functionCall' => [Financial\Depreciation::class, 'SYD'], 'argumentCount' => '4', ], 'T' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'RETURNSTRING'], + 'functionCall' => [TextData\Text::class, 'test'], 'argumentCount' => '1', ], 'TAN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'tan', + 'functionCall' => [MathTrig\Trig\Tangent::class, 'tan'], 'argumentCount' => '1', ], 'TANH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'tanh', + 'functionCall' => [MathTrig\Trig\Tangent::class, 'tanh'], 'argumentCount' => '1', ], 'TBILLEQ' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'TBILLEQ'], + 'functionCall' => [Financial\TreasuryBill::class, 'bondEquivalentYield'], 'argumentCount' => '3', ], 'TBILLPRICE' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'TBILLPRICE'], + 'functionCall' => [Financial\TreasuryBill::class, 'price'], 'argumentCount' => '3', ], 'TBILLYIELD' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'TBILLYIELD'], + 'functionCall' => [Financial\TreasuryBill::class, 'yield'], 'argumentCount' => '3', ], 'TDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'TDIST'], + 'functionCall' => [Statistical\Distributions\StudentT::class, 'distribution'], 'argumentCount' => '3', ], 'T.DIST' => [ @@ -2409,32 +2451,67 @@ class Calculation ], 'TEXT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'TEXTFORMAT'], + 'functionCall' => [TextData\Format::class, 'TEXTFORMAT'], 'argumentCount' => '2', ], 'TEXTJOIN' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'TEXTJOIN'], + 'functionCall' => [TextData\Concatenate::class, 'TEXTJOIN'], 'argumentCount' => '3+', ], + 'THAIDAYOFWEEK' => [ + 'category' => Category::CATEGORY_DATE_AND_TIME, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], + 'THAIDIGIT' => [ + 'category' => Category::CATEGORY_TEXT_AND_DATA, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], + 'THAIMONTHOFYEAR' => [ + 'category' => Category::CATEGORY_DATE_AND_TIME, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], + 'THAINUMSOUND' => [ + 'category' => Category::CATEGORY_TEXT_AND_DATA, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], + 'THAINUMSTRING' => [ + 'category' => Category::CATEGORY_TEXT_AND_DATA, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], + 'THAISTRINGLENGTH' => [ + 'category' => Category::CATEGORY_TEXT_AND_DATA, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], + 'THAIYEAR' => [ + 'category' => Category::CATEGORY_DATE_AND_TIME, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], 'TIME' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'TIME'], + 'functionCall' => [DateTimeExcel\Time::class, 'fromHMS'], 'argumentCount' => '3', ], 'TIMEVALUE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'TIMEVALUE'], + 'functionCall' => [DateTimeExcel\TimeValue::class, 'fromString'], 'argumentCount' => '1', ], 'TINV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'TINV'], + 'functionCall' => [Statistical\Distributions\StudentT::class, 'inverse'], 'argumentCount' => '2', ], 'T.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'TINV'], + 'functionCall' => [Statistical\Distributions\StudentT::class, 'inverse'], 'argumentCount' => '2', ], 'T.INV.2T' => [ @@ -2444,37 +2521,37 @@ class Calculation ], 'TODAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'DATENOW'], + 'functionCall' => [DateTimeExcel\Current::class, 'today'], 'argumentCount' => '0', ], 'TRANSPOSE' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'TRANSPOSE'], + 'functionCall' => [LookupRef\Matrix::class, 'transpose'], 'argumentCount' => '1', ], 'TREND' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'TREND'], + 'functionCall' => [Statistical\Trends::class, 'TREND'], 'argumentCount' => '1-4', ], 'TRIM' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'TRIMSPACES'], + 'functionCall' => [TextData\Trim::class, 'spaces'], 'argumentCount' => '1', ], 'TRIMMEAN' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'TRIMMEAN'], + 'functionCall' => [Statistical\Averages\Mean::class, 'trim'], 'argumentCount' => '2', ], 'TRUE' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'TRUE'], + 'functionCall' => [Logical\Boolean::class, 'TRUE'], 'argumentCount' => '0', ], 'TRUNC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'TRUNC'], + 'functionCall' => [MathTrig\Trunc::class, 'evaluate'], 'argumentCount' => '1,2', ], 'TTEST' => [ @@ -2494,12 +2571,12 @@ class Calculation ], 'UNICHAR' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'CHARACTER'], + 'functionCall' => [TextData\CharacterConvert::class, 'character'], 'argumentCount' => '1', ], 'UNICODE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'ASCIICODE'], + 'functionCall' => [TextData\CharacterConvert::class, 'code'], 'argumentCount' => '1', ], 'UNIQUE' => [ @@ -2509,47 +2586,52 @@ class Calculation ], 'UPPER' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'UPPERCASE'], + 'functionCall' => [TextData\CaseConvert::class, 'upper'], 'argumentCount' => '1', ], 'USDOLLAR' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Functions::class, 'DUMMY'], + 'functionCall' => [Financial\Dollar::class, 'format'], 'argumentCount' => '2', ], 'VALUE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'VALUE'], + 'functionCall' => [TextData\Format::class, 'VALUE'], 'argumentCount' => '1', ], + 'VALUETOTEXT' => [ + 'category' => Category::CATEGORY_TEXT_AND_DATA, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], 'VAR' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'VARFunc'], + 'functionCall' => [Statistical\Variances::class, 'VAR'], 'argumentCount' => '1+', ], 'VAR.P' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'VARP'], + 'functionCall' => [Statistical\Variances::class, 'VARP'], 'argumentCount' => '1+', ], 'VAR.S' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'VARFunc'], + 'functionCall' => [Statistical\Variances::class, 'VAR'], 'argumentCount' => '1+', ], 'VARA' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'VARA'], + 'functionCall' => [Statistical\Variances::class, 'VARA'], 'argumentCount' => '1+', ], 'VARP' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'VARP'], + 'functionCall' => [Statistical\Variances::class, 'VARP'], 'argumentCount' => '1+', ], 'VARPA' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'VARPA'], + 'functionCall' => [Statistical\Variances::class, 'VARPA'], 'argumentCount' => '1+', ], 'VDB' => [ @@ -2559,37 +2641,37 @@ class Calculation ], 'VLOOKUP' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'VLOOKUP'], + 'functionCall' => [LookupRef\VLookup::class, 'lookup'], 'argumentCount' => '3,4', ], 'WEBSERVICE' => [ 'category' => Category::CATEGORY_WEB, - 'functionCall' => [Web::class, 'WEBSERVICE'], + 'functionCall' => [Web\Service::class, 'webService'], 'argumentCount' => '1', ], 'WEEKDAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'WEEKDAY'], + 'functionCall' => [DateTimeExcel\Week::class, 'day'], 'argumentCount' => '1,2', ], 'WEEKNUM' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'WEEKNUM'], + 'functionCall' => [DateTimeExcel\Week::class, 'number'], 'argumentCount' => '1,2', ], 'WEIBULL' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'WEIBULL'], + 'functionCall' => [Statistical\Distributions\Weibull::class, 'distribution'], 'argumentCount' => '4', ], 'WEIBULL.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'WEIBULL'], + 'functionCall' => [Statistical\Distributions\Weibull::class, 'distribution'], 'argumentCount' => '4', ], 'WORKDAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'WORKDAY'], + 'functionCall' => [DateTimeExcel\WorkDay::class, 'date'], 'argumentCount' => '2-3', ], 'WORKDAY.INTL' => [ @@ -2599,7 +2681,7 @@ class Calculation ], 'XIRR' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'XIRR'], + 'functionCall' => [Financial\CashFlow\Variable\NonPeriodic::class, 'rate'], 'argumentCount' => '2,3', ], 'XLOOKUP' => [ @@ -2609,7 +2691,7 @@ class Calculation ], 'XNPV' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'XNPV'], + 'functionCall' => [Financial\CashFlow\Variable\NonPeriodic::class, 'presentValue'], 'argumentCount' => '3', ], 'XMATCH' => [ @@ -2619,17 +2701,17 @@ class Calculation ], 'XOR' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'logicalXor'], + 'functionCall' => [Logical\Operations::class, 'logicalXor'], 'argumentCount' => '1+', ], 'YEAR' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'YEAR'], + 'functionCall' => [DateTimeExcel\DateParts::class, 'year'], 'argumentCount' => '1', ], 'YEARFRAC' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'YEARFRAC'], + 'functionCall' => [DateTimeExcel\YearFrac::class, 'fraction'], 'argumentCount' => '2,3', ], 'YIELD' => [ @@ -2639,22 +2721,22 @@ class Calculation ], 'YIELDDISC' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'YIELDDISC'], + 'functionCall' => [Financial\Securities\Yields::class, 'yieldDiscounted'], 'argumentCount' => '4,5', ], 'YIELDMAT' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'YIELDMAT'], + 'functionCall' => [Financial\Securities\Yields::class, 'yieldAtMaturity'], 'argumentCount' => '5,6', ], 'ZTEST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'ZTEST'], + 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'zTest'], 'argumentCount' => '2-3', ], 'Z.TEST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'ZTEST'], + 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'zTest'], 'argumentCount' => '2-3', ], ]; @@ -2663,12 +2745,16 @@ class Calculation private static $controlFunctions = [ 'MKMATRIX' => [ 'argumentCount' => '*', - 'functionCall' => [__CLASS__, 'mkMatrix'], + 'functionCall' => [Internal\MakeMatrix::class, 'make'], ], 'NAME.ERROR' => [ 'argumentCount' => '*', 'functionCall' => [Functions::class, 'NAME'], ], + 'WILDCARDMATCH' => [ + 'argumentCount' => '2', + 'functionCall' => [Internal\WildcardMatch::class, 'compare'], + ], ]; public function __construct(?Spreadsheet $spreadsheet = null) @@ -2695,12 +2781,10 @@ class Calculation /** * Get an instance of this class. * - * @param Spreadsheet $spreadsheet Injected spreadsheet for working with a PhpSpreadsheet Spreadsheet object, - * or NULL to create a standalone claculation engine - * - * @return Calculation + * @param ?Spreadsheet $spreadsheet Injected spreadsheet for working with a PhpSpreadsheet Spreadsheet object, + * or NULL to create a standalone calculation engine */ - public static function getInstance(?Spreadsheet $spreadsheet = null) + public static function getInstance(?Spreadsheet $spreadsheet = null): self { if ($spreadsheet !== null) { $instance = $spreadsheet->getCalculationEngine(); @@ -2749,7 +2833,7 @@ class Calculation * * @return string locale-specific translation of TRUE */ - public static function getTRUE() + public static function getTRUE(): string { return self::$localeBoolean['TRUE']; } @@ -2759,7 +2843,7 @@ class Calculation * * @return string locale-specific translation of FALSE */ - public static function getFALSE() + public static function getFALSE(): string { return self::$localeBoolean['FALSE']; } @@ -2902,6 +2986,21 @@ class Calculation return self::$localeLanguage; } + private function getLocaleFile(string $localeDir, string $locale, string $language, string $file): string + { + $localeFileName = $localeDir . str_replace('_', DIRECTORY_SEPARATOR, $locale) . + DIRECTORY_SEPARATOR . $file; + if (!file_exists($localeFileName)) { + // If there isn't a locale specific file, look for a language specific file + $localeFileName = $localeDir . $language . DIRECTORY_SEPARATOR . $file; + if (!file_exists($localeFileName)) { + throw new Exception('Locale file not found'); + } + } + + return $localeFileName; + } + /** * Set the locale code. * @@ -2909,7 +3008,7 @@ class Calculation * * @return bool */ - public function setLocale($locale) + public function setLocale(string $locale) { // Identify our locale and language $language = $locale = strtolower($locale); @@ -2919,31 +3018,30 @@ class Calculation if (count(self::$validLocaleLanguages) == 1) { self::loadLocales(); } + // Test whether we have any language data for this language (any locale) if (in_array($language, self::$validLocaleLanguages)) { // initialise language/locale settings self::$localeFunctions = []; self::$localeArgumentSeparator = ','; self::$localeBoolean = ['TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL']; - // Default is English, if user isn't requesting english, then read the necessary data from the locale files - if ($locale != 'en_us') { + + // Default is US English, if user isn't requesting US english, then read the necessary data from the locale files + if ($locale !== 'en_us') { + $localeDir = implode(DIRECTORY_SEPARATOR, [__DIR__, 'locale', null]); // Search for a file with a list of function names for locale - $functionNamesFile = __DIR__ . '/locale/' . str_replace('_', DIRECTORY_SEPARATOR, $locale) . DIRECTORY_SEPARATOR . 'functions'; - if (!file_exists($functionNamesFile)) { - // If there isn't a locale specific function file, look for a language specific function file - $functionNamesFile = __DIR__ . '/locale/' . $language . DIRECTORY_SEPARATOR . 'functions'; - if (!file_exists($functionNamesFile)) { - return false; - } + try { + $functionNamesFile = $this->getLocaleFile($localeDir, $locale, $language, 'functions'); + } catch (Exception $e) { + return false; } + // Retrieve the list of locale or language specific function names $localeFunctions = file($functionNamesFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); foreach ($localeFunctions as $localeFunction) { [$localeFunction] = explode('##', $localeFunction); // Strip out comments if (strpos($localeFunction, '=') !== false) { - [$fName, $lfName] = explode('=', $localeFunction); - $fName = trim($fName); - $lfName = trim($lfName); + [$fName, $lfName] = array_map('trim', explode('=', $localeFunction)); if ((isset(self::$phpSpreadsheetFunctions[$fName])) && ($lfName != '') && ($fName != $lfName)) { self::$localeFunctions[$fName] = $lfName; } @@ -2957,20 +3055,22 @@ class Calculation self::$localeBoolean['FALSE'] = self::$localeFunctions['FALSE']; } - $configFile = __DIR__ . '/locale/' . str_replace('_', DIRECTORY_SEPARATOR, $locale) . DIRECTORY_SEPARATOR . 'config'; - if (!file_exists($configFile)) { - $configFile = __DIR__ . '/locale/' . $language . DIRECTORY_SEPARATOR . 'config'; + try { + $configFile = $this->getLocaleFile($localeDir, $locale, $language, 'config'); + } catch (Exception $e) { + return false; } - if (file_exists($configFile)) { - $localeSettings = file($configFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); - foreach ($localeSettings as $localeSetting) { - [$localeSetting] = explode('##', $localeSetting); // Strip out comments - if (strpos($localeSetting, '=') !== false) { - [$settingName, $settingValue] = explode('=', $localeSetting); - $settingName = strtoupper(trim($settingName)); + + $localeSettings = file($configFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); + foreach ($localeSettings as $localeSetting) { + [$localeSetting] = explode('##', $localeSetting); // Strip out comments + if (strpos($localeSetting, '=') !== false) { + [$settingName, $settingValue] = array_map('trim', explode('=', $localeSetting)); + $settingName = strtoupper($settingName); + if ($settingValue !== '') { switch ($settingName) { case 'ARGUMENTSEPARATOR': - self::$localeArgumentSeparator = trim($settingValue); + self::$localeArgumentSeparator = $settingValue; break; } @@ -3061,9 +3161,9 @@ class Calculation return $formula; } - private static $functionReplaceFromExcel = null; + private static $functionReplaceFromExcel; - private static $functionReplaceToLocale = null; + private static $functionReplaceToLocale; public function _translateFormulaToLocale($formula) { @@ -3090,9 +3190,9 @@ class Calculation return self::translateFormula(self::$functionReplaceFromExcel, self::$functionReplaceToLocale, $formula, ',', self::$localeArgumentSeparator); } - private static $functionReplaceFromLocale = null; + private static $functionReplaceFromLocale; - private static $functionReplaceToExcel = null; + private static $functionReplaceToExcel; public function _translateFormulaToEnglish($formula) { @@ -3150,6 +3250,7 @@ class Calculation // Return Excel errors "as is" return $value; } + // Return strings wrapped in quotes return self::FORMULA_STRING_QUOTE . $value . self::FORMULA_STRING_QUOTE; } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) { @@ -3341,18 +3442,15 @@ class Calculation } /** - * @param string $cellReference * @param mixed $cellValue - * - * @return bool */ - public function getValueFromCache($cellReference, &$cellValue) + public function getValueFromCache(string $cellReference, &$cellValue): bool { + $this->debugLog->writeDebugLog("Testing cache value for cell {$cellReference}"); // Is calculation cacheing enabled? - // Is the value present in calculation cache? - $this->debugLog->writeDebugLog('Testing cache value for cell ', $cellReference); + // If so, is the required value present in calculation cache? if (($this->calculationCacheEnabled) && (isset($this->calculationCache[$cellReference]))) { - $this->debugLog->writeDebugLog('Retrieving value for cell ', $cellReference, ' from cache'); + $this->debugLog->writeDebugLog("Retrieving value for cell {$cellReference} from cache"); // Return the cached result $cellValue = $this->calculationCache[$cellReference]; @@ -3414,7 +3512,7 @@ class Calculation if (($cellID !== null) && ($this->getValueFromCache($wsCellReference, $cellValue))) { return $cellValue; } - $this->debugLog->writeDebugLog('Evaluating formula for cell ', $wsCellReference); + $this->debugLog->writeDebugLog("Evaluating formula for cell {$wsCellReference}"); if (($wsTitle[0] !== "\x00") && ($this->cyclicReferenceStack->onStack($wsCellReference))) { if ($this->cyclicFormulaCount <= 0) { @@ -3436,9 +3534,10 @@ class Calculation } } - $this->debugLog->writeDebugLog('Formula for cell ', $wsCellReference, ' is ', $formula); + $this->debugLog->writeDebugLog("Formula for cell {$wsCellReference} is {$formula}"); // Parse the formula onto the token stack and calculate the value $this->cyclicReferenceStack->push($wsCellReference); + $cellValue = $this->processTokenStack($this->internalParseFormula($formula, $pCell), $cellID, $pCell); $this->cyclicReferenceStack->pop(); @@ -3454,8 +3553,8 @@ class Calculation /** * Ensure that paired matrix operands are both matrices and of the same size. * - * @param mixed &$operand1 First matrix operand - * @param mixed &$operand2 Second matrix operand + * @param mixed $operand1 First matrix operand + * @param mixed $operand2 Second matrix operand * @param int $resize Flag indicating whether the matrices should be resized to match * and (if so), whether the smaller dimension should grow or the * larger should shrink. @@ -3499,7 +3598,7 @@ class Calculation /** * Read the dimensions of a matrix, and re-index it with straight numeric keys starting from row 0, column 0. * - * @param array &$matrix matrix operand + * @param array $matrix matrix operand * * @return int[] An array comprising the number of rows, and number of columns */ @@ -3524,8 +3623,8 @@ class Calculation /** * Ensure that paired matrix operands are both matrices of the same size. * - * @param mixed &$matrix1 First matrix operand - * @param mixed &$matrix2 Second matrix operand + * @param mixed $matrix1 First matrix operand + * @param mixed $matrix2 Second matrix operand * @param int $matrix1Rows Row size of first matrix operand * @param int $matrix1Columns Column size of first matrix operand * @param int $matrix2Rows Row size of second matrix operand @@ -3567,8 +3666,8 @@ class Calculation /** * Ensure that paired matrix operands are both matrices of the same size. * - * @param mixed &$matrix1 First matrix operand - * @param mixed &$matrix2 Second matrix operand + * @param mixed $matrix1 First matrix operand + * @param mixed $matrix2 Second matrix operand * @param int $matrix1Rows Row size of first matrix operand * @param int $matrix1Columns Column size of first matrix operand * @param int $matrix2Rows Row size of second matrix operand @@ -3685,6 +3784,8 @@ class Calculation return $typeString . ' with a value of ' . $this->showValue($value); } + + return null; } /** @@ -3743,11 +3844,6 @@ class Calculation return $formula; } - private static function mkMatrix(...$args) - { - return $args; - } - // Binary Operators // These operators always work on two values // Array key is the operator, the value indicates whether this is a left or right associative operator @@ -3784,7 +3880,7 @@ class Calculation /** * @param string $formula * - * @return bool + * @return array|false */ private function internalParseFormula($formula, ?Cell $pCell = null) { @@ -3798,6 +3894,8 @@ class Calculation $regexpMatchString = '/^(' . self::CALCULATION_REGEXP_FUNCTION . '|' . self::CALCULATION_REGEXP_CELLREF . + '|' . self::CALCULATION_REGEXP_COLUMN_RANGE . + '|' . self::CALCULATION_REGEXP_ROW_RANGE . '|' . self::CALCULATION_REGEXP_NUMBER . '|' . self::CALCULATION_REGEXP_STRING . '|' . self::CALCULATION_REGEXP_OPENBRACE . @@ -3866,7 +3964,8 @@ class Calculation $opCharacter .= $formula[++$index]; } // Find out if we're currently at the beginning of a number, variable, cell reference, function, parenthesis or operand - $isOperandOrFunction = preg_match($regexpMatchString, substr($formula, $index), $match); + $isOperandOrFunction = (bool) preg_match($regexpMatchString, substr($formula, $index), $match); + if ($opCharacter == '-' && !$expectingOperator) { // Is it a negation instead of a minus? // Put a negation on the stack $stack->push('Unary Operator', '~', null, $currentCondition, $currentOnlyIf, $currentOnlyIfNot); @@ -3942,6 +4041,7 @@ class Calculation } // Check the argument count $argumentCountError = false; + $expectedArgumentCountString = null; if (is_numeric($expectedArgumentCount)) { if ($expectedArgumentCount < 0) { if ($argumentCount > abs($expectedArgumentCount)) { @@ -4010,7 +4110,7 @@ class Calculation // If we've a comma when we're expecting an operand, then what we actually have is a null operand; // so push a null onto the stack if (($expectingOperand) || (!$expectingOperator)) { - $output[] = ['type' => 'NULL Value', 'value' => self::$excelConstants['NULL'], 'reference' => null]; + $output[] = ['type' => 'Empty Argument', 'value' => self::$excelConstants['NULL'], 'reference' => null]; } // make sure there was a function $d = $stack->last(2); @@ -4037,6 +4137,7 @@ class Calculation $expectingOperand = false; $val = $match[1]; $length = strlen($val); + if (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $val, $matches)) { $val = preg_replace('/\s/u', '', $val); if (isset(self::$phpSpreadsheetFunctions[strtoupper($matches[1])]) || isset(self::$controlFunctions[strtoupper($matches[1])])) { // it's a function @@ -4073,7 +4174,7 @@ class Calculation // Should only be applied to the actual cell column, not the worksheet name // If the last entry on the stack was a : operator, then we have a cell range reference $testPrevOp = $stack->last(1); - if ($testPrevOp !== null && $testPrevOp['value'] == ':') { + if ($testPrevOp !== null && $testPrevOp['value'] === ':') { // If we have a worksheet reference, then we're playing with a 3D reference if ($matches[2] == '') { // Otherwise, we 'inherit' the worksheet reference from the start cell reference @@ -4090,62 +4191,57 @@ class Calculation return $this->raiseFormulaError('3D Range references are not yet supported'); } } + } elseif (strpos($val, '!') === false && $pCellParent !== null) { + $worksheet = $pCellParent->getTitle(); + $val = "'{$worksheet}'!{$val}"; } $outputItem = $stack->getStackItem('Cell Reference', $val, $val, $currentCondition, $currentOnlyIf, $currentOnlyIfNot); $output[] = $outputItem; } else { // it's a variable, constant, string, number or boolean + $localeConstant = false; + $stackItemType = 'Value'; + $stackItemReference = null; + // If the last entry on the stack was a : operator, then we may have a row or column range reference $testPrevOp = $stack->last(1); if ($testPrevOp !== null && $testPrevOp['value'] === ':') { + $stackItemType = 'Cell Reference'; $startRowColRef = $output[count($output) - 1]['value']; [$rangeWS1, $startRowColRef] = Worksheet::extractSheetTitle($startRowColRef, true); $rangeSheetRef = $rangeWS1; - if ($rangeWS1 != '') { + if ($rangeWS1 !== '') { $rangeWS1 .= '!'; } + $rangeSheetRef = trim($rangeSheetRef, "'"); [$rangeWS2, $val] = Worksheet::extractSheetTitle($val, true); - if ($rangeWS2 != '') { + if ($rangeWS2 !== '') { $rangeWS2 .= '!'; } else { $rangeWS2 = $rangeWS1; } + $refSheet = $pCellParent; - if ($pCellParent !== null && $rangeSheetRef !== $pCellParent->getTitle()) { + if ($pCellParent !== null && $rangeSheetRef !== '' && $rangeSheetRef !== $pCellParent->getTitle()) { $refSheet = $pCellParent->getParent()->getSheetByName($rangeSheetRef); } - if ( - (is_int($startRowColRef)) && (ctype_digit($val)) && - ($startRowColRef <= 1048576) && ($val <= 1048576) - ) { - // Row range - $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestColumn() : 'XFD'; // Max 16,384 columns for Excel2007 - $output[count($output) - 1]['value'] = $rangeWS1 . 'A' . $startRowColRef; - $val = $rangeWS2 . $endRowColRef . $val; - } elseif ( - (ctype_alpha($startRowColRef)) && (ctype_alpha($val)) && - (strlen($startRowColRef) <= 3) && (strlen($val) <= 3) - ) { - // Column range - $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestRow() : 1048576; // Max 1,048,576 rows for Excel2007 - $output[count($output) - 1]['value'] = $rangeWS1 . strtoupper($startRowColRef) . '1'; - $val = $rangeWS2 . $val . $endRowColRef; - } - } - $localeConstant = false; - $stackItemType = 'Value'; - $stackItemReference = null; - if ($opCharacter == self::FORMULA_STRING_QUOTE) { + if (ctype_digit($val) && $val <= 1048576) { + // Row range + $stackItemType = 'Row Reference'; + $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataColumn($val) : 'XFD'; // Max 16,384 columns for Excel2007 + $val = "{$rangeWS2}{$endRowColRef}{$val}"; + } elseif (ctype_alpha($val) && strlen($val) <= 3) { + // Column range + $stackItemType = 'Column Reference'; + $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataRow($val) : 1048576; // Max 1,048,576 rows for Excel2007 + $val = "{$rangeWS2}{$val}{$endRowColRef}"; + } + $stackItemReference = $val; + } elseif ($opCharacter == self::FORMULA_STRING_QUOTE) { // UnEscape any quotes within the string $val = self::wrapResult(str_replace('""', self::FORMULA_STRING_QUOTE, self::unwrapResult($val))); - } elseif (is_numeric($val)) { - if ((strpos($val, '.') !== false) || (stripos($val, 'e') !== false) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) { - $val = (float) $val; - } else { - $val = (int) $val; - } } elseif (isset(self::$excelConstants[trim(strtoupper($val))])) { $stackItemType = 'Constant'; $excelConstant = trim(strtoupper($val)); @@ -4153,10 +4249,41 @@ class Calculation } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$localeBoolean)) !== false) { $stackItemType = 'Constant'; $val = self::$excelConstants[$localeConstant]; + } elseif ( + preg_match('/^' . self::CALCULATION_REGEXP_ROW_RANGE . '/miu', substr($formula, $index), $rowRangeReference) + ) { + $val = $rowRangeReference[1]; + $length = strlen($rowRangeReference[1]); + $stackItemType = 'Row Reference'; + $column = 'A'; + if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) { + $column = $pCellParent->getHighestDataColumn($val); + } + $val = "{$rowRangeReference[2]}{$column}{$rowRangeReference[7]}"; + $stackItemReference = $val; + } elseif ( + preg_match('/^' . self::CALCULATION_REGEXP_COLUMN_RANGE . '/miu', substr($formula, $index), $columnRangeReference) + ) { + $val = $columnRangeReference[1]; + $length = strlen($val); + $stackItemType = 'Column Reference'; + $row = '1'; + if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) { + $row = $pCellParent->getHighestDataRow($val); + } + $val = "{$val}{$row}"; + $stackItemReference = $val; } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', $val, $match)) { $stackItemType = 'Defined Name'; $stackItemReference = $val; + } elseif (is_numeric($val)) { + if ((strpos($val, '.') !== false) || (stripos($val, 'e') !== false) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) { + $val = (float) $val; + } else { + $val = (int) $val; + } } + $details = $stack->getStackItem($stackItemType, $val, $stackItemReference, $currentCondition, $currentOnlyIf, $currentOnlyIfNot); if ($localeConstant) { $details['localeValue'] = $localeConstant; @@ -4168,7 +4295,7 @@ class Calculation ++$index; } elseif ($opCharacter == ')') { // miscellaneous error checking if ($expectingOperand) { - $output[] = ['type' => 'NULL Value', 'value' => self::$excelConstants['NULL'], 'reference' => null]; + $output[] = ['type' => 'Empty Argument', 'value' => self::$excelConstants['NULL'], 'reference' => null]; $expectingOperand = false; $expectingOperator = true; } else { @@ -4241,7 +4368,7 @@ class Calculation $rowKey = array_shift($rKeys); $cKeys = array_keys(array_keys($operand[$rowKey])); $colKey = array_shift($cKeys); - if (ctype_upper($colKey)) { + if (ctype_upper("$colKey")) { $operandData['reference'] = $colKey . $rowKey; } } @@ -4255,7 +4382,7 @@ class Calculation * @param mixed $tokens * @param null|string $cellID * - * @return bool + * @return array|false */ private function processTokenStack($tokens, $cellID = null, ?Cell $pCell = null) { @@ -4350,7 +4477,7 @@ class Calculation } // if the token is a binary operator, pop the top two values off the stack, do the operation, and push the result back on the stack - if (isset(self::$binaryOperators[$token])) { + if (!is_numeric($token) && isset(self::$binaryOperators[$token])) { // We must have two operands, error if we don't if (($operand2Data = $stack->pop()) === null) { return $this->raiseFormulaError('Internal error - Operand value missing from stack'); @@ -4397,7 +4524,7 @@ class Calculation $sheet2 = $sheet1; } - if ($sheet1 == $sheet2) { + if (trim($sheet1, "'") === trim($sheet2, "'")) { if ($operand1Data['reference'] === null) { if ((trim($operand1Data['value']) != '') && (is_numeric($operand1Data['value']))) { $operand1Data['reference'] = $pCell->getColumn() . $operand1Data['value']; @@ -4430,6 +4557,7 @@ class Calculation } else { return $this->raiseFormulaError('Unable to access Cell Reference'); } + $stack->push('Cell Reference', $cellValue, $cellRef); } else { $stack->push('Error', Functions::REF(), null); @@ -4561,8 +4689,9 @@ class Calculation } else { $this->executeNumericBinaryOperation($multiplier, $arg, '*', 'arrayTimesEquals', $stack); } - } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/i', $token, $matches)) { + } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/i', $token ?? '', $matches)) { $cellRef = null; + if (isset($matches[8])) { if ($pCell === null) { // We can't access the range, so return a REF error @@ -4612,6 +4741,7 @@ class Calculation $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false); $pCell->attach($pCellParent); } else { + $cellRef = ($cellSheet !== null) ? "'{$matches[2]}'!{$cellRef}" : $cellRef; $cellValue = null; } } else { @@ -4630,13 +4760,14 @@ class Calculation } } } - $stack->push('Value', $cellValue, $cellRef); + + $stack->push('Cell Value', $cellValue, $cellRef); if (isset($storeKey)) { $branchStore[$storeKey] = $cellValue; } // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on - } elseif (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $token, $matches)) { + } elseif (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $token ?? '', $matches)) { if ($pCellParent) { $pCell->attach($pCellParent); } @@ -4644,10 +4775,13 @@ class Calculation $functionName = $matches[1]; $argCount = $stack->pop(); $argCount = $argCount['value']; - if ($functionName != 'MKMATRIX') { + if ($functionName !== 'MKMATRIX') { $this->debugLog->writeDebugLog('Evaluating Function ', self::localeFunc($functionName), '() with ', (($argCount == 0) ? 'no' : $argCount), ' argument', (($argCount == 1) ? '' : 's')); } if ((isset(self::$phpSpreadsheetFunctions[$functionName])) || (isset(self::$controlFunctions[$functionName]))) { // function + $passByReference = false; + $passCellReference = false; + $functionCall = null; if (isset(self::$phpSpreadsheetFunctions[$functionName])) { $functionCall = self::$phpSpreadsheetFunctions[$functionName]['functionCall']; $passByReference = isset(self::$phpSpreadsheetFunctions[$functionName]['passByReference']); @@ -4657,8 +4791,10 @@ class Calculation $passByReference = isset(self::$controlFunctions[$functionName]['passByReference']); $passCellReference = isset(self::$controlFunctions[$functionName]['passCellReference']); } + // get the arguments for this function $args = $argArrayVals = []; + $emptyArguments = []; for ($i = 0; $i < $argCount; ++$i) { $arg = $stack->pop(); $a = $argCount - $i - 1; @@ -4669,18 +4805,19 @@ class Calculation ) { if ($arg['reference'] === null) { $args[] = $cellID; - if ($functionName != 'MKMATRIX') { + if ($functionName !== 'MKMATRIX') { $argArrayVals[] = $this->showValue($cellID); } } else { $args[] = $arg['reference']; - if ($functionName != 'MKMATRIX') { + if ($functionName !== 'MKMATRIX') { $argArrayVals[] = $this->showValue($arg['reference']); } } } else { + $emptyArguments[] = ($arg['type'] === 'Empty Argument'); $args[] = self::unwrapResult($arg['value']); - if ($functionName != 'MKMATRIX') { + if ($functionName !== 'MKMATRIX') { $argArrayVals[] = $this->showValue($arg['value']); } } @@ -4688,13 +4825,18 @@ class Calculation // Reverse the order of the arguments krsort($args); + krsort($emptyArguments); + + if ($argCount > 0) { + $args = $this->addDefaultArgumentValues($functionCall, $args, $emptyArguments); + } if (($passByReference) && ($argCount == 0)) { $args[] = $cellID; $argArrayVals[] = $this->showValue($cellID); } - if ($functionName != 'MKMATRIX') { + if ($functionName !== 'MKMATRIX') { if ($this->debugLog->getWriteDebugLog()) { krsort($argArrayVals); $this->debugLog->writeDebugLog('Evaluating ', self::localeFunc($functionName), '( ', implode(self::$localeArgumentSeparator . ' ', Functions::flattenArray($argArrayVals)), ' )'); @@ -4713,7 +4855,7 @@ class Calculation $result = call_user_func_array($functionCall, $args); - if ($functionName != 'MKMATRIX') { + if ($functionName !== 'MKMATRIX') { $this->debugLog->writeDebugLog('Evaluation Result for ', self::localeFunc($functionName), '() function call is ', $this->showTypeDetails($result)); } $stack->push('Value', self::wrapResult($result)); @@ -4723,7 +4865,7 @@ class Calculation } } else { // if the token is a number, boolean, string or an Excel error, push it onto the stack - if (isset(self::$excelConstants[strtoupper($token)])) { + if (isset(self::$excelConstants[strtoupper($token ?? '')])) { $excelConstant = strtoupper($token); $stack->push('Constant Value', self::$excelConstants[$excelConstant]); if (isset($storeKey)) { @@ -4731,7 +4873,7 @@ class Calculation } $this->debugLog->writeDebugLog('Evaluating Constant ', $excelConstant, ' as ', $this->showTypeDetails(self::$excelConstants[$excelConstant])); } elseif ((is_numeric($token)) || ($token === null) || (is_bool($token)) || ($token == '') || ($token[0] == self::FORMULA_STRING_QUOTE) || ($token[0] == '#')) { - $stack->push('Value', $token); + $stack->push($tokenData['type'], $token, $tokenData['reference']); if (isset($storeKey)) { $branchStore[$storeKey] = $token; } @@ -4805,6 +4947,53 @@ class Calculation return true; } + /** + * @param null|string $cellID + * @param mixed $operand1 + * @param mixed $operand2 + * @param string $operation + * + * @return array + */ + private function executeArrayComparison($cellID, $operand1, $operand2, $operation, Stack &$stack, bool $recursingArrays) + { + $result = []; + if (!is_array($operand2)) { + // Operand 1 is an array, Operand 2 is a scalar + foreach ($operand1 as $x => $operandData) { + $this->debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operandData), ' ', $operation, ' ', $this->showValue($operand2)); + $this->executeBinaryComparisonOperation($cellID, $operandData, $operand2, $operation, $stack); + $r = $stack->pop(); + $result[$x] = $r['value']; + } + } elseif (!is_array($operand1)) { + // Operand 1 is a scalar, Operand 2 is an array + foreach ($operand2 as $x => $operandData) { + $this->debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operand1), ' ', $operation, ' ', $this->showValue($operandData)); + $this->executeBinaryComparisonOperation($cellID, $operand1, $operandData, $operation, $stack); + $r = $stack->pop(); + $result[$x] = $r['value']; + } + } else { + // Operand 1 and Operand 2 are both arrays + if (!$recursingArrays) { + self::checkMatrixOperands($operand1, $operand2, 2); + } + foreach ($operand1 as $x => $operandData) { + $this->debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operandData), ' ', $operation, ' ', $this->showValue($operand2[$x])); + $this->executeBinaryComparisonOperation($cellID, $operandData, $operand2[$x], $operation, $stack, true); + $r = $stack->pop(); + $result[$x] = $r['value']; + } + } + // Log the result details + $this->debugLog->writeDebugLog('Comparison Evaluation Result is ', $this->showTypeDetails($result)); + // And push the result onto the stack + $stack->push('Array', $result); + + return $result; + } + /** * @param null|string $cellID * @param mixed $operand1 @@ -4818,38 +5007,7 @@ class Calculation { // If we're dealing with matrix operations, we want a matrix result if ((is_array($operand1)) || (is_array($operand2))) { - $result = []; - if ((is_array($operand1)) && (!is_array($operand2))) { - foreach ($operand1 as $x => $operandData) { - $this->debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operandData), ' ', $operation, ' ', $this->showValue($operand2)); - $this->executeBinaryComparisonOperation($cellID, $operandData, $operand2, $operation, $stack); - $r = $stack->pop(); - $result[$x] = $r['value']; - } - } elseif ((!is_array($operand1)) && (is_array($operand2))) { - foreach ($operand2 as $x => $operandData) { - $this->debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operand1), ' ', $operation, ' ', $this->showValue($operandData)); - $this->executeBinaryComparisonOperation($cellID, $operand1, $operandData, $operation, $stack); - $r = $stack->pop(); - $result[$x] = $r['value']; - } - } else { - if (!$recursingArrays) { - self::checkMatrixOperands($operand1, $operand2, 2); - } - foreach ($operand1 as $x => $operandData) { - $this->debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operandData), ' ', $operation, ' ', $this->showValue($operand2[$x])); - $this->executeBinaryComparisonOperation($cellID, $operandData, $operand2[$x], $operation, $stack, true); - $r = $stack->pop(); - $result[$x] = $r['value']; - } - } - // Log the result details - $this->debugLog->writeDebugLog('Comparison Evaluation Result is ', $this->showTypeDetails($result)); - // And push the result onto the stack - $stack->push('Array', $result); - - return $result; + return $this->executeArrayComparison($cellID, $operand1, $operand2, $operation, $stack, $recursingArrays); } // Simple validate the two operands if they are string values @@ -4863,10 +5021,10 @@ class Calculation // Use case insensitive comparaison if not OpenOffice mode if (Functions::getCompatibilityMode() != Functions::COMPATIBILITY_OPENOFFICE) { if (is_string($operand1)) { - $operand1 = strtoupper($operand1); + $operand1 = Shared\StringHelper::strToUpper($operand1); } if (is_string($operand2)) { - $operand2 = strtoupper($operand2); + $operand2 = Shared\StringHelper::strToUpper($operand2); } } @@ -4897,7 +5055,7 @@ class Calculation if (is_numeric($operand1) && is_numeric($operand2)) { $result = (abs($operand1 - $operand2) < $this->delta); } else { - $result = strcmp($operand1, $operand2) == 0; + $result = $this->strcmpAllowNull($operand1, $operand2) == 0; } break; @@ -4908,7 +5066,7 @@ class Calculation } elseif ($useLowercaseFirstComparison) { $result = $this->strcmpLowercaseFirst($operand1, $operand2) >= 0; } else { - $result = strcmp($operand1, $operand2) >= 0; + $result = $this->strcmpAllowNull($operand1, $operand2) >= 0; } break; @@ -4919,7 +5077,7 @@ class Calculation } elseif ($useLowercaseFirstComparison) { $result = $this->strcmpLowercaseFirst($operand1, $operand2) <= 0; } else { - $result = strcmp($operand1, $operand2) <= 0; + $result = $this->strcmpAllowNull($operand1, $operand2) <= 0; } break; @@ -4928,10 +5086,13 @@ class Calculation if (is_numeric($operand1) && is_numeric($operand2)) { $result = (abs($operand1 - $operand2) > 1E-14); } else { - $result = strcmp($operand1, $operand2) != 0; + $result = $this->strcmpAllowNull($operand1, $operand2) != 0; } break; + + default: + throw new Exception('Unsupported binary comparison operation'); } // Log the result details @@ -4945,8 +5106,8 @@ class Calculation /** * Compare two strings in the same way as strcmp() except that lowercase come before uppercase letters. * - * @param string $str1 First string value for the comparison - * @param string $str2 Second string value for the comparison + * @param null|string $str1 First string value for the comparison + * @param null|string $str2 Second string value for the comparison * * @return int */ @@ -4955,7 +5116,20 @@ class Calculation $inversedStr1 = Shared\StringHelper::strCaseReverse($str1); $inversedStr2 = Shared\StringHelper::strCaseReverse($str2); - return strcmp($inversedStr1, $inversedStr2); + return strcmp($inversedStr1 ?? '', $inversedStr2 ?? ''); + } + + /** + * PHP8.1 deprecates passing null to strcmp. + * + * @param null|string $str1 First string value for the comparison + * @param null|string $str2 Second string value for the comparison + * + * @return int + */ + private function strcmpAllowNull($str1, $str2) + { + return strcmp($str1 ?? '', $str2 ?? ''); } /** @@ -5036,6 +5210,9 @@ class Calculation $result = $operand1 ** $operand2; break; + + default: + throw new Exception('Unsupported numeric binary operation'); } } } @@ -5064,34 +5241,35 @@ class Calculation /** * Extract range values. * - * @param string &$pRange String based range representation - * @param Worksheet $pSheet Worksheet + * @param string $pRange String based range representation + * @param Worksheet $worksheet Worksheet * @param bool $resetLog Flag indicating whether calculation log should be reset or not * * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned. */ - public function extractCellRange(&$pRange = 'A1', ?Worksheet $pSheet = null, $resetLog = true) + public function extractCellRange(&$pRange = 'A1', ?Worksheet $worksheet = null, $resetLog = true) { // Return value $returnValue = []; - if ($pSheet !== null) { - $pSheetName = $pSheet->getTitle(); + if ($worksheet !== null) { + $worksheetName = $worksheet->getTitle(); + if (strpos($pRange, '!') !== false) { - [$pSheetName, $pRange] = Worksheet::extractSheetTitle($pRange, true); - $pSheet = $this->spreadsheet->getSheetByName($pSheetName); + [$worksheetName, $pRange] = Worksheet::extractSheetTitle($pRange, true); + $worksheet = $this->spreadsheet->getSheetByName($worksheetName); } // Extract range $aReferences = Coordinate::extractAllCellReferencesInRange($pRange); - $pRange = $pSheetName . '!' . $pRange; + $pRange = "'" . $worksheetName . "'" . '!' . $pRange; if (!isset($aReferences[1])) { $currentCol = ''; $currentRow = 0; // Single cell in range sscanf($aReferences[0], '%[A-Z]%d', $currentCol, $currentRow); - if ($pSheet->cellExists($aReferences[0])) { - $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog); + if ($worksheet->cellExists($aReferences[0])) { + $returnValue[$currentRow][$currentCol] = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog); } else { $returnValue[$currentRow][$currentCol] = null; } @@ -5102,8 +5280,8 @@ class Calculation $currentRow = 0; // Extract range sscanf($reference, '%[A-Z]%d', $currentCol, $currentRow); - if ($pSheet->cellExists($reference)) { - $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog); + if ($worksheet->cellExists($reference)) { + $returnValue[$currentRow][$currentCol] = $worksheet->getCell($reference)->getCalculatedValue($resetLog); } else { $returnValue[$currentRow][$currentCol] = null; } @@ -5117,22 +5295,22 @@ class Calculation /** * Extract range values. * - * @param string &$range String based range representation + * @param string $range String based range representation * @param null|Worksheet $worksheet Worksheet * @param bool $resetLog Flag indicating whether calculation log should be reset or not * * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned. */ - public function extractNamedRange(&$range = 'A1', ?Worksheet $worksheet = null, $resetLog = true) + public function extractNamedRange(string &$range = 'A1', ?Worksheet $worksheet = null, $resetLog = true) { // Return value $returnValue = []; if ($worksheet !== null) { - $pSheetName = $worksheet->getTitle(); + $worksheetName = $worksheet->getTitle(); if (strpos($range, '!') !== false) { - [$pSheetName, $range] = Worksheet::extractSheetTitle($range, true); - $worksheet = $this->spreadsheet->getSheetByName($pSheetName); + [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true); + $worksheet = $this->spreadsheet->getSheetByName($worksheetName); } // Named range? @@ -5195,10 +5373,8 @@ class Calculation /** * Get a list of all implemented functions as an array of function objects. - * - * @return array of Category */ - public function getFunctions() + public function getFunctions(): array { return self::$phpSpreadsheetFunctions; } @@ -5220,6 +5396,57 @@ class Calculation return $returnValue; } + private function addDefaultArgumentValues(array $functionCall, array $args, array $emptyArguments): array + { + $reflector = new ReflectionMethod(implode('::', $functionCall)); + $methodArguments = $reflector->getParameters(); + + if (count($methodArguments) > 0) { + // Apply any defaults for empty argument values + foreach ($emptyArguments as $argumentId => $isArgumentEmpty) { + if ($isArgumentEmpty === true) { + $reflectedArgumentId = count($args) - (int) $argumentId - 1; + if ( + !array_key_exists($reflectedArgumentId, $methodArguments) || + $methodArguments[$reflectedArgumentId]->isVariadic() + ) { + break; + } + + $args[$argumentId] = $this->getArgumentDefaultValue($methodArguments[$reflectedArgumentId]); + } + } + } + + return $args; + } + + /** + * @return null|mixed + */ + private function getArgumentDefaultValue(ReflectionParameter $methodArgument) + { + $defaultValue = null; + + if ($methodArgument->isDefaultValueAvailable()) { + $defaultValue = $methodArgument->getDefaultValue(); + if ($methodArgument->isDefaultValueConstant()) { + $constantName = $methodArgument->getDefaultValueConstantName() ?? ''; + // read constant value + if (strpos($constantName, '::') !== false) { + [$className, $constantName] = explode('::', $constantName); + $constantReflector = new ReflectionClassConstant($className, $constantName); + + return $constantReflector->getValue(); + } + + return constant($constantName); + } + } + + return $defaultValue; + } + /** * Add cell reference if needed while making sure that it is the last argument. * @@ -5297,9 +5524,7 @@ class Calculation $recursiveCalculationCell = ($definedNameWorksheet !== null && $definedNameWorksheet !== $pCellWorksheet) ? $definedNameWorksheet->getCell('A1') : $pCell; - $recursiveCalculationCellAddress = $recursiveCalculationCell !== null - ? $recursiveCalculationCell->getCoordinate() - : null; + $recursiveCalculationCellAddress = $recursiveCalculationCell->getCoordinate(); // Adjust relative references in ranges and formulae so that we execute the calculation for the correct rows and columns $definedNameValue = self::$referenceHelper->updateFormulaReferencesAnyWorksheet( diff --git a/src/PhpSpreadsheet/Calculation/Database.php b/src/PhpSpreadsheet/Calculation/Database.php index 2ba4af2d..65031674 100644 --- a/src/PhpSpreadsheet/Calculation/Database.php +++ b/src/PhpSpreadsheet/Calculation/Database.php @@ -2,126 +2,11 @@ namespace PhpOffice\PhpSpreadsheet\Calculation; +/** + * @deprecated 1.17.0 + */ class Database { - /** - * fieldExtract. - * - * Extracts the column ID to use for the data field. - * - * @param mixed[] $database The range of cells that makes up the list or database. - * A database is a list of related data in which rows of related - * information are records, and columns of data are fields. The - * first row of the list contains labels for each column. - * @param mixed $field Indicates which column is used in the function. Enter the - * column label enclosed between double quotation marks, such as - * "Age" or "Yield," or a number (without quotation marks) that - * represents the position of the column within the list: 1 for - * the first column, 2 for the second column, and so on. - * - * @return null|string - */ - private static function fieldExtract($database, $field) - { - $field = strtoupper(Functions::flattenSingleValue($field)); - $fieldNames = array_map('strtoupper', array_shift($database)); - - if (is_numeric($field)) { - $keys = array_keys($fieldNames); - - return $keys[$field - 1]; - } - $key = array_search($field, $fieldNames); - - return ($key) ? $key : null; - } - - /** - * filter. - * - * Parses the selection criteria, extracts the database rows that match those criteria, and - * returns that subset of rows. - * - * @param mixed[] $database The range of cells that makes up the list or database. - * A database is a list of related data in which rows of related - * information are records, and columns of data are fields. The - * first row of the list contains labels for each column. - * @param mixed[] $criteria The range of cells that contains the conditions you specify. - * You can use any range for the criteria argument, as long as it - * includes at least one column label and at least one cell below - * the column label in which you specify a condition for the - * column. - * - * @return array of mixed - */ - private static function filter($database, $criteria) - { - $fieldNames = array_shift($database); - $criteriaNames = array_shift($criteria); - - // Convert the criteria into a set of AND/OR conditions with [:placeholders] - $testConditions = $testValues = []; - $testConditionsCount = 0; - foreach ($criteriaNames as $key => $criteriaName) { - $testCondition = []; - $testConditionCount = 0; - foreach ($criteria as $row => $criterion) { - if ($criterion[$key] > '') { - $testCondition[] = '[:' . $criteriaName . ']' . Functions::ifCondition($criterion[$key]); - ++$testConditionCount; - } - } - if ($testConditionCount > 1) { - $testConditions[] = 'OR(' . implode(',', $testCondition) . ')'; - ++$testConditionsCount; - } elseif ($testConditionCount == 1) { - $testConditions[] = $testCondition[0]; - ++$testConditionsCount; - } - } - - if ($testConditionsCount > 1) { - $testConditionSet = 'AND(' . implode(',', $testConditions) . ')'; - } elseif ($testConditionsCount == 1) { - $testConditionSet = $testConditions[0]; - } - - // Loop through each row of the database - foreach ($database as $dataRow => $dataValues) { - // Substitute actual values from the database row for our [:placeholders] - $testConditionList = $testConditionSet; - foreach ($criteriaNames as $key => $criteriaName) { - $k = array_search($criteriaName, $fieldNames); - if (isset($dataValues[$k])) { - $dataValue = $dataValues[$k]; - $dataValue = (is_string($dataValue)) ? Calculation::wrapResult(strtoupper($dataValue)) : $dataValue; - $testConditionList = str_replace('[:' . $criteriaName . ']', $dataValue, $testConditionList); - } - } - // evaluate the criteria against the row data - $result = Calculation::getInstance()->_calculateFormulaValue('=' . $testConditionList); - // If the row failed to meet the criteria, remove it from the database - if (!$result) { - unset($database[$dataRow]); - } - } - - return $database; - } - - private static function getFilteredColumn($database, $field, $criteria) - { - // reduce the database to a set of rows that match all the criteria - $database = self::filter($database, $criteria); - // extract an array of values for the requested column - $colData = []; - foreach ($database as $row) { - $colData[] = $row[$field]; - } - - return $colData; - } - /** * DAVERAGE. * @@ -130,6 +15,11 @@ class Database * Excel Function: * DAVERAGE(database,field,criteria) * + * @Deprecated 1.17.0 + * + * @see Database\DAverage::evaluate() + * Use the evaluate() method in the Database\DAverage class instead + * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The @@ -145,19 +35,11 @@ class Database * the column label in which you specify a condition for the * column. * - * @return float|string + * @return null|float|string */ public static function DAVERAGE($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - return Statistical::AVERAGE( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DAverage::evaluate($database, $field, $criteria); } /** @@ -169,14 +51,16 @@ class Database * Excel Function: * DCOUNT(database,[field],criteria) * - * Excel Function: - * DAVERAGE(database,field,criteria) + * @Deprecated 1.17.0 + * + * @see Database\DCount::evaluate() + * Use the evaluate() method in the Database\DCount class instead * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. - * @param int|string $field Indicates which column is used in the function. Enter the + * @param null|int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for @@ -194,15 +78,7 @@ class Database */ public static function DCOUNT($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - return Statistical::COUNT( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DCount::evaluate($database, $field, $criteria); } /** @@ -213,11 +89,16 @@ class Database * Excel Function: * DCOUNTA(database,[field],criteria) * + * @Deprecated 1.17.0 + * + * @see Database\DCountA::evaluate() + * Use the evaluate() method in the Database\DCountA class instead + * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. - * @param int|string $field Indicates which column is used in the function. Enter the + * @param null|int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for @@ -229,29 +110,10 @@ class Database * column. * * @return int - * - * @TODO The field argument is optional. If field is omitted, DCOUNTA counts all records in the - * database that match the criteria. */ public static function DCOUNTA($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // reduce the database to a set of rows that match all the criteria - $database = self::filter($database, $criteria); - // extract an array of values for the requested column - $colData = []; - foreach ($database as $row) { - $colData[] = $row[$field]; - } - - // Return - return Statistical::COUNTA( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DCountA::evaluate($database, $field, $criteria); } /** @@ -263,6 +125,11 @@ class Database * Excel Function: * DGET(database,field,criteria) * + * @Deprecated 1.17.0 + * + * @see Database\DGet::evaluate() + * Use the evaluate() method in the Database\DGet class instead + * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The @@ -282,18 +149,7 @@ class Database */ public static function DGET($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - $colData = self::getFilteredColumn($database, $field, $criteria); - if (count($colData) > 1) { - return Functions::NAN(); - } - - return $colData[0]; + return Database\DGet::evaluate($database, $field, $criteria); } /** @@ -305,6 +161,11 @@ class Database * Excel Function: * DMAX(database,field,criteria) * + * @Deprecated 1.17.0 + * + * @see Database\DMax::evaluate() + * Use the evaluate() method in the Database\DMax class instead + * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The @@ -324,15 +185,7 @@ class Database */ public static function DMAX($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - return Statistical::MAX( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DMax::evaluate($database, $field, $criteria); } /** @@ -344,6 +197,11 @@ class Database * Excel Function: * DMIN(database,field,criteria) * + * @Deprecated 1.17.0 + * + * @see Database\DMin::evaluate() + * Use the evaluate() method in the Database\DMin class instead + * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The @@ -363,15 +221,7 @@ class Database */ public static function DMIN($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - return Statistical::MIN( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DMin::evaluate($database, $field, $criteria); } /** @@ -382,6 +232,11 @@ class Database * Excel Function: * DPRODUCT(database,field,criteria) * + * @Deprecated 1.17.0 + * + * @see Database\DProduct::evaluate() + * Use the evaluate() method in the Database\DProduct class instead + * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The @@ -397,19 +252,11 @@ class Database * the column label in which you specify a condition for the * column. * - * @return float + * @return float|string */ public static function DPRODUCT($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - return MathTrig::PRODUCT( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DProduct::evaluate($database, $field, $criteria); } /** @@ -421,6 +268,11 @@ class Database * Excel Function: * DSTDEV(database,field,criteria) * + * @Deprecated 1.17.0 + * + * @see Database\DStDev::evaluate() + * Use the evaluate() method in the Database\DStDev class instead + * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The @@ -440,15 +292,7 @@ class Database */ public static function DSTDEV($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - return Statistical::STDEV( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DStDev::evaluate($database, $field, $criteria); } /** @@ -460,6 +304,11 @@ class Database * Excel Function: * DSTDEVP(database,field,criteria) * + * @Deprecated 1.17.0 + * + * @see Database\DStDevP::evaluate() + * Use the evaluate() method in the Database\DStDevP class instead + * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The @@ -479,15 +328,7 @@ class Database */ public static function DSTDEVP($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - return Statistical::STDEVP( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DStDevP::evaluate($database, $field, $criteria); } /** @@ -498,6 +339,11 @@ class Database * Excel Function: * DSUM(database,field,criteria) * + * @Deprecated 1.17.0 + * + * @see Database\DSum::evaluate() + * Use the evaluate() method in the Database\DSum class instead + * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The @@ -513,19 +359,11 @@ class Database * the column label in which you specify a condition for the * column. * - * @return float + * @return float|string */ public static function DSUM($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - return MathTrig::SUM( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DSum::evaluate($database, $field, $criteria); } /** @@ -537,6 +375,11 @@ class Database * Excel Function: * DVAR(database,field,criteria) * + * @Deprecated 1.17.0 + * + * @see Database\DVar::evaluate() + * Use the evaluate() method in the Database\DVar class instead + * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The @@ -556,15 +399,7 @@ class Database */ public static function DVAR($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - return Statistical::VARFunc( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DVar::evaluate($database, $field, $criteria); } /** @@ -576,6 +411,11 @@ class Database * Excel Function: * DVARP(database,field,criteria) * + * @Deprecated 1.17.0 + * + * @see Database\DVarP::evaluate() + * Use the evaluate() method in the Database\DVarP class instead + * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The @@ -595,14 +435,6 @@ class Database */ public static function DVARP($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - return Statistical::VARP( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DVarP::evaluate($database, $field, $criteria); } } diff --git a/src/PhpSpreadsheet/Calculation/Database/DAverage.php b/src/PhpSpreadsheet/Calculation/Database/DAverage.php new file mode 100644 index 00000000..e30842dc --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Database/DAverage.php @@ -0,0 +1,45 @@ + 1) { + return Functions::NAN(); + } + + $row = array_pop($columnData); + + return array_pop($row); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Database/DMax.php b/src/PhpSpreadsheet/Calculation/Database/DMax.php new file mode 100644 index 00000000..9c5c7301 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Database/DMax.php @@ -0,0 +1,46 @@ + $row) { + $keys = array_keys($row); + $key = $keys[$field] ?? null; + $columnKey = $key ?? 'A'; + $columnData[$rowKey][$columnKey] = $row[$key] ?? $defaultReturnColumnValue; + } + + return $columnData; + } + + private static function buildQuery(array $criteriaNames, array $criteria): string + { + $baseQuery = []; + foreach ($criteria as $key => $criterion) { + foreach ($criterion as $field => $value) { + $criterionName = $criteriaNames[$field]; + if ($value !== null) { + $condition = self::buildCondition($value, $criterionName); + $baseQuery[$key][] = $condition; + } + } + } + + $rowQuery = array_map( + function ($rowValue) { + return (count($rowValue) > 1) ? 'AND(' . implode(',', $rowValue) . ')' : ($rowValue[0] ?? ''); + }, + $baseQuery + ); + + return (count($rowQuery) > 1) ? 'OR(' . implode(',', $rowQuery) . ')' : ($rowQuery[0] ?? ''); + } + + private static function buildCondition($criterion, string $criterionName): string + { + $ifCondition = Functions::ifCondition($criterion); + + // Check for wildcard characters used in the condition + $result = preg_match('/(?[^"]*)(?".*[*?].*")/ui', $ifCondition, $matches); + if ($result !== 1) { + return "[:{$criterionName}]{$ifCondition}"; + } + + $trueFalse = ($matches['operator'] !== '<>'); + $wildcard = WildcardMatch::wildcard($matches['operand']); + $condition = "WILDCARDMATCH([:{$criterionName}],{$wildcard})"; + if ($trueFalse === false) { + $condition = "NOT({$condition})"; + } + + return $condition; + } + + private static function executeQuery(array $database, string $query, array $criteria, array $fields): array + { + foreach ($database as $dataRow => $dataValues) { + // Substitute actual values from the database row for our [:placeholders] + $conditions = $query; + foreach ($criteria as $criterion) { + $conditions = self::processCondition($criterion, $fields, $dataValues, $conditions); + } + + // evaluate the criteria against the row data + $result = Calculation::getInstance()->_calculateFormulaValue('=' . $conditions); + + // If the row failed to meet the criteria, remove it from the database + if ($result !== true) { + unset($database[$dataRow]); + } + } + + return $database; + } + + private static function processCondition(string $criterion, array $fields, array $dataValues, string $conditions) + { + $key = array_search($criterion, $fields, true); + + $dataValue = 'NULL'; + if (is_bool($dataValues[$key])) { + $dataValue = ($dataValues[$key]) ? 'TRUE' : 'FALSE'; + } elseif ($dataValues[$key] !== null) { + $dataValue = $dataValues[$key]; + // escape quotes if we have a string containing quotes + if (is_string($dataValue) && strpos($dataValue, '"') !== false) { + $dataValue = str_replace('"', '""', $dataValue); + } + $dataValue = (is_string($dataValue)) ? Calculation::wrapResult(strtoupper($dataValue)) : $dataValue; + } + + return str_replace('[:' . $criterion . ']', $dataValue, $conditions); + } +} diff --git a/src/PhpSpreadsheet/Calculation/DateTime.php b/src/PhpSpreadsheet/Calculation/DateTime.php index 4c2b108a..44a38c19 100644 --- a/src/PhpSpreadsheet/Calculation/DateTime.php +++ b/src/PhpSpreadsheet/Calculation/DateTime.php @@ -2,127 +2,49 @@ namespace PhpOffice\PhpSpreadsheet\Calculation; -use DateTimeImmutable; use DateTimeInterface; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PhpOffice\PhpSpreadsheet\Shared\StringHelper; +/** + * @deprecated 1.18.0 + */ class DateTime { /** * Identify if a year is a leap year or not. * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Helpers::isLeapYear() + * Use the isLeapYear method in the DateTimeExcel\Helpers class instead + * * @param int|string $year The year to test * * @return bool TRUE if the year is a leap year, otherwise FALSE */ public static function isLeapYear($year) { - return (($year % 4) === 0) && (($year % 100) !== 0) || (($year % 400) === 0); - } - - /** - * Return the number of days between two dates based on a 360 day calendar. - * - * @param int $startDay Day of month of the start date - * @param int $startMonth Month of the start date - * @param int $startYear Year of the start date - * @param int $endDay Day of month of the start date - * @param int $endMonth Month of the start date - * @param int $endYear Year of the start date - * @param bool $methodUS Whether to use the US method or the European method of calculation - * - * @return int Number of days between the start date and the end date - */ - private static function dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, $methodUS) - { - if ($startDay == 31) { - --$startDay; - } elseif ($methodUS && ($startMonth == 2 && ($startDay == 29 || ($startDay == 28 && !self::isLeapYear($startYear))))) { - $startDay = 30; - } - if ($endDay == 31) { - if ($methodUS && $startDay != 30) { - $endDay = 1; - if ($endMonth == 12) { - ++$endYear; - $endMonth = 1; - } else { - ++$endMonth; - } - } else { - $endDay = 30; - } - } - - return $endDay + $endMonth * 30 + $endYear * 360 - $startDay - $startMonth * 30 - $startYear * 360; + return DateTimeExcel\Helpers::isLeapYear($year); } /** * getDateValue. * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Helpers::getDateValue() + * Use the getDateValue method in the DateTimeExcel\Helpers class instead + * * @param mixed $dateValue * * @return mixed Excel date/time serial value, or string if error */ public static function getDateValue($dateValue) { - if (!is_numeric($dateValue)) { - if ((is_object($dateValue)) && ($dateValue instanceof DateTimeInterface)) { - $dateValue = Date::PHPToExcel($dateValue); - } else { - $saveReturnDateType = Functions::getReturnDateType(); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - $dateValue = self::DATEVALUE($dateValue); - Functions::setReturnDateType($saveReturnDateType); - } + try { + return DateTimeExcel\Helpers::getDateValue($dateValue); + } catch (Exception $e) { + return $e->getMessage(); } - - return $dateValue; - } - - /** - * getTimeValue. - * - * @param string $timeValue - * - * @return mixed Excel date/time serial value, or string if error - */ - private static function getTimeValue($timeValue) - { - $saveReturnDateType = Functions::getReturnDateType(); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - $timeValue = self::TIMEVALUE($timeValue); - Functions::setReturnDateType($saveReturnDateType); - - return $timeValue; - } - - private static function adjustDateByMonths($dateValue = 0, $adjustmentMonths = 0) - { - // Execute function - $PHPDateObject = Date::excelToDateTimeObject($dateValue); - $oMonth = (int) $PHPDateObject->format('m'); - $oYear = (int) $PHPDateObject->format('Y'); - - $adjustmentMonthsString = (string) $adjustmentMonths; - if ($adjustmentMonths > 0) { - $adjustmentMonthsString = '+' . $adjustmentMonths; - } - if ($adjustmentMonths != 0) { - $PHPDateObject->modify($adjustmentMonthsString . ' months'); - } - $nMonth = (int) $PHPDateObject->format('m'); - $nYear = (int) $PHPDateObject->format('Y'); - - $monthDiff = ($nMonth - $oMonth) + (($nYear - $oYear) * 12); - if ($monthDiff != $adjustmentMonths) { - $adjustDays = (int) $PHPDateObject->format('d'); - $adjustDaysString = '-' . $adjustDays . ' days'; - $PHPDateObject->modify($adjustDaysString); - } - - return $PHPDateObject; } /** @@ -139,31 +61,17 @@ class DateTime * Excel Function: * NOW() * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Current::now() + * Use the now method in the DateTimeExcel\Current class instead + * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function DATETIMENOW() { - $saveTimeZone = date_default_timezone_get(); - date_default_timezone_set('UTC'); - $retValue = false; - switch (Functions::getReturnDateType()) { - case Functions::RETURNDATE_EXCEL: - $retValue = (float) Date::PHPToExcel(time()); - - break; - case Functions::RETURNDATE_UNIX_TIMESTAMP: - $retValue = (int) time(); - - break; - case Functions::RETURNDATE_PHP_DATETIME_OBJECT: - $retValue = new \DateTime(); - - break; - } - date_default_timezone_set($saveTimeZone); - - return $retValue; + return DateTimeExcel\Current::now(); } /** @@ -180,32 +88,17 @@ class DateTime * Excel Function: * TODAY() * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Current::today() + * Use the today method in the DateTimeExcel\Current class instead + * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function DATENOW() { - $saveTimeZone = date_default_timezone_get(); - date_default_timezone_set('UTC'); - $retValue = false; - $excelDateTime = floor(Date::PHPToExcel(time())); - switch (Functions::getReturnDateType()) { - case Functions::RETURNDATE_EXCEL: - $retValue = (float) $excelDateTime; - - break; - case Functions::RETURNDATE_UNIX_TIMESTAMP: - $retValue = (int) Date::excelToTimestamp($excelDateTime); - - break; - case Functions::RETURNDATE_PHP_DATETIME_OBJECT: - $retValue = Date::excelToDateTimeObject($excelDateTime); - - break; - } - date_default_timezone_set($saveTimeZone); - - return $retValue; + return DateTimeExcel\Current::today(); } /** @@ -216,9 +109,15 @@ class DateTime * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date * format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * + * * Excel Function: * DATE(year,month,day) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Date::fromYMD() + * Use the fromYMD method in the DateTimeExcel\Date class instead + * * PhpSpreadsheet is a lot more forgiving than MS Excel when passing non numeric values to this function. * A Month name or abbreviation (English only at this point) such as 'January' or 'Jan' will still be accepted, * as will a day value with a suffix (e.g. '21st' rather than simply 21); again only English language. @@ -259,71 +158,7 @@ class DateTime */ public static function DATE($year = 0, $month = 1, $day = 1) { - $year = Functions::flattenSingleValue($year); - $month = Functions::flattenSingleValue($month); - $day = Functions::flattenSingleValue($day); - - if (($month !== null) && (!is_numeric($month))) { - $month = Date::monthStringToNumber($month); - } - - if (($day !== null) && (!is_numeric($day))) { - $day = Date::dayStringToNumber($day); - } - - $year = ($year !== null) ? StringHelper::testStringAsNumeric($year) : 0; - $month = ($month !== null) ? StringHelper::testStringAsNumeric($month) : 0; - $day = ($day !== null) ? StringHelper::testStringAsNumeric($day) : 0; - if ( - (!is_numeric($year)) || - (!is_numeric($month)) || - (!is_numeric($day)) - ) { - return Functions::VALUE(); - } - $year = (int) $year; - $month = (int) $month; - $day = (int) $day; - - $baseYear = Date::getExcelCalendar(); - // Validate parameters - if ($year < ($baseYear - 1900)) { - return Functions::NAN(); - } - if ((($baseYear - 1900) != 0) && ($year < $baseYear) && ($year >= 1900)) { - return Functions::NAN(); - } - - if (($year < $baseYear) && ($year >= ($baseYear - 1900))) { - $year += 1900; - } - - if ($month < 1) { - // Handle year/month adjustment if month < 1 - --$month; - $year += ceil($month / 12) - 1; - $month = 13 - abs($month % 12); - } elseif ($month > 12) { - // Handle year/month adjustment if month > 12 - $year += floor($month / 12); - $month = ($month % 12); - } - - // Re-validate the year parameter after adjustments - if (($year < $baseYear) || ($year >= 10000)) { - return Functions::NAN(); - } - - // Execute function - $excelDateValue = Date::formattedPHPToExcel($year, $month, $day); - switch (Functions::getReturnDateType()) { - case Functions::RETURNDATE_EXCEL: - return (float) $excelDateValue; - case Functions::RETURNDATE_UNIX_TIMESTAMP: - return (int) Date::excelToTimestamp($excelDateValue); - case Functions::RETURNDATE_PHP_DATETIME_OBJECT: - return Date::excelToDateTimeObject($excelDateValue); - } + return DateTimeExcel\Date::fromYMD($year, $month, $day); } /** @@ -337,6 +172,11 @@ class DateTime * Excel Function: * TIME(hour,minute,second) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Time::fromHMS() + * Use the fromHMS method in the DateTimeExcel\Time class instead + * * @param int $hour A number from 0 (zero) to 32767 representing the hour. * Any value greater than 23 will be divided by 24 and the remainder * will be treated as the hour value. For example, TIME(27,0,0) = @@ -354,85 +194,7 @@ class DateTime */ public static function TIME($hour = 0, $minute = 0, $second = 0) { - $hour = Functions::flattenSingleValue($hour); - $minute = Functions::flattenSingleValue($minute); - $second = Functions::flattenSingleValue($second); - - if ($hour == '') { - $hour = 0; - } - if ($minute == '') { - $minute = 0; - } - if ($second == '') { - $second = 0; - } - - if ((!is_numeric($hour)) || (!is_numeric($minute)) || (!is_numeric($second))) { - return Functions::VALUE(); - } - $hour = (int) $hour; - $minute = (int) $minute; - $second = (int) $second; - - if ($second < 0) { - $minute += floor($second / 60); - $second = 60 - abs($second % 60); - if ($second == 60) { - $second = 0; - } - } elseif ($second >= 60) { - $minute += floor($second / 60); - $second = $second % 60; - } - if ($minute < 0) { - $hour += floor($minute / 60); - $minute = 60 - abs($minute % 60); - if ($minute == 60) { - $minute = 0; - } - } elseif ($minute >= 60) { - $hour += floor($minute / 60); - $minute = $minute % 60; - } - - if ($hour > 23) { - $hour = $hour % 24; - } elseif ($hour < 0) { - return Functions::NAN(); - } - - // Execute function - switch (Functions::getReturnDateType()) { - case Functions::RETURNDATE_EXCEL: - $date = 0; - $calendar = Date::getExcelCalendar(); - if ($calendar != Date::CALENDAR_WINDOWS_1900) { - $date = 1; - } - - return (float) Date::formattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second); - case Functions::RETURNDATE_UNIX_TIMESTAMP: - return (int) Date::excelToTimestamp(Date::formattedPHPToExcel(1970, 1, 1, $hour, $minute, $second)); // -2147468400; // -2147472000 + 3600 - case Functions::RETURNDATE_PHP_DATETIME_OBJECT: - $dayAdjust = 0; - if ($hour < 0) { - $dayAdjust = floor($hour / 24); - $hour = 24 - abs($hour % 24); - if ($hour == 24) { - $hour = 0; - } - } elseif ($hour >= 24) { - $dayAdjust = floor($hour / 24); - $hour = $hour % 24; - } - $phpDateObject = new \DateTime('1900-01-01 ' . $hour . ':' . $minute . ':' . $second); - if ($dayAdjust != 0) { - $phpDateObject->modify($dayAdjust . ' days'); - } - - return $phpDateObject; - } + return DateTimeExcel\Time::fromHMS($hour, $minute, $second); } /** @@ -448,6 +210,11 @@ class DateTime * Excel Function: * DATEVALUE(dateValue) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\DateValue::fromString() + * Use the fromString method in the DateTimeExcel\DateValue class instead + * * @param string $dateValue Text that represents a date in a Microsoft Excel date format. * For example, "1/30/2008" or "30-Jan-2008" are text strings within * quotation marks that represent dates. Using the default date @@ -460,112 +227,9 @@ class DateTime * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ - public static function DATEVALUE($dateValue = 1) + public static function DATEVALUE($dateValue) { - $dateValue = trim(Functions::flattenSingleValue($dateValue), '"'); - // Strip any ordinals because they're allowed in Excel (English only) - $dateValue = preg_replace('/(\d)(st|nd|rd|th)([ -\/])/Ui', '$1$3', $dateValue); - // Convert separators (/ . or space) to hyphens (should also handle dot used for ordinals in some countries, e.g. Denmark, Germany) - $dateValue = str_replace(['/', '.', '-', ' '], ' ', $dateValue); - - $yearFound = false; - $t1 = explode(' ', $dateValue); - foreach ($t1 as &$t) { - if ((is_numeric($t)) && ($t > 31)) { - if ($yearFound) { - return Functions::VALUE(); - } - if ($t < 100) { - $t += 1900; - } - $yearFound = true; - } - } - if ((count($t1) == 1) && (strpos($t, ':') !== false)) { - // We've been fed a time value without any date - return 0.0; - } elseif (count($t1) == 2) { - // We only have two parts of the date: either day/month or month/year - if ($yearFound) { - array_unshift($t1, 1); - } else { - if (is_numeric($t1[1]) && $t1[1] > 29) { - $t1[1] += 1900; - array_unshift($t1, 1); - } else { - $t1[] = date('Y'); - } - } - } - unset($t); - $dateValue = implode(' ', $t1); - - $PHPDateArray = date_parse($dateValue); - if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) { - $testVal1 = strtok($dateValue, '- '); - if ($testVal1 !== false) { - $testVal2 = strtok('- '); - if ($testVal2 !== false) { - $testVal3 = strtok('- '); - if ($testVal3 === false) { - $testVal3 = strftime('%Y'); - } - } else { - return Functions::VALUE(); - } - } else { - return Functions::VALUE(); - } - if ($testVal1 < 31 && $testVal2 < 12 && $testVal3 < 12 && strlen($testVal3) == 2) { - $testVal3 += 2000; - } - $PHPDateArray = date_parse($testVal1 . '-' . $testVal2 . '-' . $testVal3); - if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) { - $PHPDateArray = date_parse($testVal2 . '-' . $testVal1 . '-' . $testVal3); - if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) { - return Functions::VALUE(); - } - } - } - - if (($PHPDateArray !== false) && ($PHPDateArray['error_count'] == 0)) { - // Execute function - if ($PHPDateArray['year'] == '') { - $PHPDateArray['year'] = strftime('%Y'); - } - if ($PHPDateArray['year'] < 1900) { - return Functions::VALUE(); - } - if ($PHPDateArray['month'] == '') { - $PHPDateArray['month'] = strftime('%m'); - } - if ($PHPDateArray['day'] == '') { - $PHPDateArray['day'] = strftime('%d'); - } - if (!checkdate($PHPDateArray['month'], $PHPDateArray['day'], $PHPDateArray['year'])) { - return Functions::VALUE(); - } - $excelDateValue = floor( - Date::formattedPHPToExcel( - $PHPDateArray['year'], - $PHPDateArray['month'], - $PHPDateArray['day'], - $PHPDateArray['hour'], - $PHPDateArray['minute'], - $PHPDateArray['second'] - ) - ); - switch (Functions::getReturnDateType()) { - case Functions::RETURNDATE_EXCEL: - return (float) $excelDateValue; - case Functions::RETURNDATE_UNIX_TIMESTAMP: - return (int) Date::excelToTimestamp($excelDateValue); - case Functions::RETURNDATE_PHP_DATETIME_OBJECT: - return new \DateTime($PHPDateArray['year'] . '-' . $PHPDateArray['month'] . '-' . $PHPDateArray['day'] . ' 00:00:00'); - } - } - - return Functions::VALUE(); + return DateTimeExcel\DateValue::fromString($dateValue); } /** @@ -581,6 +245,11 @@ class DateTime * Excel Function: * TIMEVALUE(timeValue) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\TimeValue::fromString() + * Use the fromString method in the DateTimeExcel\TimeValue class instead + * * @param string $timeValue A text string that represents a time in any one of the Microsoft * Excel time formats; for example, "6:45 PM" and "18:45" text strings * within quotation marks that represent time. @@ -591,46 +260,20 @@ class DateTime */ public static function TIMEVALUE($timeValue) { - $timeValue = trim(Functions::flattenSingleValue($timeValue), '"'); - $timeValue = str_replace(['/', '.'], '-', $timeValue); - - $arraySplit = preg_split('/[\/:\-\s]/', $timeValue); - if ((count($arraySplit) == 2 || count($arraySplit) == 3) && $arraySplit[0] > 24) { - $arraySplit[0] = ($arraySplit[0] % 24); - $timeValue = implode(':', $arraySplit); - } - - $PHPDateArray = date_parse($timeValue); - if (($PHPDateArray !== false) && ($PHPDateArray['error_count'] == 0)) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - $excelDateValue = Date::formattedPHPToExcel( - $PHPDateArray['year'], - $PHPDateArray['month'], - $PHPDateArray['day'], - $PHPDateArray['hour'], - $PHPDateArray['minute'], - $PHPDateArray['second'] - ); - } else { - $excelDateValue = Date::formattedPHPToExcel(1900, 1, 1, $PHPDateArray['hour'], $PHPDateArray['minute'], $PHPDateArray['second']) - 1; - } - - switch (Functions::getReturnDateType()) { - case Functions::RETURNDATE_EXCEL: - return (float) $excelDateValue; - case Functions::RETURNDATE_UNIX_TIMESTAMP: - return (int) $phpDateValue = Date::excelToTimestamp($excelDateValue + 25569) - 3600; - case Functions::RETURNDATE_PHP_DATETIME_OBJECT: - return new \DateTime('1900-01-01 ' . $PHPDateArray['hour'] . ':' . $PHPDateArray['minute'] . ':' . $PHPDateArray['second']); - } - } - - return Functions::VALUE(); + return DateTimeExcel\TimeValue::fromString($timeValue); } /** * DATEDIF. * + * Excel Function: + * DATEDIF(startdate, enddate, unit) + * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Difference::interval() + * Use the interval method in the DateTimeExcel\Difference class instead + * * @param mixed $startDate Excel date serial value, PHP date/time stamp, PHP DateTime object * or a standard date string * @param mixed $endDate Excel date serial value, PHP date/time stamp, PHP DateTime object @@ -641,95 +284,7 @@ class DateTime */ public static function DATEDIF($startDate = 0, $endDate = 0, $unit = 'D') { - $startDate = Functions::flattenSingleValue($startDate); - $endDate = Functions::flattenSingleValue($endDate); - $unit = strtoupper(Functions::flattenSingleValue($unit)); - - if (is_string($startDate = self::getDateValue($startDate))) { - return Functions::VALUE(); - } - if (is_string($endDate = self::getDateValue($endDate))) { - return Functions::VALUE(); - } - - // Validate parameters - if ($startDate > $endDate) { - return Functions::NAN(); - } - - // Execute function - $difference = $endDate - $startDate; - - $PHPStartDateObject = Date::excelToDateTimeObject($startDate); - $startDays = $PHPStartDateObject->format('j'); - $startMonths = $PHPStartDateObject->format('n'); - $startYears = $PHPStartDateObject->format('Y'); - - $PHPEndDateObject = Date::excelToDateTimeObject($endDate); - $endDays = $PHPEndDateObject->format('j'); - $endMonths = $PHPEndDateObject->format('n'); - $endYears = $PHPEndDateObject->format('Y'); - - $PHPDiffDateObject = $PHPEndDateObject->diff($PHPStartDateObject); - - switch ($unit) { - case 'D': - $retVal = (int) $difference; - - break; - case 'M': - $retVal = (int) 12 * $PHPDiffDateObject->format('%y') + $PHPDiffDateObject->format('%m'); - - break; - case 'Y': - $retVal = (int) $PHPDiffDateObject->format('%y'); - - break; - case 'MD': - if ($endDays < $startDays) { - $retVal = $endDays; - $PHPEndDateObject->modify('-' . $endDays . ' days'); - $adjustDays = $PHPEndDateObject->format('j'); - $retVal += ($adjustDays - $startDays); - } else { - $retVal = (int) $PHPDiffDateObject->format('%d'); - } - - break; - case 'YM': - $retVal = (int) $PHPDiffDateObject->format('%m'); - - break; - case 'YD': - $retVal = (int) $difference; - if ($endYears > $startYears) { - $isLeapStartYear = $PHPStartDateObject->format('L'); - $wasLeapEndYear = $PHPEndDateObject->format('L'); - - // Adjust end year to be as close as possible as start year - while ($PHPEndDateObject >= $PHPStartDateObject) { - $PHPEndDateObject->modify('-1 year'); - $endYears = $PHPEndDateObject->format('Y'); - } - $PHPEndDateObject->modify('+1 year'); - - // Get the result - $retVal = $PHPEndDateObject->diff($PHPStartDateObject)->days; - - // Adjust for leap years cases - $isLeapEndYear = $PHPEndDateObject->format('L'); - $limit = new \DateTime($PHPEndDateObject->format('Y-02-29')); - if (!$isLeapStartYear && !$wasLeapEndYear && $isLeapEndYear && $PHPEndDateObject >= $limit) { - --$retVal; - } - } - - break; - default: - $retVal = Functions::VALUE(); - } - - return $retVal; + return DateTimeExcel\Difference::interval($startDate, $endDate, $unit); } /** @@ -740,40 +295,21 @@ class DateTime * Excel Function: * DAYS(endDate, startDate) * - * @param DateTimeImmutable|float|int|string $endDate Excel date serial value (float), + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Days::between() + * Use the between method in the DateTimeExcel\Days class instead + * + * @param DateTimeInterface|float|int|string $endDate Excel date serial value (float), * PHP date timestamp (integer), PHP DateTime object, or a standard date string - * @param DateTimeImmutable|float|int|string $startDate Excel date serial value (float), + * @param DateTimeInterface|float|int|string $startDate Excel date serial value (float), * PHP date timestamp (integer), PHP DateTime object, or a standard date string * * @return int|string Number of days between start date and end date or an error */ public static function DAYS($endDate = 0, $startDate = 0) { - $startDate = Functions::flattenSingleValue($startDate); - $endDate = Functions::flattenSingleValue($endDate); - - $startDate = self::getDateValue($startDate); - if (is_string($startDate)) { - return Functions::VALUE(); - } - - $endDate = self::getDateValue($endDate); - if (is_string($endDate)) { - return Functions::VALUE(); - } - - // Execute function - $PHPStartDateObject = Date::excelToDateTimeObject($startDate); - $PHPEndDateObject = Date::excelToDateTimeObject($endDate); - - $diff = $PHPStartDateObject->diff($PHPEndDateObject); - $days = $diff->days; - - if ($diff->invert) { - $days = -$days; - } - - return $days; + return DateTimeExcel\Days::between($endDate, $startDate); } /** @@ -786,6 +322,11 @@ class DateTime * Excel Function: * DAYS360(startDate,endDate[,method]) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Days360::between() + * Use the between method in the DateTimeExcel\Days360 class instead + * * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), @@ -806,32 +347,7 @@ class DateTime */ public static function DAYS360($startDate = 0, $endDate = 0, $method = false) { - $startDate = Functions::flattenSingleValue($startDate); - $endDate = Functions::flattenSingleValue($endDate); - - if (is_string($startDate = self::getDateValue($startDate))) { - return Functions::VALUE(); - } - if (is_string($endDate = self::getDateValue($endDate))) { - return Functions::VALUE(); - } - - if (!is_bool($method)) { - return Functions::VALUE(); - } - - // Execute function - $PHPStartDateObject = Date::excelToDateTimeObject($startDate); - $startDay = $PHPStartDateObject->format('j'); - $startMonth = $PHPStartDateObject->format('n'); - $startYear = $PHPStartDateObject->format('Y'); - - $PHPEndDateObject = Date::excelToDateTimeObject($endDate); - $endDay = $PHPEndDateObject->format('j'); - $endMonth = $PHPEndDateObject->format('n'); - $endYear = $PHPEndDateObject->format('Y'); - - return self::dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, !$method); + return DateTimeExcel\Days360::between($startDate, $endDate, $method); } /** @@ -844,6 +360,12 @@ class DateTime * * Excel Function: * YEARFRAC(startDate,endDate[,method]) + * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\YearFrac::fraction() + * Use the fraction method in the DateTimeExcel\YearFrac class instead + * * See https://lists.oasis-open.org/archives/office-formula/200806/msg00039.html * for description of algorithm used in Excel * @@ -862,78 +384,7 @@ class DateTime */ public static function YEARFRAC($startDate = 0, $endDate = 0, $method = 0) { - $startDate = Functions::flattenSingleValue($startDate); - $endDate = Functions::flattenSingleValue($endDate); - $method = Functions::flattenSingleValue($method); - - if (is_string($startDate = self::getDateValue($startDate))) { - return Functions::VALUE(); - } - if (is_string($endDate = self::getDateValue($endDate))) { - return Functions::VALUE(); - } - if ($startDate > $endDate) { - $temp = $startDate; - $startDate = $endDate; - $endDate = $temp; - } - - if (((is_numeric($method)) && (!is_string($method))) || ($method == '')) { - switch ($method) { - case 0: - return self::DAYS360($startDate, $endDate) / 360; - case 1: - $days = self::DATEDIF($startDate, $endDate); - $startYear = self::YEAR($startDate); - $endYear = self::YEAR($endDate); - $years = $endYear - $startYear + 1; - $startMonth = self::MONTHOFYEAR($startDate); - $startDay = self::DAYOFMONTH($startDate); - $endMonth = self::MONTHOFYEAR($endDate); - $endDay = self::DAYOFMONTH($endDate); - $startMonthDay = 100 * $startMonth + $startDay; - $endMonthDay = 100 * $endMonth + $endDay; - if ($years == 1) { - if (self::isLeapYear($endYear)) { - $tmpCalcAnnualBasis = 366; - } else { - $tmpCalcAnnualBasis = 365; - } - } elseif ($years == 2 && $startMonthDay >= $endMonthDay) { - if (self::isLeapYear($startYear)) { - if ($startMonthDay <= 229) { - $tmpCalcAnnualBasis = 366; - } else { - $tmpCalcAnnualBasis = 365; - } - } elseif (self::isLeapYear($endYear)) { - if ($endMonthDay >= 229) { - $tmpCalcAnnualBasis = 366; - } else { - $tmpCalcAnnualBasis = 365; - } - } else { - $tmpCalcAnnualBasis = 365; - } - } else { - $tmpCalcAnnualBasis = 0; - for ($year = $startYear; $year <= $endYear; ++$year) { - $tmpCalcAnnualBasis += self::isLeapYear($year) ? 366 : 365; - } - $tmpCalcAnnualBasis /= $years; - } - - return $days / $tmpCalcAnnualBasis; - case 2: - return self::DATEDIF($startDate, $endDate) / 360; - case 3: - return self::DATEDIF($startDate, $endDate) / 365; - case 4: - return self::DAYS360($startDate, $endDate, true) / 360; - } - } - - return Functions::VALUE(); + return DateTimeExcel\YearFrac::fraction($startDate, $endDate, $method); } /** @@ -947,71 +398,22 @@ class DateTime * Excel Function: * NETWORKDAYS(startDate,endDate[,holidays[,holiday[,...]]]) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\NetworkDays::count() + * Use the count method in the DateTimeExcel\NetworkDays class instead + * * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string + * @param mixed $dateArgs * * @return int|string Interval between the dates */ public static function NETWORKDAYS($startDate, $endDate, ...$dateArgs) { - // Retrieve the mandatory start and end date that are referenced in the function definition - $startDate = Functions::flattenSingleValue($startDate); - $endDate = Functions::flattenSingleValue($endDate); - // Get the optional days - $dateArgs = Functions::flattenArray($dateArgs); - - // Validate the start and end dates - if (is_string($startDate = $sDate = self::getDateValue($startDate))) { - return Functions::VALUE(); - } - $startDate = (float) floor($startDate); - if (is_string($endDate = $eDate = self::getDateValue($endDate))) { - return Functions::VALUE(); - } - $endDate = (float) floor($endDate); - - if ($sDate > $eDate) { - $startDate = $eDate; - $endDate = $sDate; - } - - // Execute function - $startDoW = 6 - self::WEEKDAY($startDate, 2); - if ($startDoW < 0) { - $startDoW = 0; - } - $endDoW = self::WEEKDAY($endDate, 2); - if ($endDoW >= 6) { - $endDoW = 0; - } - - $wholeWeekDays = floor(($endDate - $startDate) / 7) * 5; - $partWeekDays = $endDoW + $startDoW; - if ($partWeekDays > 5) { - $partWeekDays -= 5; - } - - // Test any extra holiday parameters - $holidayCountedArray = []; - foreach ($dateArgs as $holidayDate) { - if (is_string($holidayDate = self::getDateValue($holidayDate))) { - return Functions::VALUE(); - } - if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) { - if ((self::WEEKDAY($holidayDate, 2) < 6) && (!in_array($holidayDate, $holidayCountedArray))) { - --$partWeekDays; - $holidayCountedArray[] = $holidayDate; - } - } - } - - if ($sDate > $eDate) { - return 0 - ($wholeWeekDays + $partWeekDays); - } - - return $wholeWeekDays + $partWeekDays; + return DateTimeExcel\NetworkDays::count($startDate, $endDate, ...$dateArgs); } /** @@ -1025,102 +427,24 @@ class DateTime * Excel Function: * WORKDAY(startDate,endDays[,holidays[,holiday[,...]]]) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\WorkDay::date() + * Use the date method in the DateTimeExcel\WorkDay class instead + * * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param int $endDays The number of nonweekend and nonholiday days before or after * startDate. A positive value for days yields a future date; a * negative value yields a past date. + * @param mixed $dateArgs * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function WORKDAY($startDate, $endDays, ...$dateArgs) { - // Retrieve the mandatory start date and days that are referenced in the function definition - $startDate = Functions::flattenSingleValue($startDate); - $endDays = Functions::flattenSingleValue($endDays); - // Get the optional days - $dateArgs = Functions::flattenArray($dateArgs); - - if ((is_string($startDate = self::getDateValue($startDate))) || (!is_numeric($endDays))) { - return Functions::VALUE(); - } - $startDate = (float) floor($startDate); - $endDays = (int) floor($endDays); - // If endDays is 0, we always return startDate - if ($endDays == 0) { - return $startDate; - } - - $decrementing = $endDays < 0; - - // Adjust the start date if it falls over a weekend - - $startDoW = self::WEEKDAY($startDate, 3); - if (self::WEEKDAY($startDate, 3) >= 5) { - $startDate += ($decrementing) ? -$startDoW + 4 : 7 - $startDoW; - ($decrementing) ? $endDays++ : $endDays--; - } - - // Add endDays - $endDate = (float) $startDate + ((int) ($endDays / 5) * 7) + ($endDays % 5); - - // Adjust the calculated end date if it falls over a weekend - $endDoW = self::WEEKDAY($endDate, 3); - if ($endDoW >= 5) { - $endDate += ($decrementing) ? -$endDoW + 4 : 7 - $endDoW; - } - - // Test any extra holiday parameters - if (!empty($dateArgs)) { - $holidayCountedArray = $holidayDates = []; - foreach ($dateArgs as $holidayDate) { - if (($holidayDate !== null) && (trim($holidayDate) > '')) { - if (is_string($holidayDate = self::getDateValue($holidayDate))) { - return Functions::VALUE(); - } - if (self::WEEKDAY($holidayDate, 3) < 5) { - $holidayDates[] = $holidayDate; - } - } - } - if ($decrementing) { - rsort($holidayDates, SORT_NUMERIC); - } else { - sort($holidayDates, SORT_NUMERIC); - } - foreach ($holidayDates as $holidayDate) { - if ($decrementing) { - if (($holidayDate <= $startDate) && ($holidayDate >= $endDate)) { - if (!in_array($holidayDate, $holidayCountedArray)) { - --$endDate; - $holidayCountedArray[] = $holidayDate; - } - } - } else { - if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) { - if (!in_array($holidayDate, $holidayCountedArray)) { - ++$endDate; - $holidayCountedArray[] = $holidayDate; - } - } - } - // Adjust the calculated end date if it falls over a weekend - $endDoW = self::WEEKDAY($endDate, 3); - if ($endDoW >= 5) { - $endDate += ($decrementing) ? -$endDoW + 4 : 7 - $endDoW; - } - } - } - - switch (Functions::getReturnDateType()) { - case Functions::RETURNDATE_EXCEL: - return (float) $endDate; - case Functions::RETURNDATE_UNIX_TIMESTAMP: - return (int) Date::excelToTimestamp($endDate); - case Functions::RETURNDATE_PHP_DATETIME_OBJECT: - return Date::excelToDateTimeObject($endDate); - } + return DateTimeExcel\WorkDay::date($startDate, $endDays, ...$dateArgs); } /** @@ -1132,6 +456,11 @@ class DateTime * Excel Function: * DAY(dateValue) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\DateParts::day() + * Use the day method in the DateTimeExcel\DateParts class instead + * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @@ -1139,26 +468,7 @@ class DateTime */ public static function DAYOFMONTH($dateValue = 1) { - $dateValue = Functions::flattenSingleValue($dateValue); - - if ($dateValue === null) { - $dateValue = 1; - } elseif (is_string($dateValue = self::getDateValue($dateValue))) { - return Functions::VALUE(); - } - - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) { - if ($dateValue < 0.0) { - return Functions::NAN(); - } elseif ($dateValue < 1.0) { - return 0; - } - } - - // Execute function - $PHPDateObject = Date::excelToDateTimeObject($dateValue); - - return (int) $PHPDateObject->format('j'); + return DateTimeExcel\DateParts::day($dateValue); } /** @@ -1170,7 +480,12 @@ class DateTime * Excel Function: * WEEKDAY(dateValue[,style]) * - * @param int $dateValue Excel date serial value (float), PHP date timestamp (integer), + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Week::day() + * Use the day method in the DateTimeExcel\Week class instead + * + * @param float|int|string $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param int $style A number that determines the type of return value * 1 or omitted Numbers 1 (Sunday) through 7 (Saturday). @@ -1181,79 +496,169 @@ class DateTime */ public static function WEEKDAY($dateValue = 1, $style = 1) { - $dateValue = Functions::flattenSingleValue($dateValue); - $style = Functions::flattenSingleValue($style); - - if (!is_numeric($style)) { - return Functions::VALUE(); - } elseif (($style < 1) || ($style > 3)) { - return Functions::NAN(); - } - $style = floor($style); - - if ($dateValue === null) { - $dateValue = 1; - } elseif (is_string($dateValue = self::getDateValue($dateValue))) { - return Functions::VALUE(); - } elseif ($dateValue < 0.0) { - return Functions::NAN(); - } - - // Execute function - $PHPDateObject = Date::excelToDateTimeObject($dateValue); - $DoW = (int) $PHPDateObject->format('w'); - - $firstDay = 1; - switch ($style) { - case 1: - ++$DoW; - - break; - case 2: - if ($DoW === 0) { - $DoW = 7; - } - - break; - case 3: - if ($DoW === 0) { - $DoW = 7; - } - $firstDay = 0; - --$DoW; - - break; - } - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) { - // Test for Excel's 1900 leap year, and introduce the error as required - if (($PHPDateObject->format('Y') == 1900) && ($PHPDateObject->format('n') <= 2)) { - --$DoW; - if ($DoW < $firstDay) { - $DoW += 7; - } - } - } - - return $DoW; + return DateTimeExcel\Week::day($dateValue, $style); } + /** + * STARTWEEK_SUNDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\STARTWEEK_SUNDAY instead + */ const STARTWEEK_SUNDAY = 1; + + /** + * STARTWEEK_MONDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\STARTWEEK_MONDAY instead + */ const STARTWEEK_MONDAY = 2; + + /** + * STARTWEEK_MONDAY_ALT. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\STARTWEEK_MONDAY_ALT instead + */ const STARTWEEK_MONDAY_ALT = 11; + + /** + * STARTWEEK_TUESDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\STARTWEEK_TUESDAY instead + */ const STARTWEEK_TUESDAY = 12; + + /** + * STARTWEEK_WEDNESDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\STARTWEEK_WEDNESDAY instead + */ const STARTWEEK_WEDNESDAY = 13; + + /** + * STARTWEEK_THURSDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\STARTWEEK_THURSDAY instead + */ const STARTWEEK_THURSDAY = 14; + + /** + * STARTWEEK_FRIDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\STARTWEEK_FRIDAY instead + */ const STARTWEEK_FRIDAY = 15; + + /** + * STARTWEEK_SATURDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\STARTWEEK_SATURDAY instead + */ const STARTWEEK_SATURDAY = 16; + + /** + * STARTWEEK_SUNDAY_ALT. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\STARTWEEK_SUNDAY_ALT instead + */ const STARTWEEK_SUNDAY_ALT = 17; + + /** + * DOW_SUNDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\DOW_SUNDAY instead + */ const DOW_SUNDAY = 1; + + /** + * DOW_MONDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\DOW_MONDAY instead + */ const DOW_MONDAY = 2; + + /** + * DOW_TUESDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\DOW_TUESDAY instead + */ const DOW_TUESDAY = 3; + + /** + * DOW_WEDNESDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\DOW_WEDNESDAY instead + */ const DOW_WEDNESDAY = 4; + + /** + * DOW_THURSDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\DOW_THURSDAY instead + */ const DOW_THURSDAY = 5; + + /** + * DOW_FRIDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\DOW_FRIDAY instead + */ const DOW_FRIDAY = 6; + + /** + * DOW_SATURDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\DOW_SATURDAY instead + */ const DOW_SATURDAY = 7; + + /** + * STARTWEEK_MONDAY_ISO. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\STARTWEEK_MONDAY_ISO instead + */ const STARTWEEK_MONDAY_ISO = 21; + + /** + * METHODARR. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\METHODARR instead + */ const METHODARR = [ self::STARTWEEK_SUNDAY => self::DOW_SUNDAY, self::DOW_MONDAY, @@ -1280,6 +685,11 @@ class DateTime * Excel Function: * WEEKNUM(dateValue[,style]) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Week::number(() + * Use the number method in the DateTimeExcel\Week class instead + * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param int $method Week begins on Sunday or Monday @@ -1298,40 +708,7 @@ class DateTime */ public static function WEEKNUM($dateValue = 1, $method = self::STARTWEEK_SUNDAY) { - $dateValue = Functions::flattenSingleValue($dateValue); - $method = Functions::flattenSingleValue($method); - - if (!is_numeric($method)) { - return Functions::VALUE(); - } - $method = (int) $method; - if (!array_key_exists($method, self::METHODARR)) { - return Functions::NaN(); - } - $method = self::METHODARR[$method]; - - $dateValue = self::getDateValue($dateValue); - if (is_string($dateValue)) { - return Functions::VALUE(); - } - if ($dateValue < 0.0) { - return Functions::NAN(); - } - - // Execute function - $PHPDateObject = Date::excelToDateTimeObject($dateValue); - if ($method == self::STARTWEEK_MONDAY_ISO) { - return (int) $PHPDateObject->format('W'); - } - $dayOfYear = $PHPDateObject->format('z'); - $PHPDateObject->modify('-' . $dayOfYear . ' days'); - $firstDayOfFirstWeek = $PHPDateObject->format('w'); - $daysInFirstWeek = (6 - $firstDayOfFirstWeek + $method) % 7; - $daysInFirstWeek += 7 * !$daysInFirstWeek; - $endFirstWeek = $daysInFirstWeek - 1; - $weekOfYear = floor(($dayOfYear - $endFirstWeek + 13) / 7); - - return (int) $weekOfYear; + return DateTimeExcel\Week::number($dateValue, $method); } /** @@ -1342,6 +719,11 @@ class DateTime * Excel Function: * ISOWEEKNUM(dateValue) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Week::isoWeekNumber() + * Use the isoWeekNumber method in the DateTimeExcel\Week class instead + * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @@ -1349,20 +731,7 @@ class DateTime */ public static function ISOWEEKNUM($dateValue = 1) { - $dateValue = Functions::flattenSingleValue($dateValue); - - if ($dateValue === null) { - $dateValue = 1; - } elseif (is_string($dateValue = self::getDateValue($dateValue))) { - return Functions::VALUE(); - } elseif ($dateValue < 0.0) { - return Functions::NAN(); - } - - // Execute function - $PHPDateObject = Date::excelToDateTimeObject($dateValue); - - return (int) $PHPDateObject->format('W'); + return DateTimeExcel\Week::isoWeekNumber($dateValue); } /** @@ -1374,6 +743,11 @@ class DateTime * Excel Function: * MONTH(dateValue) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\DateParts::month() + * Use the month method in the DateTimeExcel\DateParts class instead + * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @@ -1381,21 +755,7 @@ class DateTime */ public static function MONTHOFYEAR($dateValue = 1) { - $dateValue = Functions::flattenSingleValue($dateValue); - - if (empty($dateValue)) { - $dateValue = 1; - } - if (is_string($dateValue = self::getDateValue($dateValue))) { - return Functions::VALUE(); - } elseif ($dateValue < 0.0) { - return Functions::NAN(); - } - - // Execute function - $PHPDateObject = Date::excelToDateTimeObject($dateValue); - - return (int) $PHPDateObject->format('n'); + return DateTimeExcel\DateParts::month($dateValue); } /** @@ -1407,6 +767,11 @@ class DateTime * Excel Function: * YEAR(dateValue) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\DateParts::year() + * Use the ear method in the DateTimeExcel\DateParts class instead + * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @@ -1414,20 +779,7 @@ class DateTime */ public static function YEAR($dateValue = 1) { - $dateValue = Functions::flattenSingleValue($dateValue); - - if ($dateValue === null) { - $dateValue = 1; - } elseif (is_string($dateValue = self::getDateValue($dateValue))) { - return Functions::VALUE(); - } elseif ($dateValue < 0.0) { - return Functions::NAN(); - } - - // Execute function - $PHPDateObject = Date::excelToDateTimeObject($dateValue); - - return (int) $PHPDateObject->format('Y'); + return DateTimeExcel\DateParts::year($dateValue); } /** @@ -1439,6 +791,11 @@ class DateTime * Excel Function: * HOUR(timeValue) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\TimeParts::hour() + * Use the hour method in the DateTimeExcel\TimeParts class instead + * * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard time string * @@ -1446,29 +803,7 @@ class DateTime */ public static function HOUROFDAY($timeValue = 0) { - $timeValue = Functions::flattenSingleValue($timeValue); - - if (!is_numeric($timeValue)) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { - $testVal = strtok($timeValue, '/-: '); - if (strlen($testVal) < strlen($timeValue)) { - return Functions::VALUE(); - } - } - $timeValue = self::getTimeValue($timeValue); - if (is_string($timeValue)) { - return Functions::VALUE(); - } - } - // Execute function - if ($timeValue >= 1) { - $timeValue = fmod($timeValue, 1); - } elseif ($timeValue < 0.0) { - return Functions::NAN(); - } - $timeValue = Date::excelToTimestamp($timeValue); - - return (int) gmdate('G', $timeValue); + return DateTimeExcel\TimeParts::hour($timeValue); } /** @@ -1480,6 +815,11 @@ class DateTime * Excel Function: * MINUTE(timeValue) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\TimeParts::minute() + * Use the minute method in the DateTimeExcel\TimeParts class instead + * * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard time string * @@ -1487,29 +827,7 @@ class DateTime */ public static function MINUTE($timeValue = 0) { - $timeValue = $timeTester = Functions::flattenSingleValue($timeValue); - - if (!is_numeric($timeValue)) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { - $testVal = strtok($timeValue, '/-: '); - if (strlen($testVal) < strlen($timeValue)) { - return Functions::VALUE(); - } - } - $timeValue = self::getTimeValue($timeValue); - if (is_string($timeValue)) { - return Functions::VALUE(); - } - } - // Execute function - if ($timeValue >= 1) { - $timeValue = fmod($timeValue, 1); - } elseif ($timeValue < 0.0) { - return Functions::NAN(); - } - $timeValue = Date::excelToTimestamp($timeValue); - - return (int) gmdate('i', $timeValue); + return DateTimeExcel\TimeParts::minute($timeValue); } /** @@ -1521,6 +839,11 @@ class DateTime * Excel Function: * SECOND(timeValue) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\TimeParts::second() + * Use the second method in the DateTimeExcel\TimeParts class instead + * * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard time string * @@ -1528,29 +851,7 @@ class DateTime */ public static function SECOND($timeValue = 0) { - $timeValue = Functions::flattenSingleValue($timeValue); - - if (!is_numeric($timeValue)) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { - $testVal = strtok($timeValue, '/-: '); - if (strlen($testVal) < strlen($timeValue)) { - return Functions::VALUE(); - } - } - $timeValue = self::getTimeValue($timeValue); - if (is_string($timeValue)) { - return Functions::VALUE(); - } - } - // Execute function - if ($timeValue >= 1) { - $timeValue = fmod($timeValue, 1); - } elseif ($timeValue < 0.0) { - return Functions::NAN(); - } - $timeValue = Date::excelToTimestamp($timeValue); - - return (int) gmdate('s', $timeValue); + return DateTimeExcel\TimeParts::second($timeValue); } /** @@ -1564,6 +865,11 @@ class DateTime * Excel Function: * EDATE(dateValue,adjustmentMonths) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Month::adjust() + * Use the adjust method in the DateTimeExcel\Edate class instead + * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param int $adjustmentMonths The number of months before or after start_date. @@ -1575,29 +881,7 @@ class DateTime */ public static function EDATE($dateValue = 1, $adjustmentMonths = 0) { - $dateValue = Functions::flattenSingleValue($dateValue); - $adjustmentMonths = Functions::flattenSingleValue($adjustmentMonths); - - if (!is_numeric($adjustmentMonths)) { - return Functions::VALUE(); - } - $adjustmentMonths = floor($adjustmentMonths); - - if (is_string($dateValue = self::getDateValue($dateValue))) { - return Functions::VALUE(); - } - - // Execute function - $PHPDateObject = self::adjustDateByMonths($dateValue, $adjustmentMonths); - - switch (Functions::getReturnDateType()) { - case Functions::RETURNDATE_EXCEL: - return (float) Date::PHPToExcel($PHPDateObject); - case Functions::RETURNDATE_UNIX_TIMESTAMP: - return (int) Date::excelToTimestamp(Date::PHPToExcel($PHPDateObject)); - case Functions::RETURNDATE_PHP_DATETIME_OBJECT: - return $PHPDateObject; - } + return DateTimeExcel\Month::adjust($dateValue, $adjustmentMonths); } /** @@ -1610,6 +894,11 @@ class DateTime * Excel Function: * EOMONTH(dateValue,adjustmentMonths) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Month::lastDay() + * Use the lastDay method in the DateTimeExcel\EoMonth class instead + * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param int $adjustmentMonths The number of months before or after start_date. @@ -1621,31 +910,6 @@ class DateTime */ public static function EOMONTH($dateValue = 1, $adjustmentMonths = 0) { - $dateValue = Functions::flattenSingleValue($dateValue); - $adjustmentMonths = Functions::flattenSingleValue($adjustmentMonths); - - if (!is_numeric($adjustmentMonths)) { - return Functions::VALUE(); - } - $adjustmentMonths = floor($adjustmentMonths); - - if (is_string($dateValue = self::getDateValue($dateValue))) { - return Functions::VALUE(); - } - - // Execute function - $PHPDateObject = self::adjustDateByMonths($dateValue, $adjustmentMonths + 1); - $adjustDays = (int) $PHPDateObject->format('d'); - $adjustDaysString = '-' . $adjustDays . ' days'; - $PHPDateObject->modify($adjustDaysString); - - switch (Functions::getReturnDateType()) { - case Functions::RETURNDATE_EXCEL: - return (float) Date::PHPToExcel($PHPDateObject); - case Functions::RETURNDATE_UNIX_TIMESTAMP: - return (int) Date::excelToTimestamp(Date::PHPToExcel($PHPDateObject)); - case Functions::RETURNDATE_PHP_DATETIME_OBJECT: - return $PHPDateObject; - } + return DateTimeExcel\Month::lastDay($dateValue, $adjustmentMonths); } } diff --git a/src/PhpSpreadsheet/Calculation/DateTimeExcel/Constants.php b/src/PhpSpreadsheet/Calculation/DateTimeExcel/Constants.php new file mode 100644 index 00000000..1165eb1f --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/DateTimeExcel/Constants.php @@ -0,0 +1,38 @@ + self::DOW_SUNDAY, + self::DOW_MONDAY, + self::STARTWEEK_MONDAY_ALT => self::DOW_MONDAY, + self::DOW_TUESDAY, + self::DOW_WEDNESDAY, + self::DOW_THURSDAY, + self::DOW_FRIDAY, + self::DOW_SATURDAY, + self::DOW_SUNDAY, + self::STARTWEEK_MONDAY_ISO => self::STARTWEEK_MONDAY_ISO, + ]; +} diff --git a/src/PhpSpreadsheet/Calculation/DateTimeExcel/Current.php b/src/PhpSpreadsheet/Calculation/DateTimeExcel/Current.php new file mode 100644 index 00000000..7a70978e --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/DateTimeExcel/Current.php @@ -0,0 +1,59 @@ +format('c')); + + return is_array($dateArray) ? Helpers::returnIn3FormatsArray($dateArray, true) : Functions::VALUE(); + } + + /** + * DATETIMENOW. + * + * Returns the current date and time. + * The NOW function is useful when you need to display the current date and time on a worksheet or + * calculate a value based on the current date and time, and have that value updated each time you + * open the worksheet. + * + * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date + * and time format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. + * + * Excel Function: + * NOW() + * + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function now() + { + $dti = new DateTimeImmutable(); + $dateArray = date_parse($dti->format('c')); + + return is_array($dateArray) ? Helpers::returnIn3FormatsArray($dateArray) : Functions::VALUE(); + } +} diff --git a/src/PhpSpreadsheet/Calculation/DateTimeExcel/Date.php b/src/PhpSpreadsheet/Calculation/DateTimeExcel/Date.php new file mode 100644 index 00000000..d18e2371 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/DateTimeExcel/Date.php @@ -0,0 +1,168 @@ +getMessage(); + } + + // Execute function + $excelDateValue = SharedDateHelper::formattedPHPToExcel($year, $month, $day); + + return Helpers::returnIn3FormatsFloat($excelDateValue); + } + + /** + * Convert year from multiple formats to int. + * + * @param mixed $year + */ + private static function getYear($year, int $baseYear): int + { + $year = Functions::flattenSingleValue($year); + $year = ($year !== null) ? StringHelper::testStringAsNumeric((string) $year) : 0; + if (!is_numeric($year)) { + throw new Exception(Functions::VALUE()); + } + $year = (int) $year; + + if ($year < ($baseYear - 1900)) { + throw new Exception(Functions::NAN()); + } + if ((($baseYear - 1900) !== 0) && ($year < $baseYear) && ($year >= 1900)) { + throw new Exception(Functions::NAN()); + } + + if (($year < $baseYear) && ($year >= ($baseYear - 1900))) { + $year += 1900; + } + + return (int) $year; + } + + /** + * Convert month from multiple formats to int. + * + * @param mixed $month + */ + private static function getMonth($month): int + { + $month = Functions::flattenSingleValue($month); + + if (($month !== null) && (!is_numeric($month))) { + $month = SharedDateHelper::monthStringToNumber($month); + } + + $month = ($month !== null) ? StringHelper::testStringAsNumeric((string) $month) : 0; + if (!is_numeric($month)) { + throw new Exception(Functions::VALUE()); + } + + return (int) $month; + } + + /** + * Convert day from multiple formats to int. + * + * @param mixed $day + */ + private static function getDay($day): int + { + $day = Functions::flattenSingleValue($day); + + if (($day !== null) && (!is_numeric($day))) { + $day = SharedDateHelper::dayStringToNumber($day); + } + + $day = ($day !== null) ? StringHelper::testStringAsNumeric((string) $day) : 0; + if (!is_numeric($day)) { + throw new Exception(Functions::VALUE()); + } + + return (int) $day; + } + + private static function adjustYearMonth(int &$year, int &$month, int $baseYear): void + { + if ($month < 1) { + // Handle year/month adjustment if month < 1 + --$month; + $year += ceil($month / 12) - 1; + $month = 13 - abs($month % 12); + } elseif ($month > 12) { + // Handle year/month adjustment if month > 12 + $year += floor($month / 12); + $month = ($month % 12); + } + + // Re-validate the year parameter after adjustments + if (($year < $baseYear) || ($year >= 10000)) { + throw new Exception(Functions::NAN()); + } + } +} diff --git a/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateParts.php b/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateParts.php new file mode 100644 index 00000000..37ea0315 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateParts.php @@ -0,0 +1,127 @@ += 0) { + return $weirdResult; + } + + try { + $dateValue = Helpers::getDateValue($dateValue); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Execute function + $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); + + return (int) $PHPDateObject->format('j'); + } + + /** + * MONTHOFYEAR. + * + * Returns the month of a date represented by a serial number. + * The month is given as an integer, ranging from 1 (January) to 12 (December). + * + * Excel Function: + * MONTH(dateValue) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * + * @return int|string Month of the year + */ + public static function month($dateValue) + { + try { + $dateValue = Helpers::getDateValue($dateValue); + } catch (Exception $e) { + return $e->getMessage(); + } + if ($dateValue < 1 && SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_WINDOWS_1900) { + return 1; + } + + // Execute function + $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); + + return (int) $PHPDateObject->format('n'); + } + + /** + * YEAR. + * + * Returns the year corresponding to a date. + * The year is returned as an integer in the range 1900-9999. + * + * Excel Function: + * YEAR(dateValue) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * + * @return int|string Year + */ + public static function year($dateValue) + { + try { + $dateValue = Helpers::getDateValue($dateValue); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($dateValue < 1 && SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_WINDOWS_1900) { + return 1900; + } + // Execute function + $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); + + return (int) $PHPDateObject->format('Y'); + } + + /** + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + */ + private static function weirdCondition($dateValue): int + { + // Excel does not treat 0 consistently for DAY vs. (MONTH or YEAR) + if (SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_WINDOWS_1900 && Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) { + if (is_bool($dateValue)) { + return (int) $dateValue; + } + if ($dateValue === null) { + return 0; + } + if (is_numeric($dateValue) && $dateValue < 1 && $dateValue >= 0) { + return 0; + } + } + + return -1; + } +} diff --git a/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateValue.php b/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateValue.php new file mode 100644 index 00000000..d8e88a21 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateValue.php @@ -0,0 +1,151 @@ + 31)) { + if ($yearFound) { + return Functions::VALUE(); + } + if ($t < 100) { + $t += 1900; + } + $yearFound = true; + } + } + if (count($t1) === 1) { + // We've been fed a time value without any date + return ((strpos((string) $t, ':') === false)) ? Functions::Value() : 0.0; + } + unset($t); + + $dateValue = self::t1ToString($t1, $dti, $yearFound); + + $PHPDateArray = self::setUpArray($dateValue, $dti); + + return self::finalResults($PHPDateArray, $dti, $baseYear); + } + + private static function t1ToString(array $t1, DateTimeImmutable $dti, bool $yearFound): string + { + if (count($t1) == 2) { + // We only have two parts of the date: either day/month or month/year + if ($yearFound) { + array_unshift($t1, 1); + } else { + if (is_numeric($t1[1]) && $t1[1] > 29) { + $t1[1] += 1900; + array_unshift($t1, 1); + } else { + $t1[] = $dti->format('Y'); + } + } + } + $dateValue = implode(' ', $t1); + + return $dateValue; + } + + /** + * Parse date. + * + * @return array|bool + */ + private static function setUpArray(string $dateValue, DateTimeImmutable $dti) + { + $PHPDateArray = date_parse($dateValue); + if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) { + // If original count was 1, we've already returned. + // If it was 2, we added another. + // Therefore, neither of the first 2 stroks below can fail. + $testVal1 = strtok($dateValue, '- '); + $testVal2 = strtok('- '); + $testVal3 = strtok('- ') ?: $dti->format('Y'); + Helpers::adjustYear((string) $testVal1, (string) $testVal2, $testVal3); + $PHPDateArray = date_parse($testVal1 . '-' . $testVal2 . '-' . $testVal3); + if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) { + $PHPDateArray = date_parse($testVal2 . '-' . $testVal1 . '-' . $testVal3); + } + } + + return $PHPDateArray; + } + + /** + * Final results. + * + * @param array|bool $PHPDateArray + * + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + private static function finalResults($PHPDateArray, DateTimeImmutable $dti, int $baseYear) + { + $retValue = Functions::Value(); + if (is_array($PHPDateArray) && $PHPDateArray['error_count'] == 0) { + // Execute function + Helpers::replaceIfEmpty($PHPDateArray['year'], $dti->format('Y')); + if ($PHPDateArray['year'] < $baseYear) { + return Functions::VALUE(); + } + Helpers::replaceIfEmpty($PHPDateArray['month'], $dti->format('m')); + Helpers::replaceIfEmpty($PHPDateArray['day'], $dti->format('d')); + $PHPDateArray['hour'] = 0; + $PHPDateArray['minute'] = 0; + $PHPDateArray['second'] = 0; + $month = (int) $PHPDateArray['month']; + $day = (int) $PHPDateArray['day']; + $year = (int) $PHPDateArray['year']; + if (!checkdate($month, $day, $year)) { + return ($year === 1900 && $month === 2 && $day === 29) ? Helpers::returnIn3FormatsFloat(60.0) : Functions::VALUE(); + } + $retValue = Helpers::returnIn3FormatsArray($PHPDateArray, true); + } + + return $retValue; + } +} diff --git a/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days.php b/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days.php new file mode 100644 index 00000000..5a97d8df --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days.php @@ -0,0 +1,51 @@ +getMessage(); + } + + // Execute function + $PHPStartDateObject = SharedDateHelper::excelToDateTimeObject($startDate); + $PHPEndDateObject = SharedDateHelper::excelToDateTimeObject($endDate); + + $days = Functions::VALUE(); + $diff = $PHPStartDateObject->diff($PHPEndDateObject); + if ($diff !== false && !is_bool($diff->days)) { + $days = $diff->days; + if ($diff->invert) { + $days = -$days; + } + } + + return $days; + } +} diff --git a/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days360.php b/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days360.php new file mode 100644 index 00000000..bbc5d16a --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days360.php @@ -0,0 +1,106 @@ +getMessage(); + } + + if (!is_bool($method)) { + return Functions::VALUE(); + } + + // Execute function + $PHPStartDateObject = SharedDateHelper::excelToDateTimeObject($startDate); + $startDay = $PHPStartDateObject->format('j'); + $startMonth = $PHPStartDateObject->format('n'); + $startYear = $PHPStartDateObject->format('Y'); + + $PHPEndDateObject = SharedDateHelper::excelToDateTimeObject($endDate); + $endDay = $PHPEndDateObject->format('j'); + $endMonth = $PHPEndDateObject->format('n'); + $endYear = $PHPEndDateObject->format('Y'); + + return self::dateDiff360((int) $startDay, (int) $startMonth, (int) $startYear, (int) $endDay, (int) $endMonth, (int) $endYear, !$method); + } + + /** + * Return the number of days between two dates based on a 360 day calendar. + */ + private static function dateDiff360(int $startDay, int $startMonth, int $startYear, int $endDay, int $endMonth, int $endYear, bool $methodUS): int + { + $startDay = self::getStartDay($startDay, $startMonth, $startYear, $methodUS); + $endDay = self::getEndDay($endDay, $endMonth, $endYear, $startDay, $methodUS); + + return $endDay + $endMonth * 30 + $endYear * 360 - $startDay - $startMonth * 30 - $startYear * 360; + } + + private static function getStartDay(int $startDay, int $startMonth, int $startYear, bool $methodUS): int + { + if ($startDay == 31) { + --$startDay; + } elseif ($methodUS && ($startMonth == 2 && ($startDay == 29 || ($startDay == 28 && !Helpers::isLeapYear($startYear))))) { + $startDay = 30; + } + + return $startDay; + } + + private static function getEndDay(int $endDay, int &$endMonth, int &$endYear, int $startDay, bool $methodUS): int + { + if ($endDay == 31) { + if ($methodUS && $startDay != 30) { + $endDay = 1; + if ($endMonth == 12) { + ++$endYear; + $endMonth = 1; + } else { + ++$endMonth; + } + } else { + $endDay = 30; + } + } + + return $endDay; + } +} diff --git a/src/PhpSpreadsheet/Calculation/DateTimeExcel/Difference.php b/src/PhpSpreadsheet/Calculation/DateTimeExcel/Difference.php new file mode 100644 index 00000000..6adeca17 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/DateTimeExcel/Difference.php @@ -0,0 +1,146 @@ +getMessage(); + } + + // Execute function + $PHPStartDateObject = SharedDateHelper::excelToDateTimeObject($startDate); + $startDays = (int) $PHPStartDateObject->format('j'); + $startMonths = (int) $PHPStartDateObject->format('n'); + $startYears = (int) $PHPStartDateObject->format('Y'); + + $PHPEndDateObject = SharedDateHelper::excelToDateTimeObject($endDate); + $endDays = (int) $PHPEndDateObject->format('j'); + $endMonths = (int) $PHPEndDateObject->format('n'); + $endYears = (int) $PHPEndDateObject->format('Y'); + + $PHPDiffDateObject = $PHPEndDateObject->diff($PHPStartDateObject); + + $retVal = false; + $retVal = self::replaceRetValue($retVal, $unit, 'D') ?? self::datedifD($difference); + $retVal = self::replaceRetValue($retVal, $unit, 'M') ?? self::datedifM($PHPDiffDateObject); + $retVal = self::replaceRetValue($retVal, $unit, 'MD') ?? self::datedifMD($startDays, $endDays, $PHPEndDateObject, $PHPDiffDateObject); + $retVal = self::replaceRetValue($retVal, $unit, 'Y') ?? self::datedifY($PHPDiffDateObject); + $retVal = self::replaceRetValue($retVal, $unit, 'YD') ?? self::datedifYD($difference, $startYears, $endYears, $PHPStartDateObject, $PHPEndDateObject); + $retVal = self::replaceRetValue($retVal, $unit, 'YM') ?? self::datedifYM($PHPDiffDateObject); + + return is_bool($retVal) ? Functions::VALUE() : $retVal; + } + + private static function initialDiff(float $startDate, float $endDate): float + { + // Validate parameters + if ($startDate > $endDate) { + throw new Exception(Functions::NAN()); + } + + return $endDate - $startDate; + } + + /** + * Decide whether it's time to set retVal. + * + * @param bool|int $retVal + * + * @return null|bool|int + */ + private static function replaceRetValue($retVal, string $unit, string $compare) + { + if ($retVal !== false || $unit !== $compare) { + return $retVal; + } + + return null; + } + + private static function datedifD(float $difference): int + { + return (int) $difference; + } + + private static function datedifM(DateInterval $PHPDiffDateObject): int + { + return 12 * (int) $PHPDiffDateObject->format('%y') + (int) $PHPDiffDateObject->format('%m'); + } + + private static function datedifMD(int $startDays, int $endDays, DateTime $PHPEndDateObject, DateInterval $PHPDiffDateObject): int + { + if ($endDays < $startDays) { + $retVal = $endDays; + $PHPEndDateObject->modify('-' . $endDays . ' days'); + $adjustDays = (int) $PHPEndDateObject->format('j'); + $retVal += ($adjustDays - $startDays); + } else { + $retVal = (int) $PHPDiffDateObject->format('%d'); + } + + return $retVal; + } + + private static function datedifY(DateInterval $PHPDiffDateObject): int + { + return (int) $PHPDiffDateObject->format('%y'); + } + + private static function datedifYD(float $difference, int $startYears, int $endYears, DateTime $PHPStartDateObject, DateTime $PHPEndDateObject): int + { + $retVal = (int) $difference; + if ($endYears > $startYears) { + $isLeapStartYear = $PHPStartDateObject->format('L'); + $wasLeapEndYear = $PHPEndDateObject->format('L'); + + // Adjust end year to be as close as possible as start year + while ($PHPEndDateObject >= $PHPStartDateObject) { + $PHPEndDateObject->modify('-1 year'); + $endYears = $PHPEndDateObject->format('Y'); + } + $PHPEndDateObject->modify('+1 year'); + + // Get the result + $retVal = $PHPEndDateObject->diff($PHPStartDateObject)->days; + + // Adjust for leap years cases + $isLeapEndYear = $PHPEndDateObject->format('L'); + $limit = new DateTime($PHPEndDateObject->format('Y-02-29')); + if (!$isLeapStartYear && !$wasLeapEndYear && $isLeapEndYear && $PHPEndDateObject >= $limit) { + --$retVal; + } + } + + return (int) $retVal; + } + + private static function datedifYM(DateInterval $PHPDiffDateObject): int + { + return (int) $PHPDiffDateObject->format('%m'); + } +} diff --git a/src/PhpSpreadsheet/Calculation/DateTimeExcel/Helpers.php b/src/PhpSpreadsheet/Calculation/DateTimeExcel/Helpers.php new file mode 100644 index 00000000..9503401c --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/DateTimeExcel/Helpers.php @@ -0,0 +1,285 @@ +format('m'); + $oYear = (int) $PHPDateObject->format('Y'); + + $adjustmentMonthsString = (string) $adjustmentMonths; + if ($adjustmentMonths > 0) { + $adjustmentMonthsString = '+' . $adjustmentMonths; + } + if ($adjustmentMonths != 0) { + $PHPDateObject->modify($adjustmentMonthsString . ' months'); + } + $nMonth = (int) $PHPDateObject->format('m'); + $nYear = (int) $PHPDateObject->format('Y'); + + $monthDiff = ($nMonth - $oMonth) + (($nYear - $oYear) * 12); + if ($monthDiff != $adjustmentMonths) { + $adjustDays = (int) $PHPDateObject->format('d'); + $adjustDaysString = '-' . $adjustDays . ' days'; + $PHPDateObject->modify($adjustDaysString); + } + + return $PHPDateObject; + } + + /** + * Help reduce perceived complexity of some tests. + * + * @param mixed $value + * @param mixed $altValue + */ + public static function replaceIfEmpty(&$value, $altValue): void + { + $value = $value ?: $altValue; + } + + /** + * Adjust year in ambiguous situations. + */ + public static function adjustYear(string $testVal1, string $testVal2, string &$testVal3): void + { + if (!is_numeric($testVal1) || $testVal1 < 31) { + if (!is_numeric($testVal2) || $testVal2 < 12) { + if (is_numeric($testVal3) && $testVal3 < 12) { + $testVal3 += 2000; + } + } + } + } + + /** + * Return result in one of three formats. + * + * @return mixed + */ + public static function returnIn3FormatsArray(array $dateArray, bool $noFrac = false) + { + $retType = Functions::getReturnDateType(); + if ($retType === Functions::RETURNDATE_PHP_DATETIME_OBJECT) { + return new DateTime( + $dateArray['year'] + . '-' . $dateArray['month'] + . '-' . $dateArray['day'] + . ' ' . $dateArray['hour'] + . ':' . $dateArray['minute'] + . ':' . $dateArray['second'] + ); + } + $excelDateValue = + SharedDateHelper::formattedPHPToExcel( + $dateArray['year'], + $dateArray['month'], + $dateArray['day'], + $dateArray['hour'], + $dateArray['minute'], + $dateArray['second'] + ); + if ($retType === Functions::RETURNDATE_EXCEL) { + return $noFrac ? floor($excelDateValue) : (float) $excelDateValue; + } + // RETURNDATE_UNIX_TIMESTAMP) + + return (int) SharedDateHelper::excelToTimestamp($excelDateValue); + } + + /** + * Return result in one of three formats. + * + * @return mixed + */ + public static function returnIn3FormatsFloat(float $excelDateValue) + { + $retType = Functions::getReturnDateType(); + if ($retType === Functions::RETURNDATE_EXCEL) { + return $excelDateValue; + } + if ($retType === Functions::RETURNDATE_UNIX_TIMESTAMP) { + return (int) SharedDateHelper::excelToTimestamp($excelDateValue); + } + // RETURNDATE_PHP_DATETIME_OBJECT + + return SharedDateHelper::excelToDateTimeObject($excelDateValue); + } + + /** + * Return result in one of three formats. + * + * @return mixed + */ + public static function returnIn3FormatsObject(DateTime $PHPDateObject) + { + $retType = Functions::getReturnDateType(); + if ($retType === Functions::RETURNDATE_PHP_DATETIME_OBJECT) { + return $PHPDateObject; + } + if ($retType === Functions::RETURNDATE_EXCEL) { + return (float) SharedDateHelper::PHPToExcel($PHPDateObject); + } + // RETURNDATE_UNIX_TIMESTAMP + $stamp = SharedDateHelper::PHPToExcel($PHPDateObject); + $stamp = is_bool($stamp) ? ((int) $stamp) : $stamp; + + return (int) SharedDateHelper::excelToTimestamp($stamp); + } + + private static function baseDate(): int + { + if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { + return 0; + } + if (SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_MAC_1904) { + return 0; + } + + return 1; + } + + /** + * Many functions accept null/false/true argument treated as 0/0/1. + * + * @param mixed $number + */ + public static function nullFalseTrueToNumber(&$number, bool $allowBool = true): void + { + $number = Functions::flattenSingleValue($number); + $nullVal = self::baseDate(); + if ($number === null) { + $number = $nullVal; + } elseif ($allowBool && is_bool($number)) { + $number = $nullVal + (int) $number; + } + } + + /** + * Many functions accept null argument treated as 0. + * + * @param mixed $number + * + * @return float|int + */ + public static function validateNumericNull($number) + { + $number = Functions::flattenSingleValue($number); + if ($number === null) { + return 0; + } + if (is_int($number)) { + return $number; + } + if (is_numeric($number)) { + return (float) $number; + } + + throw new Exception(Functions::VALUE()); + } + + /** + * Many functions accept null/false/true argument treated as 0/0/1. + * + * @param mixed $number + * + * @return float + */ + public static function validateNotNegative($number) + { + if (!is_numeric($number)) { + throw new Exception(Functions::VALUE()); + } + if ($number >= 0) { + return (float) $number; + } + + throw new Exception(Functions::NAN()); + } + + public static function silly1900(DateTime $PHPDateObject, string $mod = '-1 day'): void + { + $isoDate = $PHPDateObject->format('c'); + if ($isoDate < '1900-03-01') { + $PHPDateObject->modify($mod); + } + } +} diff --git a/src/PhpSpreadsheet/Calculation/DateTimeExcel/Month.php b/src/PhpSpreadsheet/Calculation/DateTimeExcel/Month.php new file mode 100644 index 00000000..560b7a80 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/DateTimeExcel/Month.php @@ -0,0 +1,82 @@ +getMessage(); + } + $adjustmentMonths = floor($adjustmentMonths); + + // Execute function + $PHPDateObject = Helpers::adjustDateByMonths($dateValue, $adjustmentMonths); + + return Helpers::returnIn3FormatsObject($PHPDateObject); + } + + /** + * EOMONTH. + * + * Returns the date value for the last day of the month that is the indicated number of months + * before or after start_date. + * Use EOMONTH to calculate maturity dates or due dates that fall on the last day of the month. + * + * Excel Function: + * EOMONTH(dateValue,adjustmentMonths) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param int $adjustmentMonths The number of months before or after start_date. + * A positive value for months yields a future date; + * a negative value yields a past date. + * + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function lastDay($dateValue, $adjustmentMonths) + { + try { + $dateValue = Helpers::getDateValue($dateValue, false); + $adjustmentMonths = Helpers::validateNumericNull($adjustmentMonths); + } catch (Exception $e) { + return $e->getMessage(); + } + $adjustmentMonths = floor($adjustmentMonths); + + // Execute function + $PHPDateObject = Helpers::adjustDateByMonths($dateValue, $adjustmentMonths + 1); + $adjustDays = (int) $PHPDateObject->format('d'); + $adjustDaysString = '-' . $adjustDays . ' days'; + $PHPDateObject->modify($adjustDaysString); + + return Helpers::returnIn3FormatsObject($PHPDateObject); + } +} diff --git a/src/PhpSpreadsheet/Calculation/DateTimeExcel/NetworkDays.php b/src/PhpSpreadsheet/Calculation/DateTimeExcel/NetworkDays.php new file mode 100644 index 00000000..d0f53cf3 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/DateTimeExcel/NetworkDays.php @@ -0,0 +1,102 @@ +getMessage(); + } + + // Execute function + $startDow = self::calcStartDow($startDate); + $endDow = self::calcEndDow($endDate); + $wholeWeekDays = (int) floor(($endDate - $startDate) / 7) * 5; + $partWeekDays = self::calcPartWeekDays($startDow, $endDow); + + // Test any extra holiday parameters + $holidayCountedArray = []; + foreach ($holidayArray as $holidayDate) { + if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) { + if ((Week::day($holidayDate, 2) < 6) && (!in_array($holidayDate, $holidayCountedArray))) { + --$partWeekDays; + $holidayCountedArray[] = $holidayDate; + } + } + } + + return self::applySign($wholeWeekDays + $partWeekDays, $sDate, $eDate); + } + + private static function calcStartDow(float $startDate): int + { + $startDow = 6 - (int) Week::day($startDate, 2); + if ($startDow < 0) { + $startDow = 5; + } + + return $startDow; + } + + private static function calcEndDow(float $endDate): int + { + $endDow = (int) Week::day($endDate, 2); + if ($endDow >= 6) { + $endDow = 0; + } + + return $endDow; + } + + private static function calcPartWeekDays(int $startDow, int $endDow): int + { + $partWeekDays = $endDow + $startDow; + if ($partWeekDays > 5) { + $partWeekDays -= 5; + } + + return $partWeekDays; + } + + private static function applySign(int $result, float $sDate, float $eDate): int + { + return ($sDate > $eDate) ? -$result : $result; + } +} diff --git a/src/PhpSpreadsheet/Calculation/DateTimeExcel/Time.php b/src/PhpSpreadsheet/Calculation/DateTimeExcel/Time.php new file mode 100644 index 00000000..fb5e4965 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/DateTimeExcel/Time.php @@ -0,0 +1,119 @@ +getMessage(); + } + + self::adjustSecond($second, $minute); + self::adjustMinute($minute, $hour); + + if ($hour > 23) { + $hour = $hour % 24; + } elseif ($hour < 0) { + return Functions::NAN(); + } + + // Execute function + $retType = Functions::getReturnDateType(); + if ($retType === Functions::RETURNDATE_EXCEL) { + $calendar = SharedDateHelper::getExcelCalendar(); + $date = (int) ($calendar !== SharedDateHelper::CALENDAR_WINDOWS_1900); + + return (float) SharedDateHelper::formattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second); + } + if ($retType === Functions::RETURNDATE_UNIX_TIMESTAMP) { + return (int) SharedDateHelper::excelToTimestamp(SharedDateHelper::formattedPHPToExcel(1970, 1, 1, $hour, $minute, $second)); // -2147468400; // -2147472000 + 3600 + } + // RETURNDATE_PHP_DATETIME_OBJECT + // Hour has already been normalized (0-23) above + $phpDateObject = new DateTime('1900-01-01 ' . $hour . ':' . $minute . ':' . $second); + + return $phpDateObject; + } + + private static function adjustSecond(int &$second, int &$minute): void + { + if ($second < 0) { + $minute += floor($second / 60); + $second = 60 - abs($second % 60); + if ($second == 60) { + $second = 0; + } + } elseif ($second >= 60) { + $minute += floor($second / 60); + $second = $second % 60; + } + } + + private static function adjustMinute(int &$minute, int &$hour): void + { + if ($minute < 0) { + $hour += floor($minute / 60); + $minute = 60 - abs($minute % 60); + if ($minute == 60) { + $minute = 0; + } + } elseif ($minute >= 60) { + $hour += floor($minute / 60); + $minute = $minute % 60; + } + } + + /** + * @param mixed $value expect int + */ + private static function toIntWithNullBool($value): int + { + $value = Functions::flattenSingleValue($value); + $value = $value ?? 0; + if (is_bool($value)) { + $value = (int) $value; + } + if (!is_numeric($value)) { + throw new Exception(Functions::VALUE()); + } + + return (int) $value; + } +} diff --git a/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeParts.php b/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeParts.php new file mode 100644 index 00000000..49cd983d --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeParts.php @@ -0,0 +1,112 @@ +getMessage(); + } + + // Execute function + $timeValue = fmod($timeValue, 1); + $timeValue = SharedDateHelper::excelToDateTimeObject($timeValue); + + return (int) $timeValue->format('H'); + } + + /** + * MINUTE. + * + * Returns the minutes of a time value. + * The minute is given as an integer, ranging from 0 to 59. + * + * Excel Function: + * MINUTE(timeValue) + * + * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard time string + * + * @return int|string Minute + */ + public static function minute($timeValue) + { + try { + $timeValue = Functions::flattenSingleValue($timeValue); + Helpers::nullFalseTrueToNumber($timeValue); + if (!is_numeric($timeValue)) { + $timeValue = Helpers::getTimeValue($timeValue); + } + Helpers::validateNotNegative($timeValue); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Execute function + $timeValue = fmod($timeValue, 1); + $timeValue = SharedDateHelper::excelToDateTimeObject($timeValue); + + return (int) $timeValue->format('i'); + } + + /** + * SECOND. + * + * Returns the seconds of a time value. + * The minute is given as an integer, ranging from 0 to 59. + * + * Excel Function: + * SECOND(timeValue) + * + * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard time string + * + * @return int|string Second + */ + public static function second($timeValue) + { + try { + $timeValue = Functions::flattenSingleValue($timeValue); + Helpers::nullFalseTrueToNumber($timeValue); + if (!is_numeric($timeValue)) { + $timeValue = Helpers::getTimeValue($timeValue); + } + Helpers::validateNotNegative($timeValue); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Execute function + $timeValue = fmod($timeValue, 1); + $timeValue = SharedDateHelper::excelToDateTimeObject($timeValue); + + return (int) $timeValue->format('s'); + } +} diff --git a/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeValue.php b/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeValue.php new file mode 100644 index 00000000..2a294344 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeValue.php @@ -0,0 +1,61 @@ + 24) { + $arraySplit[0] = ($arraySplit[0] % 24); + $timeValue = implode(':', $arraySplit); + } + + $PHPDateArray = date_parse($timeValue); + $retValue = Functions::VALUE(); + if (($PHPDateArray !== false) && ($PHPDateArray['error_count'] == 0)) { + // OpenOffice-specific code removed - it works just like Excel + $excelDateValue = SharedDateHelper::formattedPHPToExcel(1900, 1, 1, $PHPDateArray['hour'], $PHPDateArray['minute'], $PHPDateArray['second']) - 1; + + $retType = Functions::getReturnDateType(); + if ($retType === Functions::RETURNDATE_EXCEL) { + $retValue = (float) $excelDateValue; + } elseif ($retType === Functions::RETURNDATE_UNIX_TIMESTAMP) { + $retValue = (int) $phpDateValue = SharedDateHelper::excelToTimestamp($excelDateValue + 25569) - 3600; + } else { + $retValue = new DateTime('1900-01-01 ' . $PHPDateArray['hour'] . ':' . $PHPDateArray['minute'] . ':' . $PHPDateArray['second']); + } + } + + return $retValue; + } +} diff --git a/src/PhpSpreadsheet/Calculation/DateTimeExcel/Week.php b/src/PhpSpreadsheet/Calculation/DateTimeExcel/Week.php new file mode 100644 index 00000000..66362221 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/DateTimeExcel/Week.php @@ -0,0 +1,254 @@ +getMessage(); + } + + // Execute function + $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); + if ($method == Constants::STARTWEEK_MONDAY_ISO) { + Helpers::silly1900($PHPDateObject); + + return (int) $PHPDateObject->format('W'); + } + if (self::buggyWeekNum1904($method, $origDateValueNull, $PHPDateObject)) { + return 0; + } + Helpers::silly1900($PHPDateObject, '+ 5 years'); // 1905 calendar matches + $dayOfYear = (int) $PHPDateObject->format('z'); + $PHPDateObject->modify('-' . $dayOfYear . ' days'); + $firstDayOfFirstWeek = (int) $PHPDateObject->format('w'); + $daysInFirstWeek = (6 - $firstDayOfFirstWeek + $method) % 7; + $daysInFirstWeek += 7 * !$daysInFirstWeek; + $endFirstWeek = $daysInFirstWeek - 1; + $weekOfYear = floor(($dayOfYear - $endFirstWeek + 13) / 7); + + return (int) $weekOfYear; + } + + /** + * ISOWEEKNUM. + * + * Returns the ISO 8601 week number of the year for a specified date. + * + * Excel Function: + * ISOWEEKNUM(dateValue) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * + * @return int|string Week Number + */ + public static function isoWeekNumber($dateValue) + { + if (self::apparentBug($dateValue)) { + return 52; + } + + try { + $dateValue = Helpers::getDateValue($dateValue); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Execute function + $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); + Helpers::silly1900($PHPDateObject); + + return (int) $PHPDateObject->format('W'); + } + + /** + * WEEKDAY. + * + * Returns the day of the week for a specified date. The day is given as an integer + * ranging from 0 to 7 (dependent on the requested style). + * + * Excel Function: + * WEEKDAY(dateValue[,style]) + * + * @param null|float|int|string $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param mixed $style A number that determines the type of return value + * 1 or omitted Numbers 1 (Sunday) through 7 (Saturday). + * 2 Numbers 1 (Monday) through 7 (Sunday). + * 3 Numbers 0 (Monday) through 6 (Sunday). + * + * @return int|string Day of the week value + */ + public static function day($dateValue, $style = 1) + { + try { + $dateValue = Helpers::getDateValue($dateValue); + $style = self::validateStyle($style); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Execute function + $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); + Helpers::silly1900($PHPDateObject); + $DoW = (int) $PHPDateObject->format('w'); + + switch ($style) { + case 1: + ++$DoW; + + break; + case 2: + $DoW = self::dow0Becomes7($DoW); + + break; + case 3: + $DoW = self::dow0Becomes7($DoW) - 1; + + break; + } + + return $DoW; + } + + /** + * @param mixed $style expect int + */ + private static function validateStyle($style): int + { + $style = Functions::flattenSingleValue($style); + + if (!is_numeric($style)) { + throw new Exception(Functions::VALUE()); + } + $style = (int) $style; + if (($style < 1) || ($style > 3)) { + throw new Exception(Functions::NAN()); + } + + return $style; + } + + private static function dow0Becomes7(int $DoW): int + { + return ($DoW === 0) ? 7 : $DoW; + } + + /** + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + */ + private static function apparentBug($dateValue): bool + { + if (SharedDateHelper::getExcelCalendar() !== SharedDateHelper::CALENDAR_MAC_1904) { + if (is_bool($dateValue)) { + return true; + } + if (is_numeric($dateValue) && !((int) $dateValue)) { + return true; + } + } + + return false; + } + + /** + * Validate dateValue parameter. + * + * @param mixed $dateValue + */ + private static function validateDateValue($dateValue): float + { + if (is_bool($dateValue)) { + throw new Exception(Functions::VALUE()); + } + + return Helpers::getDateValue($dateValue); + } + + /** + * Validate method parameter. + * + * @param mixed $method + */ + private static function validateMethod($method): int + { + if ($method === null) { + $method = Constants::STARTWEEK_SUNDAY; + } + $method = Functions::flattenSingleValue($method); + if (!is_numeric($method)) { + throw new Exception(Functions::VALUE()); + } + + $method = (int) $method; + if (!array_key_exists($method, Constants::METHODARR)) { + throw new Exception(Functions::NAN()); + } + $method = Constants::METHODARR[$method]; + + return $method; + } + + private static function buggyWeekNum1900(int $method): bool + { + return $method === Constants::DOW_SUNDAY && SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_WINDOWS_1900; + } + + private static function buggyWeekNum1904(int $method, bool $origNull, DateTime $dateObject): bool + { + // This appears to be another Excel bug. + + return $method === Constants::DOW_SUNDAY && SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_MAC_1904 && + !$origNull && $dateObject->format('Y-m-d') === '1904-01-01'; + } +} diff --git a/src/PhpSpreadsheet/Calculation/DateTimeExcel/WorkDay.php b/src/PhpSpreadsheet/Calculation/DateTimeExcel/WorkDay.php new file mode 100644 index 00000000..89e47b96 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/DateTimeExcel/WorkDay.php @@ -0,0 +1,189 @@ +getMessage(); + } + + $startDate = (float) floor($startDate); + $endDays = (int) floor($endDays); + // If endDays is 0, we always return startDate + if ($endDays == 0) { + return $startDate; + } + if ($endDays < 0) { + return self::decrementing($startDate, $endDays, $holidayArray); + } + + return self::incrementing($startDate, $endDays, $holidayArray); + } + + /** + * Use incrementing logic to determine Workday. + * + * @return mixed + */ + private static function incrementing(float $startDate, int $endDays, array $holidayArray) + { + // Adjust the start date if it falls over a weekend + + $startDoW = self::getWeekDay($startDate, 3); + if (self::getWeekDay($startDate, 3) >= 5) { + $startDate += 7 - $startDoW; + --$endDays; + } + + // Add endDays + $endDate = (float) $startDate + ((int) ($endDays / 5) * 7); + $endDays = $endDays % 5; + while ($endDays > 0) { + ++$endDate; + // Adjust the calculated end date if it falls over a weekend + $endDow = self::getWeekDay($endDate, 3); + if ($endDow >= 5) { + $endDate += 7 - $endDow; + } + --$endDays; + } + + // Test any extra holiday parameters + if (!empty($holidayArray)) { + $endDate = self::incrementingArray($startDate, $endDate, $holidayArray); + } + + return Helpers::returnIn3FormatsFloat($endDate); + } + + private static function incrementingArray(float $startDate, float $endDate, array $holidayArray): float + { + $holidayCountedArray = $holidayDates = []; + foreach ($holidayArray as $holidayDate) { + if (self::getWeekDay($holidayDate, 3) < 5) { + $holidayDates[] = $holidayDate; + } + } + sort($holidayDates, SORT_NUMERIC); + foreach ($holidayDates as $holidayDate) { + if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) { + if (!in_array($holidayDate, $holidayCountedArray)) { + ++$endDate; + $holidayCountedArray[] = $holidayDate; + } + } + // Adjust the calculated end date if it falls over a weekend + $endDoW = self::getWeekDay($endDate, 3); + if ($endDoW >= 5) { + $endDate += 7 - $endDoW; + } + } + + return $endDate; + } + + /** + * Use decrementing logic to determine Workday. + * + * @return mixed + */ + private static function decrementing(float $startDate, int $endDays, array $holidayArray) + { + // Adjust the start date if it falls over a weekend + + $startDoW = self::getWeekDay($startDate, 3); + if (self::getWeekDay($startDate, 3) >= 5) { + $startDate += -$startDoW + 4; + ++$endDays; + } + + // Add endDays + $endDate = (float) $startDate + ((int) ($endDays / 5) * 7); + $endDays = $endDays % 5; + while ($endDays < 0) { + --$endDate; + // Adjust the calculated end date if it falls over a weekend + $endDow = self::getWeekDay($endDate, 3); + if ($endDow >= 5) { + $endDate += 4 - $endDow; + } + ++$endDays; + } + + // Test any extra holiday parameters + if (!empty($holidayArray)) { + $endDate = self::decrementingArray($startDate, $endDate, $holidayArray); + } + + return Helpers::returnIn3FormatsFloat($endDate); + } + + private static function decrementingArray(float $startDate, float $endDate, array $holidayArray): float + { + $holidayCountedArray = $holidayDates = []; + foreach ($holidayArray as $holidayDate) { + if (self::getWeekDay($holidayDate, 3) < 5) { + $holidayDates[] = $holidayDate; + } + } + rsort($holidayDates, SORT_NUMERIC); + foreach ($holidayDates as $holidayDate) { + if (($holidayDate <= $startDate) && ($holidayDate >= $endDate)) { + if (!in_array($holidayDate, $holidayCountedArray)) { + --$endDate; + $holidayCountedArray[] = $holidayDate; + } + } + // Adjust the calculated end date if it falls over a weekend + $endDoW = self::getWeekDay($endDate, 3); + if ($endDoW >= 5) { + $endDate += -$endDoW + 4; + } + } + + return $endDate; + } + + private static function getWeekDay(float $date, int $wd): int + { + $result = Week::day($date, $wd); + + return is_string($result) ? -1 : $result; + } +} diff --git a/src/PhpSpreadsheet/Calculation/DateTimeExcel/YearFrac.php b/src/PhpSpreadsheet/Calculation/DateTimeExcel/YearFrac.php new file mode 100644 index 00000000..da2ac12f --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/DateTimeExcel/YearFrac.php @@ -0,0 +1,120 @@ +getMessage(); + } + + switch ($method) { + case 0: + return Days360::between($startDate, $endDate) / 360; + case 1: + return self::method1($startDate, $endDate); + case 2: + return Difference::interval($startDate, $endDate) / 360; + case 3: + return Difference::interval($startDate, $endDate) / 365; + case 4: + return Days360::between($startDate, $endDate, true) / 360; + } + + return Functions::NAN(); + } + + /** + * Excel 1900 calendar treats date argument of null as 1900-01-00. Really. + * + * @param mixed $startDate + * @param mixed $endDate + */ + private static function excelBug(float $sDate, $startDate, $endDate, int $method): float + { + if (Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_OPENOFFICE && SharedDateHelper::getExcelCalendar() !== SharedDateHelper::CALENDAR_MAC_1904) { + if ($endDate === null && $startDate !== null) { + if (DateParts::month($sDate) == 12 && DateParts::day($sDate) === 31 && $method === 0) { + $sDate += 2; + } else { + ++$sDate; + } + } + } + + return $sDate; + } + + private static function method1(float $startDate, float $endDate): float + { + $days = Difference::interval($startDate, $endDate); + $startYear = (int) DateParts::year($startDate); + $endYear = (int) DateParts::year($endDate); + $years = $endYear - $startYear + 1; + $startMonth = (int) DateParts::month($startDate); + $startDay = (int) DateParts::day($startDate); + $endMonth = (int) DateParts::month($endDate); + $endDay = (int) DateParts::day($endDate); + $startMonthDay = 100 * $startMonth + $startDay; + $endMonthDay = 100 * $endMonth + $endDay; + if ($years == 1) { + $tmpCalcAnnualBasis = 365 + (int) Helpers::isLeapYear($endYear); + } elseif ($years == 2 && $startMonthDay >= $endMonthDay) { + if (Helpers::isLeapYear($startYear)) { + $tmpCalcAnnualBasis = 365 + (int) ($startMonthDay <= 229); + } elseif (Helpers::isLeapYear($endYear)) { + $tmpCalcAnnualBasis = 365 + (int) ($endMonthDay >= 229); + } else { + $tmpCalcAnnualBasis = 365; + } + } else { + $tmpCalcAnnualBasis = 0; + for ($year = $startYear; $year <= $endYear; ++$year) { + $tmpCalcAnnualBasis += 365 + (int) Helpers::isLeapYear($year); + } + $tmpCalcAnnualBasis /= $years; + } + + return $days / $tmpCalcAnnualBasis; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Engineering.php b/src/PhpSpreadsheet/Calculation/Engineering.php index 1256dd90..a70ddac5 100644 --- a/src/PhpSpreadsheet/Calculation/Engineering.php +++ b/src/PhpSpreadsheet/Calculation/Engineering.php @@ -3,725 +3,28 @@ namespace PhpOffice\PhpSpreadsheet\Calculation; use Complex\Complex; -use Complex\Exception as ComplexException; +use PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions; +use PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexOperations; +/** + * @deprecated 1.18.0 + */ class Engineering { /** * EULER. - */ - const EULER = 2.71828182845904523536; - - /** - * Details of the Units of measure that can be used in CONVERTUOM(). * - * @var mixed[] + * @deprecated 1.18.0 + * @see Use Engineering\Constants\EULER instead */ - private static $conversionUnits = [ - 'g' => ['Group' => 'Mass', 'Unit Name' => 'Gram', 'AllowPrefix' => true], - 'sg' => ['Group' => 'Mass', 'Unit Name' => 'Slug', 'AllowPrefix' => false], - 'lbm' => ['Group' => 'Mass', 'Unit Name' => 'Pound mass (avoirdupois)', 'AllowPrefix' => false], - 'u' => ['Group' => 'Mass', 'Unit Name' => 'U (atomic mass unit)', 'AllowPrefix' => true], - 'ozm' => ['Group' => 'Mass', 'Unit Name' => 'Ounce mass (avoirdupois)', 'AllowPrefix' => false], - 'm' => ['Group' => 'Distance', 'Unit Name' => 'Meter', 'AllowPrefix' => true], - 'mi' => ['Group' => 'Distance', 'Unit Name' => 'Statute mile', 'AllowPrefix' => false], - 'Nmi' => ['Group' => 'Distance', 'Unit Name' => 'Nautical mile', 'AllowPrefix' => false], - 'in' => ['Group' => 'Distance', 'Unit Name' => 'Inch', 'AllowPrefix' => false], - 'ft' => ['Group' => 'Distance', 'Unit Name' => 'Foot', 'AllowPrefix' => false], - 'yd' => ['Group' => 'Distance', 'Unit Name' => 'Yard', 'AllowPrefix' => false], - 'ang' => ['Group' => 'Distance', 'Unit Name' => 'Angstrom', 'AllowPrefix' => true], - 'Pica' => ['Group' => 'Distance', 'Unit Name' => 'Pica (1/72 in)', 'AllowPrefix' => false], - 'yr' => ['Group' => 'Time', 'Unit Name' => 'Year', 'AllowPrefix' => false], - 'day' => ['Group' => 'Time', 'Unit Name' => 'Day', 'AllowPrefix' => false], - 'hr' => ['Group' => 'Time', 'Unit Name' => 'Hour', 'AllowPrefix' => false], - 'mn' => ['Group' => 'Time', 'Unit Name' => 'Minute', 'AllowPrefix' => false], - 'sec' => ['Group' => 'Time', 'Unit Name' => 'Second', 'AllowPrefix' => true], - 'Pa' => ['Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => true], - 'p' => ['Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => true], - 'atm' => ['Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => true], - 'at' => ['Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => true], - 'mmHg' => ['Group' => 'Pressure', 'Unit Name' => 'mm of Mercury', 'AllowPrefix' => true], - 'N' => ['Group' => 'Force', 'Unit Name' => 'Newton', 'AllowPrefix' => true], - 'dyn' => ['Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => true], - 'dy' => ['Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => true], - 'lbf' => ['Group' => 'Force', 'Unit Name' => 'Pound force', 'AllowPrefix' => false], - 'J' => ['Group' => 'Energy', 'Unit Name' => 'Joule', 'AllowPrefix' => true], - 'e' => ['Group' => 'Energy', 'Unit Name' => 'Erg', 'AllowPrefix' => true], - 'c' => ['Group' => 'Energy', 'Unit Name' => 'Thermodynamic calorie', 'AllowPrefix' => true], - 'cal' => ['Group' => 'Energy', 'Unit Name' => 'IT calorie', 'AllowPrefix' => true], - 'eV' => ['Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => true], - 'ev' => ['Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => true], - 'HPh' => ['Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => false], - 'hh' => ['Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => false], - 'Wh' => ['Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => true], - 'wh' => ['Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => true], - 'flb' => ['Group' => 'Energy', 'Unit Name' => 'Foot-pound', 'AllowPrefix' => false], - 'BTU' => ['Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => false], - 'btu' => ['Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => false], - 'HP' => ['Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => false], - 'h' => ['Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => false], - 'W' => ['Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => true], - 'w' => ['Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => true], - 'T' => ['Group' => 'Magnetism', 'Unit Name' => 'Tesla', 'AllowPrefix' => true], - 'ga' => ['Group' => 'Magnetism', 'Unit Name' => 'Gauss', 'AllowPrefix' => true], - 'C' => ['Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => false], - 'cel' => ['Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => false], - 'F' => ['Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => false], - 'fah' => ['Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => false], - 'K' => ['Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => false], - 'kel' => ['Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => false], - 'tsp' => ['Group' => 'Liquid', 'Unit Name' => 'Teaspoon', 'AllowPrefix' => false], - 'tbs' => ['Group' => 'Liquid', 'Unit Name' => 'Tablespoon', 'AllowPrefix' => false], - 'oz' => ['Group' => 'Liquid', 'Unit Name' => 'Fluid Ounce', 'AllowPrefix' => false], - 'cup' => ['Group' => 'Liquid', 'Unit Name' => 'Cup', 'AllowPrefix' => false], - 'pt' => ['Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => false], - 'us_pt' => ['Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => false], - 'uk_pt' => ['Group' => 'Liquid', 'Unit Name' => 'U.K. Pint', 'AllowPrefix' => false], - 'qt' => ['Group' => 'Liquid', 'Unit Name' => 'Quart', 'AllowPrefix' => false], - 'gal' => ['Group' => 'Liquid', 'Unit Name' => 'Gallon', 'AllowPrefix' => false], - 'l' => ['Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => true], - 'lt' => ['Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => true], - ]; - - /** - * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM(). - * - * @var mixed[] - */ - private static $conversionMultipliers = [ - 'Y' => ['multiplier' => 1E24, 'name' => 'yotta'], - 'Z' => ['multiplier' => 1E21, 'name' => 'zetta'], - 'E' => ['multiplier' => 1E18, 'name' => 'exa'], - 'P' => ['multiplier' => 1E15, 'name' => 'peta'], - 'T' => ['multiplier' => 1E12, 'name' => 'tera'], - 'G' => ['multiplier' => 1E9, 'name' => 'giga'], - 'M' => ['multiplier' => 1E6, 'name' => 'mega'], - 'k' => ['multiplier' => 1E3, 'name' => 'kilo'], - 'h' => ['multiplier' => 1E2, 'name' => 'hecto'], - 'e' => ['multiplier' => 1E1, 'name' => 'deka'], - 'd' => ['multiplier' => 1E-1, 'name' => 'deci'], - 'c' => ['multiplier' => 1E-2, 'name' => 'centi'], - 'm' => ['multiplier' => 1E-3, 'name' => 'milli'], - 'u' => ['multiplier' => 1E-6, 'name' => 'micro'], - 'n' => ['multiplier' => 1E-9, 'name' => 'nano'], - 'p' => ['multiplier' => 1E-12, 'name' => 'pico'], - 'f' => ['multiplier' => 1E-15, 'name' => 'femto'], - 'a' => ['multiplier' => 1E-18, 'name' => 'atto'], - 'z' => ['multiplier' => 1E-21, 'name' => 'zepto'], - 'y' => ['multiplier' => 1E-24, 'name' => 'yocto'], - ]; - - /** - * Details of the Units of measure conversion factors, organised by group. - * - * @var mixed[] - */ - private static $unitConversions = [ - 'Mass' => [ - 'g' => [ - 'g' => 1.0, - 'sg' => 6.85220500053478E-05, - 'lbm' => 2.20462291469134E-03, - 'u' => 6.02217000000000E+23, - 'ozm' => 3.52739718003627E-02, - ], - 'sg' => [ - 'g' => 1.45938424189287E+04, - 'sg' => 1.0, - 'lbm' => 3.21739194101647E+01, - 'u' => 8.78866000000000E+27, - 'ozm' => 5.14782785944229E+02, - ], - 'lbm' => [ - 'g' => 4.5359230974881148E+02, - 'sg' => 3.10810749306493E-02, - 'lbm' => 1.0, - 'u' => 2.73161000000000E+26, - 'ozm' => 1.60000023429410E+01, - ], - 'u' => [ - 'g' => 1.66053100460465E-24, - 'sg' => 1.13782988532950E-28, - 'lbm' => 3.66084470330684E-27, - 'u' => 1.0, - 'ozm' => 5.85735238300524E-26, - ], - 'ozm' => [ - 'g' => 2.83495152079732E+01, - 'sg' => 1.94256689870811E-03, - 'lbm' => 6.24999908478882E-02, - 'u' => 1.70725600000000E+25, - 'ozm' => 1.0, - ], - ], - 'Distance' => [ - 'm' => [ - 'm' => 1.0, - 'mi' => 6.21371192237334E-04, - 'Nmi' => 5.39956803455724E-04, - 'in' => 3.93700787401575E+01, - 'ft' => 3.28083989501312E+00, - 'yd' => 1.09361329797891E+00, - 'ang' => 1.00000000000000E+10, - 'Pica' => 2.83464566929116E+03, - ], - 'mi' => [ - 'm' => 1.60934400000000E+03, - 'mi' => 1.0, - 'Nmi' => 8.68976241900648E-01, - 'in' => 6.33600000000000E+04, - 'ft' => 5.28000000000000E+03, - 'yd' => 1.76000000000000E+03, - 'ang' => 1.60934400000000E+13, - 'Pica' => 4.56191999999971E+06, - ], - 'Nmi' => [ - 'm' => 1.85200000000000E+03, - 'mi' => 1.15077944802354E+00, - 'Nmi' => 1.0, - 'in' => 7.29133858267717E+04, - 'ft' => 6.07611548556430E+03, - 'yd' => 2.02537182785694E+03, - 'ang' => 1.85200000000000E+13, - 'Pica' => 5.24976377952723E+06, - ], - 'in' => [ - 'm' => 2.54000000000000E-02, - 'mi' => 1.57828282828283E-05, - 'Nmi' => 1.37149028077754E-05, - 'in' => 1.0, - 'ft' => 8.33333333333333E-02, - 'yd' => 2.77777777686643E-02, - 'ang' => 2.54000000000000E+08, - 'Pica' => 7.19999999999955E+01, - ], - 'ft' => [ - 'm' => 3.04800000000000E-01, - 'mi' => 1.89393939393939E-04, - 'Nmi' => 1.64578833693305E-04, - 'in' => 1.20000000000000E+01, - 'ft' => 1.0, - 'yd' => 3.33333333223972E-01, - 'ang' => 3.04800000000000E+09, - 'Pica' => 8.63999999999946E+02, - ], - 'yd' => [ - 'm' => 9.14400000300000E-01, - 'mi' => 5.68181818368230E-04, - 'Nmi' => 4.93736501241901E-04, - 'in' => 3.60000000118110E+01, - 'ft' => 3.00000000000000E+00, - 'yd' => 1.0, - 'ang' => 9.14400000300000E+09, - 'Pica' => 2.59200000085023E+03, - ], - 'ang' => [ - 'm' => 1.00000000000000E-10, - 'mi' => 6.21371192237334E-14, - 'Nmi' => 5.39956803455724E-14, - 'in' => 3.93700787401575E-09, - 'ft' => 3.28083989501312E-10, - 'yd' => 1.09361329797891E-10, - 'ang' => 1.0, - 'Pica' => 2.83464566929116E-07, - ], - 'Pica' => [ - 'm' => 3.52777777777800E-04, - 'mi' => 2.19205948372629E-07, - 'Nmi' => 1.90484761219114E-07, - 'in' => 1.38888888888898E-02, - 'ft' => 1.15740740740748E-03, - 'yd' => 3.85802469009251E-04, - 'ang' => 3.52777777777800E+06, - 'Pica' => 1.0, - ], - ], - 'Time' => [ - 'yr' => [ - 'yr' => 1.0, - 'day' => 365.25, - 'hr' => 8766.0, - 'mn' => 525960.0, - 'sec' => 31557600.0, - ], - 'day' => [ - 'yr' => 2.73785078713210E-03, - 'day' => 1.0, - 'hr' => 24.0, - 'mn' => 1440.0, - 'sec' => 86400.0, - ], - 'hr' => [ - 'yr' => 1.14077116130504E-04, - 'day' => 4.16666666666667E-02, - 'hr' => 1.0, - 'mn' => 60.0, - 'sec' => 3600.0, - ], - 'mn' => [ - 'yr' => 1.90128526884174E-06, - 'day' => 6.94444444444444E-04, - 'hr' => 1.66666666666667E-02, - 'mn' => 1.0, - 'sec' => 60.0, - ], - 'sec' => [ - 'yr' => 3.16880878140289E-08, - 'day' => 1.15740740740741E-05, - 'hr' => 2.77777777777778E-04, - 'mn' => 1.66666666666667E-02, - 'sec' => 1.0, - ], - ], - 'Pressure' => [ - 'Pa' => [ - 'Pa' => 1.0, - 'p' => 1.0, - 'atm' => 9.86923299998193E-06, - 'at' => 9.86923299998193E-06, - 'mmHg' => 7.50061707998627E-03, - ], - 'p' => [ - 'Pa' => 1.0, - 'p' => 1.0, - 'atm' => 9.86923299998193E-06, - 'at' => 9.86923299998193E-06, - 'mmHg' => 7.50061707998627E-03, - ], - 'atm' => [ - 'Pa' => 1.01324996583000E+05, - 'p' => 1.01324996583000E+05, - 'atm' => 1.0, - 'at' => 1.0, - 'mmHg' => 760.0, - ], - 'at' => [ - 'Pa' => 1.01324996583000E+05, - 'p' => 1.01324996583000E+05, - 'atm' => 1.0, - 'at' => 1.0, - 'mmHg' => 760.0, - ], - 'mmHg' => [ - 'Pa' => 1.33322363925000E+02, - 'p' => 1.33322363925000E+02, - 'atm' => 1.31578947368421E-03, - 'at' => 1.31578947368421E-03, - 'mmHg' => 1.0, - ], - ], - 'Force' => [ - 'N' => [ - 'N' => 1.0, - 'dyn' => 1.0E+5, - 'dy' => 1.0E+5, - 'lbf' => 2.24808923655339E-01, - ], - 'dyn' => [ - 'N' => 1.0E-5, - 'dyn' => 1.0, - 'dy' => 1.0, - 'lbf' => 2.24808923655339E-06, - ], - 'dy' => [ - 'N' => 1.0E-5, - 'dyn' => 1.0, - 'dy' => 1.0, - 'lbf' => 2.24808923655339E-06, - ], - 'lbf' => [ - 'N' => 4.448222, - 'dyn' => 4.448222E+5, - 'dy' => 4.448222E+5, - 'lbf' => 1.0, - ], - ], - 'Energy' => [ - 'J' => [ - 'J' => 1.0, - 'e' => 9.99999519343231E+06, - 'c' => 2.39006249473467E-01, - 'cal' => 2.38846190642017E-01, - 'eV' => 6.24145700000000E+18, - 'ev' => 6.24145700000000E+18, - 'HPh' => 3.72506430801000E-07, - 'hh' => 3.72506430801000E-07, - 'Wh' => 2.77777916238711E-04, - 'wh' => 2.77777916238711E-04, - 'flb' => 2.37304222192651E+01, - 'BTU' => 9.47815067349015E-04, - 'btu' => 9.47815067349015E-04, - ], - 'e' => [ - 'J' => 1.00000048065700E-07, - 'e' => 1.0, - 'c' => 2.39006364353494E-08, - 'cal' => 2.38846305445111E-08, - 'eV' => 6.24146000000000E+11, - 'ev' => 6.24146000000000E+11, - 'HPh' => 3.72506609848824E-14, - 'hh' => 3.72506609848824E-14, - 'Wh' => 2.77778049754611E-11, - 'wh' => 2.77778049754611E-11, - 'flb' => 2.37304336254586E-06, - 'BTU' => 9.47815522922962E-11, - 'btu' => 9.47815522922962E-11, - ], - 'c' => [ - 'J' => 4.18399101363672E+00, - 'e' => 4.18398900257312E+07, - 'c' => 1.0, - 'cal' => 9.99330315287563E-01, - 'eV' => 2.61142000000000E+19, - 'ev' => 2.61142000000000E+19, - 'HPh' => 1.55856355899327E-06, - 'hh' => 1.55856355899327E-06, - 'Wh' => 1.16222030532950E-03, - 'wh' => 1.16222030532950E-03, - 'flb' => 9.92878733152102E+01, - 'BTU' => 3.96564972437776E-03, - 'btu' => 3.96564972437776E-03, - ], - 'cal' => [ - 'J' => 4.18679484613929E+00, - 'e' => 4.18679283372801E+07, - 'c' => 1.00067013349059E+00, - 'cal' => 1.0, - 'eV' => 2.61317000000000E+19, - 'ev' => 2.61317000000000E+19, - 'HPh' => 1.55960800463137E-06, - 'hh' => 1.55960800463137E-06, - 'Wh' => 1.16299914807955E-03, - 'wh' => 1.16299914807955E-03, - 'flb' => 9.93544094443283E+01, - 'BTU' => 3.96830723907002E-03, - 'btu' => 3.96830723907002E-03, - ], - 'eV' => [ - 'J' => 1.60219000146921E-19, - 'e' => 1.60218923136574E-12, - 'c' => 3.82933423195043E-20, - 'cal' => 3.82676978535648E-20, - 'eV' => 1.0, - 'ev' => 1.0, - 'HPh' => 5.96826078912344E-26, - 'hh' => 5.96826078912344E-26, - 'Wh' => 4.45053000026614E-23, - 'wh' => 4.45053000026614E-23, - 'flb' => 3.80206452103492E-18, - 'BTU' => 1.51857982414846E-22, - 'btu' => 1.51857982414846E-22, - ], - 'ev' => [ - 'J' => 1.60219000146921E-19, - 'e' => 1.60218923136574E-12, - 'c' => 3.82933423195043E-20, - 'cal' => 3.82676978535648E-20, - 'eV' => 1.0, - 'ev' => 1.0, - 'HPh' => 5.96826078912344E-26, - 'hh' => 5.96826078912344E-26, - 'Wh' => 4.45053000026614E-23, - 'wh' => 4.45053000026614E-23, - 'flb' => 3.80206452103492E-18, - 'BTU' => 1.51857982414846E-22, - 'btu' => 1.51857982414846E-22, - ], - 'HPh' => [ - 'J' => 2.68451741316170E+06, - 'e' => 2.68451612283024E+13, - 'c' => 6.41616438565991E+05, - 'cal' => 6.41186757845835E+05, - 'eV' => 1.67553000000000E+25, - 'ev' => 1.67553000000000E+25, - 'HPh' => 1.0, - 'hh' => 1.0, - 'Wh' => 7.45699653134593E+02, - 'wh' => 7.45699653134593E+02, - 'flb' => 6.37047316692964E+07, - 'BTU' => 2.54442605275546E+03, - 'btu' => 2.54442605275546E+03, - ], - 'hh' => [ - 'J' => 2.68451741316170E+06, - 'e' => 2.68451612283024E+13, - 'c' => 6.41616438565991E+05, - 'cal' => 6.41186757845835E+05, - 'eV' => 1.67553000000000E+25, - 'ev' => 1.67553000000000E+25, - 'HPh' => 1.0, - 'hh' => 1.0, - 'Wh' => 7.45699653134593E+02, - 'wh' => 7.45699653134593E+02, - 'flb' => 6.37047316692964E+07, - 'BTU' => 2.54442605275546E+03, - 'btu' => 2.54442605275546E+03, - ], - 'Wh' => [ - 'J' => 3.59999820554720E+03, - 'e' => 3.59999647518369E+10, - 'c' => 8.60422069219046E+02, - 'cal' => 8.59845857713046E+02, - 'eV' => 2.24692340000000E+22, - 'ev' => 2.24692340000000E+22, - 'HPh' => 1.34102248243839E-03, - 'hh' => 1.34102248243839E-03, - 'Wh' => 1.0, - 'wh' => 1.0, - 'flb' => 8.54294774062316E+04, - 'BTU' => 3.41213254164705E+00, - 'btu' => 3.41213254164705E+00, - ], - 'wh' => [ - 'J' => 3.59999820554720E+03, - 'e' => 3.59999647518369E+10, - 'c' => 8.60422069219046E+02, - 'cal' => 8.59845857713046E+02, - 'eV' => 2.24692340000000E+22, - 'ev' => 2.24692340000000E+22, - 'HPh' => 1.34102248243839E-03, - 'hh' => 1.34102248243839E-03, - 'Wh' => 1.0, - 'wh' => 1.0, - 'flb' => 8.54294774062316E+04, - 'BTU' => 3.41213254164705E+00, - 'btu' => 3.41213254164705E+00, - ], - 'flb' => [ - 'J' => 4.21400003236424E-02, - 'e' => 4.21399800687660E+05, - 'c' => 1.00717234301644E-02, - 'cal' => 1.00649785509554E-02, - 'eV' => 2.63015000000000E+17, - 'ev' => 2.63015000000000E+17, - 'HPh' => 1.56974211145130E-08, - 'hh' => 1.56974211145130E-08, - 'Wh' => 1.17055614802000E-05, - 'wh' => 1.17055614802000E-05, - 'flb' => 1.0, - 'BTU' => 3.99409272448406E-05, - 'btu' => 3.99409272448406E-05, - ], - 'BTU' => [ - 'J' => 1.05505813786749E+03, - 'e' => 1.05505763074665E+10, - 'c' => 2.52165488508168E+02, - 'cal' => 2.51996617135510E+02, - 'eV' => 6.58510000000000E+21, - 'ev' => 6.58510000000000E+21, - 'HPh' => 3.93015941224568E-04, - 'hh' => 3.93015941224568E-04, - 'Wh' => 2.93071851047526E-01, - 'wh' => 2.93071851047526E-01, - 'flb' => 2.50369750774671E+04, - 'BTU' => 1.0, - 'btu' => 1.0, - ], - 'btu' => [ - 'J' => 1.05505813786749E+03, - 'e' => 1.05505763074665E+10, - 'c' => 2.52165488508168E+02, - 'cal' => 2.51996617135510E+02, - 'eV' => 6.58510000000000E+21, - 'ev' => 6.58510000000000E+21, - 'HPh' => 3.93015941224568E-04, - 'hh' => 3.93015941224568E-04, - 'Wh' => 2.93071851047526E-01, - 'wh' => 2.93071851047526E-01, - 'flb' => 2.50369750774671E+04, - 'BTU' => 1.0, - 'btu' => 1.0, - ], - ], - 'Power' => [ - 'HP' => [ - 'HP' => 1.0, - 'h' => 1.0, - 'W' => 7.45701000000000E+02, - 'w' => 7.45701000000000E+02, - ], - 'h' => [ - 'HP' => 1.0, - 'h' => 1.0, - 'W' => 7.45701000000000E+02, - 'w' => 7.45701000000000E+02, - ], - 'W' => [ - 'HP' => 1.34102006031908E-03, - 'h' => 1.34102006031908E-03, - 'W' => 1.0, - 'w' => 1.0, - ], - 'w' => [ - 'HP' => 1.34102006031908E-03, - 'h' => 1.34102006031908E-03, - 'W' => 1.0, - 'w' => 1.0, - ], - ], - 'Magnetism' => [ - 'T' => [ - 'T' => 1.0, - 'ga' => 10000.0, - ], - 'ga' => [ - 'T' => 0.0001, - 'ga' => 1.0, - ], - ], - 'Liquid' => [ - 'tsp' => [ - 'tsp' => 1.0, - 'tbs' => 3.33333333333333E-01, - 'oz' => 1.66666666666667E-01, - 'cup' => 2.08333333333333E-02, - 'pt' => 1.04166666666667E-02, - 'us_pt' => 1.04166666666667E-02, - 'uk_pt' => 8.67558516821960E-03, - 'qt' => 5.20833333333333E-03, - 'gal' => 1.30208333333333E-03, - 'l' => 4.92999408400710E-03, - 'lt' => 4.92999408400710E-03, - ], - 'tbs' => [ - 'tsp' => 3.00000000000000E+00, - 'tbs' => 1.0, - 'oz' => 5.00000000000000E-01, - 'cup' => 6.25000000000000E-02, - 'pt' => 3.12500000000000E-02, - 'us_pt' => 3.12500000000000E-02, - 'uk_pt' => 2.60267555046588E-02, - 'qt' => 1.56250000000000E-02, - 'gal' => 3.90625000000000E-03, - 'l' => 1.47899822520213E-02, - 'lt' => 1.47899822520213E-02, - ], - 'oz' => [ - 'tsp' => 6.00000000000000E+00, - 'tbs' => 2.00000000000000E+00, - 'oz' => 1.0, - 'cup' => 1.25000000000000E-01, - 'pt' => 6.25000000000000E-02, - 'us_pt' => 6.25000000000000E-02, - 'uk_pt' => 5.20535110093176E-02, - 'qt' => 3.12500000000000E-02, - 'gal' => 7.81250000000000E-03, - 'l' => 2.95799645040426E-02, - 'lt' => 2.95799645040426E-02, - ], - 'cup' => [ - 'tsp' => 4.80000000000000E+01, - 'tbs' => 1.60000000000000E+01, - 'oz' => 8.00000000000000E+00, - 'cup' => 1.0, - 'pt' => 5.00000000000000E-01, - 'us_pt' => 5.00000000000000E-01, - 'uk_pt' => 4.16428088074541E-01, - 'qt' => 2.50000000000000E-01, - 'gal' => 6.25000000000000E-02, - 'l' => 2.36639716032341E-01, - 'lt' => 2.36639716032341E-01, - ], - 'pt' => [ - 'tsp' => 9.60000000000000E+01, - 'tbs' => 3.20000000000000E+01, - 'oz' => 1.60000000000000E+01, - 'cup' => 2.00000000000000E+00, - 'pt' => 1.0, - 'us_pt' => 1.0, - 'uk_pt' => 8.32856176149081E-01, - 'qt' => 5.00000000000000E-01, - 'gal' => 1.25000000000000E-01, - 'l' => 4.73279432064682E-01, - 'lt' => 4.73279432064682E-01, - ], - 'us_pt' => [ - 'tsp' => 9.60000000000000E+01, - 'tbs' => 3.20000000000000E+01, - 'oz' => 1.60000000000000E+01, - 'cup' => 2.00000000000000E+00, - 'pt' => 1.0, - 'us_pt' => 1.0, - 'uk_pt' => 8.32856176149081E-01, - 'qt' => 5.00000000000000E-01, - 'gal' => 1.25000000000000E-01, - 'l' => 4.73279432064682E-01, - 'lt' => 4.73279432064682E-01, - ], - 'uk_pt' => [ - 'tsp' => 1.15266000000000E+02, - 'tbs' => 3.84220000000000E+01, - 'oz' => 1.92110000000000E+01, - 'cup' => 2.40137500000000E+00, - 'pt' => 1.20068750000000E+00, - 'us_pt' => 1.20068750000000E+00, - 'uk_pt' => 1.0, - 'qt' => 6.00343750000000E-01, - 'gal' => 1.50085937500000E-01, - 'l' => 5.68260698087162E-01, - 'lt' => 5.68260698087162E-01, - ], - 'qt' => [ - 'tsp' => 1.92000000000000E+02, - 'tbs' => 6.40000000000000E+01, - 'oz' => 3.20000000000000E+01, - 'cup' => 4.00000000000000E+00, - 'pt' => 2.00000000000000E+00, - 'us_pt' => 2.00000000000000E+00, - 'uk_pt' => 1.66571235229816E+00, - 'qt' => 1.0, - 'gal' => 2.50000000000000E-01, - 'l' => 9.46558864129363E-01, - 'lt' => 9.46558864129363E-01, - ], - 'gal' => [ - 'tsp' => 7.68000000000000E+02, - 'tbs' => 2.56000000000000E+02, - 'oz' => 1.28000000000000E+02, - 'cup' => 1.60000000000000E+01, - 'pt' => 8.00000000000000E+00, - 'us_pt' => 8.00000000000000E+00, - 'uk_pt' => 6.66284940919265E+00, - 'qt' => 4.00000000000000E+00, - 'gal' => 1.0, - 'l' => 3.78623545651745E+00, - 'lt' => 3.78623545651745E+00, - ], - 'l' => [ - 'tsp' => 2.02840000000000E+02, - 'tbs' => 6.76133333333333E+01, - 'oz' => 3.38066666666667E+01, - 'cup' => 4.22583333333333E+00, - 'pt' => 2.11291666666667E+00, - 'us_pt' => 2.11291666666667E+00, - 'uk_pt' => 1.75975569552166E+00, - 'qt' => 1.05645833333333E+00, - 'gal' => 2.64114583333333E-01, - 'l' => 1.0, - 'lt' => 1.0, - ], - 'lt' => [ - 'tsp' => 2.02840000000000E+02, - 'tbs' => 6.76133333333333E+01, - 'oz' => 3.38066666666667E+01, - 'cup' => 4.22583333333333E+00, - 'pt' => 2.11291666666667E+00, - 'us_pt' => 2.11291666666667E+00, - 'uk_pt' => 1.75975569552166E+00, - 'qt' => 1.05645833333333E+00, - 'gal' => 2.64114583333333E-01, - 'l' => 1.0, - 'lt' => 1.0, - ], - ], - ]; + public const EULER = 2.71828182845904523536; /** * parseComplex. * * Parses a complex number into its real and imaginary parts, and an I or J suffix * - * @deprecated 2.0.0 No longer used by internal code. Please use the Complex\Complex class instead + * @deprecated 1.12.0 No longer used by internal code. Please use the \Complex\Complex class instead * * @param string $complexNumber The complex number * @@ -738,35 +41,6 @@ class Engineering ]; } - /** - * Formats a number base string value with leading zeroes. - * - * @param string $xVal The "number" to pad - * @param int $places The length that we want to pad this value - * - * @return string The padded "number" - */ - private static function nbrConversionFormat($xVal, $places) - { - if ($places !== null) { - if (is_numeric($places)) { - $places = (int) $places; - } else { - return Functions::VALUE(); - } - if ($places < 0) { - return Functions::NAN(); - } - if (strlen($xVal) <= $places) { - return substr(str_pad($xVal, $places, '0', STR_PAD_LEFT), -10); - } - - return Functions::NAN(); - } - - return substr($xVal, -10); - } - /** * BESSELI. * @@ -776,6 +50,10 @@ class Engineering * Excel Function: * BESSELI(x,ord) * + * @Deprecated 1.17.0 + * + * @see Use the BESSELI() method in the Engineering\BesselI class instead + * * @param float $x The value at which to evaluate the function. * If x is nonnumeric, BESSELI returns the #VALUE! error value. * @param int $ord The order of the Bessel function. @@ -787,38 +65,7 @@ class Engineering */ public static function BESSELI($x, $ord) { - $x = ($x === null) ? 0.0 : Functions::flattenSingleValue($x); - $ord = ($ord === null) ? 0.0 : Functions::flattenSingleValue($ord); - - if ((is_numeric($x)) && (is_numeric($ord))) { - $ord = floor($ord); - if ($ord < 0) { - return Functions::NAN(); - } - - if (abs($x) <= 30) { - $fResult = $fTerm = ($x / 2) ** $ord / MathTrig::FACT($ord); - $ordK = 1; - $fSqrX = ($x * $x) / 4; - do { - $fTerm *= $fSqrX; - $fTerm /= ($ordK * ($ordK + $ord)); - $fResult += $fTerm; - } while ((abs($fTerm) > 1e-12) && (++$ordK < 100)); - } else { - $f_2_PI = 2 * M_PI; - - $fXAbs = abs($x); - $fResult = exp($fXAbs) / sqrt($f_2_PI * $fXAbs); - if (($ord & 1) && ($x < 0)) { - $fResult = -$fResult; - } - } - - return (is_nan($fResult)) ? Functions::NAN() : $fResult; - } - - return Functions::VALUE(); + return Engineering\BesselI::BESSELI($x, $ord); } /** @@ -829,6 +76,10 @@ class Engineering * Excel Function: * BESSELJ(x,ord) * + * @Deprecated 1.17.0 + * + * @see Use the BESSELJ() method in the Engineering\BesselJ class instead + * * @param float $x The value at which to evaluate the function. * If x is nonnumeric, BESSELJ returns the #VALUE! error value. * @param int $ord The order of the Bessel function. If n is not an integer, it is truncated. @@ -839,76 +90,7 @@ class Engineering */ public static function BESSELJ($x, $ord) { - $x = ($x === null) ? 0.0 : Functions::flattenSingleValue($x); - $ord = ($ord === null) ? 0.0 : Functions::flattenSingleValue($ord); - - if ((is_numeric($x)) && (is_numeric($ord))) { - $ord = floor($ord); - if ($ord < 0) { - return Functions::NAN(); - } - - $fResult = 0; - if (abs($x) <= 30) { - $fResult = $fTerm = ($x / 2) ** $ord / MathTrig::FACT($ord); - $ordK = 1; - $fSqrX = ($x * $x) / -4; - do { - $fTerm *= $fSqrX; - $fTerm /= ($ordK * ($ordK + $ord)); - $fResult += $fTerm; - } while ((abs($fTerm) > 1e-12) && (++$ordK < 100)); - } else { - $f_PI_DIV_2 = M_PI / 2; - $f_PI_DIV_4 = M_PI / 4; - - $fXAbs = abs($x); - $fResult = sqrt(Functions::M_2DIVPI / $fXAbs) * cos($fXAbs - $ord * $f_PI_DIV_2 - $f_PI_DIV_4); - if (($ord & 1) && ($x < 0)) { - $fResult = -$fResult; - } - } - - return (is_nan($fResult)) ? Functions::NAN() : $fResult; - } - - return Functions::VALUE(); - } - - private static function besselK0($fNum) - { - if ($fNum <= 2) { - $fNum2 = $fNum * 0.5; - $y = ($fNum2 * $fNum2); - $fRet = -log($fNum2) * self::BESSELI($fNum, 0) + - (-0.57721566 + $y * (0.42278420 + $y * (0.23069756 + $y * (0.3488590e-1 + $y * (0.262698e-2 + $y * - (0.10750e-3 + $y * 0.74e-5)))))); - } else { - $y = 2 / $fNum; - $fRet = exp(-$fNum) / sqrt($fNum) * - (1.25331414 + $y * (-0.7832358e-1 + $y * (0.2189568e-1 + $y * (-0.1062446e-1 + $y * - (0.587872e-2 + $y * (-0.251540e-2 + $y * 0.53208e-3)))))); - } - - return $fRet; - } - - private static function besselK1($fNum) - { - if ($fNum <= 2) { - $fNum2 = $fNum * 0.5; - $y = ($fNum2 * $fNum2); - $fRet = log($fNum2) * self::BESSELI($fNum, 1) + - (1 + $y * (0.15443144 + $y * (-0.67278579 + $y * (-0.18156897 + $y * (-0.1919402e-1 + $y * - (-0.110404e-2 + $y * (-0.4686e-4))))))) / $fNum; - } else { - $y = 2 / $fNum; - $fRet = exp(-$fNum) / sqrt($fNum) * - (1.25331414 + $y * (0.23498619 + $y * (-0.3655620e-1 + $y * (0.1504268e-1 + $y * (-0.780353e-2 + $y * - (0.325614e-2 + $y * (-0.68245e-3))))))); - } - - return $fRet; + return Engineering\BesselJ::BESSELJ($x, $ord); } /** @@ -920,6 +102,10 @@ class Engineering * Excel Function: * BESSELK(x,ord) * + * @Deprecated 1.17.0 + * + * @see Use the BESSELK() method in the Engineering\BesselK class instead + * * @param float $x The value at which to evaluate the function. * If x is nonnumeric, BESSELK returns the #VALUE! error value. * @param int $ord The order of the Bessel function. If n is not an integer, it is truncated. @@ -930,73 +116,7 @@ class Engineering */ public static function BESSELK($x, $ord) { - $x = ($x === null) ? 0.0 : Functions::flattenSingleValue($x); - $ord = ($ord === null) ? 0.0 : Functions::flattenSingleValue($ord); - - if ((is_numeric($x)) && (is_numeric($ord))) { - if (($ord < 0) || ($x == 0.0)) { - return Functions::NAN(); - } - - switch (floor($ord)) { - case 0: - $fBk = self::besselK0($x); - - break; - case 1: - $fBk = self::besselK1($x); - - break; - default: - $fTox = 2 / $x; - $fBkm = self::besselK0($x); - $fBk = self::besselK1($x); - for ($n = 1; $n < $ord; ++$n) { - $fBkp = $fBkm + $n * $fTox * $fBk; - $fBkm = $fBk; - $fBk = $fBkp; - } - } - - return (is_nan($fBk)) ? Functions::NAN() : $fBk; - } - - return Functions::VALUE(); - } - - private static function besselY0($fNum) - { - if ($fNum < 8.0) { - $y = ($fNum * $fNum); - $f1 = -2957821389.0 + $y * (7062834065.0 + $y * (-512359803.6 + $y * (10879881.29 + $y * (-86327.92757 + $y * 228.4622733)))); - $f2 = 40076544269.0 + $y * (745249964.8 + $y * (7189466.438 + $y * (47447.26470 + $y * (226.1030244 + $y)))); - $fRet = $f1 / $f2 + 0.636619772 * self::BESSELJ($fNum, 0) * log($fNum); - } else { - $z = 8.0 / $fNum; - $y = ($z * $z); - $xx = $fNum - 0.785398164; - $f1 = 1 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6))); - $f2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 + $y * (-0.934945152e-7)))); - $fRet = sqrt(0.636619772 / $fNum) * (sin($xx) * $f1 + $z * cos($xx) * $f2); - } - - return $fRet; - } - - private static function besselY1($fNum) - { - if ($fNum < 8.0) { - $y = ($fNum * $fNum); - $f1 = $fNum * (-0.4900604943e13 + $y * (0.1275274390e13 + $y * (-0.5153438139e11 + $y * (0.7349264551e9 + $y * - (-0.4237922726e7 + $y * 0.8511937935e4))))); - $f2 = 0.2499580570e14 + $y * (0.4244419664e12 + $y * (0.3733650367e10 + $y * (0.2245904002e8 + $y * - (0.1020426050e6 + $y * (0.3549632885e3 + $y))))); - $fRet = $f1 / $f2 + 0.636619772 * (self::BESSELJ($fNum, 1) * log($fNum) - 1 / $fNum); - } else { - $fRet = sqrt(0.636619772 / $fNum) * sin($fNum - 2.356194491); - } - - return $fRet; + return Engineering\BesselK::BESSELK($x, $ord); } /** @@ -1007,48 +127,21 @@ class Engineering * Excel Function: * BESSELY(x,ord) * + * @Deprecated 1.17.0 + * + * @see Use the BESSELY() method in the Engineering\BesselY class instead + * * @param float $x The value at which to evaluate the function. - * If x is nonnumeric, BESSELK returns the #VALUE! error value. + * If x is nonnumeric, BESSELY returns the #VALUE! error value. * @param int $ord The order of the Bessel function. If n is not an integer, it is truncated. - * If $ord is nonnumeric, BESSELK returns the #VALUE! error value. - * If $ord < 0, BESSELK returns the #NUM! error value. + * If $ord is nonnumeric, BESSELY returns the #VALUE! error value. + * If $ord < 0, BESSELY returns the #NUM! error value. * * @return float|string Result, or a string containing an error */ public static function BESSELY($x, $ord) { - $x = ($x === null) ? 0.0 : Functions::flattenSingleValue($x); - $ord = ($ord === null) ? 0.0 : Functions::flattenSingleValue($ord); - - if ((is_numeric($x)) && (is_numeric($ord))) { - if (($ord < 0) || ($x == 0.0)) { - return Functions::NAN(); - } - - switch (floor($ord)) { - case 0: - $fBy = self::besselY0($x); - - break; - case 1: - $fBy = self::besselY1($x); - - break; - default: - $fTox = 2 / $x; - $fBym = self::besselY0($x); - $fBy = self::besselY1($x); - for ($n = 1; $n < $ord; ++$n) { - $fByp = $n * $fTox * $fBy - $fBym; - $fBym = $fBy; - $fBy = $fByp; - } - } - - return (is_nan($fBy)) ? Functions::NAN() : $fBy; - } - - return Functions::VALUE(); + return Engineering\BesselY::BESSELY($x, $ord); } /** @@ -1059,7 +152,11 @@ class Engineering * Excel Function: * BIN2DEC(x) * - * @param string $x The binary number (as a string) that you want to convert. The number + * @Deprecated 1.17.0 + * + * @see Use the toDecimal() method in the Engineering\ConvertBinary class instead + * + * @param mixed $x The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant * bit of number is the sign bit. The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. @@ -1070,32 +167,7 @@ class Engineering */ public static function BINTODEC($x) { - $x = Functions::flattenSingleValue($x); - - if (is_bool($x)) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - $x = (int) $x; - } else { - return Functions::VALUE(); - } - } - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { - $x = floor($x); - } - $x = (string) $x; - if (strlen($x) > preg_match_all('/[01]/', $x, $out)) { - return Functions::NAN(); - } - if (strlen($x) > 10) { - return Functions::NAN(); - } elseif (strlen($x) == 10) { - // Two's Complement - $x = substr($x, -9); - - return '-' . (512 - bindec($x)); - } - - return bindec($x); + return Engineering\ConvertBinary::toDecimal($x); } /** @@ -1106,13 +178,17 @@ class Engineering * Excel Function: * BIN2HEX(x[,places]) * - * @param string $x The binary number (as a string) that you want to convert. The number + * @Deprecated 1.17.0 + * + * @see Use the toHex() method in the Engineering\ConvertBinary class instead + * + * @param mixed $x The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant * bit of number is the sign bit. The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is not a valid binary number, or if number contains more than * 10 characters (10 bits), BIN2HEX returns the #NUM! error value. - * @param int $places The number of characters to use. If places is omitted, BIN2HEX uses the + * @param mixed $places The number of characters to use. If places is omitted, BIN2HEX uses the * minimum number of characters necessary. Places is useful for padding the * return value with leading 0s (zeros). * If places is not an integer, it is truncated. @@ -1123,33 +199,7 @@ class Engineering */ public static function BINTOHEX($x, $places = null) { - $x = Functions::flattenSingleValue($x); - $places = Functions::flattenSingleValue($places); - - // Argument X - if (is_bool($x)) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - $x = (int) $x; - } else { - return Functions::VALUE(); - } - } - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { - $x = floor($x); - } - $x = (string) $x; - if (strlen($x) > preg_match_all('/[01]/', $x, $out)) { - return Functions::NAN(); - } - if (strlen($x) > 10) { - return Functions::NAN(); - } elseif (strlen($x) == 10) { - // Two's Complement - return str_repeat('F', 8) . substr(strtoupper(dechex(bindec(substr($x, -9)))), -2); - } - $hexVal = (string) strtoupper(dechex(bindec($x))); - - return self::nbrConversionFormat($hexVal, $places); + return Engineering\ConvertBinary::toHex($x, $places); } /** @@ -1160,13 +210,17 @@ class Engineering * Excel Function: * BIN2OCT(x[,places]) * - * @param string $x The binary number (as a string) that you want to convert. The number + * @Deprecated 1.17.0 + * + * @see Use the toOctal() method in the Engineering\ConvertBinary class instead + * + * @param mixed $x The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant * bit of number is the sign bit. The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is not a valid binary number, or if number contains more than * 10 characters (10 bits), BIN2OCT returns the #NUM! error value. - * @param int $places The number of characters to use. If places is omitted, BIN2OCT uses the + * @param mixed $places The number of characters to use. If places is omitted, BIN2OCT uses the * minimum number of characters necessary. Places is useful for padding the * return value with leading 0s (zeros). * If places is not an integer, it is truncated. @@ -1177,32 +231,7 @@ class Engineering */ public static function BINTOOCT($x, $places = null) { - $x = Functions::flattenSingleValue($x); - $places = Functions::flattenSingleValue($places); - - if (is_bool($x)) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - $x = (int) $x; - } else { - return Functions::VALUE(); - } - } - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { - $x = floor($x); - } - $x = (string) $x; - if (strlen($x) > preg_match_all('/[01]/', $x, $out)) { - return Functions::NAN(); - } - if (strlen($x) > 10) { - return Functions::NAN(); - } elseif (strlen($x) == 10) { - // Two's Complement - return str_repeat('7', 7) . substr(strtoupper(decoct(bindec(substr($x, -9)))), -3); - } - $octVal = (string) decoct(bindec($x)); - - return self::nbrConversionFormat($octVal, $places); + return Engineering\ConvertBinary::toOctal($x, $places); } /** @@ -1213,7 +242,11 @@ class Engineering * Excel Function: * DEC2BIN(x[,places]) * - * @param string $x The decimal integer you want to convert. If number is negative, + * @Deprecated 1.17.0 + * + * @see Use the toBinary() method in the Engineering\ConvertDecimal class instead + * + * @param mixed $x The decimal integer you want to convert. If number is negative, * valid place values are ignored and DEC2BIN returns a 10-character * (10-bit) binary number in which the most significant bit is the sign * bit. The remaining 9 bits are magnitude bits. Negative numbers are @@ -1223,7 +256,7 @@ class Engineering * If number is nonnumeric, DEC2BIN returns the #VALUE! error value. * If DEC2BIN requires more than places characters, it returns the #NUM! * error value. - * @param int $places The number of characters to use. If places is omitted, DEC2BIN uses + * @param mixed $places The number of characters to use. If places is omitted, DEC2BIN uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. @@ -1234,34 +267,7 @@ class Engineering */ public static function DECTOBIN($x, $places = null) { - $x = Functions::flattenSingleValue($x); - $places = Functions::flattenSingleValue($places); - - if (is_bool($x)) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - $x = (int) $x; - } else { - return Functions::VALUE(); - } - } - $x = (string) $x; - if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) { - return Functions::VALUE(); - } - - $x = (string) floor($x); - if ($x < -512 || $x > 511) { - return Functions::NAN(); - } - - $r = decbin($x); - // Two's Complement - $r = substr($r, -10); - if (strlen($r) >= 11) { - return Functions::NAN(); - } - - return self::nbrConversionFormat($r, $places); + return Engineering\ConvertDecimal::toBinary($x, $places); } /** @@ -1272,7 +278,11 @@ class Engineering * Excel Function: * DEC2HEX(x[,places]) * - * @param string $x The decimal integer you want to convert. If number is negative, + * @Deprecated 1.17.0 + * + * @see Use the toHex() method in the Engineering\ConvertDecimal class instead + * + * @param mixed $x The decimal integer you want to convert. If number is negative, * places is ignored and DEC2HEX returns a 10-character (40-bit) * hexadecimal number in which the most significant bit is the sign * bit. The remaining 39 bits are magnitude bits. Negative numbers @@ -1282,7 +292,7 @@ class Engineering * If number is nonnumeric, DEC2HEX returns the #VALUE! error value. * If DEC2HEX requires more than places characters, it returns the * #NUM! error value. - * @param int $places The number of characters to use. If places is omitted, DEC2HEX uses + * @param mixed $places The number of characters to use. If places is omitted, DEC2HEX uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. @@ -1293,28 +303,7 @@ class Engineering */ public static function DECTOHEX($x, $places = null) { - $x = Functions::flattenSingleValue($x); - $places = Functions::flattenSingleValue($places); - - if (is_bool($x)) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - $x = (int) $x; - } else { - return Functions::VALUE(); - } - } - $x = (string) $x; - if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) { - return Functions::VALUE(); - } - $x = (string) floor($x); - $r = strtoupper(dechex($x)); - if (strlen($r) == 8) { - // Two's Complement - $r = 'FF' . $r; - } - - return self::nbrConversionFormat($r, $places); + return Engineering\ConvertDecimal::toHex($x, $places); } /** @@ -1325,7 +314,11 @@ class Engineering * Excel Function: * DEC2OCT(x[,places]) * - * @param string $x The decimal integer you want to convert. If number is negative, + * @Deprecated 1.17.0 + * + * @see Use the toOctal() method in the Engineering\ConvertDecimal class instead + * + * @param mixed $x The decimal integer you want to convert. If number is negative, * places is ignored and DEC2OCT returns a 10-character (30-bit) * octal number in which the most significant bit is the sign bit. * The remaining 29 bits are magnitude bits. Negative numbers are @@ -1335,7 +328,7 @@ class Engineering * If number is nonnumeric, DEC2OCT returns the #VALUE! error value. * If DEC2OCT requires more than places characters, it returns the * #NUM! error value. - * @param int $places The number of characters to use. If places is omitted, DEC2OCT uses + * @param mixed $places The number of characters to use. If places is omitted, DEC2OCT uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. @@ -1346,29 +339,7 @@ class Engineering */ public static function DECTOOCT($x, $places = null) { - $xorig = $x; - $x = Functions::flattenSingleValue($x); - $places = Functions::flattenSingleValue($places); - - if (is_bool($x)) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - $x = (int) $x; - } else { - return Functions::VALUE(); - } - } - $x = (string) $x; - if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) { - return Functions::VALUE(); - } - $x = (string) floor($x); - $r = decoct($x); - if (strlen($r) == 11) { - // Two's Complement - $r = substr($r, -10); - } - - return self::nbrConversionFormat($r, $places); + return Engineering\ConvertDecimal::toOctal($x, $places); } /** @@ -1379,7 +350,11 @@ class Engineering * Excel Function: * HEX2BIN(x[,places]) * - * @param string $x the hexadecimal number you want to convert. + * @Deprecated 1.17.0 + * + * @see Use the toBinary() method in the Engineering\ConvertHex class instead + * + * @param mixed $x the hexadecimal number (as a string) that you want to convert. * Number cannot contain more than 10 characters. * The most significant bit of number is the sign bit (40th bit from the right). * The remaining 9 bits are magnitude bits. @@ -1389,7 +364,7 @@ class Engineering * and if number is positive, it cannot be greater than 1FF. * If number is not a valid hexadecimal number, HEX2BIN returns the #NUM! error value. * If HEX2BIN requires more than places characters, it returns the #NUM! error value. - * @param int $places The number of characters to use. If places is omitted, + * @param mixed $places The number of characters to use. If places is omitted, * HEX2BIN uses the minimum number of characters necessary. Places * is useful for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. @@ -1400,18 +375,7 @@ class Engineering */ public static function HEXTOBIN($x, $places = null) { - $x = Functions::flattenSingleValue($x); - $places = Functions::flattenSingleValue($places); - - if (is_bool($x)) { - return Functions::VALUE(); - } - $x = (string) $x; - if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) { - return Functions::NAN(); - } - - return self::DECTOBIN(self::HEXTODEC($x), $places); + return Engineering\ConvertHex::toBinary($x, $places); } /** @@ -1422,7 +386,11 @@ class Engineering * Excel Function: * HEX2DEC(x) * - * @param string $x The hexadecimal number you want to convert. This number cannot + * @Deprecated 1.17.0 + * + * @see Use the toDecimal() method in the Engineering\ConvertHex class instead + * + * @param mixed $x The hexadecimal number (as a string) that you want to convert. This number cannot * contain more than 10 characters (40 bits). The most significant * bit of number is the sign bit. The remaining 39 bits are magnitude * bits. Negative numbers are represented using two's-complement @@ -1434,33 +402,7 @@ class Engineering */ public static function HEXTODEC($x) { - $x = Functions::flattenSingleValue($x); - - if (is_bool($x)) { - return Functions::VALUE(); - } - $x = (string) $x; - if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) { - return Functions::NAN(); - } - - if (strlen($x) > 10) { - return Functions::NAN(); - } - - $binX = ''; - foreach (str_split($x) as $char) { - $binX .= str_pad(base_convert($char, 16, 2), 4, '0', STR_PAD_LEFT); - } - if (strlen($binX) == 40 && $binX[0] == '1') { - for ($i = 0; $i < 40; ++$i) { - $binX[$i] = ($binX[$i] == '1' ? '0' : '1'); - } - - return (bindec($binX) + 1) * -1; - } - - return bindec($binX); + return Engineering\ConvertHex::toDecimal($x); } /** @@ -1471,7 +413,11 @@ class Engineering * Excel Function: * HEX2OCT(x[,places]) * - * @param string $x The hexadecimal number you want to convert. Number cannot + * @Deprecated 1.17.0 + * + * @see Use the toOctal() method in the Engineering\ConvertHex class instead + * + * @param mixed $x The hexadecimal number (as a string) that you want to convert. Number cannot * contain more than 10 characters. The most significant bit of * number is the sign bit. The remaining 39 bits are magnitude * bits. Negative numbers are represented using two's-complement @@ -1484,7 +430,7 @@ class Engineering * the #NUM! error value. * If HEX2OCT requires more than places characters, it returns * the #NUM! error value. - * @param int $places The number of characters to use. If places is omitted, HEX2OCT + * @param mixed $places The number of characters to use. If places is omitted, HEX2OCT * uses the minimum number of characters necessary. Places is * useful for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. @@ -1496,23 +442,7 @@ class Engineering */ public static function HEXTOOCT($x, $places = null) { - $x = Functions::flattenSingleValue($x); - $places = Functions::flattenSingleValue($places); - - if (is_bool($x)) { - return Functions::VALUE(); - } - $x = (string) $x; - if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) { - return Functions::NAN(); - } - - $decimal = self::HEXTODEC($x); - if ($decimal < -536870912 || $decimal > 536870911) { - return Functions::NAN(); - } - - return self::DECTOOCT($decimal, $places); + return Engineering\ConvertHex::toOctal($x, $places); } /** @@ -1523,7 +453,11 @@ class Engineering * Excel Function: * OCT2BIN(x[,places]) * - * @param string $x The octal number you want to convert. Number may not + * @Deprecated 1.17.0 + * + * @see Use the toBinary() method in the Engineering\ConvertOctal class instead + * + * @param mixed $x The octal number you want to convert. Number may not * contain more than 10 characters. The most significant * bit of number is the sign bit. The remaining 29 bits * are magnitude bits. Negative numbers are represented @@ -1536,7 +470,7 @@ class Engineering * the #NUM! error value. * If OCT2BIN requires more than places characters, it * returns the #NUM! error value. - * @param int $places The number of characters to use. If places is omitted, + * @param mixed $places The number of characters to use. If places is omitted, * OCT2BIN uses the minimum number of characters necessary. * Places is useful for padding the return value with * leading 0s (zeros). @@ -1550,18 +484,7 @@ class Engineering */ public static function OCTTOBIN($x, $places = null) { - $x = Functions::flattenSingleValue($x); - $places = Functions::flattenSingleValue($places); - - if (is_bool($x)) { - return Functions::VALUE(); - } - $x = (string) $x; - if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) { - return Functions::NAN(); - } - - return self::DECTOBIN(self::OCTTODEC($x), $places); + return Engineering\ConvertOctal::toBinary($x, $places); } /** @@ -1572,7 +495,11 @@ class Engineering * Excel Function: * OCT2DEC(x) * - * @param string $x The octal number you want to convert. Number may not contain + * @Deprecated 1.17.0 + * + * @see Use the toDecimal() method in the Engineering\ConvertOctal class instead + * + * @param mixed $x The octal number you want to convert. Number may not contain * more than 10 octal characters (30 bits). The most significant * bit of number is the sign bit. The remaining 29 bits are * magnitude bits. Negative numbers are represented using @@ -1584,28 +511,7 @@ class Engineering */ public static function OCTTODEC($x) { - $x = Functions::flattenSingleValue($x); - - if (is_bool($x)) { - return Functions::VALUE(); - } - $x = (string) $x; - if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) { - return Functions::NAN(); - } - $binX = ''; - foreach (str_split($x) as $char) { - $binX .= str_pad(decbin((int) $char), 3, '0', STR_PAD_LEFT); - } - if (strlen($binX) == 30 && $binX[0] == '1') { - for ($i = 0; $i < 30; ++$i) { - $binX[$i] = ($binX[$i] == '1' ? '0' : '1'); - } - - return (bindec($binX) + 1) * -1; - } - - return bindec($binX); + return Engineering\ConvertOctal::toDecimal($x); } /** @@ -1616,7 +522,11 @@ class Engineering * Excel Function: * OCT2HEX(x[,places]) * - * @param string $x The octal number you want to convert. Number may not contain + * @Deprecated 1.17.0 + * + * @see Use the toHex() method in the Engineering\ConvertOctal class instead + * + * @param mixed $x The octal number you want to convert. Number may not contain * more than 10 octal characters (30 bits). The most significant * bit of number is the sign bit. The remaining 29 bits are * magnitude bits. Negative numbers are represented using @@ -1627,7 +537,7 @@ class Engineering * #NUM! error value. * If OCT2HEX requires more than places characters, it returns * the #NUM! error value. - * @param int $places The number of characters to use. If places is omitted, OCT2HEX + * @param mixed $places The number of characters to use. If places is omitted, OCT2HEX * uses the minimum number of characters necessary. Places is useful * for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. @@ -1638,19 +548,7 @@ class Engineering */ public static function OCTTOHEX($x, $places = null) { - $x = Functions::flattenSingleValue($x); - $places = Functions::flattenSingleValue($places); - - if (is_bool($x)) { - return Functions::VALUE(); - } - $x = (string) $x; - if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) { - return Functions::NAN(); - } - $hexVal = strtoupper(dechex(self::OCTTODEC($x))); - - return self::nbrConversionFormat($hexVal, $places); + return Engineering\ConvertOctal::toHex($x, $places); } /** @@ -1661,6 +559,10 @@ class Engineering * Excel Function: * COMPLEX(realNumber,imaginary[,suffix]) * + * @Deprecated 1.18.0 + * + * @see Use the COMPLEX() method in the Engineering\Complex class instead + * * @param float $realNumber the real coefficient of the complex number * @param float $imaginary the imaginary coefficient of the complex number * @param string $suffix The suffix for the imaginary component of the complex number. @@ -1670,20 +572,7 @@ class Engineering */ public static function COMPLEX($realNumber = 0.0, $imaginary = 0.0, $suffix = 'i') { - $realNumber = ($realNumber === null) ? 0.0 : Functions::flattenSingleValue($realNumber); - $imaginary = ($imaginary === null) ? 0.0 : Functions::flattenSingleValue($imaginary); - $suffix = ($suffix === null) ? 'i' : Functions::flattenSingleValue($suffix); - - if ( - ((is_numeric($realNumber)) && (is_numeric($imaginary))) && - (($suffix == 'i') || ($suffix == 'j') || ($suffix == '')) - ) { - $complex = new Complex($realNumber, $imaginary, $suffix); - - return (string) $complex; - } - - return Functions::VALUE(); + return Engineering\Complex::COMPLEX($realNumber, $imaginary, $suffix); } /** @@ -1694,16 +583,18 @@ class Engineering * Excel Function: * IMAGINARY(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMAGINARY() method in the Engineering\Complex class instead + * * @param string $complexNumber the complex number for which you want the imaginary * coefficient * - * @return float + * @return float|string */ public static function IMAGINARY($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (new Complex($complexNumber))->getImaginary(); + return Engineering\Complex::IMAGINARY($complexNumber); } /** @@ -1714,15 +605,17 @@ class Engineering * Excel Function: * IMREAL(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMREAL() method in the Engineering\Complex class instead + * * @param string $complexNumber the complex number for which you want the real coefficient * - * @return float + * @return float|string */ public static function IMREAL($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (new Complex($complexNumber))->getReal(); + return Engineering\Complex::IMREAL($complexNumber); } /** @@ -1733,15 +626,17 @@ class Engineering * Excel Function: * IMABS(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMABS() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the absolute value * - * @return float + * @return float|string */ public static function IMABS($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (new Complex($complexNumber))->abs(); + return ComplexFunctions::IMABS($complexNumber); } /** @@ -1753,20 +648,17 @@ class Engineering * Excel Function: * IMARGUMENT(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMARGUMENT() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the argument theta * * @return float|string */ public static function IMARGUMENT($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - $complex = new Complex($complexNumber); - if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { - return Functions::DIV0(); - } - - return $complex->argument(); + return ComplexFunctions::IMARGUMENT($complexNumber); } /** @@ -1777,15 +669,17 @@ class Engineering * Excel Function: * IMCONJUGATE(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMARGUMENT() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the conjugate * * @return string */ public static function IMCONJUGATE($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->conjugate(); + return ComplexFunctions::IMCONJUGATE($complexNumber); } /** @@ -1796,15 +690,17 @@ class Engineering * Excel Function: * IMCOS(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMCOS() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the cosine * * @return float|string */ public static function IMCOS($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->cos(); + return ComplexFunctions::IMCOS($complexNumber); } /** @@ -1815,15 +711,17 @@ class Engineering * Excel Function: * IMCOSH(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMCOSH() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the hyperbolic cosine * * @return float|string */ public static function IMCOSH($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->cosh(); + return ComplexFunctions::IMCOSH($complexNumber); } /** @@ -1834,15 +732,17 @@ class Engineering * Excel Function: * IMCOT(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMCOT() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the cotangent * * @return float|string */ public static function IMCOT($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->cot(); + return ComplexFunctions::IMCOT($complexNumber); } /** @@ -1853,15 +753,17 @@ class Engineering * Excel Function: * IMCSC(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMCSC() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the cosecant * * @return float|string */ public static function IMCSC($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->csc(); + return ComplexFunctions::IMCSC($complexNumber); } /** @@ -1872,15 +774,17 @@ class Engineering * Excel Function: * IMCSCH(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMCSCH() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the hyperbolic cosecant * * @return float|string */ public static function IMCSCH($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->csch(); + return ComplexFunctions::IMCSCH($complexNumber); } /** @@ -1891,15 +795,17 @@ class Engineering * Excel Function: * IMSIN(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMSIN() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the sine * * @return float|string */ public static function IMSIN($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->sin(); + return ComplexFunctions::IMSIN($complexNumber); } /** @@ -1910,15 +816,17 @@ class Engineering * Excel Function: * IMSINH(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMSINH() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the hyperbolic sine * * @return float|string */ public static function IMSINH($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->sinh(); + return ComplexFunctions::IMSINH($complexNumber); } /** @@ -1929,15 +837,17 @@ class Engineering * Excel Function: * IMSEC(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMSEC() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the secant * * @return float|string */ public static function IMSEC($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->sec(); + return ComplexFunctions::IMSEC($complexNumber); } /** @@ -1948,15 +858,17 @@ class Engineering * Excel Function: * IMSECH(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMSECH() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the hyperbolic secant * * @return float|string */ public static function IMSECH($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->sech(); + return ComplexFunctions::IMSECH($complexNumber); } /** @@ -1967,15 +879,17 @@ class Engineering * Excel Function: * IMTAN(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMTAN() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the tangent * * @return float|string */ public static function IMTAN($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->tan(); + return ComplexFunctions::IMTAN($complexNumber); } /** @@ -1986,20 +900,17 @@ class Engineering * Excel Function: * IMSQRT(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMSQRT() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the square root * * @return string */ public static function IMSQRT($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - $theta = self::IMARGUMENT($complexNumber); - if ($theta === Functions::DIV0()) { - return '0'; - } - - return (string) (new Complex($complexNumber))->sqrt(); + return ComplexFunctions::IMSQRT($complexNumber); } /** @@ -2010,20 +921,17 @@ class Engineering * Excel Function: * IMLN(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMLN() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the natural logarithm * * @return string */ public static function IMLN($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - $complex = new Complex($complexNumber); - if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { - return Functions::NAN(); - } - - return (string) (new Complex($complexNumber))->ln(); + return ComplexFunctions::IMLN($complexNumber); } /** @@ -2034,20 +942,17 @@ class Engineering * Excel Function: * IMLOG10(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMLOG10() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the common logarithm * * @return string */ public static function IMLOG10($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - $complex = new Complex($complexNumber); - if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { - return Functions::NAN(); - } - - return (string) (new Complex($complexNumber))->log10(); + return ComplexFunctions::IMLOG10($complexNumber); } /** @@ -2058,20 +963,17 @@ class Engineering * Excel Function: * IMLOG2(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMLOG2() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the base-2 logarithm * * @return string */ public static function IMLOG2($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - $complex = new Complex($complexNumber); - if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { - return Functions::NAN(); - } - - return (string) (new Complex($complexNumber))->log2(); + return ComplexFunctions::IMLOG2($complexNumber); } /** @@ -2082,15 +984,17 @@ class Engineering * Excel Function: * IMEXP(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMEXP() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the exponential * * @return string */ public static function IMEXP($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->exp(); + return ComplexFunctions::IMEXP($complexNumber); } /** @@ -2101,6 +1005,10 @@ class Engineering * Excel Function: * IMPOWER(complexNumber,realNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMPOWER() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number you want to raise to a power * @param float $realNumber the power to which you want to raise the complex number * @@ -2108,14 +1016,7 @@ class Engineering */ public static function IMPOWER($complexNumber, $realNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - $realNumber = Functions::flattenSingleValue($realNumber); - - if (!is_numeric($realNumber)) { - return Functions::VALUE(); - } - - return (string) (new Complex($complexNumber))->pow($realNumber); + return ComplexFunctions::IMPOWER($complexNumber, $realNumber); } /** @@ -2126,6 +1027,10 @@ class Engineering * Excel Function: * IMDIV(complexDividend,complexDivisor) * + * @Deprecated 1.18.0 + * + * @see Use the IMDIV() method in the Engineering\ComplexOperations class instead + * * @param string $complexDividend the complex numerator or dividend * @param string $complexDivisor the complex denominator or divisor * @@ -2133,14 +1038,7 @@ class Engineering */ public static function IMDIV($complexDividend, $complexDivisor) { - $complexDividend = Functions::flattenSingleValue($complexDividend); - $complexDivisor = Functions::flattenSingleValue($complexDivisor); - - try { - return (string) (new Complex($complexDividend))->divideby(new Complex($complexDivisor)); - } catch (ComplexException $e) { - return Functions::NAN(); - } + return ComplexOperations::IMDIV($complexDividend, $complexDivisor); } /** @@ -2151,6 +1049,10 @@ class Engineering * Excel Function: * IMSUB(complexNumber1,complexNumber2) * + * @Deprecated 1.18.0 + * + * @see Use the IMSUB() method in the Engineering\ComplexOperations class instead + * * @param string $complexNumber1 the complex number from which to subtract complexNumber2 * @param string $complexNumber2 the complex number to subtract from complexNumber1 * @@ -2158,14 +1060,7 @@ class Engineering */ public static function IMSUB($complexNumber1, $complexNumber2) { - $complexNumber1 = Functions::flattenSingleValue($complexNumber1); - $complexNumber2 = Functions::flattenSingleValue($complexNumber2); - - try { - return (string) (new Complex($complexNumber1))->subtract(new Complex($complexNumber2)); - } catch (ComplexException $e) { - return Functions::NAN(); - } + return ComplexOperations::IMSUB($complexNumber1, $complexNumber2); } /** @@ -2176,26 +1071,17 @@ class Engineering * Excel Function: * IMSUM(complexNumber[,complexNumber[,...]]) * + * @Deprecated 1.18.0 + * + * @see Use the IMSUM() method in the Engineering\ComplexOperations class instead + * * @param string ...$complexNumbers Series of complex numbers to add * * @return string */ public static function IMSUM(...$complexNumbers) { - // Return value - $returnValue = new Complex(0.0); - $aArgs = Functions::flattenArray($complexNumbers); - - try { - // Loop through the arguments - foreach ($aArgs as $complex) { - $returnValue = $returnValue->add(new Complex($complex)); - } - } catch (ComplexException $e) { - return Functions::NAN(); - } - - return (string) $returnValue; + return ComplexOperations::IMSUM(...$complexNumbers); } /** @@ -2206,50 +1092,42 @@ class Engineering * Excel Function: * IMPRODUCT(complexNumber[,complexNumber[,...]]) * + * @Deprecated 1.18.0 + * + * @see Use the IMPRODUCT() method in the Engineering\ComplexOperations class instead + * * @param string ...$complexNumbers Series of complex numbers to multiply * * @return string */ public static function IMPRODUCT(...$complexNumbers) { - // Return value - $returnValue = new Complex(1.0); - $aArgs = Functions::flattenArray($complexNumbers); - - try { - // Loop through the arguments - foreach ($aArgs as $complex) { - $returnValue = $returnValue->multiply(new Complex($complex)); - } - } catch (ComplexException $e) { - return Functions::NAN(); - } - - return (string) $returnValue; + return ComplexOperations::IMPRODUCT(...$complexNumbers); } /** * DELTA. * * Tests whether two values are equal. Returns 1 if number1 = number2; returns 0 otherwise. - * Use this function to filter a set of values. For example, by summing several DELTA - * functions you calculate the count of equal pairs. This function is also known as the - * Kronecker Delta function. + * Use this function to filter a set of values. For example, by summing several DELTA + * functions you calculate the count of equal pairs. This function is also known as the + * Kronecker Delta function. * * Excel Function: * DELTA(a[,b]) * + * @Deprecated 1.17.0 + * + * @see Use the DELTA() method in the Engineering\Compare class instead + * * @param float $a the first number * @param float $b The second number. If omitted, b is assumed to be zero. * - * @return int + * @return int|string (string in the event of an error) */ public static function DELTA($a, $b = 0) { - $a = Functions::flattenSingleValue($a); - $b = Functions::flattenSingleValue($b); - - return (int) ($a == $b); + return Engineering\Compare::DELTA($a, $b); } /** @@ -2260,77 +1138,20 @@ class Engineering * * Returns 1 if number >= step; returns 0 (zero) otherwise * Use this function to filter a set of values. For example, by summing several GESTEP - * functions you calculate the count of values that exceed a threshold. + * functions you calculate the count of values that exceed a threshold. + * + * @Deprecated 1.17.0 + * + * @see Use the GESTEP() method in the Engineering\Compare class instead * * @param float $number the value to test against step - * @param float $step The threshold value. - * If you omit a value for step, GESTEP uses zero. + * @param float $step The threshold value. If you omit a value for step, GESTEP uses zero. * - * @return int + * @return int|string (string in the event of an error) */ public static function GESTEP($number, $step = 0) { - $number = Functions::flattenSingleValue($number); - $step = Functions::flattenSingleValue($step); - - return (int) ($number >= $step); - } - - // - // Private method to calculate the erf value - // - private static $twoSqrtPi = 1.128379167095512574; - - public static function erfVal($x) - { - if (abs($x) > 2.2) { - return 1 - self::erfcVal($x); - } - $sum = $term = $x; - $xsqr = ($x * $x); - $j = 1; - do { - $term *= $xsqr / $j; - $sum -= $term / (2 * $j + 1); - ++$j; - $term *= $xsqr / $j; - $sum += $term / (2 * $j + 1); - ++$j; - if ($sum == 0.0) { - break; - } - } while (abs($term / $sum) > Functions::PRECISION); - - return self::$twoSqrtPi * $sum; - } - - /** - * Validate arguments passed to the bitwise functions. - * - * @param mixed $value - * - * @return int - */ - private static function validateBitwiseArgument($value) - { - $value = Functions::flattenSingleValue($value); - - if (is_int($value)) { - return $value; - } elseif (is_numeric($value)) { - if ($value == (int) ($value)) { - $value = (int) ($value); - if (($value > 2 ** 48 - 1) || ($value < 0)) { - throw new Exception(Functions::NAN()); - } - - return $value; - } - - throw new Exception(Functions::NAN()); - } - - throw new Exception(Functions::VALUE()); + return Engineering\Compare::GESTEP($number, $step); } /** @@ -2341,6 +1162,10 @@ class Engineering * Excel Function: * BITAND(number1, number2) * + * @Deprecated 1.17.0 + * + * @see Use the BITAND() method in the Engineering\BitWise class instead + * * @param int $number1 * @param int $number2 * @@ -2348,14 +1173,7 @@ class Engineering */ public static function BITAND($number1, $number2) { - try { - $number1 = self::validateBitwiseArgument($number1); - $number2 = self::validateBitwiseArgument($number2); - } catch (Exception $e) { - return $e->getMessage(); - } - - return $number1 & $number2; + return Engineering\BitWise::BITAND($number1, $number2); } /** @@ -2366,6 +1184,10 @@ class Engineering * Excel Function: * BITOR(number1, number2) * + * @Deprecated 1.17.0 + * + * @see Use the BITOR() method in the Engineering\BitWise class instead + * * @param int $number1 * @param int $number2 * @@ -2373,14 +1195,7 @@ class Engineering */ public static function BITOR($number1, $number2) { - try { - $number1 = self::validateBitwiseArgument($number1); - $number2 = self::validateBitwiseArgument($number2); - } catch (Exception $e) { - return $e->getMessage(); - } - - return $number1 | $number2; + return Engineering\BitWise::BITOR($number1, $number2); } /** @@ -2391,6 +1206,10 @@ class Engineering * Excel Function: * BITXOR(number1, number2) * + * @Deprecated 1.17.0 + * + * @see Use the BITXOR() method in the Engineering\BitWise class instead + * * @param int $number1 * @param int $number2 * @@ -2398,14 +1217,7 @@ class Engineering */ public static function BITXOR($number1, $number2) { - try { - $number1 = self::validateBitwiseArgument($number1); - $number2 = self::validateBitwiseArgument($number2); - } catch (Exception $e) { - return $e->getMessage(); - } - - return $number1 ^ $number2; + return Engineering\BitWise::BITXOR($number1, $number2); } /** @@ -2416,6 +1228,10 @@ class Engineering * Excel Function: * BITLSHIFT(number, shift_amount) * + * @Deprecated 1.17.0 + * + * @see Use the BITLSHIFT() method in the Engineering\BitWise class instead + * * @param int $number * @param int $shiftAmount * @@ -2423,20 +1239,7 @@ class Engineering */ public static function BITLSHIFT($number, $shiftAmount) { - try { - $number = self::validateBitwiseArgument($number); - } catch (Exception $e) { - return $e->getMessage(); - } - - $shiftAmount = Functions::flattenSingleValue($shiftAmount); - - $result = $number << $shiftAmount; - if ($result > 2 ** 48 - 1) { - return Functions::NAN(); - } - - return $result; + return Engineering\BitWise::BITLSHIFT($number, $shiftAmount); } /** @@ -2447,6 +1250,10 @@ class Engineering * Excel Function: * BITRSHIFT(number, shift_amount) * + * @Deprecated 1.17.0 + * + * @see Use the BITRSHIFT() method in the Engineering\BitWise class instead + * * @param int $number * @param int $shiftAmount * @@ -2454,15 +1261,7 @@ class Engineering */ public static function BITRSHIFT($number, $shiftAmount) { - try { - $number = self::validateBitwiseArgument($number); - } catch (Exception $e) { - return $e->getMessage(); - } - - $shiftAmount = Functions::flattenSingleValue($shiftAmount); - - return $number >> $shiftAmount; + return Engineering\BitWise::BITRSHIFT($number, $shiftAmount); } /** @@ -2478,6 +1277,10 @@ class Engineering * Excel Function: * ERF(lower[,upper]) * + * @Deprecated 1.17.0 + * + * @see Use the ERF() method in the Engineering\Erf class instead + * * @param float $lower lower bound for integrating ERF * @param float $upper upper bound for integrating ERF. * If omitted, ERF integrates between zero and lower_limit @@ -2486,19 +1289,7 @@ class Engineering */ public static function ERF($lower, $upper = null) { - $lower = Functions::flattenSingleValue($lower); - $upper = Functions::flattenSingleValue($upper); - - if (is_numeric($lower)) { - if ($upper === null) { - return self::erfVal($lower); - } - if (is_numeric($upper)) { - return self::erfVal($upper) - self::erfVal($lower); - } - } - - return Functions::VALUE(); + return Engineering\Erf::ERF($lower, $upper); } /** @@ -2509,48 +1300,17 @@ class Engineering * Excel Function: * ERF.PRECISE(limit) * + * @Deprecated 1.17.0 + * + * @see Use the ERFPRECISE() method in the Engineering\Erf class instead + * * @param float $limit bound for integrating ERF * * @return float|string */ public static function ERFPRECISE($limit) { - $limit = Functions::flattenSingleValue($limit); - - return self::ERF($limit); - } - - // - // Private method to calculate the erfc value - // - private static $oneSqrtPi = 0.564189583547756287; - - private static function erfcVal($x) - { - if (abs($x) < 2.2) { - return 1 - self::erfVal($x); - } - if ($x < 0) { - return 2 - self::ERFC(-$x); - } - $a = $n = 1; - $b = $c = $x; - $d = ($x * $x) + 0.5; - $q1 = $q2 = $b / $d; - $t = 0; - do { - $t = $a * $n + $b * $x; - $a = $b; - $b = $t; - $t = $c * $n + $d * $x; - $c = $d; - $d = $t; - $n += 0.5; - $q1 = $q2; - $q2 = $b / $d; - } while ((abs($q1 - $q2) / $q2) > Functions::PRECISION); - - return self::$oneSqrtPi * exp(-$x * $x) * $q2; + return Engineering\Erf::ERFPRECISE($limit); } /** @@ -2566,88 +1326,97 @@ class Engineering * Excel Function: * ERFC(x) * + * @Deprecated 1.17.0 + * + * @see Use the ERFC() method in the Engineering\ErfC class instead + * * @param float $x The lower bound for integrating ERFC * * @return float|string */ public static function ERFC($x) { - $x = Functions::flattenSingleValue($x); - - if (is_numeric($x)) { - return self::erfcVal($x); - } - - return Functions::VALUE(); + return Engineering\ErfC::ERFC($x); } /** * getConversionGroups * Returns a list of the different conversion groups for UOM conversions. * + * @Deprecated 1.16.0 + * + * @see Use the getConversionCategories() method in the Engineering\ConvertUOM class instead + * * @return array */ public static function getConversionGroups() { - $conversionGroups = []; - foreach (self::$conversionUnits as $conversionUnit) { - $conversionGroups[] = $conversionUnit['Group']; - } - - return array_merge(array_unique($conversionGroups)); + return Engineering\ConvertUOM::getConversionCategories(); } /** * getConversionGroupUnits * Returns an array of units of measure, for a specified conversion group, or for all groups. * - * @param string $group The group whose units of measure you want to retrieve + * @Deprecated 1.16.0 + * + * @see Use the getConversionCategoryUnits() method in the ConvertUOM class instead + * + * @param null|mixed $category * * @return array */ - public static function getConversionGroupUnits($group = null) + public static function getConversionGroupUnits($category = null) { - $conversionGroups = []; - foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) { - if (($group === null) || ($conversionGroup['Group'] == $group)) { - $conversionGroups[$conversionGroup['Group']][] = $conversionUnit; - } - } - - return $conversionGroups; + return Engineering\ConvertUOM::getConversionCategoryUnits($category); } /** * getConversionGroupUnitDetails. * - * @param string $group The group whose units of measure you want to retrieve + * @Deprecated 1.16.0 + * + * @see Use the getConversionCategoryUnitDetails() method in the ConvertUOM class instead + * + * @param null|mixed $category * * @return array */ - public static function getConversionGroupUnitDetails($group = null) + public static function getConversionGroupUnitDetails($category = null) { - $conversionGroups = []; - foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) { - if (($group === null) || ($conversionGroup['Group'] == $group)) { - $conversionGroups[$conversionGroup['Group']][] = [ - 'unit' => $conversionUnit, - 'description' => $conversionGroup['Unit Name'], - ]; - } - } - - return $conversionGroups; + return Engineering\ConvertUOM::getConversionCategoryUnitDetails($category); } /** * getConversionMultipliers * Returns an array of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM(). * - * @return array of mixed + * @Deprecated 1.16.0 + * + * @see Use the getConversionMultipliers() method in the ConvertUOM class instead + * + * @return mixed[] */ public static function getConversionMultipliers() { - return self::$conversionMultipliers; + return Engineering\ConvertUOM::getConversionMultipliers(); + } + + /** + * getBinaryConversionMultipliers. + * + * Returns an array of the additional Multiplier prefixes that can be used with Information Units of Measure + * in CONVERTUOM(). + * + * @Deprecated 1.16.0 + * + * @see Use the getBinaryConversionMultipliers() method in the ConvertUOM class instead + * + * @return mixed[] + */ + public static function getBinaryConversionMultipliers() + { + return Engineering\ConvertUOM::getBinaryConversionMultipliers(); } /** @@ -2660,7 +1429,11 @@ class Engineering * Excel Function: * CONVERT(value,fromUOM,toUOM) * - * @param float $value the value in fromUOM to convert + * @Deprecated 1.16.0 + * + * @see Use the CONVERT() method in the ConvertUOM class instead + * + * @param float|int $value the value in fromUOM to convert * @param string $fromUOM the units for value * @param string $toUOM the units for the result * @@ -2668,93 +1441,6 @@ class Engineering */ public static function CONVERTUOM($value, $fromUOM, $toUOM) { - $value = Functions::flattenSingleValue($value); - $fromUOM = Functions::flattenSingleValue($fromUOM); - $toUOM = Functions::flattenSingleValue($toUOM); - - if (!is_numeric($value)) { - return Functions::VALUE(); - } - $fromMultiplier = 1.0; - if (isset(self::$conversionUnits[$fromUOM])) { - $unitGroup1 = self::$conversionUnits[$fromUOM]['Group']; - } else { - $fromMultiplier = substr($fromUOM, 0, 1); - $fromUOM = substr($fromUOM, 1); - if (isset(self::$conversionMultipliers[$fromMultiplier])) { - $fromMultiplier = self::$conversionMultipliers[$fromMultiplier]['multiplier']; - } else { - return Functions::NA(); - } - if ((isset(self::$conversionUnits[$fromUOM])) && (self::$conversionUnits[$fromUOM]['AllowPrefix'])) { - $unitGroup1 = self::$conversionUnits[$fromUOM]['Group']; - } else { - return Functions::NA(); - } - } - $value *= $fromMultiplier; - - $toMultiplier = 1.0; - if (isset(self::$conversionUnits[$toUOM])) { - $unitGroup2 = self::$conversionUnits[$toUOM]['Group']; - } else { - $toMultiplier = substr($toUOM, 0, 1); - $toUOM = substr($toUOM, 1); - if (isset(self::$conversionMultipliers[$toMultiplier])) { - $toMultiplier = self::$conversionMultipliers[$toMultiplier]['multiplier']; - } else { - return Functions::NA(); - } - if ((isset(self::$conversionUnits[$toUOM])) && (self::$conversionUnits[$toUOM]['AllowPrefix'])) { - $unitGroup2 = self::$conversionUnits[$toUOM]['Group']; - } else { - return Functions::NA(); - } - } - if ($unitGroup1 != $unitGroup2) { - return Functions::NA(); - } - - if (($fromUOM == $toUOM) && ($fromMultiplier == $toMultiplier)) { - // We've already factored $fromMultiplier into the value, so we need - // to reverse it again - return $value / $fromMultiplier; - } elseif ($unitGroup1 == 'Temperature') { - if (($fromUOM == 'F') || ($fromUOM == 'fah')) { - if (($toUOM == 'F') || ($toUOM == 'fah')) { - return $value; - } - $value = (($value - 32) / 1.8); - if (($toUOM == 'K') || ($toUOM == 'kel')) { - $value += 273.15; - } - - return $value; - } elseif ( - (($fromUOM == 'K') || ($fromUOM == 'kel')) && - (($toUOM == 'K') || ($toUOM == 'kel')) - ) { - return $value; - } elseif ( - (($fromUOM == 'C') || ($fromUOM == 'cel')) && - (($toUOM == 'C') || ($toUOM == 'cel')) - ) { - return $value; - } - if (($toUOM == 'F') || ($toUOM == 'fah')) { - if (($fromUOM == 'K') || ($fromUOM == 'kel')) { - $value -= 273.15; - } - - return ($value * 1.8) + 32; - } - if (($toUOM == 'C') || ($toUOM == 'cel')) { - return $value - 273.15; - } - - return $value + 273.15; - } - - return ($value * self::$unitConversions[$unitGroup1][$fromUOM][$toUOM]) / $toMultiplier; + return Engineering\ConvertUOM::CONVERT($value, $fromUOM, $toUOM); } } diff --git a/src/PhpSpreadsheet/Calculation/Engineering/BesselI.php b/src/PhpSpreadsheet/Calculation/Engineering/BesselI.php new file mode 100644 index 00000000..ea2577cd --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Engineering/BesselI.php @@ -0,0 +1,137 @@ +getMessage(); + } + + if ($ord < 0) { + return Functions::NAN(); + } + + $fResult = self::calculate($x, $ord); + + return (is_nan($fResult)) ? Functions::NAN() : $fResult; + } + + private static function calculate(float $x, int $ord): float + { + // special cases + switch ($ord) { + case 0: + return self::besselI0($x); + case 1: + return self::besselI1($x); + } + + return self::besselI2($x, $ord); + } + + private static function besselI0(float $x): float + { + $ax = abs($x); + + if ($ax < 3.75) { + $y = $x / 3.75; + $y = $y * $y; + + return 1.0 + $y * (3.5156229 + $y * (3.0899424 + $y * (1.2067492 + + $y * (0.2659732 + $y * (0.360768e-1 + $y * 0.45813e-2))))); + } + + $y = 3.75 / $ax; + + return (exp($ax) / sqrt($ax)) * (0.39894228 + $y * (0.1328592e-1 + $y * (0.225319e-2 + $y * (-0.157565e-2 + + $y * (0.916281e-2 + $y * (-0.2057706e-1 + $y * (0.2635537e-1 + + $y * (-0.1647633e-1 + $y * 0.392377e-2)))))))); + } + + private static function besselI1(float $x): float + { + $ax = abs($x); + + if ($ax < 3.75) { + $y = $x / 3.75; + $y = $y * $y; + $ans = $ax * (0.5 + $y * (0.87890594 + $y * (0.51498869 + $y * (0.15084934 + $y * (0.2658733e-1 + + $y * (0.301532e-2 + $y * 0.32411e-3)))))); + + return ($x < 0.0) ? -$ans : $ans; + } + + $y = 3.75 / $ax; + $ans = 0.2282967e-1 + $y * (-0.2895312e-1 + $y * (0.1787654e-1 - $y * 0.420059e-2)); + $ans = 0.39894228 + $y * (-0.3988024e-1 + $y * (-0.362018e-2 + $y * (0.163801e-2 + + $y * (-0.1031555e-1 + $y * $ans)))); + $ans *= exp($ax) / sqrt($ax); + + return ($x < 0.0) ? -$ans : $ans; + } + + private static function besselI2(float $x, int $ord): float + { + if ($x === 0.0) { + return 0.0; + } + + $tox = 2.0 / abs($x); + $bip = 0; + $ans = 0.0; + $bi = 1.0; + + for ($j = 2 * ($ord + (int) sqrt(40.0 * $ord)); $j > 0; --$j) { + $bim = $bip + $j * $tox * $bi; + $bip = $bi; + $bi = $bim; + + if (abs($bi) > 1.0e+12) { + $ans *= 1.0e-12; + $bi *= 1.0e-12; + $bip *= 1.0e-12; + } + + if ($j === $ord) { + $ans = $bip; + } + } + + $ans *= self::besselI0($x) / $bi; + + return ($x < 0.0 && (($ord % 2) === 1)) ? -$ans : $ans; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Engineering/BesselJ.php b/src/PhpSpreadsheet/Calculation/Engineering/BesselJ.php new file mode 100644 index 00000000..7ea45a74 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Engineering/BesselJ.php @@ -0,0 +1,172 @@ + 8. This code provides a more accurate calculation + * + * @param mixed $x A float value at which to evaluate the function. + * If x is nonnumeric, BESSELJ returns the #VALUE! error value. + * @param mixed $ord The integer order of the Bessel function. + * If ord is not an integer, it is truncated. + * If $ord is nonnumeric, BESSELJ returns the #VALUE! error value. + * If $ord < 0, BESSELJ returns the #NUM! error value. + * + * @return float|string Result, or a string containing an error + */ + public static function BESSELJ($x, $ord) + { + $x = Functions::flattenSingleValue($x); + $ord = Functions::flattenSingleValue($ord); + + try { + $x = EngineeringValidations::validateFloat($x); + $ord = EngineeringValidations::validateInt($ord); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($ord < 0) { + return Functions::NAN(); + } + + $fResult = self::calculate($x, $ord); + + return (is_nan($fResult)) ? Functions::NAN() : $fResult; + } + + private static function calculate(float $x, int $ord): float + { + // special cases + switch ($ord) { + case 0: + return self::besselJ0($x); + case 1: + return self::besselJ1($x); + } + + return self::besselJ2($x, $ord); + } + + private static function besselJ0(float $x): float + { + $ax = abs($x); + + if ($ax < 8.0) { + $y = $x * $x; + $ans1 = 57568490574.0 + $y * (-13362590354.0 + $y * (651619640.7 + $y * (-11214424.18 + $y * + (77392.33017 + $y * (-184.9052456))))); + $ans2 = 57568490411.0 + $y * (1029532985.0 + $y * (9494680.718 + $y * (59272.64853 + $y * + (267.8532712 + $y * 1.0)))); + + return $ans1 / $ans2; + } + + $z = 8.0 / $ax; + $y = $z * $z; + $xx = $ax - 0.785398164; + $ans1 = 1.0 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6))); + $ans2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * + (0.7621095161e-6 - $y * 0.934935152e-7))); + + return sqrt(0.636619772 / $ax) * (cos($xx) * $ans1 - $z * sin($xx) * $ans2); + } + + private static function besselJ1(float $x): float + { + $ax = abs($x); + + if ($ax < 8.0) { + $y = $x * $x; + $ans1 = $x * (72362614232.0 + $y * (-7895059235.0 + $y * (242396853.1 + $y * + (-2972611.439 + $y * (15704.48260 + $y * (-30.16036606)))))); + $ans2 = 144725228442.0 + $y * (2300535178.0 + $y * (18583304.74 + $y * (99447.43394 + $y * + (376.9991397 + $y * 1.0)))); + + return $ans1 / $ans2; + } + + $z = 8.0 / $ax; + $y = $z * $z; + $xx = $ax - 2.356194491; + + $ans1 = 1.0 + $y * (0.183105e-2 + $y * (-0.3516396496e-4 + $y * (0.2457520174e-5 + $y * (-0.240337019e-6)))); + $ans2 = 0.04687499995 + $y * (-0.2002690873e-3 + $y * (0.8449199096e-5 + $y * + (-0.88228987e-6 + $y * 0.105787412e-6))); + $ans = sqrt(0.636619772 / $ax) * (cos($xx) * $ans1 - $z * sin($xx) * $ans2); + + return ($x < 0.0) ? -$ans : $ans; + } + + private static function besselJ2(float $x, int $ord): float + { + $ax = abs($x); + if ($ax === 0.0) { + return 0.0; + } + + if ($ax > $ord) { + return self::besselj2a($ax, $ord, $x); + } + + return self::besselj2b($ax, $ord, $x); + } + + private static function besselj2a(float $ax, int $ord, float $x) + { + $tox = 2.0 / $ax; + $bjm = self::besselJ0($ax); + $bj = self::besselJ1($ax); + for ($j = 1; $j < $ord; ++$j) { + $bjp = $j * $tox * $bj - $bjm; + $bjm = $bj; + $bj = $bjp; + } + $ans = $bj; + + return ($x < 0.0 && ($ord % 2) == 1) ? -$ans : $ans; + } + + private static function besselj2b(float $ax, int $ord, float $x) + { + $tox = 2.0 / $ax; + $jsum = false; + $bjp = $ans = $sum = 0.0; + $bj = 1.0; + for ($j = 2 * ($ord + (int) sqrt(40.0 * $ord)); $j > 0; --$j) { + $bjm = $j * $tox * $bj - $bjp; + $bjp = $bj; + $bj = $bjm; + if (abs($bj) > 1.0e+10) { + $bj *= 1.0e-10; + $bjp *= 1.0e-10; + $ans *= 1.0e-10; + $sum *= 1.0e-10; + } + if ($jsum === true) { + $sum += $bj; + } + $jsum = !$jsum; + if ($j === $ord) { + $ans = $bjp; + } + } + $sum = 2.0 * $sum - $bj; + $ans /= $sum; + + return ($x < 0.0 && ($ord % 2) === 1) ? -$ans : $ans; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Engineering/BesselK.php b/src/PhpSpreadsheet/Calculation/Engineering/BesselK.php new file mode 100644 index 00000000..8facdffc --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Engineering/BesselK.php @@ -0,0 +1,111 @@ +getMessage(); + } + + if (($ord < 0) || ($x <= 0.0)) { + return Functions::NAN(); + } + + $fBk = self::calculate($x, $ord); + + return (is_nan($fBk)) ? Functions::NAN() : $fBk; + } + + private static function calculate(float $x, int $ord): float + { + // special cases + switch ($ord) { + case 0: + return self::besselK0($x); + case 1: + return self::besselK1($x); + } + + return self::besselK2($x, $ord); + } + + private static function besselK0(float $x): float + { + if ($x <= 2) { + $fNum2 = $x * 0.5; + $y = ($fNum2 * $fNum2); + + return -log($fNum2) * BesselI::BESSELI($x, 0) + + (-0.57721566 + $y * (0.42278420 + $y * (0.23069756 + $y * (0.3488590e-1 + $y * (0.262698e-2 + $y * + (0.10750e-3 + $y * 0.74e-5)))))); + } + + $y = 2 / $x; + + return exp(-$x) / sqrt($x) * + (1.25331414 + $y * (-0.7832358e-1 + $y * (0.2189568e-1 + $y * (-0.1062446e-1 + $y * + (0.587872e-2 + $y * (-0.251540e-2 + $y * 0.53208e-3)))))); + } + + private static function besselK1(float $x): float + { + if ($x <= 2) { + $fNum2 = $x * 0.5; + $y = ($fNum2 * $fNum2); + + return log($fNum2) * BesselI::BESSELI($x, 1) + + (1 + $y * (0.15443144 + $y * (-0.67278579 + $y * (-0.18156897 + $y * (-0.1919402e-1 + $y * + (-0.110404e-2 + $y * (-0.4686e-4))))))) / $x; + } + + $y = 2 / $x; + + return exp(-$x) / sqrt($x) * + (1.25331414 + $y * (0.23498619 + $y * (-0.3655620e-1 + $y * (0.1504268e-1 + $y * (-0.780353e-2 + $y * + (0.325614e-2 + $y * (-0.68245e-3))))))); + } + + private static function besselK2(float $x, int $ord) + { + $fTox = 2 / $x; + $fBkm = self::besselK0($x); + $fBk = self::besselK1($x); + for ($n = 1; $n < $ord; ++$n) { + $fBkp = $fBkm + $n * $fTox * $fBk; + $fBkm = $fBk; + $fBk = $fBkp; + } + + return $fBk; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Engineering/BesselY.php b/src/PhpSpreadsheet/Calculation/Engineering/BesselY.php new file mode 100644 index 00000000..7f387497 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Engineering/BesselY.php @@ -0,0 +1,118 @@ +getMessage(); + } + + if (($ord < 0) || ($x <= 0.0)) { + return Functions::NAN(); + } + + $fBy = self::calculate($x, $ord); + + return (is_nan($fBy)) ? Functions::NAN() : $fBy; + } + + private static function calculate(float $x, int $ord): float + { + // special cases + switch ($ord) { + case 0: + return self::besselY0($x); + case 1: + return self::besselY1($x); + } + + return self::besselY2($x, $ord); + } + + private static function besselY0(float $x): float + { + if ($x < 8.0) { + $y = ($x * $x); + $ans1 = -2957821389.0 + $y * (7062834065.0 + $y * (-512359803.6 + $y * (10879881.29 + $y * + (-86327.92757 + $y * 228.4622733)))); + $ans2 = 40076544269.0 + $y * (745249964.8 + $y * (7189466.438 + $y * + (47447.26470 + $y * (226.1030244 + $y)))); + + return $ans1 / $ans2 + 0.636619772 * BesselJ::BESSELJ($x, 0) * log($x); + } + + $z = 8.0 / $x; + $y = ($z * $z); + $xx = $x - 0.785398164; + $ans1 = 1 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6))); + $ans2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 + $y * + (-0.934945152e-7)))); + + return sqrt(0.636619772 / $x) * (sin($xx) * $ans1 + $z * cos($xx) * $ans2); + } + + private static function besselY1(float $x): float + { + if ($x < 8.0) { + $y = ($x * $x); + $ans1 = $x * (-0.4900604943e13 + $y * (0.1275274390e13 + $y * (-0.5153438139e11 + $y * + (0.7349264551e9 + $y * (-0.4237922726e7 + $y * 0.8511937935e4))))); + $ans2 = 0.2499580570e14 + $y * (0.4244419664e12 + $y * (0.3733650367e10 + $y * (0.2245904002e8 + $y * + (0.1020426050e6 + $y * (0.3549632885e3 + $y))))); + + return ($ans1 / $ans2) + 0.636619772 * (BesselJ::BESSELJ($x, 1) * log($x) - 1 / $x); + } + + $z = 8.0 / $x; + $y = $z * $z; + $xx = $x - 2.356194491; + $ans1 = 1.0 + $y * (0.183105e-2 + $y * (-0.3516396496e-4 + $y * (0.2457520174e-5 + $y * (-0.240337019e-6)))); + $ans2 = 0.04687499995 + $y * (-0.2002690873e-3 + $y * (0.8449199096e-5 + $y * + (-0.88228987e-6 + $y * 0.105787412e-6))); + + return sqrt(0.636619772 / $x) * (sin($xx) * $ans1 + $z * cos($xx) * $ans2); + } + + private static function besselY2(float $x, int $ord): float + { + $fTox = 2.0 / $x; + $fBym = self::besselY0($x); + $fBy = self::besselY1($x); + for ($n = 1; $n < $ord; ++$n) { + $fByp = $n * $fTox * $fBy - $fBym; + $fBym = $fBy; + $fBy = $fByp; + } + + return $fBy; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Engineering/BitWise.php b/src/PhpSpreadsheet/Calculation/Engineering/BitWise.php new file mode 100644 index 00000000..9958f054 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Engineering/BitWise.php @@ -0,0 +1,227 @@ +getMessage(); + } + $split1 = self::splitNumber($number1); + $split2 = self::splitNumber($number2); + + return self::SPLIT_DIVISOR * ($split1[0] & $split2[0]) + ($split1[1] & $split2[1]); + } + + /** + * BITOR. + * + * Returns the bitwise OR of two integer values. + * + * Excel Function: + * BITOR(number1, number2) + * + * @param int $number1 + * @param int $number2 + * + * @return int|string + */ + public static function BITOR($number1, $number2) + { + try { + $number1 = self::validateBitwiseArgument($number1); + $number2 = self::validateBitwiseArgument($number2); + } catch (Exception $e) { + return $e->getMessage(); + } + + $split1 = self::splitNumber($number1); + $split2 = self::splitNumber($number2); + + return self::SPLIT_DIVISOR * ($split1[0] | $split2[0]) + ($split1[1] | $split2[1]); + } + + /** + * BITXOR. + * + * Returns the bitwise XOR of two integer values. + * + * Excel Function: + * BITXOR(number1, number2) + * + * @param int $number1 + * @param int $number2 + * + * @return int|string + */ + public static function BITXOR($number1, $number2) + { + try { + $number1 = self::validateBitwiseArgument($number1); + $number2 = self::validateBitwiseArgument($number2); + } catch (Exception $e) { + return $e->getMessage(); + } + + $split1 = self::splitNumber($number1); + $split2 = self::splitNumber($number2); + + return self::SPLIT_DIVISOR * ($split1[0] ^ $split2[0]) + ($split1[1] ^ $split2[1]); + } + + /** + * BITLSHIFT. + * + * Returns the number value shifted left by shift_amount bits. + * + * Excel Function: + * BITLSHIFT(number, shift_amount) + * + * @param int $number + * @param int $shiftAmount + * + * @return float|int|string + */ + public static function BITLSHIFT($number, $shiftAmount) + { + try { + $number = self::validateBitwiseArgument($number); + $shiftAmount = self::validateShiftAmount($shiftAmount); + } catch (Exception $e) { + return $e->getMessage(); + } + + $result = floor($number * (2 ** $shiftAmount)); + if ($result > 2 ** 48 - 1) { + return Functions::NAN(); + } + + return $result; + } + + /** + * BITRSHIFT. + * + * Returns the number value shifted right by shift_amount bits. + * + * Excel Function: + * BITRSHIFT(number, shift_amount) + * + * @param int $number + * @param int $shiftAmount + * + * @return float|int|string + */ + public static function BITRSHIFT($number, $shiftAmount) + { + try { + $number = self::validateBitwiseArgument($number); + $shiftAmount = self::validateShiftAmount($shiftAmount); + } catch (Exception $e) { + return $e->getMessage(); + } + + $result = floor($number / (2 ** $shiftAmount)); + if ($result > 2 ** 48 - 1) { // possible because shiftAmount can be negative + return Functions::NAN(); + } + + return $result; + } + + /** + * Validate arguments passed to the bitwise functions. + * + * @param mixed $value + * + * @return float|int + */ + private static function validateBitwiseArgument($value) + { + self::nullFalseTrueToNumber($value); + + if (is_numeric($value)) { + if ($value == floor($value)) { + if (($value > 2 ** 48 - 1) || ($value < 0)) { + throw new Exception(Functions::NAN()); + } + + return floor($value); + } + + throw new Exception(Functions::NAN()); + } + + throw new Exception(Functions::VALUE()); + } + + /** + * Validate arguments passed to the bitwise functions. + * + * @param mixed $value + * + * @return int + */ + private static function validateShiftAmount($value) + { + self::nullFalseTrueToNumber($value); + + if (is_numeric($value)) { + if (abs($value) > 53) { + throw new Exception(Functions::NAN()); + } + + return (int) $value; + } + + throw new Exception(Functions::VALUE()); + } + + /** + * Many functions accept null/false/true argument treated as 0/0/1. + * + * @param mixed $number + */ + public static function nullFalseTrueToNumber(&$number): void + { + $number = Functions::flattenSingleValue($number); + if ($number === null) { + $number = 0; + } elseif (is_bool($number)) { + $number = (int) $number; + } + } +} diff --git a/src/PhpSpreadsheet/Calculation/Engineering/Compare.php b/src/PhpSpreadsheet/Calculation/Engineering/Compare.php new file mode 100644 index 00000000..0a634206 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Engineering/Compare.php @@ -0,0 +1,70 @@ +getMessage(); + } + + return (int) ($a == $b); + } + + /** + * GESTEP. + * + * Excel Function: + * GESTEP(number[,step]) + * + * Returns 1 if number >= step; returns 0 (zero) otherwise + * Use this function to filter a set of values. For example, by summing several GESTEP + * functions you calculate the count of values that exceed a threshold. + * + * @param float $number the value to test against step + * @param float $step The threshold value. If you omit a value for step, GESTEP uses zero. + * + * @return int|string (string in the event of an error) + */ + public static function GESTEP($number, $step = 0) + { + $number = Functions::flattenSingleValue($number); + $step = Functions::flattenSingleValue($step); + + try { + $number = EngineeringValidations::validateFloat($number); + $step = EngineeringValidations::validateFloat($step); + } catch (Exception $e) { + return $e->getMessage(); + } + + return (int) ($number >= $step); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Engineering/Complex.php b/src/PhpSpreadsheet/Calculation/Engineering/Complex.php new file mode 100644 index 00000000..1c2f5f77 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Engineering/Complex.php @@ -0,0 +1,99 @@ +getMessage(); + } + + if (($suffix == 'i') || ($suffix == 'j') || ($suffix == '')) { + $complex = new ComplexObject($realNumber, $imaginary, $suffix); + + return (string) $complex; + } + + return Functions::VALUE(); + } + + /** + * IMAGINARY. + * + * Returns the imaginary coefficient of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMAGINARY(complexNumber) + * + * @param string $complexNumber the complex number for which you want the imaginary + * coefficient + * + * @return float|string + */ + public static function IMAGINARY($complexNumber) + { + $complexNumber = Functions::flattenSingleValue($complexNumber); + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return Functions::NAN(); + } + + return $complex->getImaginary(); + } + + /** + * IMREAL. + * + * Returns the real coefficient of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMREAL(complexNumber) + * + * @param string $complexNumber the complex number for which you want the real coefficient + * + * @return float|string + */ + public static function IMREAL($complexNumber) + { + $complexNumber = Functions::flattenSingleValue($complexNumber); + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return Functions::NAN(); + } + + return $complex->getReal(); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Engineering/ComplexFunctions.php b/src/PhpSpreadsheet/Calculation/Engineering/ComplexFunctions.php new file mode 100644 index 00000000..3f37f373 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Engineering/ComplexFunctions.php @@ -0,0 +1,513 @@ +abs(); + } + + /** + * IMARGUMENT. + * + * Returns the argument theta of a complex number, i.e. the angle in radians from the real + * axis to the representation of the number in polar coordinates. + * + * Excel Function: + * IMARGUMENT(complexNumber) + * + * @param string $complexNumber the complex number for which you want the argument theta + * + * @return float|string + */ + public static function IMARGUMENT($complexNumber) + { + $complexNumber = Functions::flattenSingleValue($complexNumber); + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return Functions::NAN(); + } + + if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { + return Functions::DIV0(); + } + + return $complex->argument(); + } + + /** + * IMCONJUGATE. + * + * Returns the complex conjugate of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMCONJUGATE(complexNumber) + * + * @param string $complexNumber the complex number for which you want the conjugate + * + * @return string + */ + public static function IMCONJUGATE($complexNumber) + { + $complexNumber = Functions::flattenSingleValue($complexNumber); + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return Functions::NAN(); + } + + return (string) $complex->conjugate(); + } + + /** + * IMCOS. + * + * Returns the cosine of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMCOS(complexNumber) + * + * @param string $complexNumber the complex number for which you want the cosine + * + * @return float|string + */ + public static function IMCOS($complexNumber) + { + $complexNumber = Functions::flattenSingleValue($complexNumber); + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return Functions::NAN(); + } + + return (string) $complex->cos(); + } + + /** + * IMCOSH. + * + * Returns the hyperbolic cosine of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMCOSH(complexNumber) + * + * @param string $complexNumber the complex number for which you want the hyperbolic cosine + * + * @return float|string + */ + public static function IMCOSH($complexNumber) + { + $complexNumber = Functions::flattenSingleValue($complexNumber); + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return Functions::NAN(); + } + + return (string) $complex->cosh(); + } + + /** + * IMCOT. + * + * Returns the cotangent of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMCOT(complexNumber) + * + * @param string $complexNumber the complex number for which you want the cotangent + * + * @return float|string + */ + public static function IMCOT($complexNumber) + { + $complexNumber = Functions::flattenSingleValue($complexNumber); + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return Functions::NAN(); + } + + return (string) $complex->cot(); + } + + /** + * IMCSC. + * + * Returns the cosecant of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMCSC(complexNumber) + * + * @param string $complexNumber the complex number for which you want the cosecant + * + * @return float|string + */ + public static function IMCSC($complexNumber) + { + $complexNumber = Functions::flattenSingleValue($complexNumber); + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return Functions::NAN(); + } + + return (string) $complex->csc(); + } + + /** + * IMCSCH. + * + * Returns the hyperbolic cosecant of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMCSCH(complexNumber) + * + * @param string $complexNumber the complex number for which you want the hyperbolic cosecant + * + * @return float|string + */ + public static function IMCSCH($complexNumber) + { + $complexNumber = Functions::flattenSingleValue($complexNumber); + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return Functions::NAN(); + } + + return (string) $complex->csch(); + } + + /** + * IMSIN. + * + * Returns the sine of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMSIN(complexNumber) + * + * @param string $complexNumber the complex number for which you want the sine + * + * @return float|string + */ + public static function IMSIN($complexNumber) + { + $complexNumber = Functions::flattenSingleValue($complexNumber); + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return Functions::NAN(); + } + + return (string) $complex->sin(); + } + + /** + * IMSINH. + * + * Returns the hyperbolic sine of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMSINH(complexNumber) + * + * @param string $complexNumber the complex number for which you want the hyperbolic sine + * + * @return float|string + */ + public static function IMSINH($complexNumber) + { + $complexNumber = Functions::flattenSingleValue($complexNumber); + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return Functions::NAN(); + } + + return (string) $complex->sinh(); + } + + /** + * IMSEC. + * + * Returns the secant of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMSEC(complexNumber) + * + * @param string $complexNumber the complex number for which you want the secant + * + * @return float|string + */ + public static function IMSEC($complexNumber) + { + $complexNumber = Functions::flattenSingleValue($complexNumber); + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return Functions::NAN(); + } + + return (string) $complex->sec(); + } + + /** + * IMSECH. + * + * Returns the hyperbolic secant of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMSECH(complexNumber) + * + * @param string $complexNumber the complex number for which you want the hyperbolic secant + * + * @return float|string + */ + public static function IMSECH($complexNumber) + { + $complexNumber = Functions::flattenSingleValue($complexNumber); + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return Functions::NAN(); + } + + return (string) $complex->sech(); + } + + /** + * IMTAN. + * + * Returns the tangent of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMTAN(complexNumber) + * + * @param string $complexNumber the complex number for which you want the tangent + * + * @return float|string + */ + public static function IMTAN($complexNumber) + { + $complexNumber = Functions::flattenSingleValue($complexNumber); + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return Functions::NAN(); + } + + return (string) $complex->tan(); + } + + /** + * IMSQRT. + * + * Returns the square root of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMSQRT(complexNumber) + * + * @param string $complexNumber the complex number for which you want the square root + * + * @return string + */ + public static function IMSQRT($complexNumber) + { + $complexNumber = Functions::flattenSingleValue($complexNumber); + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return Functions::NAN(); + } + + $theta = self::IMARGUMENT($complexNumber); + if ($theta === Functions::DIV0()) { + return '0'; + } + + return (string) $complex->sqrt(); + } + + /** + * IMLN. + * + * Returns the natural logarithm of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMLN(complexNumber) + * + * @param string $complexNumber the complex number for which you want the natural logarithm + * + * @return string + */ + public static function IMLN($complexNumber) + { + $complexNumber = Functions::flattenSingleValue($complexNumber); + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return Functions::NAN(); + } + + if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { + return Functions::NAN(); + } + + return (string) $complex->ln(); + } + + /** + * IMLOG10. + * + * Returns the common logarithm (base 10) of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMLOG10(complexNumber) + * + * @param string $complexNumber the complex number for which you want the common logarithm + * + * @return string + */ + public static function IMLOG10($complexNumber) + { + $complexNumber = Functions::flattenSingleValue($complexNumber); + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return Functions::NAN(); + } + + if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { + return Functions::NAN(); + } + + return (string) $complex->log10(); + } + + /** + * IMLOG2. + * + * Returns the base-2 logarithm of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMLOG2(complexNumber) + * + * @param string $complexNumber the complex number for which you want the base-2 logarithm + * + * @return string + */ + public static function IMLOG2($complexNumber) + { + $complexNumber = Functions::flattenSingleValue($complexNumber); + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return Functions::NAN(); + } + + if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { + return Functions::NAN(); + } + + return (string) $complex->log2(); + } + + /** + * IMEXP. + * + * Returns the exponential of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMEXP(complexNumber) + * + * @param string $complexNumber the complex number for which you want the exponential + * + * @return string + */ + public static function IMEXP($complexNumber) + { + $complexNumber = Functions::flattenSingleValue($complexNumber); + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return Functions::NAN(); + } + + return (string) $complex->exp(); + } + + /** + * IMPOWER. + * + * Returns a complex number in x + yi or x + yj text format raised to a power. + * + * Excel Function: + * IMPOWER(complexNumber,realNumber) + * + * @param string $complexNumber the complex number you want to raise to a power + * @param float $realNumber the power to which you want to raise the complex number + * + * @return string + */ + public static function IMPOWER($complexNumber, $realNumber) + { + $complexNumber = Functions::flattenSingleValue($complexNumber); + $realNumber = Functions::flattenSingleValue($realNumber); + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return Functions::NAN(); + } + + if (!is_numeric($realNumber)) { + return Functions::VALUE(); + } + + return (string) $complex->pow($realNumber); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Engineering/ComplexOperations.php b/src/PhpSpreadsheet/Calculation/Engineering/ComplexOperations.php new file mode 100644 index 00000000..681aad8c --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Engineering/ComplexOperations.php @@ -0,0 +1,120 @@ +divideby(new ComplexObject($complexDivisor)); + } catch (ComplexException $e) { + return Functions::NAN(); + } + } + + /** + * IMSUB. + * + * Returns the difference of two complex numbers in x + yi or x + yj text format. + * + * Excel Function: + * IMSUB(complexNumber1,complexNumber2) + * + * @param string $complexNumber1 the complex number from which to subtract complexNumber2 + * @param string $complexNumber2 the complex number to subtract from complexNumber1 + * + * @return string + */ + public static function IMSUB($complexNumber1, $complexNumber2) + { + $complexNumber1 = Functions::flattenSingleValue($complexNumber1); + $complexNumber2 = Functions::flattenSingleValue($complexNumber2); + + try { + return (string) (new ComplexObject($complexNumber1))->subtract(new ComplexObject($complexNumber2)); + } catch (ComplexException $e) { + return Functions::NAN(); + } + } + + /** + * IMSUM. + * + * Returns the sum of two or more complex numbers in x + yi or x + yj text format. + * + * Excel Function: + * IMSUM(complexNumber[,complexNumber[,...]]) + * + * @param string ...$complexNumbers Series of complex numbers to add + * + * @return string + */ + public static function IMSUM(...$complexNumbers) + { + // Return value + $returnValue = new ComplexObject(0.0); + $aArgs = Functions::flattenArray($complexNumbers); + + try { + // Loop through the arguments + foreach ($aArgs as $complex) { + $returnValue = $returnValue->add(new ComplexObject($complex)); + } + } catch (ComplexException $e) { + return Functions::NAN(); + } + + return (string) $returnValue; + } + + /** + * IMPRODUCT. + * + * Returns the product of two or more complex numbers in x + yi or x + yj text format. + * + * Excel Function: + * IMPRODUCT(complexNumber[,complexNumber[,...]]) + * + * @param string ...$complexNumbers Series of complex numbers to multiply + * + * @return string + */ + public static function IMPRODUCT(...$complexNumbers) + { + // Return value + $returnValue = new ComplexObject(1.0); + $aArgs = Functions::flattenArray($complexNumbers); + + try { + // Loop through the arguments + foreach ($aArgs as $complex) { + $returnValue = $returnValue->multiply(new ComplexObject($complex)); + } + } catch (ComplexException $e) { + return Functions::NAN(); + } + + return (string) $returnValue; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Engineering/Constants.php b/src/PhpSpreadsheet/Calculation/Engineering/Constants.php new file mode 100644 index 00000000..a926db6e --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Engineering/Constants.php @@ -0,0 +1,11 @@ + 10) { + throw new Exception(Functions::NAN()); + } + + return (int) $places; + } + + throw new Exception(Functions::VALUE()); + } + + /** + * Formats a number base string value with leading zeroes. + * + * @param string $value The "number" to pad + * @param ?int $places The length that we want to pad this value + * + * @return string The padded "number" + */ + protected static function nbrConversionFormat(string $value, ?int $places): string + { + if ($places !== null) { + if (strlen($value) <= $places) { + return substr(str_pad($value, $places, '0', STR_PAD_LEFT), -10); + } + + return Functions::NAN(); + } + + return substr($value, -10); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Engineering/ConvertBinary.php b/src/PhpSpreadsheet/Calculation/Engineering/ConvertBinary.php new file mode 100644 index 00000000..a662b78d --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Engineering/ConvertBinary.php @@ -0,0 +1,134 @@ +getMessage(); + } + + if (strlen($value) == 10) { + // Two's Complement + $value = substr($value, -9); + + return '-' . (512 - bindec($value)); + } + + return (string) bindec($value); + } + + /** + * toHex. + * + * Return a binary value as hex. + * + * Excel Function: + * BIN2HEX(x[,places]) + * + * @param string $value The binary number (as a string) that you want to convert. The number + * cannot contain more than 10 characters (10 bits). The most significant + * bit of number is the sign bit. The remaining 9 bits are magnitude bits. + * Negative numbers are represented using two's-complement notation. + * If number is not a valid binary number, or if number contains more than + * 10 characters (10 bits), BIN2HEX returns the #NUM! error value. + * @param int $places The number of characters to use. If places is omitted, BIN2HEX uses the + * minimum number of characters necessary. Places is useful for padding the + * return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, BIN2HEX returns the #VALUE! error value. + * If places is negative, BIN2HEX returns the #NUM! error value. + */ + public static function toHex($value, $places = null): string + { + try { + $value = self::validateValue(Functions::flattenSingleValue($value)); + $value = self::validateBinary($value); + $places = self::validatePlaces(Functions::flattenSingleValue($places)); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (strlen($value) == 10) { + $high2 = substr($value, 0, 2); + $low8 = substr($value, 2); + $xarr = ['00' => '00000000', '01' => '00000001', '10' => 'FFFFFFFE', '11' => 'FFFFFFFF']; + + return $xarr[$high2] . strtoupper(substr('0' . dechex((int) bindec($low8)), -2)); + } + $hexVal = (string) strtoupper(dechex((int) bindec($value))); + + return self::nbrConversionFormat($hexVal, $places); + } + + /** + * toOctal. + * + * Return a binary value as octal. + * + * Excel Function: + * BIN2OCT(x[,places]) + * + * @param string $value The binary number (as a string) that you want to convert. The number + * cannot contain more than 10 characters (10 bits). The most significant + * bit of number is the sign bit. The remaining 9 bits are magnitude bits. + * Negative numbers are represented using two's-complement notation. + * If number is not a valid binary number, or if number contains more than + * 10 characters (10 bits), BIN2OCT returns the #NUM! error value. + * @param int $places The number of characters to use. If places is omitted, BIN2OCT uses the + * minimum number of characters necessary. Places is useful for padding the + * return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, BIN2OCT returns the #VALUE! error value. + * If places is negative, BIN2OCT returns the #NUM! error value. + */ + public static function toOctal($value, $places = null): string + { + try { + $value = self::validateValue(Functions::flattenSingleValue($value)); + $value = self::validateBinary($value); + $places = self::validatePlaces(Functions::flattenSingleValue($places)); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (strlen($value) == 10 && substr($value, 0, 1) === '1') { // Two's Complement + return str_repeat('7', 6) . strtoupper(decoct((int) bindec("11$value"))); + } + $octVal = (string) decoct((int) bindec($value)); + + return self::nbrConversionFormat($octVal, $places); + } + + protected static function validateBinary(string $value): string + { + if ((strlen($value) > preg_match_all('/[01]/', $value)) || (strlen($value) > 10)) { + throw new Exception(Functions::NAN()); + } + + return $value; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Engineering/ConvertDecimal.php b/src/PhpSpreadsheet/Calculation/Engineering/ConvertDecimal.php new file mode 100644 index 00000000..a34332fb --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Engineering/ConvertDecimal.php @@ -0,0 +1,183 @@ + 511, DEC2BIN returns the #NUM! error + * value. + * If number is nonnumeric, DEC2BIN returns the #VALUE! error value. + * If DEC2BIN requires more than places characters, it returns the #NUM! + * error value. + * @param int $places The number of characters to use. If places is omitted, DEC2BIN uses + * the minimum number of characters necessary. Places is useful for + * padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, DEC2BIN returns the #VALUE! error value. + * If places is zero or negative, DEC2BIN returns the #NUM! error value. + */ + public static function toBinary($value, $places = null): string + { + try { + $value = self::validateValue(Functions::flattenSingleValue($value)); + $value = self::validateDecimal($value); + $places = self::validatePlaces(Functions::flattenSingleValue($places)); + } catch (Exception $e) { + return $e->getMessage(); + } + + $value = (int) floor((float) $value); + if ($value > self::LARGEST_BINARY_IN_DECIMAL || $value < self::SMALLEST_BINARY_IN_DECIMAL) { + return Functions::NAN(); + } + + $r = decbin($value); + // Two's Complement + $r = substr($r, -10); + + return self::nbrConversionFormat($r, $places); + } + + /** + * toHex. + * + * Return a decimal value as hex. + * + * Excel Function: + * DEC2HEX(x[,places]) + * + * @param string $value The decimal integer you want to convert. If number is negative, + * places is ignored and DEC2HEX returns a 10-character (40-bit) + * hexadecimal number in which the most significant bit is the sign + * bit. The remaining 39 bits are magnitude bits. Negative numbers + * are represented using two's-complement notation. + * If number < -549,755,813,888 or if number > 549,755,813,887, + * DEC2HEX returns the #NUM! error value. + * If number is nonnumeric, DEC2HEX returns the #VALUE! error value. + * If DEC2HEX requires more than places characters, it returns the + * #NUM! error value. + * @param int $places The number of characters to use. If places is omitted, DEC2HEX uses + * the minimum number of characters necessary. Places is useful for + * padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, DEC2HEX returns the #VALUE! error value. + * If places is zero or negative, DEC2HEX returns the #NUM! error value. + */ + public static function toHex($value, $places = null): string + { + try { + $value = self::validateValue(Functions::flattenSingleValue($value)); + $value = self::validateDecimal($value); + $places = self::validatePlaces(Functions::flattenSingleValue($places)); + } catch (Exception $e) { + return $e->getMessage(); + } + + $value = floor((float) $value); + if ($value > self::LARGEST_HEX_IN_DECIMAL || $value < self::SMALLEST_HEX_IN_DECIMAL) { + return Functions::NAN(); + } + $r = strtoupper(dechex((int) $value)); + $r = self::hex32bit($value, $r); + + return self::nbrConversionFormat($r, $places); + } + + public static function hex32bit(float $value, string $hexstr, bool $force = false): string + { + if (PHP_INT_SIZE === 4 || $force) { + if ($value >= 2 ** 32) { + $quotient = (int) ($value / (2 ** 32)); + + return strtoupper(substr('0' . dechex($quotient), -2) . $hexstr); + } + if ($value < -(2 ** 32)) { + $quotient = 256 - (int) ceil((-$value) / (2 ** 32)); + + return strtoupper(substr('0' . dechex($quotient), -2) . substr("00000000$hexstr", -8)); + } + if ($value < 0) { + return "FF$hexstr"; + } + } + + return $hexstr; + } + + /** + * toOctal. + * + * Return an decimal value as octal. + * + * Excel Function: + * DEC2OCT(x[,places]) + * + * @param string $value The decimal integer you want to convert. If number is negative, + * places is ignored and DEC2OCT returns a 10-character (30-bit) + * octal number in which the most significant bit is the sign bit. + * The remaining 29 bits are magnitude bits. Negative numbers are + * represented using two's-complement notation. + * If number < -536,870,912 or if number > 536,870,911, DEC2OCT + * returns the #NUM! error value. + * If number is nonnumeric, DEC2OCT returns the #VALUE! error value. + * If DEC2OCT requires more than places characters, it returns the + * #NUM! error value. + * @param int $places The number of characters to use. If places is omitted, DEC2OCT uses + * the minimum number of characters necessary. Places is useful for + * padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, DEC2OCT returns the #VALUE! error value. + * If places is zero or negative, DEC2OCT returns the #NUM! error value. + */ + public static function toOctal($value, $places = null): string + { + try { + $value = self::validateValue(Functions::flattenSingleValue($value)); + $value = self::validateDecimal($value); + $places = self::validatePlaces(Functions::flattenSingleValue($places)); + } catch (Exception $e) { + return $e->getMessage(); + } + + $value = (int) floor((float) $value); + if ($value > self::LARGEST_OCTAL_IN_DECIMAL || $value < self::SMALLEST_OCTAL_IN_DECIMAL) { + return Functions::NAN(); + } + $r = decoct($value); + $r = substr($r, -10); + + return self::nbrConversionFormat($r, $places); + } + + protected static function validateDecimal(string $value): string + { + if (strlen($value) > preg_match_all('/[-0123456789.]/', $value)) { + throw new Exception(Functions::VALUE()); + } + + return $value; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Engineering/ConvertHex.php b/src/PhpSpreadsheet/Calculation/Engineering/ConvertHex.php new file mode 100644 index 00000000..de1b0704 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Engineering/ConvertHex.php @@ -0,0 +1,146 @@ +getMessage(); + } + + $dec = self::toDecimal($value); + + return ConvertDecimal::toBinary($dec, $places); + } + + /** + * toDecimal. + * + * Return a hex value as decimal. + * + * Excel Function: + * HEX2DEC(x) + * + * @param string $value The hexadecimal number you want to convert. This number cannot + * contain more than 10 characters (40 bits). The most significant + * bit of number is the sign bit. The remaining 39 bits are magnitude + * bits. Negative numbers are represented using two's-complement + * notation. + * If number is not a valid hexadecimal number, HEX2DEC returns the + * #NUM! error value. + */ + public static function toDecimal($value): string + { + try { + $value = self::validateValue(Functions::flattenSingleValue($value)); + $value = self::validateHex($value); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (strlen($value) > 10) { + return Functions::NAN(); + } + + $binX = ''; + foreach (str_split($value) as $char) { + $binX .= str_pad(base_convert($char, 16, 2), 4, '0', STR_PAD_LEFT); + } + if (strlen($binX) == 40 && $binX[0] == '1') { + for ($i = 0; $i < 40; ++$i) { + $binX[$i] = ($binX[$i] == '1' ? '0' : '1'); + } + + return (string) ((bindec($binX) + 1) * -1); + } + + return (string) bindec($binX); + } + + /** + * toOctal. + * + * Return a hex value as octal. + * + * Excel Function: + * HEX2OCT(x[,places]) + * + * @param string $value The hexadecimal number you want to convert. Number cannot + * contain more than 10 characters. The most significant bit of + * number is the sign bit. The remaining 39 bits are magnitude + * bits. Negative numbers are represented using two's-complement + * notation. + * If number is negative, HEX2OCT ignores places and returns a + * 10-character octal number. + * If number is negative, it cannot be less than FFE0000000, and + * if number is positive, it cannot be greater than 1FFFFFFF. + * If number is not a valid hexadecimal number, HEX2OCT returns + * the #NUM! error value. + * If HEX2OCT requires more than places characters, it returns + * the #NUM! error value. + * @param int $places The number of characters to use. If places is omitted, HEX2OCT + * uses the minimum number of characters necessary. Places is + * useful for padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, HEX2OCT returns the #VALUE! error + * value. + * If places is negative, HEX2OCT returns the #NUM! error value. + */ + public static function toOctal($value, $places = null): string + { + try { + $value = self::validateValue(Functions::flattenSingleValue($value)); + $value = self::validateHex($value); + $places = self::validatePlaces(Functions::flattenSingleValue($places)); + } catch (Exception $e) { + return $e->getMessage(); + } + + $decimal = self::toDecimal($value); + + return ConvertDecimal::toOctal($decimal, $places); + } + + protected static function validateHex(string $value): string + { + if (strlen($value) > preg_match_all('/[0123456789ABCDEF]/', $value)) { + throw new Exception(Functions::NAN()); + } + + return $value; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Engineering/ConvertOctal.php b/src/PhpSpreadsheet/Calculation/Engineering/ConvertOctal.php new file mode 100644 index 00000000..1181e2ee --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Engineering/ConvertOctal.php @@ -0,0 +1,145 @@ +getMessage(); + } + + return ConvertDecimal::toBinary(self::toDecimal($value), $places); + } + + /** + * toDecimal. + * + * Return an octal value as decimal. + * + * Excel Function: + * OCT2DEC(x) + * + * @param string $value The octal number you want to convert. Number may not contain + * more than 10 octal characters (30 bits). The most significant + * bit of number is the sign bit. The remaining 29 bits are + * magnitude bits. Negative numbers are represented using + * two's-complement notation. + * If number is not a valid octal number, OCT2DEC returns the + * #NUM! error value. + */ + public static function toDecimal($value): string + { + try { + $value = self::validateValue(Functions::flattenSingleValue($value)); + $value = self::validateOctal($value); + } catch (Exception $e) { + return $e->getMessage(); + } + + $binX = ''; + foreach (str_split($value) as $char) { + $binX .= str_pad(decbin((int) $char), 3, '0', STR_PAD_LEFT); + } + if (strlen($binX) == 30 && $binX[0] == '1') { + for ($i = 0; $i < 30; ++$i) { + $binX[$i] = ($binX[$i] == '1' ? '0' : '1'); + } + + return (string) ((bindec($binX) + 1) * -1); + } + + return (string) bindec($binX); + } + + /** + * toHex. + * + * Return an octal value as hex. + * + * Excel Function: + * OCT2HEX(x[,places]) + * + * @param string $value The octal number you want to convert. Number may not contain + * more than 10 octal characters (30 bits). The most significant + * bit of number is the sign bit. The remaining 29 bits are + * magnitude bits. Negative numbers are represented using + * two's-complement notation. + * If number is negative, OCT2HEX ignores places and returns a + * 10-character hexadecimal number. + * If number is not a valid octal number, OCT2HEX returns the + * #NUM! error value. + * If OCT2HEX requires more than places characters, it returns + * the #NUM! error value. + * @param int $places The number of characters to use. If places is omitted, OCT2HEX + * uses the minimum number of characters necessary. Places is useful + * for padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, OCT2HEX returns the #VALUE! error value. + * If places is negative, OCT2HEX returns the #NUM! error value. + */ + public static function toHex($value, $places = null): string + { + try { + $value = self::validateValue(Functions::flattenSingleValue($value)); + $value = self::validateOctal($value); + $places = self::validatePlaces(Functions::flattenSingleValue($places)); + } catch (Exception $e) { + return $e->getMessage(); + } + + $hexVal = strtoupper(dechex((int) self::toDecimal($value))); + $hexVal = (PHP_INT_SIZE === 4 && strlen($value) === 10 && $value[0] >= '4') ? "FF$hexVal" : $hexVal; + + return self::nbrConversionFormat($hexVal, $places); + } + + protected static function validateOctal(string $value): string + { + $numDigits = (int) preg_match_all('/[01234567]/', $value); + if (strlen($value) > $numDigits || $numDigits > 10) { + throw new Exception(Functions::NAN()); + } + + return $value; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Engineering/ConvertUOM.php b/src/PhpSpreadsheet/Calculation/Engineering/ConvertUOM.php new file mode 100644 index 00000000..d169ae54 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Engineering/ConvertUOM.php @@ -0,0 +1,684 @@ + ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Gram', 'AllowPrefix' => true], + 'sg' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Slug', 'AllowPrefix' => false], + 'lbm' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Pound mass (avoirdupois)', 'AllowPrefix' => false], + 'u' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'U (atomic mass unit)', 'AllowPrefix' => true], + 'ozm' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Ounce mass (avoirdupois)', 'AllowPrefix' => false], + 'grain' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Grain', 'AllowPrefix' => false], + 'cwt' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'U.S. (short) hundredweight', 'AllowPrefix' => false], + 'shweight' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'U.S. (short) hundredweight', 'AllowPrefix' => false], + 'uk_cwt' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Imperial hundredweight', 'AllowPrefix' => false], + 'lcwt' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Imperial hundredweight', 'AllowPrefix' => false], + 'hweight' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Imperial hundredweight', 'AllowPrefix' => false], + 'stone' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Stone', 'AllowPrefix' => false], + 'ton' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Ton', 'AllowPrefix' => false], + 'uk_ton' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Imperial ton', 'AllowPrefix' => false], + 'LTON' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Imperial ton', 'AllowPrefix' => false], + 'brton' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Imperial ton', 'AllowPrefix' => false], + // Distance + 'm' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Meter', 'AllowPrefix' => true], + 'mi' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Statute mile', 'AllowPrefix' => false], + 'Nmi' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Nautical mile', 'AllowPrefix' => false], + 'in' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Inch', 'AllowPrefix' => false], + 'ft' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Foot', 'AllowPrefix' => false], + 'yd' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Yard', 'AllowPrefix' => false], + 'ang' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Angstrom', 'AllowPrefix' => true], + 'ell' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Ell', 'AllowPrefix' => false], + 'ly' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Light Year', 'AllowPrefix' => false], + 'parsec' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Parsec', 'AllowPrefix' => false], + 'pc' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Parsec', 'AllowPrefix' => false], + 'Pica' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Pica (1/72 in)', 'AllowPrefix' => false], + 'Picapt' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Pica (1/72 in)', 'AllowPrefix' => false], + 'pica' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Pica (1/6 in)', 'AllowPrefix' => false], + 'survey_mi' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'U.S survey mile (statute mile)', 'AllowPrefix' => false], + // Time + 'yr' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Year', 'AllowPrefix' => false], + 'day' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Day', 'AllowPrefix' => false], + 'd' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Day', 'AllowPrefix' => false], + 'hr' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Hour', 'AllowPrefix' => false], + 'mn' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Minute', 'AllowPrefix' => false], + 'min' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Minute', 'AllowPrefix' => false], + 'sec' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Second', 'AllowPrefix' => true], + 's' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Second', 'AllowPrefix' => true], + // Pressure + 'Pa' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'Pascal', 'AllowPrefix' => true], + 'p' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'Pascal', 'AllowPrefix' => true], + 'atm' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'Atmosphere', 'AllowPrefix' => true], + 'at' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'Atmosphere', 'AllowPrefix' => true], + 'mmHg' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'mm of Mercury', 'AllowPrefix' => true], + 'psi' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'PSI', 'AllowPrefix' => true], + 'Torr' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'Torr', 'AllowPrefix' => true], + // Force + 'N' => ['Group' => self::CATEGORY_FORCE, 'Unit Name' => 'Newton', 'AllowPrefix' => true], + 'dyn' => ['Group' => self::CATEGORY_FORCE, 'Unit Name' => 'Dyne', 'AllowPrefix' => true], + 'dy' => ['Group' => self::CATEGORY_FORCE, 'Unit Name' => 'Dyne', 'AllowPrefix' => true], + 'lbf' => ['Group' => self::CATEGORY_FORCE, 'Unit Name' => 'Pound force', 'AllowPrefix' => false], + 'pond' => ['Group' => self::CATEGORY_FORCE, 'Unit Name' => 'Pond', 'AllowPrefix' => true], + // Energy + 'J' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Joule', 'AllowPrefix' => true], + 'e' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Erg', 'AllowPrefix' => true], + 'c' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Thermodynamic calorie', 'AllowPrefix' => true], + 'cal' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'IT calorie', 'AllowPrefix' => true], + 'eV' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Electron volt', 'AllowPrefix' => true], + 'ev' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Electron volt', 'AllowPrefix' => true], + 'HPh' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => false], + 'hh' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => false], + 'Wh' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Watt-hour', 'AllowPrefix' => true], + 'wh' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Watt-hour', 'AllowPrefix' => true], + 'flb' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Foot-pound', 'AllowPrefix' => false], + 'BTU' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'BTU', 'AllowPrefix' => false], + 'btu' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'BTU', 'AllowPrefix' => false], + // Power + 'HP' => ['Group' => self::CATEGORY_POWER, 'Unit Name' => 'Horsepower', 'AllowPrefix' => false], + 'h' => ['Group' => self::CATEGORY_POWER, 'Unit Name' => 'Horsepower', 'AllowPrefix' => false], + 'W' => ['Group' => self::CATEGORY_POWER, 'Unit Name' => 'Watt', 'AllowPrefix' => true], + 'w' => ['Group' => self::CATEGORY_POWER, 'Unit Name' => 'Watt', 'AllowPrefix' => true], + 'PS' => ['Group' => self::CATEGORY_POWER, 'Unit Name' => 'Pferdestärke', 'AllowPrefix' => false], + 'T' => ['Group' => self::CATEGORY_MAGNETISM, 'Unit Name' => 'Tesla', 'AllowPrefix' => true], + 'ga' => ['Group' => self::CATEGORY_MAGNETISM, 'Unit Name' => 'Gauss', 'AllowPrefix' => true], + // Temperature + 'C' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Degrees Celsius', 'AllowPrefix' => false], + 'cel' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Degrees Celsius', 'AllowPrefix' => false], + 'F' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Degrees Fahrenheit', 'AllowPrefix' => false], + 'fah' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Degrees Fahrenheit', 'AllowPrefix' => false], + 'K' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Kelvin', 'AllowPrefix' => false], + 'kel' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Kelvin', 'AllowPrefix' => false], + 'Rank' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Degrees Rankine', 'AllowPrefix' => false], + 'Reau' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Degrees Réaumur', 'AllowPrefix' => false], + // Volume + 'l' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Litre', 'AllowPrefix' => true], + 'L' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Litre', 'AllowPrefix' => true], + 'lt' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Litre', 'AllowPrefix' => true], + 'tsp' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Teaspoon', 'AllowPrefix' => false], + 'tspm' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Modern Teaspoon', 'AllowPrefix' => false], + 'tbs' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Tablespoon', 'AllowPrefix' => false], + 'oz' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Fluid Ounce', 'AllowPrefix' => false], + 'cup' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cup', 'AllowPrefix' => false], + 'pt' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => false], + 'us_pt' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => false], + 'uk_pt' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'U.K. Pint', 'AllowPrefix' => false], + 'qt' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Quart', 'AllowPrefix' => false], + 'uk_qt' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Imperial Quart (UK)', 'AllowPrefix' => false], + 'gal' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Gallon', 'AllowPrefix' => false], + 'uk_gal' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Imperial Gallon (UK)', 'AllowPrefix' => false], + 'ang3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Angstrom', 'AllowPrefix' => true], + 'ang^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Angstrom', 'AllowPrefix' => true], + 'barrel' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'US Oil Barrel', 'AllowPrefix' => false], + 'bushel' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'US Bushel', 'AllowPrefix' => false], + 'in3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Inch', 'AllowPrefix' => false], + 'in^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Inch', 'AllowPrefix' => false], + 'ft3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Foot', 'AllowPrefix' => false], + 'ft^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Foot', 'AllowPrefix' => false], + 'ly3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Light Year', 'AllowPrefix' => false], + 'ly^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Light Year', 'AllowPrefix' => false], + 'm3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Meter', 'AllowPrefix' => true], + 'm^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Meter', 'AllowPrefix' => true], + 'mi3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Mile', 'AllowPrefix' => false], + 'mi^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Mile', 'AllowPrefix' => false], + 'yd3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Yard', 'AllowPrefix' => false], + 'yd^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Yard', 'AllowPrefix' => false], + 'Nmi3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Nautical Mile', 'AllowPrefix' => false], + 'Nmi^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Nautical Mile', 'AllowPrefix' => false], + 'Pica3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Pica', 'AllowPrefix' => false], + 'Pica^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Pica', 'AllowPrefix' => false], + 'Picapt3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Pica', 'AllowPrefix' => false], + 'Picapt^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Pica', 'AllowPrefix' => false], + 'GRT' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Gross Registered Ton', 'AllowPrefix' => false], + 'regton' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Gross Registered Ton', 'AllowPrefix' => false], + 'MTON' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Measurement Ton (Freight Ton)', 'AllowPrefix' => false], + // Area + 'ha' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Hectare', 'AllowPrefix' => true], + 'uk_acre' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'International Acre', 'AllowPrefix' => false], + 'us_acre' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'US Survey/Statute Acre', 'AllowPrefix' => false], + 'ang2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Angstrom', 'AllowPrefix' => true], + 'ang^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Angstrom', 'AllowPrefix' => true], + 'ar' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Are', 'AllowPrefix' => true], + 'ft2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Feet', 'AllowPrefix' => false], + 'ft^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Feet', 'AllowPrefix' => false], + 'in2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Inches', 'AllowPrefix' => false], + 'in^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Inches', 'AllowPrefix' => false], + 'ly2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Light Years', 'AllowPrefix' => false], + 'ly^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Light Years', 'AllowPrefix' => false], + 'm2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Meters', 'AllowPrefix' => true], + 'm^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Meters', 'AllowPrefix' => true], + 'Morgen' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Morgen', 'AllowPrefix' => false], + 'mi2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Miles', 'AllowPrefix' => false], + 'mi^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Miles', 'AllowPrefix' => false], + 'Nmi2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Nautical Miles', 'AllowPrefix' => false], + 'Nmi^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Nautical Miles', 'AllowPrefix' => false], + 'Pica2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Pica', 'AllowPrefix' => false], + 'Pica^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Pica', 'AllowPrefix' => false], + 'Picapt2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Pica', 'AllowPrefix' => false], + 'Picapt^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Pica', 'AllowPrefix' => false], + 'yd2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Yards', 'AllowPrefix' => false], + 'yd^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Yards', 'AllowPrefix' => false], + // Information + 'byte' => ['Group' => self::CATEGORY_INFORMATION, 'Unit Name' => 'Byte', 'AllowPrefix' => true], + 'bit' => ['Group' => self::CATEGORY_INFORMATION, 'Unit Name' => 'Bit', 'AllowPrefix' => true], + // Speed + 'm/s' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Meters per second', 'AllowPrefix' => true], + 'm/sec' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Meters per second', 'AllowPrefix' => true], + 'm/h' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Meters per hour', 'AllowPrefix' => true], + 'm/hr' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Meters per hour', 'AllowPrefix' => true], + 'mph' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Miles per hour', 'AllowPrefix' => false], + 'admkn' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Admiralty Knot', 'AllowPrefix' => false], + 'kn' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Knot', 'AllowPrefix' => false], + ]; + + /** + * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM(). + * + * @var mixed[] + */ + private static $conversionMultipliers = [ + 'Y' => ['multiplier' => 1E24, 'name' => 'yotta'], + 'Z' => ['multiplier' => 1E21, 'name' => 'zetta'], + 'E' => ['multiplier' => 1E18, 'name' => 'exa'], + 'P' => ['multiplier' => 1E15, 'name' => 'peta'], + 'T' => ['multiplier' => 1E12, 'name' => 'tera'], + 'G' => ['multiplier' => 1E9, 'name' => 'giga'], + 'M' => ['multiplier' => 1E6, 'name' => 'mega'], + 'k' => ['multiplier' => 1E3, 'name' => 'kilo'], + 'h' => ['multiplier' => 1E2, 'name' => 'hecto'], + 'e' => ['multiplier' => 1E1, 'name' => 'dekao'], + 'da' => ['multiplier' => 1E1, 'name' => 'dekao'], + 'd' => ['multiplier' => 1E-1, 'name' => 'deci'], + 'c' => ['multiplier' => 1E-2, 'name' => 'centi'], + 'm' => ['multiplier' => 1E-3, 'name' => 'milli'], + 'u' => ['multiplier' => 1E-6, 'name' => 'micro'], + 'n' => ['multiplier' => 1E-9, 'name' => 'nano'], + 'p' => ['multiplier' => 1E-12, 'name' => 'pico'], + 'f' => ['multiplier' => 1E-15, 'name' => 'femto'], + 'a' => ['multiplier' => 1E-18, 'name' => 'atto'], + 'z' => ['multiplier' => 1E-21, 'name' => 'zepto'], + 'y' => ['multiplier' => 1E-24, 'name' => 'yocto'], + ]; + + /** + * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM(). + * + * @var mixed[] + */ + private static $binaryConversionMultipliers = [ + 'Yi' => ['multiplier' => 2 ** 80, 'name' => 'yobi'], + 'Zi' => ['multiplier' => 2 ** 70, 'name' => 'zebi'], + 'Ei' => ['multiplier' => 2 ** 60, 'name' => 'exbi'], + 'Pi' => ['multiplier' => 2 ** 50, 'name' => 'pebi'], + 'Ti' => ['multiplier' => 2 ** 40, 'name' => 'tebi'], + 'Gi' => ['multiplier' => 2 ** 30, 'name' => 'gibi'], + 'Mi' => ['multiplier' => 2 ** 20, 'name' => 'mebi'], + 'ki' => ['multiplier' => 2 ** 10, 'name' => 'kibi'], + ]; + + /** + * Details of the Units of measure conversion factors, organised by group. + * + * @var mixed[] + */ + private static $unitConversions = [ + // Conversion uses gram (g) as an intermediate unit + self::CATEGORY_WEIGHT_AND_MASS => [ + 'g' => 1.0, + 'sg' => 6.85217658567918E-05, + 'lbm' => 2.20462262184878E-03, + 'u' => 6.02214179421676E+23, + 'ozm' => 3.52739619495804E-02, + 'grain' => 1.54323583529414E+01, + 'cwt' => 2.20462262184878E-05, + 'shweight' => 2.20462262184878E-05, + 'uk_cwt' => 1.96841305522212E-05, + 'lcwt' => 1.96841305522212E-05, + 'hweight' => 1.96841305522212E-05, + 'stone' => 1.57473044417770E-04, + 'ton' => 1.10231131092439E-06, + 'uk_ton' => 9.84206527611061E-07, + 'LTON' => 9.84206527611061E-07, + 'brton' => 9.84206527611061E-07, + ], + // Conversion uses meter (m) as an intermediate unit + self::CATEGORY_DISTANCE => [ + 'm' => 1.0, + 'mi' => 6.21371192237334E-04, + 'Nmi' => 5.39956803455724E-04, + 'in' => 3.93700787401575E+01, + 'ft' => 3.28083989501312E+00, + 'yd' => 1.09361329833771E+00, + 'ang' => 1.0E+10, + 'ell' => 8.74890638670166E-01, + 'ly' => 1.05700083402462E-16, + 'parsec' => 3.24077928966473E-17, + 'pc' => 3.24077928966473E-17, + 'Pica' => 2.83464566929134E+03, + 'Picapt' => 2.83464566929134E+03, + 'pica' => 2.36220472440945E+02, + 'survey_mi' => 6.21369949494950E-04, + ], + // Conversion uses second (s) as an intermediate unit + self::CATEGORY_TIME => [ + 'yr' => 3.16880878140289E-08, + 'day' => 1.15740740740741E-05, + 'd' => 1.15740740740741E-05, + 'hr' => 2.77777777777778E-04, + 'mn' => 1.66666666666667E-02, + 'min' => 1.66666666666667E-02, + 'sec' => 1.0, + 's' => 1.0, + ], + // Conversion uses Pascal (Pa) as an intermediate unit + self::CATEGORY_PRESSURE => [ + 'Pa' => 1.0, + 'p' => 1.0, + 'atm' => 9.86923266716013E-06, + 'at' => 9.86923266716013E-06, + 'mmHg' => 7.50063755419211E-03, + 'psi' => 1.45037737730209E-04, + 'Torr' => 7.50061682704170E-03, + ], + // Conversion uses Newton (N) as an intermediate unit + self::CATEGORY_FORCE => [ + 'N' => 1.0, + 'dyn' => 1.0E+5, + 'dy' => 1.0E+5, + 'lbf' => 2.24808923655339E-01, + 'pond' => 1.01971621297793E+02, + ], + // Conversion uses Joule (J) as an intermediate unit + self::CATEGORY_ENERGY => [ + 'J' => 1.0, + 'e' => 9.99999519343231E+06, + 'c' => 2.39006249473467E-01, + 'cal' => 2.38846190642017E-01, + 'eV' => 6.24145700000000E+18, + 'ev' => 6.24145700000000E+18, + 'HPh' => 3.72506430801000E-07, + 'hh' => 3.72506430801000E-07, + 'Wh' => 2.77777916238711E-04, + 'wh' => 2.77777916238711E-04, + 'flb' => 2.37304222192651E+01, + 'BTU' => 9.47815067349015E-04, + 'btu' => 9.47815067349015E-04, + ], + // Conversion uses Horsepower (HP) as an intermediate unit + self::CATEGORY_POWER => [ + 'HP' => 1.0, + 'h' => 1.0, + 'W' => 7.45699871582270E+02, + 'w' => 7.45699871582270E+02, + 'PS' => 1.01386966542400E+00, + ], + // Conversion uses Tesla (T) as an intermediate unit + self::CATEGORY_MAGNETISM => [ + 'T' => 1.0, + 'ga' => 10000.0, + ], + // Conversion uses litre (l) as an intermediate unit + self::CATEGORY_VOLUME => [ + 'l' => 1.0, + 'L' => 1.0, + 'lt' => 1.0, + 'tsp' => 2.02884136211058E+02, + 'tspm' => 2.0E+02, + 'tbs' => 6.76280454036860E+01, + 'oz' => 3.38140227018430E+01, + 'cup' => 4.22675283773038E+00, + 'pt' => 2.11337641886519E+00, + 'us_pt' => 2.11337641886519E+00, + 'uk_pt' => 1.75975398639270E+00, + 'qt' => 1.05668820943259E+00, + 'uk_qt' => 8.79876993196351E-01, + 'gal' => 2.64172052358148E-01, + 'uk_gal' => 2.19969248299088E-01, + 'ang3' => 1.0E+27, + 'ang^3' => 1.0E+27, + 'barrel' => 6.28981077043211E-03, + 'bushel' => 2.83775932584017E-02, + 'in3' => 6.10237440947323E+01, + 'in^3' => 6.10237440947323E+01, + 'ft3' => 3.53146667214886E-02, + 'ft^3' => 3.53146667214886E-02, + 'ly3' => 1.18093498844171E-51, + 'ly^3' => 1.18093498844171E-51, + 'm3' => 1.0E-03, + 'm^3' => 1.0E-03, + 'mi3' => 2.39912758578928E-13, + 'mi^3' => 2.39912758578928E-13, + 'yd3' => 1.30795061931439E-03, + 'yd^3' => 1.30795061931439E-03, + 'Nmi3' => 1.57426214685811E-13, + 'Nmi^3' => 1.57426214685811E-13, + 'Pica3' => 2.27769904358706E+07, + 'Pica^3' => 2.27769904358706E+07, + 'Picapt3' => 2.27769904358706E+07, + 'Picapt^3' => 2.27769904358706E+07, + 'GRT' => 3.53146667214886E-04, + 'regton' => 3.53146667214886E-04, + 'MTON' => 8.82866668037215E-04, + ], + // Conversion uses hectare (ha) as an intermediate unit + self::CATEGORY_AREA => [ + 'ha' => 1.0, + 'uk_acre' => 2.47105381467165E+00, + 'us_acre' => 2.47104393046628E+00, + 'ang2' => 1.0E+24, + 'ang^2' => 1.0E+24, + 'ar' => 1.0E+02, + 'ft2' => 1.07639104167097E+05, + 'ft^2' => 1.07639104167097E+05, + 'in2' => 1.55000310000620E+07, + 'in^2' => 1.55000310000620E+07, + 'ly2' => 1.11725076312873E-28, + 'ly^2' => 1.11725076312873E-28, + 'm2' => 1.0E+04, + 'm^2' => 1.0E+04, + 'Morgen' => 4.0E+00, + 'mi2' => 3.86102158542446E-03, + 'mi^2' => 3.86102158542446E-03, + 'Nmi2' => 2.91553349598123E-03, + 'Nmi^2' => 2.91553349598123E-03, + 'Pica2' => 8.03521607043214E+10, + 'Pica^2' => 8.03521607043214E+10, + 'Picapt2' => 8.03521607043214E+10, + 'Picapt^2' => 8.03521607043214E+10, + 'yd2' => 1.19599004630108E+04, + 'yd^2' => 1.19599004630108E+04, + ], + // Conversion uses bit (bit) as an intermediate unit + self::CATEGORY_INFORMATION => [ + 'bit' => 1.0, + 'byte' => 0.125, + ], + // Conversion uses Meters per Second (m/s) as an intermediate unit + self::CATEGORY_SPEED => [ + 'm/s' => 1.0, + 'm/sec' => 1.0, + 'm/h' => 3.60E+03, + 'm/hr' => 3.60E+03, + 'mph' => 2.23693629205440E+00, + 'admkn' => 1.94260256941567E+00, + 'kn' => 1.94384449244060E+00, + ], + ]; + + /** + * getConversionGroups + * Returns a list of the different conversion groups for UOM conversions. + * + * @return array + */ + public static function getConversionCategories() + { + $conversionGroups = []; + foreach (self::$conversionUnits as $conversionUnit) { + $conversionGroups[] = $conversionUnit['Group']; + } + + return array_merge(array_unique($conversionGroups)); + } + + /** + * getConversionGroupUnits + * Returns an array of units of measure, for a specified conversion group, or for all groups. + * + * @param string $category The group whose units of measure you want to retrieve + * + * @return array + */ + public static function getConversionCategoryUnits($category = null) + { + $conversionGroups = []; + foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) { + if (($category === null) || ($conversionGroup['Group'] == $category)) { + $conversionGroups[$conversionGroup['Group']][] = $conversionUnit; + } + } + + return $conversionGroups; + } + + /** + * getConversionGroupUnitDetails. + * + * @param string $category The group whose units of measure you want to retrieve + * + * @return array + */ + public static function getConversionCategoryUnitDetails($category = null) + { + $conversionGroups = []; + foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) { + if (($category === null) || ($conversionGroup['Group'] == $category)) { + $conversionGroups[$conversionGroup['Group']][] = [ + 'unit' => $conversionUnit, + 'description' => $conversionGroup['Unit Name'], + ]; + } + } + + return $conversionGroups; + } + + /** + * getConversionMultipliers + * Returns an array of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM(). + * + * @return mixed[] + */ + public static function getConversionMultipliers() + { + return self::$conversionMultipliers; + } + + /** + * getBinaryConversionMultipliers + * Returns an array of the additional Multiplier prefixes that can be used with Information Units of Measure in CONVERTUOM(). + * + * @return mixed[] + */ + public static function getBinaryConversionMultipliers() + { + return self::$binaryConversionMultipliers; + } + + /** + * CONVERT. + * + * Converts a number from one measurement system to another. + * For example, CONVERT can translate a table of distances in miles to a table of distances + * in kilometers. + * + * Excel Function: + * CONVERT(value,fromUOM,toUOM) + * + * @param float|int $value the value in fromUOM to convert + * @param string $fromUOM the units for value + * @param string $toUOM the units for the result + * + * @return float|string + */ + public static function CONVERT($value, $fromUOM, $toUOM) + { + $value = Functions::flattenSingleValue($value); + $fromUOM = Functions::flattenSingleValue($fromUOM); + $toUOM = Functions::flattenSingleValue($toUOM); + + if (!is_numeric($value)) { + return Functions::VALUE(); + } + + try { + [$fromUOM, $fromCategory, $fromMultiplier] = self::getUOMDetails($fromUOM); + [$toUOM, $toCategory, $toMultiplier] = self::getUOMDetails($toUOM); + } catch (Exception $e) { + return Functions::NA(); + } + + if ($fromCategory !== $toCategory) { + return Functions::NA(); + } + + $value *= $fromMultiplier; + + if (($fromUOM === $toUOM) && ($fromMultiplier === $toMultiplier)) { + // We've already factored $fromMultiplier into the value, so we need + // to reverse it again + return $value / $fromMultiplier; + } elseif ($fromUOM === $toUOM) { + return $value / $toMultiplier; + } elseif ($fromCategory === self::CATEGORY_TEMPERATURE) { + return self::convertTemperature($fromUOM, $toUOM, $value); + } + + $baseValue = $value * (1.0 / self::$unitConversions[$fromCategory][$fromUOM]); + + return ($baseValue * self::$unitConversions[$fromCategory][$toUOM]) / $toMultiplier; + } + + private static function getUOMDetails(string $uom) + { + if (isset(self::$conversionUnits[$uom])) { + $unitCategory = self::$conversionUnits[$uom]['Group']; + + return [$uom, $unitCategory, 1.0]; + } + + // Check 1-character standard metric multiplier prefixes + $multiplierType = substr($uom, 0, 1); + $uom = substr($uom, 1); + if (isset(self::$conversionUnits[$uom], self::$conversionMultipliers[$multiplierType])) { + if (self::$conversionUnits[$uom]['AllowPrefix'] === false) { + throw new Exception('Prefix not allowed for UoM'); + } + $unitCategory = self::$conversionUnits[$uom]['Group']; + + return [$uom, $unitCategory, self::$conversionMultipliers[$multiplierType]['multiplier']]; + } + + $multiplierType .= substr($uom, 0, 1); + $uom = substr($uom, 1); + + // Check 2-character standard metric multiplier prefixes + if (isset(self::$conversionUnits[$uom], self::$conversionMultipliers[$multiplierType])) { + if (self::$conversionUnits[$uom]['AllowPrefix'] === false) { + throw new Exception('Prefix not allowed for UoM'); + } + $unitCategory = self::$conversionUnits[$uom]['Group']; + + return [$uom, $unitCategory, self::$conversionMultipliers[$multiplierType]['multiplier']]; + } + + // Check 2-character binary multiplier prefixes + if (isset(self::$conversionUnits[$uom], self::$binaryConversionMultipliers[$multiplierType])) { + if (self::$conversionUnits[$uom]['AllowPrefix'] === false) { + throw new Exception('Prefix not allowed for UoM'); + } + $unitCategory = self::$conversionUnits[$uom]['Group']; + if ($unitCategory !== 'Information') { + throw new Exception('Binary Prefix is only allowed for Information UoM'); + } + + return [$uom, $unitCategory, self::$binaryConversionMultipliers[$multiplierType]['multiplier']]; + } + + throw new Exception('UoM Not Found'); + } + + /** + * @param float|int $value + * + * @return float|int + */ + protected static function convertTemperature(string $fromUOM, string $toUOM, $value) + { + $fromUOM = self::resolveTemperatureSynonyms($fromUOM); + $toUOM = self::resolveTemperatureSynonyms($toUOM); + + if ($fromUOM === $toUOM) { + return $value; + } + + // Convert to Kelvin + switch ($fromUOM) { + case 'F': + $value = ($value - 32) / 1.8 + 273.15; + + break; + case 'C': + $value += 273.15; + + break; + case 'Rank': + $value /= 1.8; + + break; + case 'Reau': + $value = $value * 1.25 + 273.15; + + break; + } + + // Convert from Kelvin + switch ($toUOM) { + case 'F': + $value = ($value - 273.15) * 1.8 + 32.00; + + break; + case 'C': + $value -= 273.15; + + break; + case 'Rank': + $value *= 1.8; + + break; + case 'Reau': + $value = ($value - 273.15) * 0.80000; + + break; + } + + return $value; + } + + private static function resolveTemperatureSynonyms(string $uom) + { + switch ($uom) { + case 'fah': + return 'F'; + case 'cel': + return 'C'; + case 'kel': + return 'K'; + } + + return $uom; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Engineering/EngineeringValidations.php b/src/PhpSpreadsheet/Calculation/Engineering/EngineeringValidations.php new file mode 100644 index 00000000..01630af3 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Engineering/EngineeringValidations.php @@ -0,0 +1,33 @@ + 2.2) { + return 1 - ErfC::ERFC($value); + } + $sum = $term = $value; + $xsqr = ($value * $value); + $j = 1; + do { + $term *= $xsqr / $j; + $sum -= $term / (2 * $j + 1); + ++$j; + $term *= $xsqr / $j; + $sum += $term / (2 * $j + 1); + ++$j; + if ($sum == 0.0) { + break; + } + } while (abs($term / $sum) > Functions::PRECISION); + + return self::$twoSqrtPi * $sum; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Engineering/ErfC.php b/src/PhpSpreadsheet/Calculation/Engineering/ErfC.php new file mode 100644 index 00000000..c57a28f4 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Engineering/ErfC.php @@ -0,0 +1,68 @@ + Functions::PRECISION); + + return self::$oneSqrtPi * exp(-$value * $value) * $q2; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Financial.php b/src/PhpSpreadsheet/Calculation/Financial.php index 5a908aa5..9d933b4a 100644 --- a/src/PhpSpreadsheet/Calculation/Financial.php +++ b/src/PhpSpreadsheet/Calculation/Financial.php @@ -2,167 +2,81 @@ namespace PhpOffice\PhpSpreadsheet\Calculation; -use PhpOffice\PhpSpreadsheet\Shared\Date; +use PhpOffice\PhpSpreadsheet\Calculation\Financial\Amortization; +use PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons; +use PhpOffice\PhpSpreadsheet\Calculation\Financial\Depreciation; +use PhpOffice\PhpSpreadsheet\Calculation\Financial\Dollar; +use PhpOffice\PhpSpreadsheet\Calculation\Financial\InterestRate; +use PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities; +use PhpOffice\PhpSpreadsheet\Calculation\Financial\TreasuryBill; +/** + * @deprecated 1.18.0 + */ class Financial { const FINANCIAL_MAX_ITERATIONS = 128; const FINANCIAL_PRECISION = 1.0e-08; - /** - * isLastDayOfMonth. - * - * Returns a boolean TRUE/FALSE indicating if this date is the last date of the month - * - * @param \DateTime $testDate The date for testing - * - * @return bool - */ - private static function isLastDayOfMonth(\DateTime $testDate) - { - return $testDate->format('d') == $testDate->format('t'); - } - - private static function couponFirstPeriodDate($settlement, $maturity, $frequency, $next) - { - $months = 12 / $frequency; - - $result = Date::excelToDateTimeObject($maturity); - $eom = self::isLastDayOfMonth($result); - - while ($settlement < Date::PHPToExcel($result)) { - $result->modify('-' . $months . ' months'); - } - if ($next) { - $result->modify('+' . $months . ' months'); - } - - if ($eom) { - $result->modify('-1 day'); - } - - return Date::PHPToExcel($result); - } - - private static function isValidFrequency($frequency) - { - if (($frequency == 1) || ($frequency == 2) || ($frequency == 4)) { - return true; - } - - return false; - } - - /** - * daysPerYear. - * - * Returns the number of days in a specified year, as defined by the "basis" value - * - * @param int|string $year The year against which we're testing - * @param int|string $basis The type of day count: - * 0 or omitted US (NASD) 360 - * 1 Actual (365 or 366 in a leap year) - * 2 360 - * 3 365 - * 4 European 360 - * - * @return int|string Result, or a string containing an error - */ - private static function daysPerYear($year, $basis = 0) - { - switch ($basis) { - case 0: - case 2: - case 4: - $daysPerYear = 360; - - break; - case 3: - $daysPerYear = 365; - - break; - case 1: - $daysPerYear = (DateTime::isLeapYear($year)) ? 366 : 365; - - break; - default: - return Functions::NAN(); - } - - return $daysPerYear; - } - - private static function interestAndPrincipal($rate = 0, $per = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0) - { - $pmt = self::PMT($rate, $nper, $pv, $fv, $type); - $capital = $pv; - for ($i = 1; $i <= $per; ++$i) { - $interest = ($type && $i == 1) ? 0 : -$capital * $rate; - $principal = $pmt - $interest; - $capital += $principal; - } - - return [$interest, $principal]; - } - /** * ACCRINT. * * Returns the accrued interest for a security that pays periodic interest. * * Excel Function: - * ACCRINT(issue,firstinterest,settlement,rate,par,frequency[,basis]) + * ACCRINT(issue,firstinterest,settlement,rate,par,frequency[,basis][,calc_method]) + * + * @Deprecated 1.18.0 + * + * @see Financial\Securities\AccruedInterest::periodic() + * Use the periodic() method in the Financial\Securities\AccruedInterest class instead * * @param mixed $issue the security's issue date - * @param mixed $firstinterest the security's first interest date + * @param mixed $firstInterest the security's first interest date * @param mixed $settlement The security's settlement date. - * The security settlement date is the date after the issue date - * when the security is traded to the buyer. - * @param float $rate the security's annual coupon rate - * @param float $par The security's par value. - * If you omit par, ACCRINT uses $1,000. - * @param int $frequency the number of coupon payments per year. - * Valid frequency values are: - * 1 Annual - * 2 Semi-Annual - * 4 Quarterly - * @param int $basis The type of day count to use. - * 0 or omitted US (NASD) 30/360 - * 1 Actual/actual - * 2 Actual/360 - * 3 Actual/365 - * 4 European 30/360 + * The security settlement date is the date after the issue date + * when the security is traded to the buyer. + * @param mixed $rate the security's annual coupon rate + * @param mixed $parValue The security's par value. + * If you omit par, ACCRINT uses $1,000. + * @param mixed $frequency The number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * @param mixed $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @param mixed $calcMethod + * If true, use Issue to Settlement + * If false, use FirstInterest to Settlement * * @return float|string Result, or a string containing an error */ - public static function ACCRINT($issue, $firstinterest, $settlement, $rate, $par = 1000, $frequency = 1, $basis = 0) - { - $issue = Functions::flattenSingleValue($issue); - $firstinterest = Functions::flattenSingleValue($firstinterest); - $settlement = Functions::flattenSingleValue($settlement); - $rate = Functions::flattenSingleValue($rate); - $par = ($par === null) ? 1000 : Functions::flattenSingleValue($par); - $frequency = ($frequency === null) ? 1 : Functions::flattenSingleValue($frequency); - $basis = ($basis === null) ? 0 : Functions::flattenSingleValue($basis); - - // Validate - if ((is_numeric($rate)) && (is_numeric($par))) { - $rate = (float) $rate; - $par = (float) $par; - if (($rate <= 0) || ($par <= 0)) { - return Functions::NAN(); - } - $daysBetweenIssueAndSettlement = DateTime::YEARFRAC($issue, $settlement, $basis); - if (!is_numeric($daysBetweenIssueAndSettlement)) { - // return date error - return $daysBetweenIssueAndSettlement; - } - - return $par * $rate * $daysBetweenIssueAndSettlement; - } - - return Functions::VALUE(); + public static function ACCRINT( + $issue, + $firstInterest, + $settlement, + $rate, + $parValue = 1000, + $frequency = 1, + $basis = 0, + $calcMethod = true + ) { + return Securities\AccruedInterest::periodic( + $issue, + $firstInterest, + $settlement, + $rate, + $parValue, + $frequency, + $basis, + $calcMethod + ); } /** @@ -173,45 +87,28 @@ class Financial * Excel Function: * ACCRINTM(issue,settlement,rate[,par[,basis]]) * + * @Deprecated 1.18.0 + * + * @see Financial\Securities\AccruedInterest::atMaturity() + * Use the atMaturity() method in the Financial\Securities\AccruedInterest class instead + * * @param mixed $issue The security's issue date * @param mixed $settlement The security's settlement (or maturity) date - * @param float $rate The security's annual coupon rate - * @param float $par The security's par value. - * If you omit par, ACCRINT uses $1,000. - * @param int $basis The type of day count to use. - * 0 or omitted US (NASD) 30/360 - * 1 Actual/actual - * 2 Actual/360 - * 3 Actual/365 - * 4 European 30/360 + * @param mixed $rate The security's annual coupon rate + * @param mixed $parValue The security's par value. + * If you omit par, ACCRINT uses $1,000. + * @param mixed $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 * * @return float|string Result, or a string containing an error */ - public static function ACCRINTM($issue, $settlement, $rate, $par = 1000, $basis = 0) + public static function ACCRINTM($issue, $settlement, $rate, $parValue = 1000, $basis = 0) { - $issue = Functions::flattenSingleValue($issue); - $settlement = Functions::flattenSingleValue($settlement); - $rate = Functions::flattenSingleValue($rate); - $par = ($par === null) ? 1000 : Functions::flattenSingleValue($par); - $basis = ($basis === null) ? 0 : Functions::flattenSingleValue($basis); - - // Validate - if ((is_numeric($rate)) && (is_numeric($par))) { - $rate = (float) $rate; - $par = (float) $par; - if (($rate <= 0) || ($par <= 0)) { - return Functions::NAN(); - } - $daysBetweenIssueAndSettlement = DateTime::YEARFRAC($issue, $settlement, $basis); - if (!is_numeric($daysBetweenIssueAndSettlement)) { - // return date error - return $daysBetweenIssueAndSettlement; - } - - return $par * $rate * $daysBetweenIssueAndSettlement; - } - - return Functions::VALUE(); + return Securities\AccruedInterest::atMaturity($issue, $settlement, $rate, $parValue, $basis); } /** @@ -229,6 +126,11 @@ class Financial * Excel Function: * AMORDEGRC(cost,purchased,firstPeriod,salvage,period,rate[,basis]) * + * @Deprecated 1.18.0 + * + * @see Financial\Amortization::AMORDEGRC() + * Use the AMORDEGRC() method in the Financial\Amortization class instead + * * @param float $cost The cost of the asset * @param mixed $purchased Date of the purchase of the asset * @param mixed $firstPeriod Date of the end of the first period @@ -236,63 +138,17 @@ class Financial * @param float $period The period * @param float $rate Rate of depreciation * @param int $basis The type of day count to use. - * 0 or omitted US (NASD) 30/360 - * 1 Actual/actual - * 2 Actual/360 - * 3 Actual/365 - * 4 European 30/360 + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 * - * @return float + * @return float|string (string containing the error type if there is an error) */ public static function AMORDEGRC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis = 0) { - $cost = Functions::flattenSingleValue($cost); - $purchased = Functions::flattenSingleValue($purchased); - $firstPeriod = Functions::flattenSingleValue($firstPeriod); - $salvage = Functions::flattenSingleValue($salvage); - $period = floor(Functions::flattenSingleValue($period)); - $rate = Functions::flattenSingleValue($rate); - $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis); - - // The depreciation coefficients are: - // Life of assets (1/rate) Depreciation coefficient - // Less than 3 years 1 - // Between 3 and 4 years 1.5 - // Between 5 and 6 years 2 - // More than 6 years 2.5 - $fUsePer = 1.0 / $rate; - if ($fUsePer < 3.0) { - $amortiseCoeff = 1.0; - } elseif ($fUsePer < 5.0) { - $amortiseCoeff = 1.5; - } elseif ($fUsePer <= 6.0) { - $amortiseCoeff = 2.0; - } else { - $amortiseCoeff = 2.5; - } - - $rate *= $amortiseCoeff; - $fNRate = round(DateTime::YEARFRAC($purchased, $firstPeriod, $basis) * $rate * $cost, 0); - $cost -= $fNRate; - $fRest = $cost - $salvage; - - for ($n = 0; $n < $period; ++$n) { - $fNRate = round($rate * $cost, 0); - $fRest -= $fNRate; - - if ($fRest < 0.0) { - switch ($period - $n) { - case 0: - case 1: - return round($cost * 0.5, 0); - default: - return 0.0; - } - } - $cost -= $fNRate; - } - - return $fNRate; + return Amortization::AMORDEGRC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis); } /** @@ -305,6 +161,11 @@ class Financial * Excel Function: * AMORLINC(cost,purchased,firstPeriod,salvage,period,rate[,basis]) * + * @Deprecated 1.18.0 + * + * @see Financial\Amortization::AMORLINC() + * Use the AMORLINC() method in the Financial\Amortization class instead + * * @param float $cost The cost of the asset * @param mixed $purchased Date of the purchase of the asset * @param mixed $firstPeriod Date of the end of the first period @@ -312,46 +173,17 @@ class Financial * @param float $period The period * @param float $rate Rate of depreciation * @param int $basis The type of day count to use. - * 0 or omitted US (NASD) 30/360 - * 1 Actual/actual - * 2 Actual/360 - * 3 Actual/365 - * 4 European 30/360 + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 * - * @return float + * @return float|string (string containing the error type if there is an error) */ public static function AMORLINC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis = 0) { - $cost = Functions::flattenSingleValue($cost); - $purchased = Functions::flattenSingleValue($purchased); - $firstPeriod = Functions::flattenSingleValue($firstPeriod); - $salvage = Functions::flattenSingleValue($salvage); - $period = Functions::flattenSingleValue($period); - $rate = Functions::flattenSingleValue($rate); - $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis); - - $fOneRate = $cost * $rate; - $fCostDelta = $cost - $salvage; - // Note, quirky variation for leap years on the YEARFRAC for this function - $purchasedYear = DateTime::YEAR($purchased); - $yearFrac = DateTime::YEARFRAC($purchased, $firstPeriod, $basis); - - if (($basis == 1) && ($yearFrac < 1) && (DateTime::isLeapYear($purchasedYear))) { - $yearFrac *= 365 / 366; - } - - $f0Rate = $yearFrac * $rate * $cost; - $nNumOfFullPeriods = (int) (($cost - $salvage - $f0Rate) / $fOneRate); - - if ($period == 0) { - return $f0Rate; - } elseif ($period <= $nNumOfFullPeriods) { - return $fOneRate; - } elseif ($period == ($nNumOfFullPeriods + 1)) { - return $fCostDelta - $fOneRate * $nNumOfFullPeriods - $f0Rate; - } - - return 0.0; + return Amortization::AMORLINC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis); } /** @@ -362,6 +194,11 @@ class Financial * Excel Function: * COUPDAYBS(settlement,maturity,frequency[,basis]) * + * @Deprecated 1.18.0 + * + * @see Financial\Coupons::COUPDAYBS() + * Use the COUPDAYBS() method in the Financial\Coupons class instead + * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. @@ -383,34 +220,7 @@ class Financial */ public static function COUPDAYBS($settlement, $maturity, $frequency, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $frequency = (int) Functions::flattenSingleValue($frequency); - $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis); - - if (is_string($settlement = DateTime::getDateValue($settlement))) { - return Functions::VALUE(); - } - if (is_string($maturity = DateTime::getDateValue($maturity))) { - return Functions::VALUE(); - } - - if ( - ($settlement >= $maturity) || - (!self::isValidFrequency($frequency)) || - (($basis < 0) || ($basis > 4)) - ) { - return Functions::NAN(); - } - - $daysPerYear = self::daysPerYear(DateTime::YEAR($settlement), $basis); - $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, false); - - if ($basis == 1) { - return abs(DateTime::DAYS($prev, $settlement)); - } - - return DateTime::YEARFRAC($prev, $settlement, $basis) * $daysPerYear; + return Coupons::COUPDAYBS($settlement, $maturity, $frequency, $basis); } /** @@ -421,6 +231,11 @@ class Financial * Excel Function: * COUPDAYS(settlement,maturity,frequency[,basis]) * + * @Deprecated 1.18.0 + * + * @see Financial\Coupons::COUPDAYS() + * Use the COUPDAYS() method in the Financial\Coupons class instead + * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. @@ -442,45 +257,7 @@ class Financial */ public static function COUPDAYS($settlement, $maturity, $frequency, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $frequency = (int) Functions::flattenSingleValue($frequency); - $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis); - - if (is_string($settlement = DateTime::getDateValue($settlement))) { - return Functions::VALUE(); - } - if (is_string($maturity = DateTime::getDateValue($maturity))) { - return Functions::VALUE(); - } - - if ( - ($settlement >= $maturity) || - (!self::isValidFrequency($frequency)) || - (($basis < 0) || ($basis > 4)) - ) { - return Functions::NAN(); - } - - switch ($basis) { - case 3: - // Actual/365 - return 365 / $frequency; - case 1: - // Actual/actual - if ($frequency == 1) { - $daysPerYear = self::daysPerYear(DateTime::YEAR($settlement), $basis); - - return $daysPerYear / $frequency; - } - $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, false); - $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, true); - - return $next - $prev; - default: - // US (NASD) 30/360, Actual/360 or European 30/360 - return 360 / $frequency; - } + return Coupons::COUPDAYS($settlement, $maturity, $frequency, $basis); } /** @@ -491,6 +268,11 @@ class Financial * Excel Function: * COUPDAYSNC(settlement,maturity,frequency[,basis]) * + * @Deprecated 1.18.0 + * + * @see Financial\Coupons::COUPDAYSNC() + * Use the COUPDAYSNC() method in the Financial\Coupons class instead + * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. @@ -512,30 +294,7 @@ class Financial */ public static function COUPDAYSNC($settlement, $maturity, $frequency, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $frequency = (int) Functions::flattenSingleValue($frequency); - $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis); - - if (is_string($settlement = DateTime::getDateValue($settlement))) { - return Functions::VALUE(); - } - if (is_string($maturity = DateTime::getDateValue($maturity))) { - return Functions::VALUE(); - } - - if ( - ($settlement >= $maturity) || - (!self::isValidFrequency($frequency)) || - (($basis < 0) || ($basis > 4)) - ) { - return Functions::NAN(); - } - - $daysPerYear = self::daysPerYear(DateTime::YEAR($settlement), $basis); - $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, true); - - return DateTime::YEARFRAC($settlement, $next, $basis) * $daysPerYear; + return Coupons::COUPDAYSNC($settlement, $maturity, $frequency, $basis); } /** @@ -546,6 +305,11 @@ class Financial * Excel Function: * COUPNCD(settlement,maturity,frequency[,basis]) * + * @Deprecated 1.18.0 + * + * @see Financial\Coupons::COUPNCD() + * Use the COUPNCD() method in the Financial\Coupons class instead + * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. @@ -568,27 +332,7 @@ class Financial */ public static function COUPNCD($settlement, $maturity, $frequency, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $frequency = (int) Functions::flattenSingleValue($frequency); - $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis); - - if (is_string($settlement = DateTime::getDateValue($settlement))) { - return Functions::VALUE(); - } - if (is_string($maturity = DateTime::getDateValue($maturity))) { - return Functions::VALUE(); - } - - if ( - ($settlement >= $maturity) || - (!self::isValidFrequency($frequency)) || - (($basis < 0) || ($basis > 4)) - ) { - return Functions::NAN(); - } - - return self::couponFirstPeriodDate($settlement, $maturity, $frequency, true); + return Coupons::COUPNCD($settlement, $maturity, $frequency, $basis); } /** @@ -600,6 +344,11 @@ class Financial * Excel Function: * COUPNUM(settlement,maturity,frequency[,basis]) * + * @Deprecated 1.18.0 + * + * @see Financial\Coupons::COUPNUM() + * Use the COUPNUM() method in the Financial\Coupons class instead + * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. @@ -621,29 +370,7 @@ class Financial */ public static function COUPNUM($settlement, $maturity, $frequency, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $frequency = (int) Functions::flattenSingleValue($frequency); - $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis); - - if (is_string($settlement = DateTime::getDateValue($settlement))) { - return Functions::VALUE(); - } - if (is_string($maturity = DateTime::getDateValue($maturity))) { - return Functions::VALUE(); - } - - if ( - ($settlement >= $maturity) || - (!self::isValidFrequency($frequency)) || - (($basis < 0) || ($basis > 4)) - ) { - return Functions::NAN(); - } - - $yearsBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, 0); - - return ceil($yearsBetweenSettlementAndMaturity * $frequency); + return Coupons::COUPNUM($settlement, $maturity, $frequency, $basis); } /** @@ -654,6 +381,11 @@ class Financial * Excel Function: * COUPPCD(settlement,maturity,frequency[,basis]) * + * @Deprecated 1.18.0 + * + * @see Financial\Coupons::COUPPCD() + * Use the COUPPCD() method in the Financial\Coupons class instead + * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. @@ -676,27 +408,7 @@ class Financial */ public static function COUPPCD($settlement, $maturity, $frequency, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $frequency = (int) Functions::flattenSingleValue($frequency); - $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis); - - if (is_string($settlement = DateTime::getDateValue($settlement))) { - return Functions::VALUE(); - } - if (is_string($maturity = DateTime::getDateValue($maturity))) { - return Functions::VALUE(); - } - - if ( - ($settlement >= $maturity) || - (!self::isValidFrequency($frequency)) || - (($basis < 0) || ($basis > 4)) - ) { - return Functions::NAN(); - } - - return self::couponFirstPeriodDate($settlement, $maturity, $frequency, false); + return Coupons::COUPPCD($settlement, $maturity, $frequency, $basis); } /** @@ -707,42 +419,26 @@ class Financial * Excel Function: * CUMIPMT(rate,nper,pv,start,end[,type]) * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Constant\Periodic\Cumulative::interest() + * Use the interest() method in the Financial\CashFlow\Constant\Periodic\Cumulative class instead + * * @param float $rate The Interest rate * @param int $nper The total number of payment periods * @param float $pv Present Value * @param int $start The first period in the calculation. - * Payment periods are numbered beginning with 1. + * Payment periods are numbered beginning with 1. * @param int $end the last period in the calculation * @param int $type A number 0 or 1 and indicates when payments are due: - * 0 or omitted At the end of the period. - * 1 At the beginning of the period. + * 0 or omitted At the end of the period. + * 1 At the beginning of the period. * * @return float|string */ public static function CUMIPMT($rate, $nper, $pv, $start, $end, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $nper = (int) Functions::flattenSingleValue($nper); - $pv = Functions::flattenSingleValue($pv); - $start = (int) Functions::flattenSingleValue($start); - $end = (int) Functions::flattenSingleValue($end); - $type = (int) Functions::flattenSingleValue($type); - - // Validate parameters - if ($type != 0 && $type != 1) { - return Functions::NAN(); - } - if ($start < 1 || $start > $end) { - return Functions::VALUE(); - } - - // Calculate - $interest = 0; - for ($per = $start; $per <= $end; ++$per) { - $interest += self::IPMT($rate, $per, $nper, $pv, 0, $type); - } - - return $interest; + return Financial\CashFlow\Constant\Periodic\Cumulative::interest($rate, $nper, $pv, $start, $end, $type); } /** @@ -753,42 +449,26 @@ class Financial * Excel Function: * CUMPRINC(rate,nper,pv,start,end[,type]) * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Constant\Periodic\Cumulative::principal() + * Use the principal() method in the Financial\CashFlow\Constant\Periodic\Cumulative class instead + * * @param float $rate The Interest rate * @param int $nper The total number of payment periods * @param float $pv Present Value * @param int $start The first period in the calculation. - * Payment periods are numbered beginning with 1. + * Payment periods are numbered beginning with 1. * @param int $end the last period in the calculation * @param int $type A number 0 or 1 and indicates when payments are due: - * 0 or omitted At the end of the period. - * 1 At the beginning of the period. + * 0 or omitted At the end of the period. + * 1 At the beginning of the period. * * @return float|string */ public static function CUMPRINC($rate, $nper, $pv, $start, $end, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $nper = (int) Functions::flattenSingleValue($nper); - $pv = Functions::flattenSingleValue($pv); - $start = (int) Functions::flattenSingleValue($start); - $end = (int) Functions::flattenSingleValue($end); - $type = (int) Functions::flattenSingleValue($type); - - // Validate parameters - if ($type != 0 && $type != 1) { - return Functions::NAN(); - } - if ($start < 1 || $start > $end) { - return Functions::VALUE(); - } - - // Calculate - $principal = 0; - for ($per = $start; $per <= $end; ++$per) { - $principal += self::PPMT($rate, $per, $nper, $pv, 0, $type); - } - - return $principal; + return Financial\CashFlow\Constant\Periodic\Cumulative::principal($rate, $nper, $pv, $start, $end, $type); } /** @@ -804,6 +484,11 @@ class Financial * Excel Function: * DB(cost,salvage,life,period[,month]) * + * @Deprecated 1.18.0 + * + * @see Financial\Depreciation::DB() + * Use the DB() method in the Financial\Depreciation class instead + * * @param float $cost Initial cost of the asset * @param float $salvage Value at the end of the depreciation. * (Sometimes called the salvage value of the asset) @@ -818,46 +503,7 @@ class Financial */ public static function DB($cost, $salvage, $life, $period, $month = 12) { - $cost = Functions::flattenSingleValue($cost); - $salvage = Functions::flattenSingleValue($salvage); - $life = Functions::flattenSingleValue($life); - $period = Functions::flattenSingleValue($period); - $month = Functions::flattenSingleValue($month); - - // Validate - if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($month))) { - $cost = (float) $cost; - $salvage = (float) $salvage; - $life = (int) $life; - $period = (int) $period; - $month = (int) $month; - if ($cost == 0) { - return 0.0; - } elseif (($cost < 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($month < 1)) { - return Functions::NAN(); - } - // Set Fixed Depreciation Rate - $fixedDepreciationRate = 1 - ($salvage / $cost) ** (1 / $life); - $fixedDepreciationRate = round($fixedDepreciationRate, 3); - - // Loop through each period calculating the depreciation - $previousDepreciation = 0; - $depreciation = 0; - for ($per = 1; $per <= $period; ++$per) { - if ($per == 1) { - $depreciation = $cost * $fixedDepreciationRate * $month / 12; - } elseif ($per == ($life + 1)) { - $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate * (12 - $month) / 12; - } else { - $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate; - } - $previousDepreciation += $depreciation; - } - - return $depreciation; - } - - return Functions::VALUE(); + return Depreciation::DB($cost, $salvage, $life, $period, $month); } /** @@ -869,6 +515,11 @@ class Financial * Excel Function: * DDB(cost,salvage,life,period[,factor]) * + * @Deprecated 1.18.0 + * + * @see Financial\Depreciation::DDB() + * Use the DDB() method in the Financial\Depreciation class instead + * * @param float $cost Initial cost of the asset * @param float $salvage Value at the end of the depreciation. * (Sometimes called the salvage value of the asset) @@ -884,38 +535,7 @@ class Financial */ public static function DDB($cost, $salvage, $life, $period, $factor = 2.0) { - $cost = Functions::flattenSingleValue($cost); - $salvage = Functions::flattenSingleValue($salvage); - $life = Functions::flattenSingleValue($life); - $period = Functions::flattenSingleValue($period); - $factor = Functions::flattenSingleValue($factor); - - // Validate - if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($factor))) { - $cost = (float) $cost; - $salvage = (float) $salvage; - $life = (int) $life; - $period = (int) $period; - $factor = (float) $factor; - if (($cost <= 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($factor <= 0.0) || ($period > $life)) { - return Functions::NAN(); - } - // Set Fixed Depreciation Rate - $fixedDepreciationRate = 1 - ($salvage / $cost) ** (1 / $life); - $fixedDepreciationRate = round($fixedDepreciationRate, 3); - - // Loop through each period calculating the depreciation - $previousDepreciation = 0; - $depreciation = 0; - for ($per = 1; $per <= $period; ++$per) { - $depreciation = min(($cost - $previousDepreciation) * ($factor / $life), ($cost - $salvage - $previousDepreciation)); - $previousDepreciation += $depreciation; - } - - return $depreciation; - } - - return Functions::VALUE(); + return Depreciation::DDB($cost, $salvage, $life, $period, $factor); } /** @@ -926,6 +546,11 @@ class Financial * Excel Function: * DISC(settlement,maturity,price,redemption[,basis]) * + * @Deprecated 1.18.0 + * + * @see Financial\Securities\Rates::discount() + * Use the discount() method in the Financial\Securities\Rates class instead + * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. @@ -944,30 +569,7 @@ class Financial */ public static function DISC($settlement, $maturity, $price, $redemption, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $price = Functions::flattenSingleValue($price); - $redemption = Functions::flattenSingleValue($redemption); - $basis = Functions::flattenSingleValue($basis); - - // Validate - if ((is_numeric($price)) && (is_numeric($redemption)) && (is_numeric($basis))) { - $price = (float) $price; - $redemption = (float) $redemption; - $basis = (int) $basis; - if (($price <= 0) || ($redemption <= 0)) { - return Functions::NAN(); - } - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, $basis); - if (!is_numeric($daysBetweenSettlementAndMaturity)) { - // return date error - return $daysBetweenSettlementAndMaturity; - } - - return (1 - $price / $redemption) / $daysBetweenSettlementAndMaturity; - } - - return Functions::VALUE(); + return Financial\Securities\Rates::discount($settlement, $maturity, $price, $redemption, $basis); } /** @@ -980,6 +582,11 @@ class Financial * Excel Function: * DOLLARDE(fractional_dollar,fraction) * + * @Deprecated 1.18.0 + * + * @see Financial\Dollar::decimal() + * Use the decimal() method in the Financial\Dollar class instead + * * @param float $fractional_dollar Fractional Dollar * @param int $fraction Fraction * @@ -987,23 +594,7 @@ class Financial */ public static function DOLLARDE($fractional_dollar = null, $fraction = 0) { - $fractional_dollar = Functions::flattenSingleValue($fractional_dollar); - $fraction = (int) Functions::flattenSingleValue($fraction); - - // Validate parameters - if ($fractional_dollar === null || $fraction < 0) { - return Functions::NAN(); - } - if ($fraction == 0) { - return Functions::DIV0(); - } - - $dollars = floor($fractional_dollar); - $cents = fmod($fractional_dollar, 1); - $cents /= $fraction; - $cents *= 10 ** ceil(log10($fraction)); - - return $dollars + $cents; + return Dollar::decimal($fractional_dollar, $fraction); } /** @@ -1016,6 +607,11 @@ class Financial * Excel Function: * DOLLARFR(decimal_dollar,fraction) * + * @Deprecated 1.18.0 + * + * @see Financial\Dollar::fractional() + * Use the fractional() method in the Financial\Dollar class instead + * * @param float $decimal_dollar Decimal Dollar * @param int $fraction Fraction * @@ -1023,23 +619,7 @@ class Financial */ public static function DOLLARFR($decimal_dollar = null, $fraction = 0) { - $decimal_dollar = Functions::flattenSingleValue($decimal_dollar); - $fraction = (int) Functions::flattenSingleValue($fraction); - - // Validate parameters - if ($decimal_dollar === null || $fraction < 0) { - return Functions::NAN(); - } - if ($fraction == 0) { - return Functions::DIV0(); - } - - $dollars = floor($decimal_dollar); - $cents = fmod($decimal_dollar, 1); - $cents *= $fraction; - $cents *= 10 ** (-ceil(log10($fraction))); - - return $dollars + $cents; + return Dollar::fractional($decimal_dollar, $fraction); } /** @@ -1051,22 +631,19 @@ class Financial * Excel Function: * EFFECT(nominal_rate,npery) * - * @param float $nominal_rate Nominal interest rate - * @param int $npery Number of compounding payments per year + * @Deprecated 1.18.0 + * + * @see Financial\InterestRate::effective() + * Use the effective() method in the Financial\InterestRate class instead + * + * @param float $nominalRate Nominal interest rate + * @param int $periodsPerYear Number of compounding payments per year * * @return float|string */ - public static function EFFECT($nominal_rate = 0, $npery = 0) + public static function EFFECT($nominalRate = 0, $periodsPerYear = 0) { - $nominal_rate = Functions::flattenSingleValue($nominal_rate); - $npery = (int) Functions::flattenSingleValue($npery); - - // Validate parameters - if ($nominal_rate <= 0 || $npery < 1) { - return Functions::NAN(); - } - - return (1 + $nominal_rate / $npery) ** $npery - 1; + return Financial\InterestRate::effective($nominalRate, $periodsPerYear); } /** @@ -1077,6 +654,11 @@ class Financial * Excel Function: * FV(rate,nper,pmt[,pv[,type]]) * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Constant\Periodic::futureValue() + * Use the futureValue() method in the Financial\CashFlow\Constant\Periodic class instead + * * @param float $rate The interest rate per period * @param int $nper Total number of payment periods in an annuity * @param float $pmt The payment made each period: it cannot change over the @@ -1092,23 +674,7 @@ class Financial */ public static function FV($rate = 0, $nper = 0, $pmt = 0, $pv = 0, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $nper = Functions::flattenSingleValue($nper); - $pmt = Functions::flattenSingleValue($pmt); - $pv = Functions::flattenSingleValue($pv); - $type = Functions::flattenSingleValue($type); - - // Validate parameters - if ($type != 0 && $type != 1) { - return Functions::NAN(); - } - - // Calculate - if ($rate !== null && $rate != 0) { - return -$pv * (1 + $rate) ** $nper - $pmt * (1 + $rate * $type) * ((1 + $rate) ** $nper - 1) / $rate; - } - - return -$pv - $pmt * $nper; + return Financial\CashFlow\Constant\Periodic::futureValue($rate, $nper, $pmt, $pv, $type); } /** @@ -1120,21 +686,19 @@ class Financial * Excel Function: * FVSCHEDULE(principal,schedule) * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Single::futureValue() + * Use the futureValue() method in the Financial\CashFlow\Single class instead + * * @param float $principal the present value * @param float[] $schedule an array of interest rates to apply * - * @return float + * @return float|string */ public static function FVSCHEDULE($principal, $schedule) { - $principal = Functions::flattenSingleValue($principal); - $schedule = Functions::flattenArray($schedule); - - foreach ($schedule as $rate) { - $principal *= 1 + $rate; - } - - return $principal; + return Financial\CashFlow\Single::futureValue($principal, $schedule); } /** @@ -1145,57 +709,46 @@ class Financial * Excel Function: * INTRATE(settlement,maturity,investment,redemption[,basis]) * + * @Deprecated 1.18.0 + * + * @see Financial\Securities\Rates::interest() + * Use the interest() method in the Financial\Securities\Rates class instead + * * @param mixed $settlement The security's settlement date. - * The security settlement date is the date after the issue date when the security is traded to the buyer. + * The security settlement date is the date after the issue date when the security + * is traded to the buyer. * @param mixed $maturity The security's maturity date. - * The maturity date is the date when the security expires. + * The maturity date is the date when the security expires. * @param int $investment the amount invested in the security * @param int $redemption the amount to be received at maturity * @param int $basis The type of day count to use. - * 0 or omitted US (NASD) 30/360 - * 1 Actual/actual - * 2 Actual/360 - * 3 Actual/365 - * 4 European 30/360 + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 * * @return float|string */ public static function INTRATE($settlement, $maturity, $investment, $redemption, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $investment = Functions::flattenSingleValue($investment); - $redemption = Functions::flattenSingleValue($redemption); - $basis = Functions::flattenSingleValue($basis); - - // Validate - if ((is_numeric($investment)) && (is_numeric($redemption)) && (is_numeric($basis))) { - $investment = (float) $investment; - $redemption = (float) $redemption; - $basis = (int) $basis; - if (($investment <= 0) || ($redemption <= 0)) { - return Functions::NAN(); - } - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, $basis); - if (!is_numeric($daysBetweenSettlementAndMaturity)) { - // return date error - return $daysBetweenSettlementAndMaturity; - } - - return (($redemption / $investment) - 1) / ($daysBetweenSettlementAndMaturity); - } - - return Functions::VALUE(); + return Financial\Securities\Rates::interest($settlement, $maturity, $investment, $redemption, $basis); } /** * IPMT. * - * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate. + * Returns the interest payment for a given period for an investment based on periodic, constant payments + * and a constant interest rate. * * Excel Function: * IPMT(rate,per,nper,pv[,fv][,type]) * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Constant\Periodic\Interest::payment() + * Use the payment() method in the Financial\CashFlow\Constant\Periodic class instead + * * @param float $rate Interest rate per period * @param int $per Period for which we want to find the interest * @param int $nper Number of periods @@ -1207,25 +760,7 @@ class Financial */ public static function IPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $per = (int) Functions::flattenSingleValue($per); - $nper = (int) Functions::flattenSingleValue($nper); - $pv = Functions::flattenSingleValue($pv); - $fv = Functions::flattenSingleValue($fv); - $type = (int) Functions::flattenSingleValue($type); - - // Validate parameters - if ($type != 0 && $type != 1) { - return Functions::NAN(); - } - if ($per <= 0 || $per > $nper) { - return Functions::VALUE(); - } - - // Calculate - $interestAndPrincipal = self::interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type); - - return $interestAndPrincipal[0]; + return Financial\CashFlow\Constant\Periodic\Interest::payment($rate, $per, $nper, $pv, $fv, $type); } /** @@ -1240,63 +775,22 @@ class Financial * Excel Function: * IRR(values[,guess]) * - * @param float[] $values An array or a reference to cells that contain numbers for which you want + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Variable\Periodic::rate() + * Use the rate() method in the Financial\CashFlow\Variable\Periodic class instead + * + * @param mixed $values An array or a reference to cells that contain numbers for which you want * to calculate the internal rate of return. * Values must contain at least one positive value and one negative value to * calculate the internal rate of return. - * @param float $guess A number that you guess is close to the result of IRR + * @param mixed $guess A number that you guess is close to the result of IRR * * @return float|string */ public static function IRR($values, $guess = 0.1) { - if (!is_array($values)) { - return Functions::VALUE(); - } - $values = Functions::flattenArray($values); - $guess = Functions::flattenSingleValue($guess); - - // create an initial range, with a root somewhere between 0 and guess - $x1 = 0.0; - $x2 = $guess; - $f1 = self::NPV($x1, $values); - $f2 = self::NPV($x2, $values); - for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { - if (($f1 * $f2) < 0.0) { - break; - } - if (abs($f1) < abs($f2)) { - $f1 = self::NPV($x1 += 1.6 * ($x1 - $x2), $values); - } else { - $f2 = self::NPV($x2 += 1.6 * ($x2 - $x1), $values); - } - } - if (($f1 * $f2) > 0.0) { - return Functions::VALUE(); - } - - $f = self::NPV($x1, $values); - if ($f < 0.0) { - $rtb = $x1; - $dx = $x2 - $x1; - } else { - $rtb = $x2; - $dx = $x1 - $x2; - } - - for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { - $dx *= 0.5; - $x_mid = $rtb + $dx; - $f_mid = self::NPV($x_mid, $values); - if ($f_mid <= 0.0) { - $rtb = $x_mid; - } - if ((abs($f_mid) < self::FINANCIAL_PRECISION) || (abs($dx) < self::FINANCIAL_PRECISION)) { - return $x_mid; - } - } - - return Functions::VALUE(); + return Financial\CashFlow\Variable\Periodic::rate($values, $guess); } /** @@ -1305,7 +799,12 @@ class Financial * Returns the interest payment for an investment based on an interest rate and a constant payment schedule. * * Excel Function: - * =ISPMT(interest_rate, period, number_payments, PV) + * =ISPMT(interest_rate, period, number_payments, pv) + * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Constant\Periodic\Interest::schedulePayment() + * Use the schedulePayment() method in the Financial\CashFlow\Constant\Periodic class instead * * interest_rate is the interest rate for the investment * @@ -1313,32 +812,11 @@ class Financial * * number_payments is the number of payments for the annuity * - * PV is the loan amount or present value of the payments + * pv is the loan amount or present value of the payments */ public static function ISPMT(...$args) { - // Return value - $returnValue = 0; - - // Get the parameters - $aArgs = Functions::flattenArray($args); - $interestRate = array_shift($aArgs); - $period = array_shift($aArgs); - $numberPeriods = array_shift($aArgs); - $principleRemaining = array_shift($aArgs); - - // Calculate - $principlePayment = ($principleRemaining * 1.0) / ($numberPeriods * 1.0); - for ($i = 0; $i <= $period; ++$i) { - $returnValue = $interestRate * $principleRemaining * -1; - $principleRemaining -= $principlePayment; - // principle needs to be 0 after the last payment, don't let floating point screw it up - if ($i == $numberPeriods) { - $returnValue = 0; - } - } - - return $returnValue; + return Financial\CashFlow\Constant\Periodic\Interest::schedulePayment(...$args); } /** @@ -1350,44 +828,22 @@ class Financial * Excel Function: * MIRR(values,finance_rate, reinvestment_rate) * - * @param float[] $values An array or a reference to cells that contain a series of payments and - * income occurring at regular intervals. - * Payments are negative value, income is positive values. - * @param float $finance_rate The interest rate you pay on the money used in the cash flows - * @param float $reinvestment_rate The interest rate you receive on the cash flows as you reinvest them + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Variable\Periodic::modifiedRate() + * Use the modifiedRate() method in the Financial\CashFlow\Variable\Periodic class instead + * + * @param mixed $values An array or a reference to cells that contain a series of payments and + * income occurring at regular intervals. + * Payments are negative value, income is positive values. + * @param mixed $finance_rate The interest rate you pay on the money used in the cash flows + * @param mixed $reinvestment_rate The interest rate you receive on the cash flows as you reinvest them * * @return float|string Result, or a string containing an error */ public static function MIRR($values, $finance_rate, $reinvestment_rate) { - if (!is_array($values)) { - return Functions::VALUE(); - } - $values = Functions::flattenArray($values); - $finance_rate = Functions::flattenSingleValue($finance_rate); - $reinvestment_rate = Functions::flattenSingleValue($reinvestment_rate); - $n = count($values); - - $rr = 1.0 + $reinvestment_rate; - $fr = 1.0 + $finance_rate; - - $npv_pos = $npv_neg = 0.0; - foreach ($values as $i => $v) { - if ($v >= 0) { - $npv_pos += $v / $rr ** $i; - } else { - $npv_neg += $v / $fr ** $i; - } - } - - if (($npv_neg == 0) || ($npv_pos == 0) || ($reinvestment_rate <= -1)) { - return Functions::VALUE(); - } - - $mirr = ((-$npv_pos * $rr ** $n) - / ($npv_neg * ($rr))) ** (1.0 / ($n - 1)) - 1.0; - - return is_finite($mirr) ? $mirr : Functions::VALUE(); + return Financial\CashFlow\Variable\Periodic::modifiedRate($values, $finance_rate, $reinvestment_rate); } /** @@ -1395,23 +851,22 @@ class Financial * * Returns the nominal interest rate given the effective rate and the number of compounding payments per year. * - * @param float $effect_rate Effective interest rate - * @param int $npery Number of compounding payments per year + * Excel Function: + * NOMINAL(effect_rate, npery) + * + * @Deprecated 1.18.0 + * + * @see Financial\InterestRate::nominal() + * Use the nominal() method in the Financial\InterestRate class instead + * + * @param float $effectiveRate Effective interest rate + * @param int $periodsPerYear Number of compounding payments per year * * @return float|string Result, or a string containing an error */ - public static function NOMINAL($effect_rate = 0, $npery = 0) + public static function NOMINAL($effectiveRate = 0, $periodsPerYear = 0) { - $effect_rate = Functions::flattenSingleValue($effect_rate); - $npery = (int) Functions::flattenSingleValue($npery); - - // Validate parameters - if ($effect_rate <= 0 || $npery < 1) { - return Functions::NAN(); - } - - // Calculate - return $npery * (($effect_rate + 1) ** (1 / $npery) - 1); + return InterestRate::nominal($effectiveRate, $periodsPerYear); } /** @@ -1419,6 +874,8 @@ class Financial * * Returns the number of periods for a cash flow with constant periodic payments (annuities), and interest rate. * + * @Deprecated 1.18.0 + * * @param float $rate Interest rate per period * @param int $pmt Periodic payment (annuity) * @param float $pv Present Value @@ -1426,33 +883,13 @@ class Financial * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period * * @return float|string Result, or a string containing an error + * + *@see Financial\CashFlow\Constant\Periodic::periods() + * Use the periods() method in the Financial\CashFlow\Constant\Periodic class instead */ public static function NPER($rate = 0, $pmt = 0, $pv = 0, $fv = 0, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $pmt = Functions::flattenSingleValue($pmt); - $pv = Functions::flattenSingleValue($pv); - $fv = Functions::flattenSingleValue($fv); - $type = Functions::flattenSingleValue($type); - - // Validate parameters - if ($type != 0 && $type != 1) { - return Functions::NAN(); - } - - // Calculate - if ($rate !== null && $rate != 0) { - if ($pmt == 0 && $pv == 0) { - return Functions::NAN(); - } - - return log(($pmt * (1 + $rate * $type) / $rate - $fv) / ($pv + $pmt * (1 + $rate * $type) / $rate)) / log(1 + $rate); - } - if ($pmt == 0) { - return Functions::NAN(); - } - - return (-$pv - $fv) / $pmt; + return Financial\CashFlow\Constant\Periodic::periods($rate, $pmt, $pv, $fv, $type); } /** @@ -1460,28 +897,16 @@ class Financial * * Returns the Net Present Value of a cash flow series given a discount rate. * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Variable\Periodic::presentValue() + * Use the presentValue() method in the Financial\CashFlow\Variable\Periodic class instead + * * @return float */ public static function NPV(...$args) { - // Return value - $returnValue = 0; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - - // Calculate - $rate = array_shift($aArgs); - $countArgs = count($aArgs); - for ($i = 1; $i <= $countArgs; ++$i) { - // Is it a numeric value? - if (is_numeric($aArgs[$i - 1])) { - $returnValue += $aArgs[$i - 1] / (1 + $rate) ** $i; - } - } - - // Return - return $returnValue; + return Financial\CashFlow\Variable\Periodic::presentValue(...$args); } /** @@ -1489,6 +914,11 @@ class Financial * * Calculates the number of periods required for an investment to reach a specified value. * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Single::periods() + * Use the periods() method in the Financial\CashFlow\Single class instead + * * @param float $rate Interest rate per period * @param float $pv Present Value * @param float $fv Future Value @@ -1497,18 +927,7 @@ class Financial */ public static function PDURATION($rate = 0, $pv = 0, $fv = 0) { - $rate = Functions::flattenSingleValue($rate); - $pv = Functions::flattenSingleValue($pv); - $fv = Functions::flattenSingleValue($fv); - - // Validate parameters - if (!is_numeric($rate) || !is_numeric($pv) || !is_numeric($fv)) { - return Functions::VALUE(); - } elseif ($rate <= 0.0 || $pv <= 0.0 || $fv <= 0.0) { - return Functions::NAN(); - } - - return (log($fv) - log($pv)) / log(1 + $rate); + return Financial\CashFlow\Single::periods($rate, $pv, $fv); } /** @@ -1516,6 +935,11 @@ class Financial * * Returns the constant payment (annuity) for a cash flow with a constant interest rate. * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Constant\Periodic\Payments::annuity() + * Use the annuity() method in the Financial\CashFlow\Constant\Periodic\Payments class instead + * * @param float $rate Interest rate per period * @param int $nper Number of periods * @param float $pv Present Value @@ -1526,29 +950,19 @@ class Financial */ public static function PMT($rate = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $nper = Functions::flattenSingleValue($nper); - $pv = Functions::flattenSingleValue($pv); - $fv = Functions::flattenSingleValue($fv); - $type = Functions::flattenSingleValue($type); - - // Validate parameters - if ($type != 0 && $type != 1) { - return Functions::NAN(); - } - - // Calculate - if ($rate !== null && $rate != 0) { - return (-$fv - $pv * (1 + $rate) ** $nper) / (1 + $rate * $type) / (((1 + $rate) ** $nper - 1) / $rate); - } - - return (-$pv - $fv) / $nper; + return Financial\CashFlow\Constant\Periodic\Payments::annuity($rate, $nper, $pv, $fv, $type); } /** * PPMT. * - * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate. + * Returns the interest payment for a given period for an investment based on periodic, constant payments + * and a constant interest rate. + * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Constant\Periodic\Payments::interestPayment() + * Use the interestPayment() method in the Financial\CashFlow\Constant\Periodic\Payments class instead * * @param float $rate Interest rate per period * @param int $per Period for which we want to find the interest @@ -1561,100 +975,43 @@ class Financial */ public static function PPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $per = (int) Functions::flattenSingleValue($per); - $nper = (int) Functions::flattenSingleValue($nper); - $pv = Functions::flattenSingleValue($pv); - $fv = Functions::flattenSingleValue($fv); - $type = (int) Functions::flattenSingleValue($type); - - // Validate parameters - if ($type != 0 && $type != 1) { - return Functions::NAN(); - } - if ($per <= 0 || $per > $nper) { - return Functions::VALUE(); - } - - // Calculate - $interestAndPrincipal = self::interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type); - - return $interestAndPrincipal[1]; - } - - private static function validatePrice($settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis) - { - if (is_string($settlement)) { - return Functions::VALUE(); - } - if (is_string($maturity)) { - return Functions::VALUE(); - } - if (!is_numeric($rate)) { - return Functions::VALUE(); - } - if (!is_numeric($yield)) { - return Functions::VALUE(); - } - if (!is_numeric($redemption)) { - return Functions::VALUE(); - } - if (!is_numeric($frequency)) { - return Functions::VALUE(); - } - if (!is_numeric($basis)) { - return Functions::VALUE(); - } - - return ''; + return Financial\CashFlow\Constant\Periodic\Payments::interestPayment($rate, $per, $nper, $pv, $fv, $type); } + /** + * PRICE. + * + * Returns the price per $100 face value of a security that pays periodic interest. + * + * @Deprecated 1.18.0 + * + * @see Financial\Securities\Price::price() + * Use the price() method in the Financial\Securities\Price class instead + * + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue date when the security + * is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param float $rate the security's annual coupon rate + * @param float $yield the security's annual yield + * @param float $redemption The number of coupon payments per year. + * For annual payments, frequency = 1; + * for semiannual, frequency = 2; + * for quarterly, frequency = 4. + * @param int $frequency + * @param int $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return float|string Result, or a string containing an error + */ public static function PRICE($settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $rate = Functions::flattenSingleValue($rate); - $yield = Functions::flattenSingleValue($yield); - $redemption = Functions::flattenSingleValue($redemption); - $frequency = Functions::flattenSingleValue($frequency); - $basis = Functions::flattenSingleValue($basis); - - $settlement = DateTime::getDateValue($settlement); - $maturity = DateTime::getDateValue($maturity); - $rslt = self::validatePrice($settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis); - if ($rslt) { - return $rslt; - } - $rate = (float) $rate; - $yield = (float) $yield; - $redemption = (float) $redemption; - $frequency = (int) $frequency; - $basis = (int) $basis; - - if ( - ($settlement > $maturity) || - (!self::isValidFrequency($frequency)) || - (($basis < 0) || ($basis > 4)) - ) { - return Functions::NAN(); - } - - $dsc = self::COUPDAYSNC($settlement, $maturity, $frequency, $basis); - $e = self::COUPDAYS($settlement, $maturity, $frequency, $basis); - $n = self::COUPNUM($settlement, $maturity, $frequency, $basis); - $a = self::COUPDAYBS($settlement, $maturity, $frequency, $basis); - - $baseYF = 1.0 + ($yield / $frequency); - $rfp = 100 * ($rate / $frequency); - $de = $dsc / $e; - - $result = $redemption / $baseYF ** (--$n + $de); - for ($k = 0; $k <= $n; ++$k) { - $result += $rfp / ($baseYF ** ($k + $de)); - } - $result -= $rfp * ($a / $e); - - return $result; + return Securities\Price::price($settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis); } /** @@ -1662,10 +1019,16 @@ class Financial * * Returns the price per $100 face value of a discounted security. * + * @Deprecated 1.18.0 + * + * @see Financial\Securities\Price::priceDiscounted() + * Use the priceDiscounted() method in the Financial\Securities\Price class instead + * * @param mixed $settlement The security's settlement date. - * The security settlement date is the date after the issue date when the security is traded to the buyer. + * The security settlement date is the date after the issue date when the security + * is traded to the buyer. * @param mixed $maturity The security's maturity date. - * The maturity date is the date when the security expires. + * The maturity date is the date when the security expires. * @param int $discount The security's discount rate * @param int $redemption The security's redemption value per $100 face value * @param int $basis The type of day count to use. @@ -1679,27 +1042,7 @@ class Financial */ public static function PRICEDISC($settlement, $maturity, $discount, $redemption, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $discount = (float) Functions::flattenSingleValue($discount); - $redemption = (float) Functions::flattenSingleValue($redemption); - $basis = (int) Functions::flattenSingleValue($basis); - - // Validate - if ((is_numeric($discount)) && (is_numeric($redemption)) && (is_numeric($basis))) { - if (($discount <= 0) || ($redemption <= 0)) { - return Functions::NAN(); - } - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, $basis); - if (!is_numeric($daysBetweenSettlementAndMaturity)) { - // return date error - return $daysBetweenSettlementAndMaturity; - } - - return $redemption * (1 - $discount * $daysBetweenSettlementAndMaturity); - } - - return Functions::VALUE(); + return Securities\Price::priceDiscounted($settlement, $maturity, $discount, $redemption, $basis); } /** @@ -1707,10 +1050,16 @@ class Financial * * Returns the price per $100 face value of a security that pays interest at maturity. * + * @Deprecated 1.18.0 + * + * @see Financial\Securities\Price::priceAtMaturity() + * Use the priceAtMaturity() method in the Financial\Securities\Price class instead + * * @param mixed $settlement The security's settlement date. - * The security's settlement date is the date after the issue date when the security is traded to the buyer. + * The security's settlement date is the date after the issue date when the security + * is traded to the buyer. * @param mixed $maturity The security's maturity date. - * The maturity date is the date when the security expires. + * The maturity date is the date when the security expires. * @param mixed $issue The security's issue date * @param int $rate The security's interest rate at date of issue * @param int $yield The security's annual yield @@ -1725,47 +1074,7 @@ class Financial */ public static function PRICEMAT($settlement, $maturity, $issue, $rate, $yield, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $issue = Functions::flattenSingleValue($issue); - $rate = Functions::flattenSingleValue($rate); - $yield = Functions::flattenSingleValue($yield); - $basis = (int) Functions::flattenSingleValue($basis); - - // Validate - if (is_numeric($rate) && is_numeric($yield)) { - if (($rate <= 0) || ($yield <= 0)) { - return Functions::NAN(); - } - $daysPerYear = self::daysPerYear(DateTime::YEAR($settlement), $basis); - if (!is_numeric($daysPerYear)) { - return $daysPerYear; - } - $daysBetweenIssueAndSettlement = DateTime::YEARFRAC($issue, $settlement, $basis); - if (!is_numeric($daysBetweenIssueAndSettlement)) { - // return date error - return $daysBetweenIssueAndSettlement; - } - $daysBetweenIssueAndSettlement *= $daysPerYear; - $daysBetweenIssueAndMaturity = DateTime::YEARFRAC($issue, $maturity, $basis); - if (!is_numeric($daysBetweenIssueAndMaturity)) { - // return date error - return $daysBetweenIssueAndMaturity; - } - $daysBetweenIssueAndMaturity *= $daysPerYear; - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, $basis); - if (!is_numeric($daysBetweenSettlementAndMaturity)) { - // return date error - return $daysBetweenSettlementAndMaturity; - } - $daysBetweenSettlementAndMaturity *= $daysPerYear; - - return (100 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate * 100)) / - (1 + (($daysBetweenSettlementAndMaturity / $daysPerYear) * $yield)) - - (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate * 100); - } - - return Functions::VALUE(); + return Securities\Price::priceAtMaturity($settlement, $maturity, $issue, $rate, $yield, $basis); } /** @@ -1773,6 +1082,11 @@ class Financial * * Returns the Present Value of a cash flow with constant payments and interest rate (annuities). * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Constant\Periodic::presentValue() + * Use the presentValue() method in the Financial\CashFlow\Constant\Periodic class instead + * * @param float $rate Interest rate per period * @param int $nper Number of periods * @param float $pmt Periodic payment (annuity) @@ -1783,23 +1097,7 @@ class Financial */ public static function PV($rate = 0, $nper = 0, $pmt = 0, $fv = 0, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $nper = Functions::flattenSingleValue($nper); - $pmt = Functions::flattenSingleValue($pmt); - $fv = Functions::flattenSingleValue($fv); - $type = Functions::flattenSingleValue($type); - - // Validate parameters - if ($type != 0 && $type != 1) { - return Functions::NAN(); - } - - // Calculate - if ($rate !== null && $rate != 0) { - return (-$pmt * (1 + $rate * $type) * (((1 + $rate) ** $nper - 1) / $rate) - $fv) / (1 + $rate) ** $nper; - } - - return -$fv - $pmt * $nper; + return Financial\CashFlow\Constant\Periodic::presentValue($rate, $nper, $pmt, $fv, $type); } /** @@ -1813,112 +1111,63 @@ class Financial * Excel Function: * RATE(nper,pmt,pv[,fv[,type[,guess]]]) * - * @param float $nper The total number of payment periods in an annuity - * @param float $pmt The payment made each period and cannot change over the life + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Constant\Periodic\Interest::rate() + * Use the rate() method in the Financial\CashFlow\Constant\Periodic class instead + * + * @param mixed $nper The total number of payment periods in an annuity + * @param mixed $pmt The payment made each period and cannot change over the life * of the annuity. * Typically, pmt includes principal and interest but no other * fees or taxes. - * @param float $pv The present value - the total amount that a series of future + * @param mixed $pv The present value - the total amount that a series of future * payments is worth now - * @param float $fv The future value, or a cash balance you want to attain after + * @param mixed $fv The future value, or a cash balance you want to attain after * the last payment is made. If fv is omitted, it is assumed * to be 0 (the future value of a loan, for example, is 0). - * @param int $type A number 0 or 1 and indicates when payments are due: + * @param mixed $type A number 0 or 1 and indicates when payments are due: * 0 or omitted At the end of the period. * 1 At the beginning of the period. - * @param float $guess Your guess for what the rate will be. + * @param mixed $guess Your guess for what the rate will be. * If you omit guess, it is assumed to be 10 percent. * * @return float|string */ public static function RATE($nper, $pmt, $pv, $fv = 0.0, $type = 0, $guess = 0.1) { - $nper = (int) Functions::flattenSingleValue($nper); - $pmt = Functions::flattenSingleValue($pmt); - $pv = Functions::flattenSingleValue($pv); - $fv = ($fv === null) ? 0.0 : Functions::flattenSingleValue($fv); - $type = ($type === null) ? 0 : (int) Functions::flattenSingleValue($type); - $guess = ($guess === null) ? 0.1 : Functions::flattenSingleValue($guess); - - $rate = $guess; - // rest of code adapted from python/numpy - $close = false; - $iter = 0; - while (!$close && $iter < self::FINANCIAL_MAX_ITERATIONS) { - $nextdiff = self::rateNextGuess($rate, $nper, $pmt, $pv, $fv, $type); - if (!is_numeric($nextdiff)) { - break; - } - $rate1 = $rate - $nextdiff; - $close = abs($rate1 - $rate) < self::FINANCIAL_PRECISION; - ++$iter; - $rate = $rate1; - } - - return $close ? $rate : Functions::NAN(); - } - - private static function rateNextGuess($rate, $nper, $pmt, $pv, $fv, $type) - { - if ($rate == 0) { - return Functions::NAN(); - } - $tt1 = ($rate + 1) ** $nper; - $tt2 = ($rate + 1) ** ($nper - 1); - $numerator = $fv + $tt1 * $pv + $pmt * ($tt1 - 1) * ($rate * $type + 1) / $rate; - $denominator = $nper * $tt2 * $pv - $pmt * ($tt1 - 1) * ($rate * $type + 1) / ($rate * $rate) - + $nper * $pmt * $tt2 * ($rate * $type + 1) / $rate - + $pmt * ($tt1 - 1) * $type / $rate; - if ($denominator == 0) { - return Functions::NAN(); - } - - return $numerator / $denominator; + return Financial\CashFlow\Constant\Periodic\Interest::rate($nper, $pmt, $pv, $fv, $type, $guess); } /** * RECEIVED. * - * Returns the price per $100 face value of a discounted security. + * Returns the amount received at maturity for a fully invested Security. + * + * @Deprecated 1.18.0 + * + * @see Financial\Securities\Price::received() + * Use the received() method in the Financial\Securities\Price class instead * * @param mixed $settlement The security's settlement date. - * The security settlement date is the date after the issue date when the security is traded to the buyer. + * The security settlement date is the date after the issue date when the security + * is traded to the buyer. * @param mixed $maturity The security's maturity date. - * The maturity date is the date when the security expires. - * @param int $investment The amount invested in the security - * @param int $discount The security's discount rate - * @param int $basis The type of day count to use. - * 0 or omitted US (NASD) 30/360 - * 1 Actual/actual - * 2 Actual/360 - * 3 Actual/365 - * 4 European 30/360 + * The maturity date is the date when the security expires. + * @param mixed $investment The amount invested in the security + * @param mixed $discount The security's discount rate + * @param mixed $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function RECEIVED($settlement, $maturity, $investment, $discount, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $investment = (float) Functions::flattenSingleValue($investment); - $discount = (float) Functions::flattenSingleValue($discount); - $basis = (int) Functions::flattenSingleValue($basis); - - // Validate - if ((is_numeric($investment)) && (is_numeric($discount)) && (is_numeric($basis))) { - if (($investment <= 0) || ($discount <= 0)) { - return Functions::NAN(); - } - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, $basis); - if (!is_numeric($daysBetweenSettlementAndMaturity)) { - // return date error - return $daysBetweenSettlementAndMaturity; - } - - return $investment / (1 - ($discount * $daysBetweenSettlementAndMaturity)); - } - - return Functions::VALUE(); + return Financial\Securities\Price::received($settlement, $maturity, $investment, $discount, $basis); } /** @@ -1926,6 +1175,11 @@ class Financial * * Calculates the interest rate required for an investment to grow to a specified future value . * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Single::interestRate() + * Use the interestRate() method in the Financial\CashFlow\Single class instead + * * @param float $nper The number of periods over which the investment is made * @param float $pv Present Value * @param float $fv Future Value @@ -1934,18 +1188,7 @@ class Financial */ public static function RRI($nper = 0, $pv = 0, $fv = 0) { - $nper = Functions::flattenSingleValue($nper); - $pv = Functions::flattenSingleValue($pv); - $fv = Functions::flattenSingleValue($fv); - - // Validate parameters - if (!is_numeric($nper) || !is_numeric($pv) || !is_numeric($fv)) { - return Functions::VALUE(); - } elseif ($nper <= 0.0 || $pv <= 0.0 || $fv < 0.0) { - return Functions::NAN(); - } - - return ($fv / $pv) ** (1 / $nper) - 1; + return Financial\CashFlow\Single::interestRate($nper, $pv, $fv); } /** @@ -1953,6 +1196,11 @@ class Financial * * Returns the straight-line depreciation of an asset for one period * + * @Deprecated 1.18.0 + * + * @see Financial\Depreciation::SLN() + * Use the SLN() method in the Financial\Depreciation class instead + * * @param mixed $cost Initial cost of the asset * @param mixed $salvage Value at the end of the depreciation * @param mixed $life Number of periods over which the asset is depreciated @@ -1961,20 +1209,7 @@ class Financial */ public static function SLN($cost, $salvage, $life) { - $cost = Functions::flattenSingleValue($cost); - $salvage = Functions::flattenSingleValue($salvage); - $life = Functions::flattenSingleValue($life); - - // Calculate - if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life))) { - if ($life < 0) { - return Functions::NAN(); - } - - return ($cost - $salvage) / $life; - } - - return Functions::VALUE(); + return Depreciation::SLN($cost, $salvage, $life); } /** @@ -1982,6 +1217,11 @@ class Financial * * Returns the sum-of-years' digits depreciation of an asset for a specified period. * + * @Deprecated 1.18.0 + * + * @see Financial\Depreciation::SYD() + * Use the SYD() method in the Financial\Depreciation class instead + * * @param mixed $cost Initial cost of the asset * @param mixed $salvage Value at the end of the depreciation * @param mixed $life Number of periods over which the asset is depreciated @@ -1991,21 +1231,7 @@ class Financial */ public static function SYD($cost, $salvage, $life, $period) { - $cost = Functions::flattenSingleValue($cost); - $salvage = Functions::flattenSingleValue($salvage); - $life = Functions::flattenSingleValue($life); - $period = Functions::flattenSingleValue($period); - - // Calculate - if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period))) { - if (($life < 1) || ($period > $life)) { - return Functions::NAN(); - } - - return (($cost - $salvage) * ($life - $period + 1) * 2) / ($life * ($life + 1)); - } - - return Functions::VALUE(); + return Depreciation::SYD($cost, $salvage, $life, $period); } /** @@ -2013,8 +1239,14 @@ class Financial * * Returns the bond-equivalent yield for a Treasury bill. * + * @Deprecated 1.18.0 + * + * @see Financial\TreasuryBill::bondEquivalentYield() + * Use the bondEquivalentYield() method in the Financial\TreasuryBill class instead + * * @param mixed $settlement The Treasury bill's settlement date. - * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer. + * The Treasury bill's settlement date is the date after the issue date when the + * Treasury bill is traded to the buyer. * @param mixed $maturity The Treasury bill's maturity date. * The maturity date is the date when the Treasury bill expires. * @param int $discount The Treasury bill's discount rate @@ -2023,37 +1255,22 @@ class Financial */ public static function TBILLEQ($settlement, $maturity, $discount) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $discount = Functions::flattenSingleValue($discount); - - // Use TBILLPRICE for validation - $testValue = self::TBILLPRICE($settlement, $maturity, $discount); - if (is_string($testValue)) { - return $testValue; - } - - if (is_string($maturity = DateTime::getDateValue($maturity))) { - return Functions::VALUE(); - } - - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - ++$maturity; - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity) * 360; - } else { - $daysBetweenSettlementAndMaturity = (DateTime::getDateValue($maturity) - DateTime::getDateValue($settlement)); - } - - return (365 * $discount) / (360 - $discount * $daysBetweenSettlementAndMaturity); + return TreasuryBill::bondEquivalentYield($settlement, $maturity, $discount); } /** * TBILLPRICE. * - * Returns the yield for a Treasury bill. + * Returns the price per $100 face value for a Treasury bill. + * + * @Deprecated 1.18.0 + * + * @see Financial\TreasuryBill::price() + * Use the price() method in the Financial\TreasuryBill class instead * * @param mixed $settlement The Treasury bill's settlement date. - * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer. + * The Treasury bill's settlement date is the date after the issue date + * when the Treasury bill is traded to the buyer. * @param mixed $maturity The Treasury bill's maturity date. * The maturity date is the date when the Treasury bill expires. * @param int $discount The Treasury bill's discount rate @@ -2062,44 +1279,7 @@ class Financial */ public static function TBILLPRICE($settlement, $maturity, $discount) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $discount = Functions::flattenSingleValue($discount); - - if (is_string($maturity = DateTime::getDateValue($maturity))) { - return Functions::VALUE(); - } - - // Validate - if (is_numeric($discount)) { - if ($discount <= 0) { - return Functions::NAN(); - } - - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - ++$maturity; - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity) * 360; - if (!is_numeric($daysBetweenSettlementAndMaturity)) { - // return date error - return $daysBetweenSettlementAndMaturity; - } - } else { - $daysBetweenSettlementAndMaturity = (DateTime::getDateValue($maturity) - DateTime::getDateValue($settlement)); - } - - if ($daysBetweenSettlementAndMaturity > 360) { - return Functions::NAN(); - } - - $price = 100 * (1 - (($discount * $daysBetweenSettlementAndMaturity) / 360)); - if ($price <= 0) { - return Functions::NAN(); - } - - return $price; - } - - return Functions::VALUE(); + return TreasuryBill::price($settlement, $maturity, $discount); } /** @@ -2107,8 +1287,14 @@ class Financial * * Returns the yield for a Treasury bill. * + * @Deprecated 1.18.0 + * + * @see Financial\TreasuryBill::yield() + * Use the yield() method in the Financial\TreasuryBill class instead + * * @param mixed $settlement The Treasury bill's settlement date. - * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer. + * The Treasury bill's settlement date is the date after the issue date + * when the Treasury bill is traded to the buyer. * @param mixed $maturity The Treasury bill's maturity date. * The maturity date is the date when the Treasury bill expires. * @param int $price The Treasury bill's price per $100 face value @@ -2117,113 +1303,7 @@ class Financial */ public static function TBILLYIELD($settlement, $maturity, $price) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $price = Functions::flattenSingleValue($price); - - // Validate - if (is_numeric($price)) { - if ($price <= 0) { - return Functions::NAN(); - } - - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - ++$maturity; - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity) * 360; - if (!is_numeric($daysBetweenSettlementAndMaturity)) { - // return date error - return $daysBetweenSettlementAndMaturity; - } - } else { - $daysBetweenSettlementAndMaturity = (DateTime::getDateValue($maturity) - DateTime::getDateValue($settlement)); - } - - if ($daysBetweenSettlementAndMaturity > 360) { - return Functions::NAN(); - } - - return ((100 - $price) / $price) * (360 / $daysBetweenSettlementAndMaturity); - } - - return Functions::VALUE(); - } - - private static function bothNegAndPos($neg, $pos) - { - return $neg && $pos; - } - - private static function xirrPart2(&$values) - { - $valCount = count($values); - $foundpos = false; - $foundneg = false; - for ($i = 0; $i < $valCount; ++$i) { - $fld = $values[$i]; - if (!is_numeric($fld)) { - return Functions::VALUE(); - } elseif ($fld > 0) { - $foundpos = true; - } elseif ($fld < 0) { - $foundneg = true; - } - } - if (!self::bothNegAndPos($foundneg, $foundpos)) { - return Functions::NAN(); - } - - return ''; - } - - private static function xirrPart1(&$values, &$dates) - { - if ((!is_array($values)) && (!is_array($dates))) { - return Functions::NA(); - } - $values = Functions::flattenArray($values); - $dates = Functions::flattenArray($dates); - if (count($values) != count($dates)) { - return Functions::NAN(); - } - - $datesCount = count($dates); - for ($i = 0; $i < $datesCount; ++$i) { - $dates[$i] = DateTime::getDateValue($dates[$i]); - if (!is_numeric($dates[$i])) { - return Functions::VALUE(); - } - } - - return self::xirrPart2($values); - } - - private static function xirrPart3($values, $dates, $x1, $x2) - { - $f = self::xnpvOrdered($x1, $values, $dates, false); - if ($f < 0.0) { - $rtb = $x1; - $dx = $x2 - $x1; - } else { - $rtb = $x2; - $dx = $x1 - $x2; - } - - $rslt = Functions::VALUE(); - for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { - $dx *= 0.5; - $x_mid = $rtb + $dx; - $f_mid = self::xnpvOrdered($x_mid, $values, $dates, false); - if ($f_mid <= 0.0) { - $rtb = $x_mid; - } - if ((abs($f_mid) < self::FINANCIAL_PRECISION) || (abs($dx) < self::FINANCIAL_PRECISION)) { - $rslt = $x_mid; - - break; - } - } - - return $rslt; + return TreasuryBill::yield($settlement, $maturity, $price); } /** @@ -2234,6 +1314,11 @@ class Financial * Excel Function: * =XIRR(values,dates,guess) * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Variable\NonPeriodic::rate() + * Use the rate() method in the Financial\CashFlow\Variable\NonPeriodic class instead + * * @param float[] $values A series of cash flow payments * The series of values must contain at least one positive value & one negative value * @param mixed[] $dates A series of payment dates @@ -2245,37 +1330,7 @@ class Financial */ public static function XIRR($values, $dates, $guess = 0.1) { - $rslt = self::xirrPart1($values, $dates); - if ($rslt) { - return $rslt; - } - - // create an initial range, with a root somewhere between 0 and guess - $guess = Functions::flattenSingleValue($guess); - $x1 = 0.0; - $x2 = $guess ? $guess : 0.1; - $f1 = self::xnpvOrdered($x1, $values, $dates, false); - $f2 = self::xnpvOrdered($x2, $values, $dates, false); - $found = false; - for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { - if (!is_numeric($f1) || !is_numeric($f2)) { - break; - } - if (($f1 * $f2) < 0.0) { - $found = true; - - break; - } elseif (abs($f1) < abs($f2)) { - $f1 = self::xnpvOrdered($x1 += 1.6 * ($x1 - $x2), $values, $dates, false); - } else { - $f2 = self::xnpvOrdered($x2 += 1.6 * ($x2 - $x1), $values, $dates, false); - } - } - if (!$found) { - return Functions::NAN(); - } - - return self::xirrPart3($values, $dates, $x1, $x2); + return Financial\CashFlow\Variable\NonPeriodic::rate($values, $dates, $guess); } /** @@ -2287,74 +1342,27 @@ class Financial * Excel Function: * =XNPV(rate,values,dates) * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Variable\NonPeriodic::presentValue() + * Use the presentValue() method in the Financial\CashFlow\Variable\NonPeriodic class instead + * * @param float $rate the discount rate to apply to the cash flows - * @param float[] $values A series of cash flows that corresponds to a schedule of payments in dates. - * The first payment is optional and corresponds to a cost or payment that occurs at the beginning of the investment. - * If the first value is a cost or payment, it must be a negative value. All succeeding payments are discounted based on a 365-day year. - * The series of values must contain at least one positive value and one negative value. - * @param mixed[] $dates A schedule of payment dates that corresponds to the cash flow payments. - * The first payment date indicates the beginning of the schedule of payments. - * All other dates must be later than this date, but they may occur in any order. + * @param float[] $values A series of cash flows that corresponds to a schedule of payments in dates. + * The first payment is optional and corresponds to a cost or payment that occurs + * at the beginning of the investment. + * If the first value is a cost or payment, it must be a negative value. + * All succeeding payments are discounted based on a 365-day year. + * The series of values must contain at least one positive value and one negative value. + * @param mixed[] $dates A schedule of payment dates that corresponds to the cash flow payments. + * The first payment date indicates the beginning of the schedule of payments. + * All other dates must be later than this date, but they may occur in any order. * * @return float|mixed|string */ public static function XNPV($rate, $values, $dates) { - return self::xnpvOrdered($rate, $values, $dates, true); - } - - private static function validateXnpv($rate, $values, $dates) - { - if (!is_numeric($rate)) { - return Functions::VALUE(); - } - $valCount = count($values); - if ($valCount != count($dates)) { - return Functions::NAN(); - } - if ($valCount > 1 && ((min($values) > 0) || (max($values) < 0))) { - return Functions::NAN(); - } - $date0 = DateTime::getDateValue($dates[0]); - if (is_string($date0)) { - return Functions::VALUE(); - } - - return ''; - } - - private static function xnpvOrdered($rate, $values, $dates, $ordered = true) - { - $rate = Functions::flattenSingleValue($rate); - $values = Functions::flattenArray($values); - $dates = Functions::flattenArray($dates); - $valCount = count($values); - $date0 = DateTime::getDateValue($dates[0]); - $rslt = self::validateXnpv($rate, $values, $dates); - if ($rslt) { - return $rslt; - } - $xnpv = 0.0; - for ($i = 0; $i < $valCount; ++$i) { - if (!is_numeric($values[$i])) { - return Functions::VALUE(); - } - $datei = DateTime::getDateValue($dates[$i]); - if (is_string($datei)) { - return Functions::VALUE(); - } - if ($date0 > $datei) { - $dif = $ordered ? Functions::NAN() : -DateTime::DATEDIF($datei, $date0, 'd'); - } else { - $dif = DateTime::DATEDIF($date0, $datei, 'd'); - } - if (!is_numeric($dif)) { - return $dif; - } - $xnpv += $values[$i] / (1 + $rate) ** ($dif / 365); - } - - return is_finite($xnpv) ? $xnpv : Functions::VALUE(); + return Financial\CashFlow\Variable\NonPeriodic::presentValue($rate, $values, $dates); } /** @@ -2362,10 +1370,16 @@ class Financial * * Returns the annual yield of a security that pays interest at maturity. * + * @Deprecated 1.18.0 + * + * @see Financial\Securities\Yields::yieldDiscounted() + * Use the yieldDiscounted() method in the Financial\Securities\Yields class instead + * * @param mixed $settlement The security's settlement date. - * The security's settlement date is the date after the issue date when the security is traded to the buyer. + * The security's settlement date is the date after the issue date when the security + * is traded to the buyer. * @param mixed $maturity The security's maturity date. - * The maturity date is the date when the security expires. + * The maturity date is the date when the security expires. * @param int $price The security's price per $100 face value * @param int $redemption The security's redemption value per $100 face value * @param int $basis The type of day count to use. @@ -2379,32 +1393,7 @@ class Financial */ public static function YIELDDISC($settlement, $maturity, $price, $redemption, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $price = Functions::flattenSingleValue($price); - $redemption = Functions::flattenSingleValue($redemption); - $basis = (int) Functions::flattenSingleValue($basis); - - // Validate - if (is_numeric($price) && is_numeric($redemption)) { - if (($price <= 0) || ($redemption <= 0)) { - return Functions::NAN(); - } - $daysPerYear = self::daysPerYear(DateTime::YEAR($settlement), $basis); - if (!is_numeric($daysPerYear)) { - return $daysPerYear; - } - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, $basis); - if (!is_numeric($daysBetweenSettlementAndMaturity)) { - // return date error - return $daysBetweenSettlementAndMaturity; - } - $daysBetweenSettlementAndMaturity *= $daysPerYear; - - return (($redemption - $price) / $price) * ($daysPerYear / $daysBetweenSettlementAndMaturity); - } - - return Functions::VALUE(); + return Securities\Yields::yieldDiscounted($settlement, $maturity, $price, $redemption, $basis); } /** @@ -2412,64 +1401,30 @@ class Financial * * Returns the annual yield of a security that pays interest at maturity. * + * @Deprecated 1.18.0 + * + * @see Financial\Securities\Yields::yieldAtMaturity() + * Use the yieldAtMaturity() method in the Financial\Securities\Yields class instead + * * @param mixed $settlement The security's settlement date. - * The security's settlement date is the date after the issue date when the security is traded to the buyer. + * The security's settlement date is the date after the issue date when the security + * is traded to the buyer. * @param mixed $maturity The security's maturity date. - * The maturity date is the date when the security expires. + * The maturity date is the date when the security expires. * @param mixed $issue The security's issue date * @param int $rate The security's interest rate at date of issue * @param int $price The security's price per $100 face value * @param int $basis The type of day count to use. - * 0 or omitted US (NASD) 30/360 - * 1 Actual/actual - * 2 Actual/360 - * 3 Actual/365 - * 4 European 30/360 + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function YIELDMAT($settlement, $maturity, $issue, $rate, $price, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $issue = Functions::flattenSingleValue($issue); - $rate = Functions::flattenSingleValue($rate); - $price = Functions::flattenSingleValue($price); - $basis = (int) Functions::flattenSingleValue($basis); - - // Validate - if (is_numeric($rate) && is_numeric($price)) { - if (($rate <= 0) || ($price <= 0)) { - return Functions::NAN(); - } - $daysPerYear = self::daysPerYear(DateTime::YEAR($settlement), $basis); - if (!is_numeric($daysPerYear)) { - return $daysPerYear; - } - $daysBetweenIssueAndSettlement = DateTime::YEARFRAC($issue, $settlement, $basis); - if (!is_numeric($daysBetweenIssueAndSettlement)) { - // return date error - return $daysBetweenIssueAndSettlement; - } - $daysBetweenIssueAndSettlement *= $daysPerYear; - $daysBetweenIssueAndMaturity = DateTime::YEARFRAC($issue, $maturity, $basis); - if (!is_numeric($daysBetweenIssueAndMaturity)) { - // return date error - return $daysBetweenIssueAndMaturity; - } - $daysBetweenIssueAndMaturity *= $daysPerYear; - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, $basis); - if (!is_numeric($daysBetweenSettlementAndMaturity)) { - // return date error - return $daysBetweenSettlementAndMaturity; - } - $daysBetweenSettlementAndMaturity *= $daysPerYear; - - return ((1 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate) - (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) / - (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) * - ($daysPerYear / $daysBetweenSettlementAndMaturity); - } - - return Functions::VALUE(); + return Securities\Yields::yieldAtMaturity($settlement, $maturity, $issue, $rate, $price, $basis); } } diff --git a/src/PhpSpreadsheet/Calculation/Financial/Amortization.php b/src/PhpSpreadsheet/Calculation/Financial/Amortization.php new file mode 100644 index 00000000..ba7fb521 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Financial/Amortization.php @@ -0,0 +1,210 @@ +getMessage(); + } + + $yearFrac = DateTimeExcel\YearFrac::fraction($purchased, $firstPeriod, $basis); + if (is_string($yearFrac)) { + return $yearFrac; + } + + $amortiseCoeff = self::getAmortizationCoefficient($rate); + + $rate *= $amortiseCoeff; + $fNRate = round($yearFrac * $rate * $cost, 0); + $cost -= $fNRate; + $fRest = $cost - $salvage; + + for ($n = 0; $n < $period; ++$n) { + $fNRate = round($rate * $cost, 0); + $fRest -= $fNRate; + + if ($fRest < 0.0) { + switch ($period - $n) { + case 0: + case 1: + return round($cost * 0.5, 0); + default: + return 0.0; + } + } + $cost -= $fNRate; + } + + return $fNRate; + } + + /** + * AMORLINC. + * + * Returns the depreciation for each accounting period. + * This function is provided for the French accounting system. If an asset is purchased in + * the middle of the accounting period, the prorated depreciation is taken into account. + * + * Excel Function: + * AMORLINC(cost,purchased,firstPeriod,salvage,period,rate[,basis]) + * + * @param mixed $cost The cost of the asset as a float + * @param mixed $purchased Date of the purchase of the asset + * @param mixed $firstPeriod Date of the end of the first period + * @param mixed $salvage The salvage value at the end of the life of the asset + * @param mixed $period The period as a float + * @param mixed $rate Rate of depreciation as float + * @param mixed $basis Integer indicating the type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return float|string (string containing the error type if there is an error) + */ + public static function AMORLINC( + $cost, + $purchased, + $firstPeriod, + $salvage, + $period, + $rate, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $cost = Functions::flattenSingleValue($cost); + $purchased = Functions::flattenSingleValue($purchased); + $firstPeriod = Functions::flattenSingleValue($firstPeriod); + $salvage = Functions::flattenSingleValue($salvage); + $period = Functions::flattenSingleValue($period); + $rate = Functions::flattenSingleValue($rate); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $cost = FinancialValidations::validateFloat($cost); + $purchased = FinancialValidations::validateDate($purchased); + $firstPeriod = FinancialValidations::validateDate($firstPeriod); + $salvage = FinancialValidations::validateFloat($salvage); + $period = FinancialValidations::validateFloat($period); + $rate = FinancialValidations::validateFloat($rate); + $basis = FinancialValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + $fOneRate = $cost * $rate; + $fCostDelta = $cost - $salvage; + // Note, quirky variation for leap years on the YEARFRAC for this function + $purchasedYear = DateTimeExcel\DateParts::year($purchased); + $yearFrac = DateTimeExcel\YearFrac::fraction($purchased, $firstPeriod, $basis); + if (is_string($yearFrac)) { + return $yearFrac; + } + + if ( + ($basis == FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL) && + ($yearFrac < 1) && (DateTimeExcel\Helpers::isLeapYear($purchasedYear)) + ) { + $yearFrac *= 365 / 366; + } + + $f0Rate = $yearFrac * $rate * $cost; + $nNumOfFullPeriods = (int) (($cost - $salvage - $f0Rate) / $fOneRate); + + if ($period == 0) { + return $f0Rate; + } elseif ($period <= $nNumOfFullPeriods) { + return $fOneRate; + } elseif ($period == ($nNumOfFullPeriods + 1)) { + return $fCostDelta - $fOneRate * $nNumOfFullPeriods - $f0Rate; + } + + return 0.0; + } + + private static function getAmortizationCoefficient(float $rate): float + { + // The depreciation coefficients are: + // Life of assets (1/rate) Depreciation coefficient + // Less than 3 years 1 + // Between 3 and 4 years 1.5 + // Between 5 and 6 years 2 + // More than 6 years 2.5 + $fUsePer = 1.0 / $rate; + + if ($fUsePer < 3.0) { + return 1.0; + } elseif ($fUsePer < 4.0) { + return 1.5; + } elseif ($fUsePer <= 6.0) { + return 2.0; + } + + return 2.5; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Financial/CashFlow/CashFlowValidations.php b/src/PhpSpreadsheet/Calculation/Financial/CashFlow/CashFlowValidations.php new file mode 100644 index 00000000..e4c8a3a4 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Financial/CashFlow/CashFlowValidations.php @@ -0,0 +1,53 @@ +getMessage(); + } + + return self::calculateFutureValue($rate, $numberOfPeriods, $payment, $presentValue, $type); + } + + /** + * PV. + * + * Returns the Present Value of a cash flow with constant payments and interest rate (annuities). + * + * @param mixed $rate Interest rate per period + * @param mixed $numberOfPeriods Number of periods as an integer + * @param mixed $payment Periodic payment (annuity) + * @param mixed $futureValue Future Value + * @param mixed $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period + * + * @return float|string Result, or a string containing an error + */ + public static function presentValue( + $rate, + $numberOfPeriods, + $payment = 0.0, + $futureValue = 0.0, + $type = FinancialConstants::PAYMENT_END_OF_PERIOD + ) { + $rate = Functions::flattenSingleValue($rate); + $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); + $payment = ($payment === null) ? 0.0 : Functions::flattenSingleValue($payment); + $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); + $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); + + try { + $rate = CashFlowValidations::validateRate($rate); + $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); + $payment = CashFlowValidations::validateFloat($payment); + $futureValue = CashFlowValidations::validateFutureValue($futureValue); + $type = CashFlowValidations::validatePeriodType($type); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Validate parameters + if ($numberOfPeriods < 0) { + return Functions::NAN(); + } + + return self::calculatePresentValue($rate, $numberOfPeriods, $payment, $futureValue, $type); + } + + /** + * NPER. + * + * Returns the number of periods for a cash flow with constant periodic payments (annuities), and interest rate. + * + * @param mixed $rate Interest rate per period + * @param mixed $payment Periodic payment (annuity) + * @param mixed $presentValue Present Value + * @param mixed $futureValue Future Value + * @param mixed $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period + * + * @return float|string Result, or a string containing an error + */ + public static function periods( + $rate, + $payment, + $presentValue, + $futureValue = 0.0, + $type = FinancialConstants::PAYMENT_END_OF_PERIOD + ) { + $rate = Functions::flattenSingleValue($rate); + $payment = Functions::flattenSingleValue($payment); + $presentValue = Functions::flattenSingleValue($presentValue); + $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); + $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); + + try { + $rate = CashFlowValidations::validateRate($rate); + $payment = CashFlowValidations::validateFloat($payment); + $presentValue = CashFlowValidations::validatePresentValue($presentValue); + $futureValue = CashFlowValidations::validateFutureValue($futureValue); + $type = CashFlowValidations::validatePeriodType($type); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Validate parameters + if ($payment == 0.0) { + return Functions::NAN(); + } + + return self::calculatePeriods($rate, $payment, $presentValue, $futureValue, $type); + } + + private static function calculateFutureValue( + float $rate, + int $numberOfPeriods, + float $payment, + float $presentValue, + int $type + ): float { + if ($rate !== null && $rate != 0) { + return -$presentValue * + (1 + $rate) ** $numberOfPeriods - $payment * (1 + $rate * $type) * ((1 + $rate) ** $numberOfPeriods - 1) + / $rate; + } + + return -$presentValue - $payment * $numberOfPeriods; + } + + private static function calculatePresentValue( + float $rate, + int $numberOfPeriods, + float $payment, + float $futureValue, + int $type + ): float { + if ($rate != 0.0) { + return (-$payment * (1 + $rate * $type) + * (((1 + $rate) ** $numberOfPeriods - 1) / $rate) - $futureValue) / (1 + $rate) ** $numberOfPeriods; + } + + return -$futureValue - $payment * $numberOfPeriods; + } + + /** + * @return float|string + */ + private static function calculatePeriods( + float $rate, + float $payment, + float $presentValue, + float $futureValue, + int $type + ) { + if ($rate != 0.0) { + if ($presentValue == 0.0) { + return Functions::NAN(); + } + + return log(($payment * (1 + $rate * $type) / $rate - $futureValue) / + ($presentValue + $payment * (1 + $rate * $type) / $rate)) / log(1 + $rate); + } + + return (-$presentValue - $futureValue) / $payment; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Cumulative.php b/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Cumulative.php new file mode 100644 index 00000000..b7f6011c --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Cumulative.php @@ -0,0 +1,141 @@ +getMessage(); + } + + // Validate parameters + if ($start < 1 || $start > $end) { + return Functions::NAN(); + } + + // Calculate + $interest = 0; + for ($per = $start; $per <= $end; ++$per) { + $ipmt = Interest::payment($rate, $per, $periods, $presentValue, 0, $type); + if (is_string($ipmt)) { + return $ipmt; + } + + $interest += $ipmt; + } + + return $interest; + } + + /** + * CUMPRINC. + * + * Returns the cumulative principal paid on a loan between the start and end periods. + * + * Excel Function: + * CUMPRINC(rate,nper,pv,start,end[,type]) + * + * @param mixed $rate The Interest rate + * @param mixed $periods The total number of payment periods as an integer + * @param mixed $presentValue Present Value + * @param mixed $start The first period in the calculation. + * Payment periods are numbered beginning with 1. + * @param mixed $end the last period in the calculation + * @param mixed $type A number 0 or 1 and indicates when payments are due: + * 0 or omitted At the end of the period. + * 1 At the beginning of the period. + * + * @return float|string + */ + public static function principal( + $rate, + $periods, + $presentValue, + $start, + $end, + $type = FinancialConstants::PAYMENT_END_OF_PERIOD + ) { + $rate = Functions::flattenSingleValue($rate); + $periods = Functions::flattenSingleValue($periods); + $presentValue = Functions::flattenSingleValue($presentValue); + $start = Functions::flattenSingleValue($start); + $end = Functions::flattenSingleValue($end); + $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); + + try { + $rate = CashFlowValidations::validateRate($rate); + $periods = CashFlowValidations::validateInt($periods); + $presentValue = CashFlowValidations::validatePresentValue($presentValue); + $start = CashFlowValidations::validateInt($start); + $end = CashFlowValidations::validateInt($end); + $type = CashFlowValidations::validatePeriodType($type); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Validate parameters + if ($start < 1 || $start > $end) { + return Functions::VALUE(); + } + + // Calculate + $principal = 0; + for ($per = $start; $per <= $end; ++$per) { + $ppmt = Payments::interestPayment($rate, $per, $periods, $presentValue, 0, $type); + if (is_string($ppmt)) { + return $ppmt; + } + + $principal += $ppmt; + } + + return $principal; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php b/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php new file mode 100644 index 00000000..56d2e379 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php @@ -0,0 +1,216 @@ +getMessage(); + } + + // Validate parameters + if ($period <= 0 || $period > $numberOfPeriods) { + return Functions::NAN(); + } + + // Calculate + $interestAndPrincipal = new InterestAndPrincipal( + $interestRate, + $period, + $numberOfPeriods, + $presentValue, + $futureValue, + $type + ); + + return $interestAndPrincipal->interest(); + } + + /** + * ISPMT. + * + * Returns the interest payment for an investment based on an interest rate and a constant payment schedule. + * + * Excel Function: + * =ISPMT(interest_rate, period, number_payments, pv) + * + * @param mixed $interestRate is the interest rate for the investment + * @param mixed $period is the period to calculate the interest rate. It must be betweeen 1 and number_payments. + * @param mixed $numberOfPeriods is the number of payments for the annuity + * @param mixed $principleRemaining is the loan amount or present value of the payments + */ + public static function schedulePayment($interestRate, $period, $numberOfPeriods, $principleRemaining) + { + $interestRate = Functions::flattenSingleValue($interestRate); + $period = Functions::flattenSingleValue($period); + $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); + $principleRemaining = Functions::flattenSingleValue($principleRemaining); + + try { + $interestRate = CashFlowValidations::validateRate($interestRate); + $period = CashFlowValidations::validateInt($period); + $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); + $principleRemaining = CashFlowValidations::validateFloat($principleRemaining); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Validate parameters + if ($period <= 0 || $period > $numberOfPeriods) { + return Functions::NAN(); + } + + // Return value + $returnValue = 0; + + // Calculate + $principlePayment = ($principleRemaining * 1.0) / ($numberOfPeriods * 1.0); + for ($i = 0; $i <= $period; ++$i) { + $returnValue = $interestRate * $principleRemaining * -1; + $principleRemaining -= $principlePayment; + // principle needs to be 0 after the last payment, don't let floating point screw it up + if ($i == $numberOfPeriods) { + $returnValue = 0.0; + } + } + + return $returnValue; + } + + /** + * RATE. + * + * Returns the interest rate per period of an annuity. + * RATE is calculated by iteration and can have zero or more solutions. + * If the successive results of RATE do not converge to within 0.0000001 after 20 iterations, + * RATE returns the #NUM! error value. + * + * Excel Function: + * RATE(nper,pmt,pv[,fv[,type[,guess]]]) + * + * @param mixed $numberOfPeriods The total number of payment periods in an annuity + * @param mixed $payment The payment made each period and cannot change over the life of the annuity. + * Typically, pmt includes principal and interest but no other fees or taxes. + * @param mixed $presentValue The present value - the total amount that a series of future payments is worth now + * @param mixed $futureValue The future value, or a cash balance you want to attain after the last payment is made. + * If fv is omitted, it is assumed to be 0 (the future value of a loan, + * for example, is 0). + * @param mixed $type A number 0 or 1 and indicates when payments are due: + * 0 or omitted At the end of the period. + * 1 At the beginning of the period. + * @param mixed $guess Your guess for what the rate will be. + * If you omit guess, it is assumed to be 10 percent. + * + * @return float|string + */ + public static function rate( + $numberOfPeriods, + $payment, + $presentValue, + $futureValue = 0.0, + $type = FinancialConstants::PAYMENT_END_OF_PERIOD, + $guess = 0.1 + ) { + $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); + $payment = Functions::flattenSingleValue($payment); + $presentValue = Functions::flattenSingleValue($presentValue); + $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); + $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); + $guess = ($guess === null) ? 0.1 : Functions::flattenSingleValue($guess); + + try { + $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); + $payment = CashFlowValidations::validateFloat($payment); + $presentValue = CashFlowValidations::validatePresentValue($presentValue); + $futureValue = CashFlowValidations::validateFutureValue($futureValue); + $type = CashFlowValidations::validatePeriodType($type); + $guess = CashFlowValidations::validateFloat($guess); + } catch (Exception $e) { + return $e->getMessage(); + } + + $rate = $guess; + // rest of code adapted from python/numpy + $close = false; + $iter = 0; + while (!$close && $iter < self::FINANCIAL_MAX_ITERATIONS) { + $nextdiff = self::rateNextGuess($rate, $numberOfPeriods, $payment, $presentValue, $futureValue, $type); + if (!is_numeric($nextdiff)) { + break; + } + $rate1 = $rate - $nextdiff; + $close = abs($rate1 - $rate) < self::FINANCIAL_PRECISION; + ++$iter; + $rate = $rate1; + } + + return $close ? $rate : Functions::NAN(); + } + + private static function rateNextGuess($rate, $numberOfPeriods, $payment, $presentValue, $futureValue, $type) + { + if ($rate == 0.0) { + return Functions::NAN(); + } + $tt1 = ($rate + 1) ** $numberOfPeriods; + $tt2 = ($rate + 1) ** ($numberOfPeriods - 1); + $numerator = $futureValue + $tt1 * $presentValue + $payment * ($tt1 - 1) * ($rate * $type + 1) / $rate; + $denominator = $numberOfPeriods * $tt2 * $presentValue - $payment * ($tt1 - 1) + * ($rate * $type + 1) / ($rate * $rate) + $numberOfPeriods + * $payment * $tt2 * ($rate * $type + 1) / $rate + $payment * ($tt1 - 1) * $type / $rate; + if ($denominator == 0) { + return Functions::NAN(); + } + + return $numerator / $denominator; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/InterestAndPrincipal.php b/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/InterestAndPrincipal.php new file mode 100644 index 00000000..ca989e00 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/InterestAndPrincipal.php @@ -0,0 +1,44 @@ +interest = $interest; + $this->principal = $principal; + } + + public function interest(): float + { + return $this->interest; + } + + public function principal(): float + { + return $this->principal; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Payments.php b/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Payments.php new file mode 100644 index 00000000..e103f923 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Payments.php @@ -0,0 +1,115 @@ +getMessage(); + } + + // Calculate + if ($interestRate != 0.0) { + return (-$futureValue - $presentValue * (1 + $interestRate) ** $numberOfPeriods) / + (1 + $interestRate * $type) / (((1 + $interestRate) ** $numberOfPeriods - 1) / $interestRate); + } + + return (-$presentValue - $futureValue) / $numberOfPeriods; + } + + /** + * PPMT. + * + * Returns the interest payment for a given period for an investment based on periodic, constant payments + * and a constant interest rate. + * + * @param mixed $interestRate Interest rate per period + * @param mixed $period Period for which we want to find the interest + * @param mixed $numberOfPeriods Number of periods + * @param mixed $presentValue Present Value + * @param mixed $futureValue Future Value + * @param mixed $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period + * + * @return float|string Result, or a string containing an error + */ + public static function interestPayment( + $interestRate, + $period, + $numberOfPeriods, + $presentValue, + $futureValue = 0, + $type = FinancialConstants::PAYMENT_END_OF_PERIOD + ) { + $interestRate = Functions::flattenSingleValue($interestRate); + $period = Functions::flattenSingleValue($period); + $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); + $presentValue = Functions::flattenSingleValue($presentValue); + $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); + $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); + + try { + $interestRate = CashFlowValidations::validateRate($interestRate); + $period = CashFlowValidations::validateInt($period); + $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); + $presentValue = CashFlowValidations::validatePresentValue($presentValue); + $futureValue = CashFlowValidations::validateFutureValue($futureValue); + $type = CashFlowValidations::validatePeriodType($type); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Validate parameters + if ($period <= 0 || $period > $numberOfPeriods) { + return Functions::NAN(); + } + + // Calculate + $interestAndPrincipal = new InterestAndPrincipal( + $interestRate, + $period, + $numberOfPeriods, + $presentValue, + $futureValue, + $type + ); + + return $interestAndPrincipal->principal(); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Single.php b/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Single.php new file mode 100644 index 00000000..a30634da --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Single.php @@ -0,0 +1,108 @@ +getMessage(); + } + + return $principal; + } + + /** + * PDURATION. + * + * Calculates the number of periods required for an investment to reach a specified value. + * + * @param mixed $rate Interest rate per period + * @param mixed $presentValue Present Value + * @param mixed $futureValue Future Value + * + * @return float|string Result, or a string containing an error + */ + public static function periods($rate, $presentValue, $futureValue) + { + $rate = Functions::flattenSingleValue($rate); + $presentValue = Functions::flattenSingleValue($presentValue); + $futureValue = Functions::flattenSingleValue($futureValue); + + try { + $rate = CashFlowValidations::validateRate($rate); + $presentValue = CashFlowValidations::validatePresentValue($presentValue); + $futureValue = CashFlowValidations::validateFutureValue($futureValue); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Validate parameters + if ($rate <= 0.0 || $presentValue <= 0.0 || $futureValue <= 0.0) { + return Functions::NAN(); + } + + return (log($futureValue) - log($presentValue)) / log(1 + $rate); + } + + /** + * RRI. + * + * Calculates the interest rate required for an investment to grow to a specified future value . + * + * @param float $periods The number of periods over which the investment is made + * @param float $presentValue Present Value + * @param float $futureValue Future Value + * + * @return float|string Result, or a string containing an error + */ + public static function interestRate($periods = 0.0, $presentValue = 0.0, $futureValue = 0.0) + { + $periods = Functions::flattenSingleValue($periods); + $presentValue = Functions::flattenSingleValue($presentValue); + $futureValue = Functions::flattenSingleValue($futureValue); + + try { + $periods = CashFlowValidations::validateFloat($periods); + $presentValue = CashFlowValidations::validatePresentValue($presentValue); + $futureValue = CashFlowValidations::validateFutureValue($futureValue); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Validate parameters + if ($periods <= 0.0 || $presentValue <= 0.0 || $futureValue < 0.0) { + return Functions::NAN(); + } + + return ($futureValue / $presentValue) ** (1 / $periods) - 1; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/NonPeriodic.php b/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/NonPeriodic.php new file mode 100644 index 00000000..8986146c --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/NonPeriodic.php @@ -0,0 +1,244 @@ +getMessage(); + } + } + + return self::xirrPart2($values); + } + + private static function xirrPart2(array &$values): string + { + $valCount = count($values); + $foundpos = false; + $foundneg = false; + for ($i = 0; $i < $valCount; ++$i) { + $fld = $values[$i]; + if (!is_numeric($fld)) { + return Functions::VALUE(); + } elseif ($fld > 0) { + $foundpos = true; + } elseif ($fld < 0) { + $foundneg = true; + } + } + if (!self::bothNegAndPos($foundneg, $foundpos)) { + return Functions::NAN(); + } + + return ''; + } + + /** + * @return float|string + */ + private static function xirrPart3(array $values, array $dates, float $x1, float $x2) + { + $f = self::xnpvOrdered($x1, $values, $dates, false); + if ($f < 0.0) { + $rtb = $x1; + $dx = $x2 - $x1; + } else { + $rtb = $x2; + $dx = $x1 - $x2; + } + + $rslt = Functions::VALUE(); + for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { + $dx *= 0.5; + $x_mid = $rtb + $dx; + $f_mid = (float) self::xnpvOrdered($x_mid, $values, $dates, false); + if ($f_mid <= 0.0) { + $rtb = $x_mid; + } + if ((abs($f_mid) < self::FINANCIAL_PRECISION) || (abs($dx) < self::FINANCIAL_PRECISION)) { + $rslt = $x_mid; + + break; + } + } + + return $rslt; + } + + /** + * @param mixed $rate + * @param mixed $values + * @param mixed $dates + * + * @return float|string + */ + private static function xnpvOrdered($rate, $values, $dates, bool $ordered = true) + { + $rate = Functions::flattenSingleValue($rate); + $values = Functions::flattenArray($values); + $dates = Functions::flattenArray($dates); + $valCount = count($values); + + try { + self::validateXnpv($rate, $values, $dates); + $date0 = DateTimeExcel\Helpers::getDateValue($dates[0]); + } catch (Exception $e) { + return $e->getMessage(); + } + + $xnpv = 0.0; + for ($i = 0; $i < $valCount; ++$i) { + if (!is_numeric($values[$i])) { + return Functions::VALUE(); + } + + try { + $datei = DateTimeExcel\Helpers::getDateValue($dates[$i]); + } catch (Exception $e) { + return $e->getMessage(); + } + if ($date0 > $datei) { + $dif = $ordered ? Functions::NAN() : -((int) DateTimeExcel\Difference::interval($datei, $date0, 'd')); + } else { + $dif = DateTimeExcel\Difference::interval($date0, $datei, 'd'); + } + if (!is_numeric($dif)) { + return $dif; + } + $xnpv += $values[$i] / (1 + $rate) ** ($dif / 365); + } + + return is_finite($xnpv) ? $xnpv : Functions::VALUE(); + } + + /** + * @param mixed $rate + */ + private static function validateXnpv($rate, array $values, array $dates): void + { + if (!is_numeric($rate)) { + throw new Exception(Functions::VALUE()); + } + $valCount = count($values); + if ($valCount != count($dates)) { + throw new Exception(Functions::NAN()); + } + if ($valCount > 1 && ((min($values) > 0) || (max($values) < 0))) { + throw new Exception(Functions::NAN()); + } + } +} diff --git a/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/Periodic.php b/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/Periodic.php new file mode 100644 index 00000000..c42df0c3 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/Periodic.php @@ -0,0 +1,160 @@ + 0.0) { + return Functions::VALUE(); + } + + $f = self::presentValue($x1, $values); + if ($f < 0.0) { + $rtb = $x1; + $dx = $x2 - $x1; + } else { + $rtb = $x2; + $dx = $x1 - $x2; + } + + for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { + $dx *= 0.5; + $x_mid = $rtb + $dx; + $f_mid = self::presentValue($x_mid, $values); + if ($f_mid <= 0.0) { + $rtb = $x_mid; + } + if ((abs($f_mid) < self::FINANCIAL_PRECISION) || (abs($dx) < self::FINANCIAL_PRECISION)) { + return $x_mid; + } + } + + return Functions::VALUE(); + } + + /** + * MIRR. + * + * Returns the modified internal rate of return for a series of periodic cash flows. MIRR considers both + * the cost of the investment and the interest received on reinvestment of cash. + * + * Excel Function: + * MIRR(values,finance_rate, reinvestment_rate) + * + * @param mixed $values An array or a reference to cells that contain a series of payments and + * income occurring at regular intervals. + * Payments are negative value, income is positive values. + * @param mixed $financeRate The interest rate you pay on the money used in the cash flows + * @param mixed $reinvestmentRate The interest rate you receive on the cash flows as you reinvest them + * + * @return float|string Result, or a string containing an error + */ + public static function modifiedRate($values, $financeRate, $reinvestmentRate) + { + if (!is_array($values)) { + return Functions::VALUE(); + } + $values = Functions::flattenArray($values); + $financeRate = Functions::flattenSingleValue($financeRate); + $reinvestmentRate = Functions::flattenSingleValue($reinvestmentRate); + $n = count($values); + + $rr = 1.0 + $reinvestmentRate; + $fr = 1.0 + $financeRate; + + $npvPos = $npvNeg = 0.0; + foreach ($values as $i => $v) { + if ($v >= 0) { + $npvPos += $v / $rr ** $i; + } else { + $npvNeg += $v / $fr ** $i; + } + } + + if (($npvNeg === 0.0) || ($npvPos === 0.0) || ($reinvestmentRate <= -1.0)) { + return Functions::VALUE(); + } + + $mirr = ((-$npvPos * $rr ** $n) + / ($npvNeg * ($rr))) ** (1.0 / ($n - 1)) - 1.0; + + return is_finite($mirr) ? $mirr : Functions::VALUE(); + } + + /** + * NPV. + * + * Returns the Net Present Value of a cash flow series given a discount rate. + * + * @param mixed $rate + * + * @return float + */ + public static function presentValue($rate, ...$args) + { + $returnValue = 0; + + $rate = Functions::flattenSingleValue($rate); + $aArgs = Functions::flattenArray($args); + + // Calculate + $countArgs = count($aArgs); + for ($i = 1; $i <= $countArgs; ++$i) { + // Is it a numeric value? + if (is_numeric($aArgs[$i - 1])) { + $returnValue += $aArgs[$i - 1] / (1 + $rate) ** $i; + } + } + + return $returnValue; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Financial/Constants.php b/src/PhpSpreadsheet/Calculation/Financial/Constants.php new file mode 100644 index 00000000..17740b0a --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Financial/Constants.php @@ -0,0 +1,19 @@ +getMessage(); + } + + $daysPerYear = Helpers::daysPerYear(DateTimeExcel\DateParts::year($settlement), $basis); + if (is_string($daysPerYear)) { + return Functions::VALUE(); + } + $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_PREVIOUS); + + if ($basis === FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL) { + return abs((float) DateTimeExcel\Days::between($prev, $settlement)); + } + + return (float) DateTimeExcel\YearFrac::fraction($prev, $settlement, $basis) * $daysPerYear; + } + + /** + * COUPDAYS. + * + * Returns the number of days in the coupon period that contains the settlement date. + * + * Excel Function: + * COUPDAYS(settlement,maturity,frequency[,basis]) + * + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed $frequency The number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * @param mixed $basis The type of day count to use (int). + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return float|string + */ + public static function COUPDAYS( + $settlement, + $maturity, + $frequency, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $frequency = Functions::flattenSingleValue($frequency); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $settlement = FinancialValidations::validateSettlementDate($settlement); + $maturity = FinancialValidations::validateMaturityDate($maturity); + self::validateCouponPeriod($settlement, $maturity); + $frequency = FinancialValidations::validateFrequency($frequency); + $basis = FinancialValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + switch ($basis) { + case FinancialConstants::BASIS_DAYS_PER_YEAR_365: + // Actual/365 + return 365 / $frequency; + case FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL: + // Actual/actual + if ($frequency == FinancialConstants::FREQUENCY_ANNUAL) { + $daysPerYear = Helpers::daysPerYear(DateTimeExcel\DateParts::year($settlement), $basis); + + return $daysPerYear / $frequency; + } + $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_PREVIOUS); + $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_NEXT); + + return $next - $prev; + default: + // US (NASD) 30/360, Actual/360 or European 30/360 + return 360 / $frequency; + } + } + + /** + * COUPDAYSNC. + * + * Returns the number of days from the settlement date to the next coupon date. + * + * Excel Function: + * COUPDAYSNC(settlement,maturity,frequency[,basis]) + * + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed $frequency The number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * @param mixed $basis The type of day count to use (int) . + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return float|string + */ + public static function COUPDAYSNC( + $settlement, + $maturity, + $frequency, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $frequency = Functions::flattenSingleValue($frequency); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $settlement = FinancialValidations::validateSettlementDate($settlement); + $maturity = FinancialValidations::validateMaturityDate($maturity); + self::validateCouponPeriod($settlement, $maturity); + $frequency = FinancialValidations::validateFrequency($frequency); + $basis = FinancialValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + $daysPerYear = Helpers::daysPerYear(DateTimeExcel\DateParts::year($settlement), $basis); + $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_NEXT); + + if ($basis === FinancialConstants::BASIS_DAYS_PER_YEAR_NASD) { + $settlementDate = Date::excelToDateTimeObject($settlement); + $settlementEoM = Helpers::isLastDayOfMonth($settlementDate); + if ($settlementEoM) { + ++$settlement; + } + } + + return (float) DateTimeExcel\YearFrac::fraction($settlement, $next, $basis) * $daysPerYear; + } + + /** + * COUPNCD. + * + * Returns the next coupon date after the settlement date. + * + * Excel Function: + * COUPNCD(settlement,maturity,frequency[,basis]) + * + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed $frequency The number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * @param mixed $basis The type of day count to use (int). + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function COUPNCD( + $settlement, + $maturity, + $frequency, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $frequency = Functions::flattenSingleValue($frequency); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $settlement = FinancialValidations::validateSettlementDate($settlement); + $maturity = FinancialValidations::validateMaturityDate($maturity); + self::validateCouponPeriod($settlement, $maturity); + $frequency = FinancialValidations::validateFrequency($frequency); + $basis = FinancialValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + return self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_NEXT); + } + + /** + * COUPNUM. + * + * Returns the number of coupons payable between the settlement date and maturity date, + * rounded up to the nearest whole coupon. + * + * Excel Function: + * COUPNUM(settlement,maturity,frequency[,basis]) + * + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed $frequency The number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * @param mixed $basis The type of day count to use (int). + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return int|string + */ + public static function COUPNUM( + $settlement, + $maturity, + $frequency, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $frequency = Functions::flattenSingleValue($frequency); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $settlement = FinancialValidations::validateSettlementDate($settlement); + $maturity = FinancialValidations::validateMaturityDate($maturity); + self::validateCouponPeriod($settlement, $maturity); + $frequency = FinancialValidations::validateFrequency($frequency); + $basis = FinancialValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + $yearsBetweenSettlementAndMaturity = DateTimeExcel\YearFrac::fraction( + $settlement, + $maturity, + FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ); + + return (int) ceil((float) $yearsBetweenSettlementAndMaturity * $frequency); + } + + /** + * COUPPCD. + * + * Returns the previous coupon date before the settlement date. + * + * Excel Function: + * COUPPCD(settlement,maturity,frequency[,basis]) + * + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed $frequency The number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * @param mixed $basis The type of day count to use (int). + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function COUPPCD( + $settlement, + $maturity, + $frequency, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $frequency = Functions::flattenSingleValue($frequency); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $settlement = FinancialValidations::validateSettlementDate($settlement); + $maturity = FinancialValidations::validateMaturityDate($maturity); + self::validateCouponPeriod($settlement, $maturity); + $frequency = FinancialValidations::validateFrequency($frequency); + $basis = FinancialValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + return self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_PREVIOUS); + } + + private static function monthsDiff(DateTime $result, int $months, string $plusOrMinus, int $day, bool $lastDayFlag): void + { + $result->setDate((int) $result->format('Y'), (int) $result->format('m'), 1); + $result->modify("$plusOrMinus $months months"); + $daysInMonth = (int) $result->format('t'); + $result->setDate((int) $result->format('Y'), (int) $result->format('m'), $lastDayFlag ? $daysInMonth : min($day, $daysInMonth)); + } + + private static function couponFirstPeriodDate(float $settlement, float $maturity, int $frequency, bool $next): float + { + $months = 12 / $frequency; + + $result = Date::excelToDateTimeObject($maturity); + $day = (int) $result->format('d'); + $lastDayFlag = Helpers::isLastDayOfMonth($result); + + while ($settlement < Date::PHPToExcel($result)) { + self::monthsDiff($result, $months, '-', $day, $lastDayFlag); + } + if ($next === true) { + self::monthsDiff($result, $months, '+', $day, $lastDayFlag); + } + + return (float) Date::PHPToExcel($result); + } + + private static function validateCouponPeriod(float $settlement, float $maturity): void + { + if ($settlement >= $maturity) { + throw new Exception(Functions::NAN()); + } + } +} diff --git a/src/PhpSpreadsheet/Calculation/Financial/Depreciation.php b/src/PhpSpreadsheet/Calculation/Financial/Depreciation.php new file mode 100644 index 00000000..650a4861 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Financial/Depreciation.php @@ -0,0 +1,266 @@ +getMessage(); + } + + if ($cost === 0.0) { + return 0.0; + } + + // Set Fixed Depreciation Rate + $fixedDepreciationRate = 1 - ($salvage / $cost) ** (1 / $life); + $fixedDepreciationRate = round($fixedDepreciationRate, 3); + + // Loop through each period calculating the depreciation + // TODO Handle period value between 0 and 1 (e.g. 0.5) + $previousDepreciation = 0; + $depreciation = 0; + for ($per = 1; $per <= $period; ++$per) { + if ($per == 1) { + $depreciation = $cost * $fixedDepreciationRate * $month / 12; + } elseif ($per == ($life + 1)) { + $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate * (12 - $month) / 12; + } else { + $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate; + } + $previousDepreciation += $depreciation; + } + + return $depreciation; + } + + /** + * DDB. + * + * Returns the depreciation of an asset for a specified period using the + * double-declining balance method or some other method you specify. + * + * Excel Function: + * DDB(cost,salvage,life,period[,factor]) + * + * @param mixed $cost Initial cost of the asset + * @param mixed $salvage Value at the end of the depreciation. + * (Sometimes called the salvage value of the asset) + * @param mixed $life Number of periods over which the asset is depreciated. + * (Sometimes called the useful life of the asset) + * @param mixed $period The period for which you want to calculate the + * depreciation. Period must use the same units as life. + * @param mixed $factor The rate at which the balance declines. + * If factor is omitted, it is assumed to be 2 (the + * double-declining balance method). + * + * @return float|string + */ + public static function DDB($cost, $salvage, $life, $period, $factor = 2.0) + { + $cost = Functions::flattenSingleValue($cost); + $salvage = Functions::flattenSingleValue($salvage); + $life = Functions::flattenSingleValue($life); + $period = Functions::flattenSingleValue($period); + $factor = Functions::flattenSingleValue($factor); + + try { + $cost = self::validateCost($cost); + $salvage = self::validateSalvage($salvage); + $life = self::validateLife($life); + $period = self::validatePeriod($period); + $factor = self::validateFactor($factor); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($period > $life) { + return Functions::NAN(); + } + + // Loop through each period calculating the depreciation + // TODO Handling for fractional $period values + $previousDepreciation = 0; + $depreciation = 0; + for ($per = 1; $per <= $period; ++$per) { + $depreciation = min( + ($cost - $previousDepreciation) * ($factor / $life), + ($cost - $salvage - $previousDepreciation) + ); + $previousDepreciation += $depreciation; + } + + return $depreciation; + } + + /** + * SLN. + * + * Returns the straight-line depreciation of an asset for one period + * + * @param mixed $cost Initial cost of the asset + * @param mixed $salvage Value at the end of the depreciation + * @param mixed $life Number of periods over which the asset is depreciated + * + * @return float|string Result, or a string containing an error + */ + public static function SLN($cost, $salvage, $life) + { + $cost = Functions::flattenSingleValue($cost); + $salvage = Functions::flattenSingleValue($salvage); + $life = Functions::flattenSingleValue($life); + + try { + $cost = self::validateCost($cost, true); + $salvage = self::validateSalvage($salvage, true); + $life = self::validateLife($life, true); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($life === 0.0) { + return Functions::DIV0(); + } + + return ($cost - $salvage) / $life; + } + + /** + * SYD. + * + * Returns the sum-of-years' digits depreciation of an asset for a specified period. + * + * @param mixed $cost Initial cost of the asset + * @param mixed $salvage Value at the end of the depreciation + * @param mixed $life Number of periods over which the asset is depreciated + * @param mixed $period Period + * + * @return float|string Result, or a string containing an error + */ + public static function SYD($cost, $salvage, $life, $period) + { + $cost = Functions::flattenSingleValue($cost); + $salvage = Functions::flattenSingleValue($salvage); + $life = Functions::flattenSingleValue($life); + $period = Functions::flattenSingleValue($period); + + try { + $cost = self::validateCost($cost, true); + $salvage = self::validateSalvage($salvage); + $life = self::validateLife($life); + $period = self::validatePeriod($period); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($period > $life) { + return Functions::NAN(); + } + + $syd = (($cost - $salvage) * ($life - $period + 1) * 2) / ($life * ($life + 1)); + + return $syd; + } + + private static function validateCost($cost, bool $negativeValueAllowed = false): float + { + $cost = FinancialValidations::validateFloat($cost); + if ($cost < 0.0 && $negativeValueAllowed === false) { + throw new Exception(Functions::NAN()); + } + + return $cost; + } + + private static function validateSalvage($salvage, bool $negativeValueAllowed = false): float + { + $salvage = FinancialValidations::validateFloat($salvage); + if ($salvage < 0.0 && $negativeValueAllowed === false) { + throw new Exception(Functions::NAN()); + } + + return $salvage; + } + + private static function validateLife($life, bool $negativeValueAllowed = false): float + { + $life = FinancialValidations::validateFloat($life); + if ($life < 0.0 && $negativeValueAllowed === false) { + throw new Exception(Functions::NAN()); + } + + return $life; + } + + private static function validatePeriod($period, bool $negativeValueAllowed = false): float + { + $period = FinancialValidations::validateFloat($period); + if ($period <= 0.0 && $negativeValueAllowed === false) { + throw new Exception(Functions::NAN()); + } + + return $period; + } + + private static function validateMonth($month): int + { + $month = FinancialValidations::validateInt($month); + if ($month < 1) { + throw new Exception(Functions::NAN()); + } + + return $month; + } + + private static function validateFactor($factor): float + { + $factor = FinancialValidations::validateFloat($factor); + if ($factor <= 0.0) { + throw new Exception(Functions::NAN()); + } + + return $factor; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Financial/Dollar.php b/src/PhpSpreadsheet/Calculation/Financial/Dollar.php new file mode 100644 index 00000000..7bebb391 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Financial/Dollar.php @@ -0,0 +1,97 @@ + 4)) { + throw new Exception(Functions::NAN()); + } + + return $basis; + } + + /** + * @param mixed $price + */ + public static function validatePrice($price): float + { + $price = self::validateFloat($price); + if ($price < 0.0) { + throw new Exception(Functions::NAN()); + } + + return $price; + } + + /** + * @param mixed $parValue + */ + public static function validateParValue($parValue): float + { + $parValue = self::validateFloat($parValue); + if ($parValue < 0.0) { + throw new Exception(Functions::NAN()); + } + + return $parValue; + } + + /** + * @param mixed $yield + */ + public static function validateYield($yield): float + { + $yield = self::validateFloat($yield); + if ($yield < 0.0) { + throw new Exception(Functions::NAN()); + } + + return $yield; + } + + /** + * @param mixed $discount + */ + public static function validateDiscount($discount): float + { + $discount = self::validateFloat($discount); + if ($discount <= 0.0) { + throw new Exception(Functions::NAN()); + } + + return $discount; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Financial/Helpers.php b/src/PhpSpreadsheet/Calculation/Financial/Helpers.php new file mode 100644 index 00000000..d339b134 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Financial/Helpers.php @@ -0,0 +1,58 @@ +format('d') === $date->format('t'); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Financial/InterestRate.php b/src/PhpSpreadsheet/Calculation/Financial/InterestRate.php new file mode 100644 index 00000000..72df31e1 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Financial/InterestRate.php @@ -0,0 +1,72 @@ +getMessage(); + } + + if ($nominalRate <= 0 || $periodsPerYear < 1) { + return Functions::NAN(); + } + + return ((1 + $nominalRate / $periodsPerYear) ** $periodsPerYear) - 1; + } + + /** + * NOMINAL. + * + * Returns the nominal interest rate given the effective rate and the number of compounding payments per year. + * + * @param mixed $effectiveRate Effective interest rate as a float + * @param mixed $periodsPerYear Integer number of compounding payments per year + * + * @return float|string Result, or a string containing an error + */ + public static function nominal($effectiveRate = 0, $periodsPerYear = 0) + { + $effectiveRate = Functions::flattenSingleValue($effectiveRate); + $periodsPerYear = Functions::flattenSingleValue($periodsPerYear); + + try { + $effectiveRate = FinancialValidations::validateFloat($effectiveRate); + $periodsPerYear = FinancialValidations::validateInt($periodsPerYear); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($effectiveRate <= 0 || $periodsPerYear < 1) { + return Functions::NAN(); + } + + // Calculate + return $periodsPerYear * (($effectiveRate + 1) ** (1 / $periodsPerYear) - 1); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Financial/Securities/AccruedInterest.php b/src/PhpSpreadsheet/Calculation/Financial/Securities/AccruedInterest.php new file mode 100644 index 00000000..e167429b --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Financial/Securities/AccruedInterest.php @@ -0,0 +1,151 @@ +getMessage(); + } + + $daysBetweenIssueAndSettlement = YearFrac::fraction($issue, $settlement, $basis); + if (!is_numeric($daysBetweenIssueAndSettlement)) { + // return date error + return $daysBetweenIssueAndSettlement; + } + $daysBetweenFirstInterestAndSettlement = YearFrac::fraction($firstInterest, $settlement, $basis); + if (!is_numeric($daysBetweenFirstInterestAndSettlement)) { + // return date error + return $daysBetweenFirstInterestAndSettlement; + } + + return $parValue * $rate * $daysBetweenIssueAndSettlement; + } + + /** + * ACCRINTM. + * + * Returns the accrued interest for a security that pays interest at maturity. + * + * Excel Function: + * ACCRINTM(issue,settlement,rate[,par[,basis]]) + * + * @param mixed $issue The security's issue date + * @param mixed $settlement The security's settlement (or maturity) date + * @param mixed $rate The security's annual coupon rate + * @param mixed $parValue The security's par value. + * If you omit parValue, ACCRINT uses $1,000. + * @param mixed $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return float|string Result, or a string containing an error + */ + public static function atMaturity( + $issue, + $settlement, + $rate, + $parValue = 1000, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $issue = Functions::flattenSingleValue($issue); + $settlement = Functions::flattenSingleValue($settlement); + $rate = Functions::flattenSingleValue($rate); + $parValue = ($parValue === null) ? 1000 : Functions::flattenSingleValue($parValue); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $issue = SecurityValidations::validateIssueDate($issue); + $settlement = SecurityValidations::validateSettlementDate($settlement); + SecurityValidations::validateSecurityPeriod($issue, $settlement); + $rate = SecurityValidations::validateRate($rate); + $parValue = SecurityValidations::validateParValue($parValue); + $basis = SecurityValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + $daysBetweenIssueAndSettlement = YearFrac::fraction($issue, $settlement, $basis); + if (!is_numeric($daysBetweenIssueAndSettlement)) { + // return date error + return $daysBetweenIssueAndSettlement; + } + + return $parValue * $rate * $daysBetweenIssueAndSettlement; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Financial/Securities/Price.php b/src/PhpSpreadsheet/Calculation/Financial/Securities/Price.php new file mode 100644 index 00000000..7d8d5a32 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Financial/Securities/Price.php @@ -0,0 +1,283 @@ +getMessage(); + } + + $dsc = Coupons::COUPDAYSNC($settlement, $maturity, $frequency, $basis); + $e = Coupons::COUPDAYS($settlement, $maturity, $frequency, $basis); + $n = Coupons::COUPNUM($settlement, $maturity, $frequency, $basis); + $a = Coupons::COUPDAYBS($settlement, $maturity, $frequency, $basis); + + $baseYF = 1.0 + ($yield / $frequency); + $rfp = 100 * ($rate / $frequency); + $de = $dsc / $e; + + $result = $redemption / $baseYF ** (--$n + $de); + for ($k = 0; $k <= $n; ++$k) { + $result += $rfp / ($baseYF ** ($k + $de)); + } + $result -= $rfp * ($a / $e); + + return $result; + } + + /** + * PRICEDISC. + * + * Returns the price per $100 face value of a discounted security. + * + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue date when the security + * is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed $discount The security's discount rate + * @param mixed $redemption The security's redemption value per $100 face value + * @param mixed $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return float|string Result, or a string containing an error + */ + public static function priceDiscounted( + $settlement, + $maturity, + $discount, + $redemption, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $discount = Functions::flattenSingleValue($discount); + $redemption = Functions::flattenSingleValue($redemption); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $settlement = SecurityValidations::validateSettlementDate($settlement); + $maturity = SecurityValidations::validateMaturityDate($maturity); + SecurityValidations::validateSecurityPeriod($settlement, $maturity); + $discount = SecurityValidations::validateDiscount($discount); + $redemption = SecurityValidations::validateRedemption($redemption); + $basis = SecurityValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + $daysBetweenSettlementAndMaturity = DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + + return $redemption * (1 - $discount * $daysBetweenSettlementAndMaturity); + } + + /** + * PRICEMAT. + * + * Returns the price per $100 face value of a security that pays interest at maturity. + * + * @param mixed $settlement The security's settlement date. + * The security's settlement date is the date after the issue date when the + * security is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed $issue The security's issue date + * @param mixed $rate The security's interest rate at date of issue + * @param mixed $yield The security's annual yield + * @param mixed $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return float|string Result, or a string containing an error + */ + public static function priceAtMaturity( + $settlement, + $maturity, + $issue, + $rate, + $yield, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $issue = Functions::flattenSingleValue($issue); + $rate = Functions::flattenSingleValue($rate); + $yield = Functions::flattenSingleValue($yield); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $settlement = SecurityValidations::validateSettlementDate($settlement); + $maturity = SecurityValidations::validateMaturityDate($maturity); + SecurityValidations::validateSecurityPeriod($settlement, $maturity); + $issue = SecurityValidations::validateIssueDate($issue); + $rate = SecurityValidations::validateRate($rate); + $yield = SecurityValidations::validateYield($yield); + $basis = SecurityValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + $daysPerYear = Helpers::daysPerYear(DateTimeExcel\DateParts::year($settlement), $basis); + if (!is_numeric($daysPerYear)) { + return $daysPerYear; + } + $daysBetweenIssueAndSettlement = DateTimeExcel\YearFrac::fraction($issue, $settlement, $basis); + if (!is_numeric($daysBetweenIssueAndSettlement)) { + // return date error + return $daysBetweenIssueAndSettlement; + } + $daysBetweenIssueAndSettlement *= $daysPerYear; + $daysBetweenIssueAndMaturity = DateTimeExcel\YearFrac::fraction($issue, $maturity, $basis); + if (!is_numeric($daysBetweenIssueAndMaturity)) { + // return date error + return $daysBetweenIssueAndMaturity; + } + $daysBetweenIssueAndMaturity *= $daysPerYear; + $daysBetweenSettlementAndMaturity = DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + $daysBetweenSettlementAndMaturity *= $daysPerYear; + + return (100 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate * 100)) / + (1 + (($daysBetweenSettlementAndMaturity / $daysPerYear) * $yield)) - + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate * 100); + } + + /** + * RECEIVED. + * + * Returns the amount received at maturity for a fully invested Security. + * + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue date when the security + * is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed $investment The amount invested in the security + * @param mixed $discount The security's discount rate + * @param mixed $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return float|string Result, or a string containing an error + */ + public static function received( + $settlement, + $maturity, + $investment, + $discount, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $investment = Functions::flattenSingleValue($investment); + $discount = Functions::flattenSingleValue($discount); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $settlement = SecurityValidations::validateSettlementDate($settlement); + $maturity = SecurityValidations::validateMaturityDate($maturity); + SecurityValidations::validateSecurityPeriod($settlement, $maturity); + $investment = SecurityValidations::validateFloat($investment); + $discount = SecurityValidations::validateDiscount($discount); + $basis = SecurityValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($investment <= 0) { + return Functions::NAN(); + } + $daysBetweenSettlementAndMaturity = DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + + return $investment / (1 - ($discount * $daysBetweenSettlementAndMaturity)); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Financial/Securities/Rates.php b/src/PhpSpreadsheet/Calculation/Financial/Securities/Rates.php new file mode 100644 index 00000000..c5c5211b --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Financial/Securities/Rates.php @@ -0,0 +1,137 @@ +getMessage(); + } + + if ($price <= 0.0) { + return Functions::NAN(); + } + + $daysBetweenSettlementAndMaturity = DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + + return (1 - $price / $redemption) / $daysBetweenSettlementAndMaturity; + } + + /** + * INTRATE. + * + * Returns the interest rate for a fully invested security. + * + * Excel Function: + * INTRATE(settlement,maturity,investment,redemption[,basis]) + * + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue date when the security + * is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed $investment the amount invested in the security + * @param mixed $redemption the amount to be received at maturity + * @param mixed $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return float|string + */ + public static function interest( + $settlement, + $maturity, + $investment, + $redemption, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $investment = Functions::flattenSingleValue($investment); + $redemption = Functions::flattenSingleValue($redemption); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $settlement = SecurityValidations::validateSettlementDate($settlement); + $maturity = SecurityValidations::validateMaturityDate($maturity); + SecurityValidations::validateSecurityPeriod($settlement, $maturity); + $investment = SecurityValidations::validateFloat($investment); + $redemption = SecurityValidations::validateRedemption($redemption); + $basis = SecurityValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($investment <= 0) { + return Functions::NAN(); + } + + $daysBetweenSettlementAndMaturity = DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + + return (($redemption / $investment) - 1) / ($daysBetweenSettlementAndMaturity); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Financial/Securities/SecurityValidations.php b/src/PhpSpreadsheet/Calculation/Financial/Securities/SecurityValidations.php new file mode 100644 index 00000000..497197b8 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Financial/Securities/SecurityValidations.php @@ -0,0 +1,42 @@ += $maturity) { + throw new Exception(Functions::NAN()); + } + } + + /** + * @param mixed $redemption + */ + public static function validateRedemption($redemption): float + { + $redemption = self::validateFloat($redemption); + if ($redemption <= 0.0) { + throw new Exception(Functions::NAN()); + } + + return $redemption; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Financial/Securities/Yields.php b/src/PhpSpreadsheet/Calculation/Financial/Securities/Yields.php new file mode 100644 index 00000000..aa626935 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Financial/Securities/Yields.php @@ -0,0 +1,153 @@ +getMessage(); + } + + $daysPerYear = Helpers::daysPerYear(DateTimeExcel\DateParts::year($settlement), $basis); + if (!is_numeric($daysPerYear)) { + return $daysPerYear; + } + $daysBetweenSettlementAndMaturity = DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + $daysBetweenSettlementAndMaturity *= $daysPerYear; + + return (($redemption - $price) / $price) * ($daysPerYear / $daysBetweenSettlementAndMaturity); + } + + /** + * YIELDMAT. + * + * Returns the annual yield of a security that pays interest at maturity. + * + * @param mixed $settlement The security's settlement date. + * The security's settlement date is the date after the issue date when the security + * is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed $issue The security's issue date + * @param mixed $rate The security's interest rate at date of issue + * @param mixed $price The security's price per $100 face value + * @param mixed $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return float|string Result, or a string containing an error + */ + public static function yieldAtMaturity( + $settlement, + $maturity, + $issue, + $rate, + $price, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $issue = Functions::flattenSingleValue($issue); + $rate = Functions::flattenSingleValue($rate); + $price = Functions::flattenSingleValue($price); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $settlement = SecurityValidations::validateSettlementDate($settlement); + $maturity = SecurityValidations::validateMaturityDate($maturity); + SecurityValidations::validateSecurityPeriod($settlement, $maturity); + $issue = SecurityValidations::validateIssueDate($issue); + $rate = SecurityValidations::validateRate($rate); + $price = SecurityValidations::validatePrice($price); + $basis = SecurityValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + $daysPerYear = Helpers::daysPerYear(DateTimeExcel\DateParts::year($settlement), $basis); + if (!is_numeric($daysPerYear)) { + return $daysPerYear; + } + $daysBetweenIssueAndSettlement = DateTimeExcel\YearFrac::fraction($issue, $settlement, $basis); + if (!is_numeric($daysBetweenIssueAndSettlement)) { + // return date error + return $daysBetweenIssueAndSettlement; + } + $daysBetweenIssueAndSettlement *= $daysPerYear; + $daysBetweenIssueAndMaturity = DateTimeExcel\YearFrac::fraction($issue, $maturity, $basis); + if (!is_numeric($daysBetweenIssueAndMaturity)) { + // return date error + return $daysBetweenIssueAndMaturity; + } + $daysBetweenIssueAndMaturity *= $daysPerYear; + $daysBetweenSettlementAndMaturity = DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + $daysBetweenSettlementAndMaturity *= $daysPerYear; + + return ((1 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate) - + (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) / + (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) * + ($daysPerYear / $daysBetweenSettlementAndMaturity); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Financial/TreasuryBill.php b/src/PhpSpreadsheet/Calculation/Financial/TreasuryBill.php new file mode 100644 index 00000000..c60af0b0 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Financial/TreasuryBill.php @@ -0,0 +1,147 @@ +getMessage(); + } + + if ($discount <= 0) { + return Functions::NAN(); + } + + $daysBetweenSettlementAndMaturity = $maturity - $settlement; + $daysPerYear = Helpers::daysPerYear( + DateTimeExcel\DateParts::year($maturity), + FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL + ); + + if ($daysBetweenSettlementAndMaturity > $daysPerYear || $daysBetweenSettlementAndMaturity < 0) { + return Functions::NAN(); + } + + return (365 * $discount) / (360 - $discount * $daysBetweenSettlementAndMaturity); + } + + /** + * TBILLPRICE. + * + * Returns the price per $100 face value for a Treasury bill. + * + * @param mixed $settlement The Treasury bill's settlement date. + * The Treasury bill's settlement date is the date after the issue date + * when the Treasury bill is traded to the buyer. + * @param mixed $maturity The Treasury bill's maturity date. + * The maturity date is the date when the Treasury bill expires. + * @param mixed $discount The Treasury bill's discount rate + * + * @return float|string Result, or a string containing an error + */ + public static function price($settlement, $maturity, $discount) + { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $discount = Functions::flattenSingleValue($discount); + + try { + $settlement = FinancialValidations::validateSettlementDate($settlement); + $maturity = FinancialValidations::validateMaturityDate($maturity); + $discount = FinancialValidations::validateFloat($discount); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($discount <= 0) { + return Functions::NAN(); + } + + $daysBetweenSettlementAndMaturity = $maturity - $settlement; + $daysPerYear = Helpers::daysPerYear( + DateTimeExcel\DateParts::year($maturity), + FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL + ); + + if ($daysBetweenSettlementAndMaturity > $daysPerYear || $daysBetweenSettlementAndMaturity < 0) { + return Functions::NAN(); + } + + $price = 100 * (1 - (($discount * $daysBetweenSettlementAndMaturity) / 360)); + if ($price < 0.0) { + return Functions::NAN(); + } + + return $price; + } + + /** + * TBILLYIELD. + * + * Returns the yield for a Treasury bill. + * + * @param mixed $settlement The Treasury bill's settlement date. + * The Treasury bill's settlement date is the date after the issue date when + * the Treasury bill is traded to the buyer. + * @param mixed $maturity The Treasury bill's maturity date. + * The maturity date is the date when the Treasury bill expires. + * @param mixed $price The Treasury bill's price per $100 face value + * + * @return float|string + */ + public static function yield($settlement, $maturity, $price) + { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $price = Functions::flattenSingleValue($price); + + try { + $settlement = FinancialValidations::validateSettlementDate($settlement); + $maturity = FinancialValidations::validateMaturityDate($maturity); + $price = FinancialValidations::validatePrice($price); + } catch (Exception $e) { + return $e->getMessage(); + } + + $daysBetweenSettlementAndMaturity = $maturity - $settlement; + $daysPerYear = Helpers::daysPerYear( + DateTimeExcel\DateParts::year($maturity), + FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL + ); + + if ($daysBetweenSettlementAndMaturity > $daysPerYear || $daysBetweenSettlementAndMaturity < 0) { + return Functions::NAN(); + } + + return ((100 - $price) / $price) * (360 / $daysBetweenSettlementAndMaturity); + } +} diff --git a/src/PhpSpreadsheet/Calculation/FormulaParser.php b/src/PhpSpreadsheet/Calculation/FormulaParser.php index c11af834..cd1402fd 100644 --- a/src/PhpSpreadsheet/Calculation/FormulaParser.php +++ b/src/PhpSpreadsheet/Calculation/FormulaParser.php @@ -90,10 +90,8 @@ class FormulaParser * Get Token. * * @param int $pId Token id - * - * @return string */ - public function getToken($pId = 0) + public function getToken(int $pId = 0): FormulaToken { if (isset($this->tokens[$pId])) { return $this->tokens[$pId]; diff --git a/src/PhpSpreadsheet/Calculation/Functions.php b/src/PhpSpreadsheet/Calculation/Functions.php index 2e8a7ecf..b334c0a1 100644 --- a/src/PhpSpreadsheet/Calculation/Functions.php +++ b/src/PhpSpreadsheet/Calculation/Functions.php @@ -3,6 +3,8 @@ namespace PhpOffice\PhpSpreadsheet\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Cell; +use PhpOffice\PhpSpreadsheet\Shared\Date; +use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Functions { @@ -250,11 +252,13 @@ class Functions $condition = self::flattenSingleValue($condition); if ($condition === '') { - $condition = '=""'; + return '=""'; } - if (!is_string($condition) || !in_array($condition[0], ['>', '<', '='])) { - if (!is_numeric($condition)) { + $condition = self::operandSpecialHandling($condition); + if (is_bool($condition)) { + return '=' . ($condition ? 'TRUE' : 'FALSE'); + } elseif (!is_numeric($condition)) { $condition = Calculation::wrapResult(strtoupper($condition)); } @@ -263,9 +267,10 @@ class Functions preg_match('/(=|<[>=]?|>=?)(.*)/', $condition, $matches); [, $operator, $operand] = $matches; + $operand = self::operandSpecialHandling($operand); if (is_numeric(trim($operand, '"'))) { $operand = trim($operand, '"'); - } elseif (!is_numeric($operand)) { + } elseif (!is_numeric($operand) && $operand !== 'FALSE' && $operand !== 'TRUE') { $operand = str_replace('"', '""', $operand); $operand = Calculation::wrapResult(strtoupper($operand)); } @@ -273,12 +278,33 @@ class Functions return str_replace('""""', '""', $operator . $operand); } + private static function operandSpecialHandling($operand) + { + if (is_numeric($operand) || is_bool($operand)) { + return $operand; + } elseif (strtoupper($operand) === Calculation::getTRUE() || strtoupper($operand) === Calculation::getFALSE()) { + return strtoupper($operand); + } + + // Check for percentage + if (preg_match('/^\-?\d*\.?\d*\s?\%$/', $operand)) { + return ((float) rtrim($operand, '%')) / 100; + } + + // Check for dates + if (($dateValueOperand = Date::stringToExcel($operand)) !== false) { + return $dateValueOperand; + } + + return $operand; + } + /** * ERROR_TYPE. * * @param mixed $value Value to check * - * @return bool + * @return int|string */ public static function errorType($value = '') { @@ -551,7 +577,7 @@ class Functions /** * Convert a multi-dimensional array to a simple 1-dimensional array. * - * @param array $array Array to be flattened + * @param array|mixed $array Array to be flattened * * @return array Flattened array */ @@ -584,7 +610,7 @@ class Functions /** * Convert a multi-dimensional array to a simple 1-dimensional array, but retain an element of indexing. * - * @param array $array Array to be flattened + * @param array|mixed $array Array to be flattened * * @return array Flattened array */ @@ -634,7 +660,7 @@ class Functions * ISFORMULA. * * @param mixed $cellReference The cell to check - * @param Cell $pCell The current cell (containing this formula) + * @param ?Cell $pCell The current cell (containing this formula) * * @return bool|string */ @@ -643,6 +669,8 @@ class Functions if ($pCell === null) { return self::REF(); } + $cellReference = self::expandDefinedName((string) $cellReference, $pCell); + $cellReference = self::trimTrailingRange($cellReference); preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellReference, $matches); @@ -655,4 +683,28 @@ class Functions return $worksheet->getCell($cellReference)->isFormula(); } + + public static function expandDefinedName(string $pCoordinate, Cell $pCell): string + { + $worksheet = $pCell->getWorksheet(); + $spreadsheet = $worksheet->getParent(); + // Uppercase coordinate + $pCoordinatex = strtoupper($pCoordinate); + // Eliminate leading equal sign + $pCoordinatex = Worksheet::pregReplace('/^=/', '', $pCoordinatex); + $defined = $spreadsheet->getDefinedName($pCoordinatex, $worksheet); + if ($defined !== null) { + $worksheet2 = $defined->getWorkSheet(); + if (!$defined->isFormula() && $worksheet2 !== null) { + $pCoordinate = "'" . $worksheet2->getTitle() . "'!" . Worksheet::pregReplace('/^=/', '', $defined->getValue()); + } + } + + return $pCoordinate; + } + + public static function trimTrailingRange(string $pCoordinate): string + { + return Worksheet::pregReplace('/:[\\w\$]+$/', '', $pCoordinate); + } } diff --git a/src/PhpSpreadsheet/Calculation/Internal/MakeMatrix.php b/src/PhpSpreadsheet/Calculation/Internal/MakeMatrix.php new file mode 100644 index 00000000..8b53464f --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Internal/MakeMatrix.php @@ -0,0 +1,11 @@ + 0) && ($returnValue == $argCount); + return Logical\Operations::logicalAnd(...$args); } /** @@ -114,8 +92,13 @@ class Logical * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False - * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds - * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string + * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * + * @Deprecated 1.17.0 + * + * @see Logical\Operations::logicalOr() + * Use the logicalOr() method in the Logical\Operations class instead * * @param mixed $args Data values * @@ -123,29 +106,15 @@ class Logical */ public static function logicalOr(...$args) { - $args = Functions::flattenArray($args); - - if (count($args) == 0) { - return Functions::VALUE(); - } - - $args = array_filter($args, function ($value) { - return $value !== null || (is_string($value) && trim($value) == ''); - }); - - $returnValue = self::countTrueValues($args); - if (is_string($returnValue)) { - return $returnValue; - } - - return $returnValue > 0; + return Logical\Operations::logicalOr(...$args); } /** * LOGICAL_XOR. * * Returns the Exclusive Or logical operation for one or more supplied conditions. - * i.e. the Xor function returns TRUE if an odd number of the supplied conditions evaluate to TRUE, and FALSE otherwise. + * i.e. the Xor function returns TRUE if an odd number of the supplied conditions evaluate to TRUE, + * and FALSE otherwise. * * Excel Function: * =XOR(logical1[,logical2[, ...]]) @@ -155,8 +124,13 @@ class Logical * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False - * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds - * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string + * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * + * @Deprecated 1.17.0 + * + * @see Logical\Operations::logicalXor() + * Use the logicalXor() method in the Logical\Operations class instead * * @param mixed $args Data values * @@ -164,22 +138,7 @@ class Logical */ public static function logicalXor(...$args) { - $args = Functions::flattenArray($args); - - if (count($args) == 0) { - return Functions::VALUE(); - } - - $args = array_filter($args, function ($value) { - return $value !== null || (is_string($value) && trim($value) == ''); - }); - - $returnValue = self::countTrueValues($args); - if (is_string($returnValue)) { - return $returnValue; - } - - return $returnValue % 2 == 1; + return Logical\Operations::logicalXor(...$args); } /** @@ -194,8 +153,13 @@ class Logical * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False - * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds - * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string + * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * + * @Deprecated 1.17.0 + * + * @see Logical\Operations::NOT() + * Use the NOT() method in the Logical\Operations class instead * * @param mixed $logical A value or expression that can be evaluated to TRUE or FALSE * @@ -203,20 +167,7 @@ class Logical */ public static function NOT($logical = false) { - $logical = Functions::flattenSingleValue($logical); - - if (is_string($logical)) { - $logical = strtoupper($logical); - if (($logical == 'TRUE') || ($logical == Calculation::getTRUE())) { - return false; - } elseif (($logical == 'FALSE') || ($logical == Calculation::getFALSE())) { - return true; - } - - return Functions::VALUE(); - } - - return !$logical; + return Logical\Operations::NOT($logical); } /** @@ -232,18 +183,23 @@ class Logical * the expression evaluates to TRUE. Otherwise, the expression evaluates to FALSE. * This argument can use any comparison calculation operator. * ReturnIfTrue is the value that is returned if condition evaluates to TRUE. - * For example, if this argument is the text string "Within budget" and the condition argument evaluates to TRUE, - * then the IF function returns the text "Within budget" - * If condition is TRUE and ReturnIfTrue is blank, this argument returns 0 (zero). To display the word TRUE, use - * the logical value TRUE for this argument. + * For example, if this argument is the text string "Within budget" and the condition argument + * evaluates to TRUE, then the IF function returns the text "Within budget" + * If condition is TRUE and ReturnIfTrue is blank, this argument returns 0 (zero). + * To display the word TRUE, use the logical value TRUE for this argument. * ReturnIfTrue can be another formula. * ReturnIfFalse is the value that is returned if condition evaluates to FALSE. - * For example, if this argument is the text string "Over budget" and the condition argument evaluates to FALSE, - * then the IF function returns the text "Over budget". + * For example, if this argument is the text string "Over budget" and the condition argument + * evaluates to FALSE, then the IF function returns the text "Over budget". * If condition is FALSE and ReturnIfFalse is omitted, then the logical value FALSE is returned. * If condition is FALSE and ReturnIfFalse is blank, then the value 0 (zero) is returned. * ReturnIfFalse can be another formula. * + * @Deprecated 1.17.0 + * + * @see Logical\Conditional::statementIf() + * Use the statementIf() method in the Logical\Conditional class instead + * * @param mixed $condition Condition to evaluate * @param mixed $returnIfTrue Value to return when condition is true * @param mixed $returnIfFalse Optional value to return when condition is false @@ -252,15 +208,7 @@ class Logical */ public static function statementIf($condition = true, $returnIfTrue = 0, $returnIfFalse = false) { - if (Functions::isError($condition)) { - return $condition; - } - - $condition = ($condition === null) ? true : (bool) Functions::flattenSingleValue($condition); - $returnIfTrue = ($returnIfTrue === null) ? 0 : Functions::flattenSingleValue($returnIfTrue); - $returnIfFalse = ($returnIfFalse === null) ? false : Functions::flattenSingleValue($returnIfFalse); - - return ($condition) ? $returnIfTrue : $returnIfFalse; + return Logical\Conditional::statementIf($condition, $returnIfTrue, $returnIfFalse); } /** @@ -274,11 +222,19 @@ class Logical * Expression * The expression to compare to a list of values. * value1, value2, ... value_n - * A list of values that are compared to expression. The SWITCH function is looking for the first value that matches the expression. + * A list of values that are compared to expression. + * The SWITCH function is looking for the first value that matches the expression. * result1, result2, ... result_n - * A list of results. The SWITCH function returns the corresponding result when a value matches expression. + * A list of results. The SWITCH function returns the corresponding result when a value + * matches expression. * default - * Optional. It is the default to return if expression does not match any of the values (value1, value2, ... value_n). + * Optional. It is the default to return if expression does not match any of the values + * (value1, value2, ... value_n). + * + * @Deprecated 1.17.0 + * + * @see Logical\Conditional::statementSwitch() + * Use the statementSwitch() method in the Logical\Conditional class instead * * @param mixed $arguments Statement arguments * @@ -286,33 +242,7 @@ class Logical */ public static function statementSwitch(...$arguments) { - $result = Functions::VALUE(); - - if (count($arguments) > 0) { - $targetValue = Functions::flattenSingleValue($arguments[0]); - $argc = count($arguments) - 1; - $switchCount = floor($argc / 2); - $switchSatisfied = false; - $hasDefaultClause = $argc % 2 !== 0; - $defaultClause = $argc % 2 === 0 ? null : $arguments[count($arguments) - 1]; - - if ($switchCount) { - for ($index = 0; $index < $switchCount; ++$index) { - if ($targetValue == $arguments[$index * 2 + 1]) { - $result = $arguments[$index * 2 + 2]; - $switchSatisfied = true; - - break; - } - } - } - - if (!$switchSatisfied) { - $result = $hasDefaultClause ? $defaultClause : Functions::NA(); - } - } - - return $result; + return Logical\Conditional::statementSwitch(...$arguments); } /** @@ -321,6 +251,11 @@ class Logical * Excel Function: * =IFERROR(testValue,errorpart) * + * @Deprecated 1.17.0 + * + * @see Logical\Conditional::IFERROR() + * Use the IFERROR() method in the Logical\Conditional class instead + * * @param mixed $testValue Value to check, is also the value returned when no error * @param mixed $errorpart Value to return when testValue is an error condition * @@ -328,10 +263,7 @@ class Logical */ public static function IFERROR($testValue = '', $errorpart = '') { - $testValue = ($testValue === null) ? '' : Functions::flattenSingleValue($testValue); - $errorpart = ($errorpart === null) ? '' : Functions::flattenSingleValue($errorpart); - - return self::statementIf(Functions::isError($testValue), $errorpart, $testValue); + return Logical\Conditional::IFERROR($testValue, $errorpart); } /** @@ -340,6 +272,11 @@ class Logical * Excel Function: * =IFNA(testValue,napart) * + * @Deprecated 1.17.0 + * + * @see Logical\Conditional::IFNA() + * Use the IFNA() method in the Logical\Conditional class instead + * * @param mixed $testValue Value to check, is also the value returned when not an NA * @param mixed $napart Value to return when testValue is an NA condition * @@ -347,10 +284,7 @@ class Logical */ public static function IFNA($testValue = '', $napart = '') { - $testValue = ($testValue === null) ? '' : Functions::flattenSingleValue($testValue); - $napart = ($napart === null) ? '' : Functions::flattenSingleValue($napart); - - return self::statementIf(Functions::isNa($testValue), $napart, $testValue); + return Logical\Conditional::IFNA($testValue, $napart); } /** @@ -364,27 +298,17 @@ class Logical * returnIfTrue1 ... returnIfTrue_n * Value returned if corresponding testValue (nth) was true * + * @Deprecated 1.17.0 + * + * @see Logical\Conditional::IFS() + * Use the IFS() method in the Logical\Conditional class instead + * * @param mixed ...$arguments Statement arguments * * @return mixed|string The value of returnIfTrue_n, if testValue_n was true. #N/A if none of testValues was true */ public static function IFS(...$arguments) { - if (count($arguments) % 2 != 0) { - return Functions::NA(); - } - // We use instance of Exception as a falseValue in order to prevent string collision with value in cell - $falseValueException = new Exception(); - for ($i = 0; $i < count($arguments); $i += 2) { - $testValue = ($arguments[$i] === null) ? '' : Functions::flattenSingleValue($arguments[$i]); - $returnIfTrue = ($arguments[$i + 1] === null) ? '' : Functions::flattenSingleValue($arguments[$i + 1]); - $result = self::statementIf($testValue, $returnIfTrue, $falseValueException); - - if ($result !== $falseValueException) { - return $result; - } - } - - return Functions::NA(); + return Logical\Conditional::IFS(...$arguments); } } diff --git a/src/PhpSpreadsheet/Calculation/Logical/Boolean.php b/src/PhpSpreadsheet/Calculation/Logical/Boolean.php new file mode 100644 index 00000000..8f1e9354 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Logical/Boolean.php @@ -0,0 +1,36 @@ + 0) { + $targetValue = Functions::flattenSingleValue($arguments[0]); + $argc = count($arguments) - 1; + $switchCount = floor($argc / 2); + $hasDefaultClause = $argc % 2 !== 0; + $defaultClause = $argc % 2 === 0 ? null : $arguments[$argc]; + + $switchSatisfied = false; + if ($switchCount > 0) { + for ($index = 0; $index < $switchCount; ++$index) { + if ($targetValue == $arguments[$index * 2 + 1]) { + $result = $arguments[$index * 2 + 2]; + $switchSatisfied = true; + + break; + } + } + } + + if ($switchSatisfied !== true) { + $result = $hasDefaultClause ? $defaultClause : Functions::NA(); + } + } + + return $result; + } + + /** + * IFERROR. + * + * Excel Function: + * =IFERROR(testValue,errorpart) + * + * @param mixed $testValue Value to check, is also the value returned when no error + * @param mixed $errorpart Value to return when testValue is an error condition + * + * @return mixed The value of errorpart or testValue determined by error condition + */ + public static function IFERROR($testValue = '', $errorpart = '') + { + $testValue = ($testValue === null) ? '' : Functions::flattenSingleValue($testValue); + $errorpart = ($errorpart === null) ? '' : Functions::flattenSingleValue($errorpart); + + return self::statementIf(Functions::isError($testValue), $errorpart, $testValue); + } + + /** + * IFNA. + * + * Excel Function: + * =IFNA(testValue,napart) + * + * @param mixed $testValue Value to check, is also the value returned when not an NA + * @param mixed $napart Value to return when testValue is an NA condition + * + * @return mixed The value of errorpart or testValue determined by error condition + */ + public static function IFNA($testValue = '', $napart = '') + { + $testValue = ($testValue === null) ? '' : Functions::flattenSingleValue($testValue); + $napart = ($napart === null) ? '' : Functions::flattenSingleValue($napart); + + return self::statementIf(Functions::isNa($testValue), $napart, $testValue); + } + + /** + * IFS. + * + * Excel Function: + * =IFS(testValue1;returnIfTrue1;testValue2;returnIfTrue2;...;testValue_n;returnIfTrue_n) + * + * testValue1 ... testValue_n + * Conditions to Evaluate + * returnIfTrue1 ... returnIfTrue_n + * Value returned if corresponding testValue (nth) was true + * + * @param mixed ...$arguments Statement arguments + * + * @return mixed|string The value of returnIfTrue_n, if testValue_n was true. #N/A if none of testValues was true + */ + public static function IFS(...$arguments) + { + $argumentCount = count($arguments); + + if ($argumentCount % 2 != 0) { + return Functions::NA(); + } + // We use instance of Exception as a falseValue in order to prevent string collision with value in cell + $falseValueException = new Exception(); + for ($i = 0; $i < $argumentCount; $i += 2) { + $testValue = ($arguments[$i] === null) ? '' : Functions::flattenSingleValue($arguments[$i]); + $returnIfTrue = ($arguments[$i + 1] === null) ? '' : Functions::flattenSingleValue($arguments[$i + 1]); + $result = self::statementIf($testValue, $returnIfTrue, $falseValueException); + + if ($result !== $falseValueException) { + return $result; + } + } + + return Functions::NA(); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Logical/Operations.php b/src/PhpSpreadsheet/Calculation/Logical/Operations.php new file mode 100644 index 00000000..6bfb6a54 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Logical/Operations.php @@ -0,0 +1,198 @@ + 0) && ($returnValue == $argCount); + } + + /** + * LOGICAL_OR. + * + * Returns boolean TRUE if any argument is TRUE; returns FALSE if all arguments are FALSE. + * + * Excel Function: + * =OR(logical1[,logical2[, ...]]) + * + * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays + * or references that contain logical values. + * + * Boolean arguments are treated as True or False as appropriate + * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False + * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string + * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * + * @param mixed $args Data values + * + * @return bool|string the logical OR of the arguments + */ + public static function logicalOr(...$args) + { + $args = Functions::flattenArray($args); + + if (count($args) == 0) { + return Functions::VALUE(); + } + + $args = array_filter($args, function ($value) { + return $value !== null || (is_string($value) && trim($value) == ''); + }); + + $returnValue = self::countTrueValues($args); + if (is_string($returnValue)) { + return $returnValue; + } + + return $returnValue > 0; + } + + /** + * LOGICAL_XOR. + * + * Returns the Exclusive Or logical operation for one or more supplied conditions. + * i.e. the Xor function returns TRUE if an odd number of the supplied conditions evaluate to TRUE, + * and FALSE otherwise. + * + * Excel Function: + * =XOR(logical1[,logical2[, ...]]) + * + * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays + * or references that contain logical values. + * + * Boolean arguments are treated as True or False as appropriate + * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False + * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string + * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * + * @param mixed $args Data values + * + * @return bool|string the logical XOR of the arguments + */ + public static function logicalXor(...$args) + { + $args = Functions::flattenArray($args); + + if (count($args) == 0) { + return Functions::VALUE(); + } + + $args = array_filter($args, function ($value) { + return $value !== null || (is_string($value) && trim($value) == ''); + }); + + $returnValue = self::countTrueValues($args); + if (is_string($returnValue)) { + return $returnValue; + } + + return $returnValue % 2 == 1; + } + + /** + * NOT. + * + * Returns the boolean inverse of the argument. + * + * Excel Function: + * =NOT(logical) + * + * The argument must evaluate to a logical value such as TRUE or FALSE + * + * Boolean arguments are treated as True or False as appropriate + * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False + * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string + * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * + * @param mixed $logical A value or expression that can be evaluated to TRUE or FALSE + * + * @return bool|string the boolean inverse of the argument + */ + public static function NOT($logical = false) + { + $logical = Functions::flattenSingleValue($logical); + + if (is_string($logical)) { + $logical = mb_strtoupper($logical, 'UTF-8'); + if (($logical == 'TRUE') || ($logical == Calculation::getTRUE())) { + return false; + } elseif (($logical == 'FALSE') || ($logical == Calculation::getFALSE())) { + return true; + } + + return Functions::VALUE(); + } + + return !$logical; + } + + /** + * @return int|string + */ + private static function countTrueValues(array $args) + { + $trueValueCount = 0; + + foreach ($args as $arg) { + // Is it a boolean value? + if (is_bool($arg)) { + $trueValueCount += $arg; + } elseif ((is_numeric($arg)) && (!is_string($arg))) { + $trueValueCount += ((int) $arg != 0); + } elseif (is_string($arg)) { + $arg = mb_strtoupper($arg, 'UTF-8'); + if (($arg == 'TRUE') || ($arg == Calculation::getTRUE())) { + $arg = true; + } elseif (($arg == 'FALSE') || ($arg == Calculation::getFALSE())) { + $arg = false; + } else { + return Functions::VALUE(); + } + $trueValueCount += ($arg != 0); + } + } + + return $trueValueCount; + } +} diff --git a/src/PhpSpreadsheet/Calculation/LookupRef.php b/src/PhpSpreadsheet/Calculation/LookupRef.php index 45aa9239..c213396d 100644 --- a/src/PhpSpreadsheet/Calculation/LookupRef.php +++ b/src/PhpSpreadsheet/Calculation/LookupRef.php @@ -2,11 +2,20 @@ namespace PhpOffice\PhpSpreadsheet\Calculation; +use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Address; +use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\HLookup; +use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Indirect; +use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Lookup; +use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Matrix; +use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Offset; +use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\RowColumnInformation; +use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\VLookup; use PhpOffice\PhpSpreadsheet\Cell\Cell; -use PhpOffice\PhpSpreadsheet\Cell\Coordinate; -use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +/** + * @deprecated 1.18.0 + */ class LookupRef { /** @@ -17,15 +26,20 @@ class LookupRef * Excel Function: * =ADDRESS(row, column, [relativity], [referenceStyle], [sheetText]) * + * @Deprecated 1.18.0 + * + * @see LookupRef\Address::cell() + * Use the cell() method in the LookupRef\Address class instead + * * @param mixed $row Row number to use in the cell reference * @param mixed $column Column number to use in the cell reference * @param int $relativity Flag indicating the type of reference to return * 1 or omitted Absolute - * 2 Absolute row; relative column - * 3 Relative row; absolute column - * 4 Relative + * 2 Absolute row; relative column + * 3 Relative row; absolute column + * 4 Relative * @param bool $referenceStyle A logical value that specifies the A1 or R1C1 reference style. - * TRUE or omitted CELL_ADDRESS returns an A1-style reference + * TRUE or omitted CELL_ADDRESS returns an A1-style reference * FALSE CELL_ADDRESS returns an R1C1-style reference * @param string $sheetText Optional Name of worksheet to use * @@ -33,87 +47,34 @@ class LookupRef */ public static function cellAddress($row, $column, $relativity = 1, $referenceStyle = true, $sheetText = '') { - $row = Functions::flattenSingleValue($row); - $column = Functions::flattenSingleValue($column); - $relativity = Functions::flattenSingleValue($relativity); - $sheetText = Functions::flattenSingleValue($sheetText); - - if (($row < 1) || ($column < 1)) { - return Functions::VALUE(); - } - - if ($sheetText > '') { - if (strpos($sheetText, ' ') !== false) { - $sheetText = "'" . $sheetText . "'"; - } - $sheetText .= '!'; - } - if ((!is_bool($referenceStyle)) || $referenceStyle) { - $rowRelative = $columnRelative = '$'; - $column = Coordinate::stringFromColumnIndex($column); - if (($relativity == 2) || ($relativity == 4)) { - $columnRelative = ''; - } - if (($relativity == 3) || ($relativity == 4)) { - $rowRelative = ''; - } - - return $sheetText . $columnRelative . $column . $rowRelative . $row; - } - if (($relativity == 2) || ($relativity == 4)) { - $column = '[' . $column . ']'; - } - if (($relativity == 3) || ($relativity == 4)) { - $row = '[' . $row . ']'; - } - - return $sheetText . 'R' . $row . 'C' . $column; + return Address::cell($row, $column, $relativity, $referenceStyle, $sheetText); } /** * COLUMN. * * Returns the column number of the given cell reference - * If the cell reference is a range of cells, COLUMN returns the column numbers of each column in the reference as a horizontal array. - * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the - * reference of the cell in which the COLUMN function appears; otherwise this function returns 0. + * If the cell reference is a range of cells, COLUMN returns the column numbers of each column + * in the reference as a horizontal array. + * If cell reference is omitted, and the function is being called through the calculation engine, + * then it is assumed to be the reference of the cell in which the COLUMN function appears; + * otherwise this function returns 1. * * Excel Function: * =COLUMN([cellAddress]) * + * @Deprecated 1.18.0 + * + * @see LookupRef\RowColumnInformation::COLUMN() + * Use the COLUMN() method in the LookupRef\RowColumnInformation class instead + * * @param null|array|string $cellAddress A reference to a range of cells for which you want the column numbers * - * @return int|int[] + * @return int|int[]|string */ - public static function COLUMN($cellAddress = null) + public static function COLUMN($cellAddress = null, ?Cell $cell = null) { - if ($cellAddress === null || trim($cellAddress) === '') { - return 0; - } - - if (is_array($cellAddress)) { - foreach ($cellAddress as $columnKey => $value) { - $columnKey = preg_replace('/[^a-z]/i', '', $columnKey); - - return (int) Coordinate::columnIndexFromString($columnKey); - } - } else { - [$sheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); - if (strpos($cellAddress, ':') !== false) { - [$startAddress, $endAddress] = explode(':', $cellAddress); - $startAddress = preg_replace('/[^a-z]/i', '', $startAddress); - $endAddress = preg_replace('/[^a-z]/i', '', $endAddress); - $returnValue = []; - do { - $returnValue[] = (int) Coordinate::columnIndexFromString($startAddress); - } while ($startAddress++ != $endAddress); - - return $returnValue; - } - $cellAddress = preg_replace('/[^a-z]/i', '', $cellAddress); - - return (int) Coordinate::columnIndexFromString($cellAddress); - } + return RowColumnInformation::COLUMN($cellAddress, $cell); } /** @@ -124,73 +85,46 @@ class LookupRef * Excel Function: * =COLUMNS(cellAddress) * - * @param null|array|string $cellAddress An array or array formula, or a reference to a range of cells for which you want the number of columns + * @Deprecated 1.18.0 + * + * @see LookupRef\RowColumnInformation::COLUMNS() + * Use the COLUMNS() method in the LookupRef\RowColumnInformation class instead + * + * @param null|array|string $cellAddress An array or array formula, or a reference to a range of cells + * for which you want the number of columns * * @return int|string The number of columns in cellAddress, or a string if arguments are invalid */ public static function COLUMNS($cellAddress = null) { - if ($cellAddress === null || $cellAddress === '') { - return 1; - } elseif (!is_array($cellAddress)) { - return Functions::VALUE(); - } - - reset($cellAddress); - $isMatrix = (is_numeric(key($cellAddress))); - [$columns, $rows] = Calculation::getMatrixDimensions($cellAddress); - - if ($isMatrix) { - return $rows; - } - - return $columns; + return RowColumnInformation::COLUMNS($cellAddress); } /** * ROW. * * Returns the row number of the given cell reference - * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference as a vertical array. - * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the - * reference of the cell in which the ROW function appears; otherwise this function returns 0. + * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference + * as a vertical array. + * If cell reference is omitted, and the function is being called through the calculation engine, + * then it is assumed to be the reference of the cell in which the ROW function appears; + * otherwise this function returns 1. * * Excel Function: * =ROW([cellAddress]) * + * @Deprecated 1.18.0 + * + * @see LookupRef\RowColumnInformation::ROW() + * Use the ROW() method in the LookupRef\RowColumnInformation class instead + * * @param null|array|string $cellAddress A reference to a range of cells for which you want the row numbers * * @return int|mixed[]|string */ - public static function ROW($cellAddress = null) + public static function ROW($cellAddress = null, ?Cell $cell = null) { - if ($cellAddress === null || trim($cellAddress) === '') { - return 0; - } - - if (is_array($cellAddress)) { - foreach ($cellAddress as $columnKey => $rowValue) { - foreach ($rowValue as $rowKey => $cellValue) { - return (int) preg_replace('/\D/', '', $rowKey); - } - } - } else { - [$sheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); - if (strpos($cellAddress, ':') !== false) { - [$startAddress, $endAddress] = explode(':', $cellAddress); - $startAddress = preg_replace('/\D/', '', $startAddress); - $endAddress = preg_replace('/\D/', '', $endAddress); - $returnValue = []; - do { - $returnValue[][] = (int) $startAddress; - } while ($startAddress++ != $endAddress); - - return $returnValue; - } - [$cellAddress] = explode(':', $cellAddress); - - return (int) preg_replace('/\D/', '', $cellAddress); - } + return RowColumnInformation::ROW($cellAddress, $cell); } /** @@ -201,27 +135,19 @@ class LookupRef * Excel Function: * =ROWS(cellAddress) * - * @param null|array|string $cellAddress An array or array formula, or a reference to a range of cells for which you want the number of rows + * @Deprecated 1.18.0 + * + * @see LookupRef\RowColumnInformation::ROWS() + * Use the ROWS() method in the LookupRef\RowColumnInformation class instead + * + * @param null|array|string $cellAddress An array or array formula, or a reference to a range of cells + * for which you want the number of rows * * @return int|string The number of rows in cellAddress, or a string if arguments are invalid */ public static function ROWS($cellAddress = null) { - if ($cellAddress === null || $cellAddress === '') { - return 1; - } elseif (!is_array($cellAddress)) { - return Functions::VALUE(); - } - - reset($cellAddress); - $isMatrix = (is_numeric(key($cellAddress))); - [$columns, $rows] = Calculation::getMatrixDimensions($cellAddress); - - if ($isMatrix) { - return $columns; - } - - return $rows; + return RowColumnInformation::ROWS($cellAddress); } /** @@ -230,29 +156,20 @@ class LookupRef * Excel Function: * =HYPERLINK(linkURL,displayName) * - * @param string $linkURL Value to check, is also the value returned when no error - * @param string $displayName Value to return when testValue is an error condition + * @Deprecated 1.18.0 + * + * @see LookupRef\Hyperlink::set() + * Use the set() method in the LookupRef\Hyperlink class instead + * + * @param mixed $linkURL Expect string. Value to check, is also the value returned when no error + * @param mixed $displayName Expect string. Value to return when testValue is an error condition * @param Cell $pCell The cell to set the hyperlink in * - * @return mixed The value of $displayName (or $linkURL if $displayName was blank) + * @return string The value of $displayName (or $linkURL if $displayName was blank) */ public static function HYPERLINK($linkURL = '', $displayName = null, ?Cell $pCell = null) { - $linkURL = ($linkURL === null) ? '' : Functions::flattenSingleValue($linkURL); - $displayName = ($displayName === null) ? '' : Functions::flattenSingleValue($displayName); - - if ((!is_object($pCell)) || (trim($linkURL) == '')) { - return Functions::REF(); - } - - if ((is_object($displayName)) || trim($displayName) == '') { - $displayName = $linkURL; - } - - $pCell->getHyperlink()->setUrl($linkURL); - $pCell->getHyperlink()->setTooltip($displayName); - - return $displayName; + return LookupRef\Hyperlink::set($linkURL, $displayName, $pCell); } /** @@ -264,56 +181,21 @@ class LookupRef * Excel Function: * =INDIRECT(cellAddress) * + * @Deprecated 1.18.0 + * + * @see LookupRef\Indirect::INDIRECT() + * Use the INDIRECT() method in the LookupRef\Indirect class instead + * * NOTE - INDIRECT() does not yet support the optional a1 parameter introduced in Excel 2010 * - * @param null|array|string $cellAddress $cellAddress The cell address of the current cell (containing this formula) + * @param array|string $cellAddress $cellAddress The cell address of the current cell (containing this formula) * @param Cell $pCell The current cell (containing this formula) * - * @return mixed The cells referenced by cellAddress - * - * @TODO Support for the optional a1 parameter introduced in Excel 2010 + * @return array|string An array containing a cell or range of cells, or a string on error */ - public static function INDIRECT($cellAddress = null, ?Cell $pCell = null) + public static function INDIRECT($cellAddress, Cell $pCell) { - $cellAddress = Functions::flattenSingleValue($cellAddress); - if ($cellAddress === null || $cellAddress === '') { - return Functions::REF(); - } - - $cellAddress1 = $cellAddress; - $cellAddress2 = null; - if (strpos($cellAddress, ':') !== false) { - [$cellAddress1, $cellAddress2] = explode(':', $cellAddress); - } - - if ( - (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellAddress1, $matches)) || - (($cellAddress2 !== null) && (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellAddress2, $matches))) - ) { - if (!preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/i', $cellAddress1, $matches)) { - return Functions::REF(); - } - - if (strpos($cellAddress, '!') !== false) { - [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); - $sheetName = trim($sheetName, "'"); - $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName); - } else { - $pSheet = $pCell->getWorksheet(); - } - - return Calculation::getInstance()->extractNamedRange($cellAddress, $pSheet, false); - } - - if (strpos($cellAddress, '!') !== false) { - [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); - $sheetName = trim($sheetName, "'"); - $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName); - } else { - $pSheet = $pCell->getWorksheet(); - } - - return Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false); + return Indirect::INDIRECT($cellAddress, true, $pCell); } /** @@ -326,87 +208,34 @@ class LookupRef * Excel Function: * =OFFSET(cellAddress, rows, cols, [height], [width]) * - * @param null|string $cellAddress The reference from which you want to base the offset. Reference must refer to a cell or - * range of adjacent cells; otherwise, OFFSET returns the #VALUE! error value. - * @param mixed $rows The number of rows, up or down, that you want the upper-left cell to refer to. - * Using 5 as the rows argument specifies that the upper-left cell in the reference is - * five rows below reference. Rows can be positive (which means below the starting reference) - * or negative (which means above the starting reference). - * @param mixed $columns The number of columns, to the left or right, that you want the upper-left cell of the result - * to refer to. Using 5 as the cols argument specifies that the upper-left cell in the - * reference is five columns to the right of reference. Cols can be positive (which means - * to the right of the starting reference) or negative (which means to the left of the - * starting reference). - * @param mixed $height The height, in number of rows, that you want the returned reference to be. Height must be a positive number. - * @param mixed $width The width, in number of columns, that you want the returned reference to be. Width must be a positive number. + * @Deprecated 1.18.0 * - * @return string A reference to a cell or range of cells + * @see LookupRef\Offset::OFFSET() + * Use the OFFSET() method in the LookupRef\Offset class instead + * + * @param null|string $cellAddress The reference from which you want to base the offset. + * Reference must refer to a cell or range of adjacent cells; + * otherwise, OFFSET returns the #VALUE! error value. + * @param mixed $rows The number of rows, up or down, that you want the upper-left cell to refer to. + * Using 5 as the rows argument specifies that the upper-left cell in the + * reference is five rows below reference. Rows can be positive (which means + * below the starting reference) or negative (which means above the starting + * reference). + * @param mixed $columns The number of columns, to the left or right, that you want the upper-left cell + * of the result to refer to. Using 5 as the cols argument specifies that the + * upper-left cell in the reference is five columns to the right of reference. + * Cols can be positive (which means to the right of the starting reference) + * or negative (which means to the left of the starting reference). + * @param mixed $height The height, in number of rows, that you want the returned reference to be. + * Height must be a positive number. + * @param mixed $width The width, in number of columns, that you want the returned reference to be. + * Width must be a positive number. + * + * @return array|string An array containing a cell or range of cells, or a string on error */ public static function OFFSET($cellAddress = null, $rows = 0, $columns = 0, $height = null, $width = null, ?Cell $pCell = null) { - $rows = Functions::flattenSingleValue($rows); - $columns = Functions::flattenSingleValue($columns); - $height = Functions::flattenSingleValue($height); - $width = Functions::flattenSingleValue($width); - if ($cellAddress === null) { - return 0; - } - - if (!is_object($pCell)) { - return Functions::REF(); - } - - $sheetName = null; - if (strpos($cellAddress, '!')) { - [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); - $sheetName = trim($sheetName, "'"); - } - if (strpos($cellAddress, ':')) { - [$startCell, $endCell] = explode(':', $cellAddress); - } else { - $startCell = $endCell = $cellAddress; - } - [$startCellColumn, $startCellRow] = Coordinate::coordinateFromString($startCell); - [$endCellColumn, $endCellRow] = Coordinate::coordinateFromString($endCell); - - $startCellRow += $rows; - $startCellColumn = Coordinate::columnIndexFromString($startCellColumn) - 1; - $startCellColumn += $columns; - - if (($startCellRow <= 0) || ($startCellColumn < 0)) { - return Functions::REF(); - } - $endCellColumn = Coordinate::columnIndexFromString($endCellColumn) - 1; - if (($width != null) && (!is_object($width))) { - $endCellColumn = $startCellColumn + $width - 1; - } else { - $endCellColumn += $columns; - } - $startCellColumn = Coordinate::stringFromColumnIndex($startCellColumn + 1); - - if (($height != null) && (!is_object($height))) { - $endCellRow = $startCellRow + $height - 1; - } else { - $endCellRow += $rows; - } - - if (($endCellRow <= 0) || ($endCellColumn < 0)) { - return Functions::REF(); - } - $endCellColumn = Coordinate::stringFromColumnIndex($endCellColumn + 1); - - $cellAddress = $startCellColumn . $startCellRow; - if (($startCellColumn != $endCellColumn) || ($startCellRow != $endCellRow)) { - $cellAddress .= ':' . $endCellColumn . $endCellRow; - } - - if ($sheetName !== null) { - $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName); - } else { - $pSheet = $pCell->getWorksheet(); - } - - return Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false); + return Offset::OFFSET($cellAddress, $rows, $columns, $height, $width, $pCell); } /** @@ -418,31 +247,16 @@ class LookupRef * Excel Function: * =CHOOSE(index_num, value1, [value2], ...) * + * @Deprecated 1.18.0 + * + * @see LookupRef\Selection::choose() + * Use the choose() method in the LookupRef\Selection class instead + * * @return mixed The selected value */ public static function CHOOSE(...$chooseArgs) { - $chosenEntry = Functions::flattenArray(array_shift($chooseArgs)); - $entryCount = count($chooseArgs) - 1; - - if (is_array($chosenEntry)) { - $chosenEntry = array_shift($chosenEntry); - } - if ((is_numeric($chosenEntry)) && (!is_bool($chosenEntry))) { - --$chosenEntry; - } else { - return Functions::VALUE(); - } - $chosenEntry = floor($chosenEntry); - if (($chosenEntry < 0) || ($chosenEntry > $entryCount)) { - return Functions::VALUE(); - } - - if (is_array($chooseArgs[$chosenEntry])) { - return Functions::flattenArray($chooseArgs[$chosenEntry]); - } - - return $chooseArgs[$chosenEntry]; + return LookupRef\Selection::choose(...$chooseArgs); } /** @@ -453,6 +267,11 @@ class LookupRef * Excel Function: * =MATCH(lookup_value, lookup_array, [match_type]) * + * @Deprecated 1.18.0 + * + * @see LookupRef\ExcelMatch::MATCH() + * Use the MATCH() method in the LookupRef\ExcelMatch class instead + * * @param mixed $lookupValue The value that you want to match in lookup_array * @param mixed $lookupArray The range of cells being searched * @param mixed $matchType The number -1, 0, or 1. -1 means above, 0 means exact match, 1 means below. @@ -462,145 +281,7 @@ class LookupRef */ public static function MATCH($lookupValue, $lookupArray, $matchType = 1) { - $lookupArray = Functions::flattenArray($lookupArray); - $lookupValue = Functions::flattenSingleValue($lookupValue); - $matchType = ($matchType === null) ? 1 : (int) Functions::flattenSingleValue($matchType); - - // MATCH is not case sensitive, so we convert lookup value to be lower cased in case it's string type. - if (is_string($lookupValue)) { - $lookupValue = StringHelper::strToLower($lookupValue); - } - - // Lookup_value type has to be number, text, or logical values - if ((!is_numeric($lookupValue)) && (!is_string($lookupValue)) && (!is_bool($lookupValue))) { - return Functions::NA(); - } - - // Match_type is 0, 1 or -1 - if (($matchType !== 0) && ($matchType !== -1) && ($matchType !== 1)) { - return Functions::NA(); - } - - // Lookup_array should not be empty - $lookupArraySize = count($lookupArray); - if ($lookupArraySize <= 0) { - return Functions::NA(); - } - - if ($matchType == 1) { - // If match_type is 1 the list has to be processed from last to first - - $lookupArray = array_reverse($lookupArray); - $keySet = array_reverse(array_keys($lookupArray)); - } - - // Lookup_array should contain only number, text, or logical values, or empty (null) cells - foreach ($lookupArray as $i => $lookupArrayValue) { - // check the type of the value - if ( - (!is_numeric($lookupArrayValue)) && (!is_string($lookupArrayValue)) && - (!is_bool($lookupArrayValue)) && ($lookupArrayValue !== null) - ) { - return Functions::NA(); - } - // Convert strings to lowercase for case-insensitive testing - if (is_string($lookupArrayValue)) { - $lookupArray[$i] = StringHelper::strToLower($lookupArrayValue); - } - if (($lookupArrayValue === null) && (($matchType == 1) || ($matchType == -1))) { - unset($lookupArray[$i]); - } - } - - // ** - // find the match - // ** - - if ($matchType === 0 || $matchType === 1) { - foreach ($lookupArray as $i => $lookupArrayValue) { - $typeMatch = ((gettype($lookupValue) === gettype($lookupArrayValue)) || (is_numeric($lookupValue) && is_numeric($lookupArrayValue))); - $exactTypeMatch = $typeMatch && $lookupArrayValue === $lookupValue; - $nonOnlyNumericExactMatch = !$typeMatch && $lookupArrayValue === $lookupValue; - $exactMatch = $exactTypeMatch || $nonOnlyNumericExactMatch; - - if ($matchType === 0) { - if ($typeMatch && is_string($lookupValue) && (bool) preg_match('/([\?\*])/', $lookupValue)) { - $splitString = $lookupValue; - $chars = array_map(function ($i) use ($splitString) { - return mb_substr($splitString, $i, 1); - }, range(0, mb_strlen($splitString) - 1)); - - $length = count($chars); - $pattern = '/^'; - for ($j = 0; $j < $length; ++$j) { - if ($chars[$j] === '~') { - if (isset($chars[$j + 1])) { - if ($chars[$j + 1] === '*') { - $pattern .= preg_quote($chars[$j + 1], '/'); - ++$j; - } elseif ($chars[$j + 1] === '?') { - $pattern .= preg_quote($chars[$j + 1], '/'); - ++$j; - } - } else { - $pattern .= preg_quote($chars[$j], '/'); - } - } elseif ($chars[$j] === '*') { - $pattern .= '.*'; - } elseif ($chars[$j] === '?') { - $pattern .= '.{1}'; - } else { - $pattern .= preg_quote($chars[$j], '/'); - } - } - - $pattern .= '$/'; - if ((bool) preg_match($pattern, $lookupArrayValue)) { - // exact match - return $i + 1; - } - } elseif ($exactMatch) { - // exact match - return $i + 1; - } - } elseif (($matchType === 1) && $typeMatch && ($lookupArrayValue <= $lookupValue)) { - $i = array_search($i, $keySet); - - // The current value is the (first) match - return $i + 1; - } - } - } else { - $maxValueKey = null; - - // The basic algorithm is: - // Iterate and keep the highest match until the next element is smaller than the searched value. - // Return immediately if perfect match is found - foreach ($lookupArray as $i => $lookupArrayValue) { - $typeMatch = gettype($lookupValue) === gettype($lookupArrayValue); - $exactTypeMatch = $typeMatch && $lookupArrayValue === $lookupValue; - $nonOnlyNumericExactMatch = !$typeMatch && $lookupArrayValue === $lookupValue; - $exactMatch = $exactTypeMatch || $nonOnlyNumericExactMatch; - - if ($exactMatch) { - // Another "special" case. If a perfect match is found, - // the algorithm gives up immediately - return $i + 1; - } elseif ($typeMatch & $lookupArrayValue >= $lookupValue) { - $maxValueKey = $i + 1; - } elseif ($typeMatch & $lookupArrayValue < $lookupValue) { - //Excel algorithm gives up immediately if the first element is smaller than the searched value - break; - } - } - - if ($maxValueKey !== null) { - return $maxValueKey; - } - } - - // Unsuccessful in finding a match, return #N/A error value - return Functions::NA(); + return LookupRef\ExcelMatch::MATCH($lookupValue, $lookupArray, $matchType); } /** @@ -611,262 +292,99 @@ class LookupRef * Excel Function: * =INDEX(range_array, row_num, [column_num]) * - * @param mixed $arrayValues A range of cells or an array constant - * @param mixed $rowNum The row in array from which to return a value. If row_num is omitted, column_num is required. - * @param mixed $columnNum The column in array from which to return a value. If column_num is omitted, row_num is required. + * @Deprecated 1.18.0 + * + * @see LookupRef\Matrix::index() + * Use the index() method in the LookupRef\Matrix class instead + * + * @param mixed $rowNum The row in the array or range from which to return a value. + * If row_num is omitted, column_num is required. + * @param mixed $columnNum The column in the array or range from which to return a value. + * If column_num is omitted, row_num is required. + * @param mixed $matrix * * @return mixed the value of a specified cell or array of cells */ - public static function INDEX($arrayValues, $rowNum = 0, $columnNum = 0) + public static function INDEX($matrix, $rowNum = 0, $columnNum = 0) { - $rowNum = Functions::flattenSingleValue($rowNum); - $columnNum = Functions::flattenSingleValue($columnNum); - - if (($rowNum < 0) || ($columnNum < 0)) { - return Functions::VALUE(); - } - - if (!is_array($arrayValues) || ($rowNum > count($arrayValues))) { - return Functions::REF(); - } - - $rowKeys = array_keys($arrayValues); - $columnKeys = @array_keys($arrayValues[$rowKeys[0]]); - - if ($columnNum > count($columnKeys)) { - return Functions::VALUE(); - } elseif ($columnNum == 0) { - if ($rowNum == 0) { - return $arrayValues; - } - $rowNum = $rowKeys[--$rowNum]; - $returnArray = []; - foreach ($arrayValues as $arrayColumn) { - if (is_array($arrayColumn)) { - if (isset($arrayColumn[$rowNum])) { - $returnArray[] = $arrayColumn[$rowNum]; - } else { - return [$rowNum => $arrayValues[$rowNum]]; - } - } else { - return $arrayValues[$rowNum]; - } - } - - return $returnArray; - } - $columnNum = $columnKeys[--$columnNum]; - if ($rowNum > count($rowKeys)) { - return Functions::VALUE(); - } elseif ($rowNum == 0) { - return $arrayValues[$columnNum]; - } - $rowNum = $rowKeys[--$rowNum]; - - return $arrayValues[$rowNum][$columnNum]; + return Matrix::index($matrix, $rowNum, $columnNum); } /** * TRANSPOSE. * + * @Deprecated 1.18.0 + * + * @see LookupRef\Matrix::transpose() + * Use the transpose() method in the LookupRef\Matrix class instead + * * @param array $matrixData A matrix of values * * @return array * - * Unlike the Excel TRANSPOSE function, which will only work on a single row or column, this function will transpose a full matrix + * Unlike the Excel TRANSPOSE function, which will only work on a single row or column, + * this function will transpose a full matrix */ public static function TRANSPOSE($matrixData) { - $returnMatrix = []; - if (!is_array($matrixData)) { - $matrixData = [[$matrixData]]; - } - - $column = 0; - foreach ($matrixData as $matrixRow) { - $row = 0; - foreach ($matrixRow as $matrixCell) { - $returnMatrix[$row][$column] = $matrixCell; - ++$row; - } - ++$column; - } - - return $returnMatrix; - } - - private static function vlookupSort($a, $b) - { - reset($a); - $firstColumn = key($a); - $aLower = StringHelper::strToLower($a[$firstColumn]); - $bLower = StringHelper::strToLower($b[$firstColumn]); - if ($aLower == $bLower) { - return 0; - } - - return ($aLower < $bLower) ? -1 : 1; + return Matrix::transpose($matrixData); } /** * VLOOKUP - * The VLOOKUP function searches for value in the left-most column of lookup_array and returns the value in the same row based on the index_number. + * The VLOOKUP function searches for value in the left-most column of lookup_array and returns the value + * in the same row based on the index_number. + * + * @Deprecated 1.18.0 + * + * @see LookupRef\VLookup::lookup() + * Use the lookup() method in the LookupRef\VLookup class instead * * @param mixed $lookup_value The value that you want to match in lookup_array * @param mixed $lookup_array The range of cells being searched - * @param mixed $index_number The column number in table_array from which the matching value must be returned. The first column is 1. + * @param mixed $index_number The column number in table_array from which the matching value must be returned. + * The first column is 1. * @param mixed $not_exact_match determines if you are looking for an exact match based on lookup_value * * @return mixed The value of the found cell */ public static function VLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true) { - $lookup_value = Functions::flattenSingleValue($lookup_value); - $index_number = Functions::flattenSingleValue($index_number); - $not_exact_match = Functions::flattenSingleValue($not_exact_match); - - // index_number must be greater than or equal to 1 - if ($index_number < 1) { - return Functions::VALUE(); - } - - // index_number must be less than or equal to the number of columns in lookup_array - if ((!is_array($lookup_array)) || (empty($lookup_array))) { - return Functions::REF(); - } - $f = array_keys($lookup_array); - $firstRow = array_pop($f); - if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) { - return Functions::REF(); - } - $columnKeys = array_keys($lookup_array[$firstRow]); - $returnColumn = $columnKeys[--$index_number]; - $firstColumn = array_shift($columnKeys); - - if (!$not_exact_match) { - uasort($lookup_array, ['self', 'vlookupSort']); - } - - $lookupLower = StringHelper::strToLower($lookup_value); - $rowNumber = $rowValue = false; - foreach ($lookup_array as $rowKey => $rowData) { - $firstLower = StringHelper::strToLower($rowData[$firstColumn]); - - // break if we have passed possible keys - if ( - (is_numeric($lookup_value) && is_numeric($rowData[$firstColumn]) && ($rowData[$firstColumn] > $lookup_value)) || - (!is_numeric($lookup_value) && !is_numeric($rowData[$firstColumn]) && ($firstLower > $lookupLower)) - ) { - break; - } - // remember the last key, but only if datatypes match - if ( - (is_numeric($lookup_value) && is_numeric($rowData[$firstColumn])) || - (!is_numeric($lookup_value) && !is_numeric($rowData[$firstColumn])) - ) { - if ($not_exact_match) { - $rowNumber = $rowKey; - - continue; - } elseif ( - ($firstLower == $lookupLower) - // Spreadsheets software returns first exact match, - // we have sorted and we might have broken key orders - // we want the first one (by its initial index) - && (($rowNumber == false) || ($rowKey < $rowNumber)) - ) { - $rowNumber = $rowKey; - } - } - } - - if ($rowNumber !== false) { - // return the appropriate value - return $lookup_array[$rowNumber][$returnColumn]; - } - - return Functions::NA(); + return VLookup::lookup($lookup_value, $lookup_array, $index_number, $not_exact_match); } /** * HLOOKUP - * The HLOOKUP function searches for value in the top-most row of lookup_array and returns the value in the same column based on the index_number. + * The HLOOKUP function searches for value in the top-most row of lookup_array and returns the value + * in the same column based on the index_number. + * + * @Deprecated 1.18.0 + * + * @see LookupRef\HLookup::lookup() + * Use the lookup() method in the LookupRef\HLookup class instead * * @param mixed $lookup_value The value that you want to match in lookup_array * @param mixed $lookup_array The range of cells being searched - * @param mixed $index_number The row number in table_array from which the matching value must be returned. The first row is 1. + * @param mixed $index_number The row number in table_array from which the matching value must be returned. + * The first row is 1. * @param mixed $not_exact_match determines if you are looking for an exact match based on lookup_value * * @return mixed The value of the found cell */ public static function HLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true) { - $lookup_value = Functions::flattenSingleValue($lookup_value); - $index_number = Functions::flattenSingleValue($index_number); - $not_exact_match = Functions::flattenSingleValue($not_exact_match); - - // index_number must be greater than or equal to 1 - if ($index_number < 1) { - return Functions::VALUE(); - } - - // index_number must be less than or equal to the number of columns in lookup_array - if ((!is_array($lookup_array)) || (empty($lookup_array))) { - return Functions::REF(); - } - $f = array_keys($lookup_array); - $firstRow = reset($f); - if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array))) { - return Functions::REF(); - } - - $firstkey = $f[0] - 1; - $returnColumn = $firstkey + $index_number; - $firstColumn = array_shift($f); - $rowNumber = null; - foreach ($lookup_array[$firstColumn] as $rowKey => $rowData) { - // break if we have passed possible keys - $bothNumeric = is_numeric($lookup_value) && is_numeric($rowData); - $bothNotNumeric = !is_numeric($lookup_value) && !is_numeric($rowData); - $lookupLower = StringHelper::strToLower($lookup_value); - $rowDataLower = StringHelper::strToLower($rowData); - - if ( - $not_exact_match && ( - ($bothNumeric && $rowData > $lookup_value) || - ($bothNotNumeric && $rowDataLower > $lookupLower) - ) - ) { - break; - } - - // Remember the last key, but only if datatypes match (as in VLOOKUP) - if ($bothNumeric || $bothNotNumeric) { - if ($not_exact_match) { - $rowNumber = $rowKey; - - continue; - } elseif ( - $rowDataLower === $lookupLower - && ($rowNumber === null || $rowKey < $rowNumber) - ) { - $rowNumber = $rowKey; - } - } - } - - if ($rowNumber !== null) { - // otherwise return the appropriate value - return $lookup_array[$returnColumn][$rowNumber]; - } - - return Functions::NA(); + return HLookup::lookup($lookup_value, $lookup_array, $index_number, $not_exact_match); } /** * LOOKUP * The LOOKUP function searches for value either from a one-row or one-column range or from an array. * + * @Deprecated 1.18.0 + * + * @see LookupRef\Lookup::lookup() + * Use the lookup() method in the LookupRef\Lookup class instead + * * @param mixed $lookup_value The value that you want to match in lookup_array * @param mixed $lookup_vector The range of cells being searched * @param null|mixed $result_vector The column from which the matching value must be returned @@ -875,71 +393,17 @@ class LookupRef */ public static function LOOKUP($lookup_value, $lookup_vector, $result_vector = null) { - $lookup_value = Functions::flattenSingleValue($lookup_value); - - if (!is_array($lookup_vector)) { - return Functions::NA(); - } - $hasResultVector = isset($result_vector); - $lookupRows = count($lookup_vector); - $l = array_keys($lookup_vector); - $l = array_shift($l); - $lookupColumns = count($lookup_vector[$l]); - // we correctly orient our results - if (($lookupRows === 1 && $lookupColumns > 1) || (!$hasResultVector && $lookupRows === 2 && $lookupColumns !== 2)) { - $lookup_vector = self::TRANSPOSE($lookup_vector); - $lookupRows = count($lookup_vector); - $l = array_keys($lookup_vector); - $lookupColumns = count($lookup_vector[array_shift($l)]); - } - - if ($result_vector === null) { - $result_vector = $lookup_vector; - } - $resultRows = count($result_vector); - $l = array_keys($result_vector); - $l = array_shift($l); - $resultColumns = count($result_vector[$l]); - // we correctly orient our results - if ($resultRows === 1 && $resultColumns > 1) { - $result_vector = self::TRANSPOSE($result_vector); - $resultRows = count($result_vector); - $r = array_keys($result_vector); - $resultColumns = count($result_vector[array_shift($r)]); - } - - if ($lookupRows === 2 && !$hasResultVector) { - $result_vector = array_pop($lookup_vector); - $lookup_vector = array_shift($lookup_vector); - } - - if ($lookupColumns !== 2) { - foreach ($lookup_vector as &$value) { - if (is_array($value)) { - $k = array_keys($value); - $key1 = $key2 = array_shift($k); - ++$key2; - $dataValue1 = $value[$key1]; - } else { - $key1 = 0; - $key2 = 1; - $dataValue1 = $value; - } - $dataValue2 = array_shift($result_vector); - if (is_array($dataValue2)) { - $dataValue2 = array_shift($dataValue2); - } - $value = [$key1 => $dataValue1, $key2 => $dataValue2]; - } - unset($value); - } - - return self::VLOOKUP($lookup_value, $lookup_vector, 2); + return Lookup::lookup($lookup_value, $lookup_vector, $result_vector); } /** * FORMULATEXT. * + * @Deprecated 1.18.0 + * + * @see LookupRef\Formula::text() + * Use the text() method in the LookupRef\Formula class instead + * * @param mixed $cellReference The cell to check * @param Cell $pCell The current cell (containing this formula) * @@ -947,22 +411,6 @@ class LookupRef */ public static function FORMULATEXT($cellReference = '', ?Cell $pCell = null) { - if ($pCell === null) { - return Functions::REF(); - } - - preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellReference, $matches); - - $cellReference = $matches[6] . $matches[7]; - $worksheetName = trim($matches[3], "'"); - $worksheet = (!empty($worksheetName)) - ? $pCell->getWorksheet()->getParent()->getSheetByName($worksheetName) - : $pCell->getWorksheet(); - - if (!$worksheet->getCell($cellReference)->isFormula()) { - return Functions::NA(); - } - - return $worksheet->getCell($cellReference)->getValue(); + return LookupRef\Formula::text($cellReference, $pCell); } } diff --git a/src/PhpSpreadsheet/Calculation/LookupRef/Address.php b/src/PhpSpreadsheet/Calculation/LookupRef/Address.php new file mode 100644 index 00000000..58215f27 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/LookupRef/Address.php @@ -0,0 +1,98 @@ + '') { + if (strpos($sheetName, ' ') !== false || strpos($sheetName, '[') !== false) { + $sheetName = "'{$sheetName}'"; + } + $sheetName .= '!'; + } + + return $sheetName; + } + + private static function formatAsA1(int $row, int $column, int $relativity, string $sheetName): string + { + $rowRelative = $columnRelative = '$'; + if (($relativity == self::ADDRESS_COLUMN_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { + $columnRelative = ''; + } + if (($relativity == self::ADDRESS_ROW_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { + $rowRelative = ''; + } + $column = Coordinate::stringFromColumnIndex($column); + + return "{$sheetName}{$columnRelative}{$column}{$rowRelative}{$row}"; + } + + private static function formatAsR1C1(int $row, int $column, int $relativity, string $sheetName): string + { + if (($relativity == self::ADDRESS_COLUMN_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { + $column = "[{$column}]"; + } + if (($relativity == self::ADDRESS_ROW_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { + $row = "[{$row}]"; + } + + return "{$sheetName}R{$row}C{$column}"; + } +} diff --git a/src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php b/src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php new file mode 100644 index 00000000..71358bf3 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php @@ -0,0 +1,198 @@ +getMessage(); + } + + // MATCH() is not case sensitive, so we convert lookup value to be lower cased if it's a string type. + if (is_string($lookupValue)) { + $lookupValue = StringHelper::strToLower($lookupValue); + } + + $valueKey = null; + switch ($matchType) { + case self::MATCHTYPE_LARGEST_VALUE: + $valueKey = self::matchLargestValue($lookupArray, $lookupValue, $keySet); + + break; + case self::MATCHTYPE_FIRST_VALUE: + $valueKey = self::matchFirstValue($lookupArray, $lookupValue); + + break; + case self::MATCHTYPE_SMALLEST_VALUE: + default: + $valueKey = self::matchSmallestValue($lookupArray, $lookupValue); + } + + if ($valueKey !== null) { + return ++$valueKey; + } + + // Unsuccessful in finding a match, return #N/A error value + return Functions::NA(); + } + + private static function matchFirstValue($lookupArray, $lookupValue) + { + $wildcardLookup = ((bool) preg_match('/([\?\*])/', $lookupValue)); + $wildcard = WildcardMatch::wildcard($lookupValue); + + foreach ($lookupArray as $i => $lookupArrayValue) { + $typeMatch = ((gettype($lookupValue) === gettype($lookupArrayValue)) || + (is_numeric($lookupValue) && is_numeric($lookupArrayValue))); + + if ( + $typeMatch && is_string($lookupValue) && + $wildcardLookup && WildcardMatch::compare($lookupArrayValue, $wildcard) + ) { + // wildcard match + return $i; + } elseif ($lookupArrayValue === $lookupValue) { + // exact match + return $i; + } + } + + return null; + } + + private static function matchLargestValue($lookupArray, $lookupValue, $keySet) + { + foreach ($lookupArray as $i => $lookupArrayValue) { + $typeMatch = ((gettype($lookupValue) === gettype($lookupArrayValue)) || + (is_numeric($lookupValue) && is_numeric($lookupArrayValue))); + + if ($typeMatch && ($lookupArrayValue <= $lookupValue)) { + return array_search($i, $keySet); + } + } + + return null; + } + + private static function matchSmallestValue($lookupArray, $lookupValue) + { + $valueKey = null; + + // The basic algorithm is: + // Iterate and keep the highest match until the next element is smaller than the searched value. + // Return immediately if perfect match is found + foreach ($lookupArray as $i => $lookupArrayValue) { + $typeMatch = gettype($lookupValue) === gettype($lookupArrayValue); + + if ($lookupArrayValue === $lookupValue) { + // Another "special" case. If a perfect match is found, + // the algorithm gives up immediately + return $i; + } elseif ($typeMatch && $lookupArrayValue >= $lookupValue) { + $valueKey = $i; + } elseif ($typeMatch && $lookupArrayValue < $lookupValue) { + //Excel algorithm gives up immediately if the first element is smaller than the searched value + break; + } + } + + return $valueKey; + } + + private static function validateLookupValue($lookupValue): void + { + // Lookup_value type has to be number, text, or logical values + if ((!is_numeric($lookupValue)) && (!is_string($lookupValue)) && (!is_bool($lookupValue))) { + throw new Exception(Functions::NA()); + } + } + + private static function validateMatchType($matchType): void + { + // Match_type is 0, 1 or -1 + if ( + ($matchType !== self::MATCHTYPE_FIRST_VALUE) && + ($matchType !== self::MATCHTYPE_LARGEST_VALUE) && ($matchType !== self::MATCHTYPE_SMALLEST_VALUE) + ) { + throw new Exception(Functions::NA()); + } + } + + private static function validateLookupArray($lookupArray): void + { + // Lookup_array should not be empty + $lookupArraySize = count($lookupArray); + if ($lookupArraySize <= 0) { + throw new Exception(Functions::NA()); + } + } + + private static function prepareLookupArray($lookupArray, $matchType) + { + // Lookup_array should contain only number, text, or logical values, or empty (null) cells + foreach ($lookupArray as $i => $value) { + // check the type of the value + if ((!is_numeric($value)) && (!is_string($value)) && (!is_bool($value)) && ($value !== null)) { + throw new Exception(Functions::NA()); + } + // Convert strings to lowercase for case-insensitive testing + if (is_string($value)) { + $lookupArray[$i] = StringHelper::strToLower($value); + } + if ( + ($value === null) && + (($matchType == self::MATCHTYPE_LARGEST_VALUE) || ($matchType == self::MATCHTYPE_SMALLEST_VALUE)) + ) { + unset($lookupArray[$i]); + } + } + + return $lookupArray; + } +} diff --git a/src/PhpSpreadsheet/Calculation/LookupRef/Formula.php b/src/PhpSpreadsheet/Calculation/LookupRef/Formula.php new file mode 100644 index 00000000..d96b5040 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/LookupRef/Formula.php @@ -0,0 +1,43 @@ +getWorksheet()->getParent()->getSheetByName($worksheetName) + : $pCell->getWorksheet(); + + if ( + $worksheet === null || + !$worksheet->cellExists($cellReference) || + !$worksheet->getCell($cellReference)->isFormula() + ) { + return Functions::NA(); + } + + return $worksheet->getCell($cellReference)->getValue(); + } +} diff --git a/src/PhpSpreadsheet/Calculation/LookupRef/HLookup.php b/src/PhpSpreadsheet/Calculation/LookupRef/HLookup.php new file mode 100644 index 00000000..7db27804 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/LookupRef/HLookup.php @@ -0,0 +1,116 @@ +getMessage(); + } + + $f = array_keys($lookupArray); + $firstRow = reset($f); + if ((!is_array($lookupArray[$firstRow])) || ($indexNumber > count($lookupArray))) { + return Functions::REF(); + } + + $firstkey = $f[0] - 1; + $returnColumn = $firstkey + $indexNumber; + $firstColumn = array_shift($f); + $rowNumber = self::hLookupSearch($lookupValue, $lookupArray, $firstColumn, $notExactMatch); + + if ($rowNumber !== null) { + // otherwise return the appropriate value + return $lookupArray[$returnColumn][Coordinate::stringFromColumnIndex($rowNumber)]; + } + + return Functions::NA(); + } + + /** + * @param mixed $lookupValue The value that you want to match in lookup_array + * @param mixed $column The column to look up + * @param mixed $notExactMatch determines if you are looking for an exact match based on lookup_value + */ + private static function hLookupSearch($lookupValue, array $lookupArray, $column, $notExactMatch): ?int + { + $lookupLower = StringHelper::strToLower($lookupValue); + + $rowNumber = null; + foreach ($lookupArray[$column] as $rowKey => $rowData) { + // break if we have passed possible keys + $bothNumeric = is_numeric($lookupValue) && is_numeric($rowData); + $bothNotNumeric = !is_numeric($lookupValue) && !is_numeric($rowData); + $cellDataLower = StringHelper::strToLower($rowData); + + if ( + $notExactMatch && + (($bothNumeric && $rowData > $lookupValue) || ($bothNotNumeric && $cellDataLower > $lookupLower)) + ) { + break; + } + + $rowNumber = self::checkMatch( + $bothNumeric, + $bothNotNumeric, + $notExactMatch, + Coordinate::columnIndexFromString($rowKey), + $cellDataLower, + $lookupLower, + $rowNumber + ); + } + + return $rowNumber; + } + + private static function convertLiteralArray(array $lookupArray): array + { + if (array_key_exists(0, $lookupArray)) { + $lookupArray2 = []; + $row = 0; + foreach ($lookupArray as $arrayVal) { + ++$row; + if (!is_array($arrayVal)) { + $arrayVal = [$arrayVal]; + } + $arrayVal2 = []; + foreach ($arrayVal as $key2 => $val2) { + $index = Coordinate::stringFromColumnIndex($key2 + 1); + $arrayVal2[$index] = $val2; + } + $lookupArray2[$row] = $arrayVal2; + } + $lookupArray = $lookupArray2; + } + + return $lookupArray; + } +} diff --git a/src/PhpSpreadsheet/Calculation/LookupRef/Helpers.php b/src/PhpSpreadsheet/Calculation/LookupRef/Helpers.php new file mode 100644 index 00000000..f38e5da8 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/LookupRef/Helpers.php @@ -0,0 +1,74 @@ +getWorkSheet(); + $sheetTitle = ($workSheet === null) ? '' : $workSheet->getTitle(); + $value = preg_replace('/^=/', '', $namedRange->getValue()); + self::adjustSheetTitle($sheetTitle, $value); + $cellAddress1 = $sheetTitle . $value; + $cellAddress = $cellAddress1; + $a1 = self::CELLADDRESS_USE_A1; + } + if (strpos($cellAddress, ':') !== false) { + [$cellAddress1, $cellAddress2] = explode(':', $cellAddress); + } + $cellAddress = self::convertR1C1($cellAddress1, $cellAddress2, $a1); + + return [$cellAddress1, $cellAddress2, $cellAddress]; + } + + public static function extractWorksheet(string $cellAddress, Cell $pCell): array + { + $sheetName = ''; + if (strpos($cellAddress, '!') !== false) { + [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); + $sheetName = trim($sheetName, "'"); + } + + $worksheet = ($sheetName !== '') + ? $pCell->getWorksheet()->getParent()->getSheetByName($sheetName) + : $pCell->getWorksheet(); + + return [$cellAddress, $worksheet, $sheetName]; + } +} diff --git a/src/PhpSpreadsheet/Calculation/LookupRef/Hyperlink.php b/src/PhpSpreadsheet/Calculation/LookupRef/Hyperlink.php new file mode 100644 index 00000000..823d70c6 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/LookupRef/Hyperlink.php @@ -0,0 +1,40 @@ +getHyperlink()->setUrl($linkURL); + $pCell->getHyperlink()->setTooltip($displayName); + + return $displayName; + } +} diff --git a/src/PhpSpreadsheet/Calculation/LookupRef/Indirect.php b/src/PhpSpreadsheet/Calculation/LookupRef/Indirect.php new file mode 100644 index 00000000..3a76bb0f --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/LookupRef/Indirect.php @@ -0,0 +1,97 @@ +getMessage(); + } + + [$cellAddress, $worksheet, $sheetName] = Helpers::extractWorksheet($cellAddress, $pCell); + + [$cellAddress1, $cellAddress2, $cellAddress] = Helpers::extractCellAddresses($cellAddress, $a1, $pCell->getWorkSheet(), $sheetName); + + if ( + (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellAddress1, $matches)) || + (($cellAddress2 !== null) && (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellAddress2, $matches))) + ) { + return Functions::REF(); + } + + return self::extractRequiredCells($worksheet, $cellAddress); + } + + /** + * Extract range values. + * + * @return mixed Array of values in range if range contains more than one element. + * Otherwise, a single value is returned. + */ + private static function extractRequiredCells(?Worksheet $worksheet, string $cellAddress) + { + return Calculation::getInstance($worksheet !== null ? $worksheet->getParent() : null) + ->extractCellRange($cellAddress, $worksheet, false); + } +} diff --git a/src/PhpSpreadsheet/Calculation/LookupRef/Lookup.php b/src/PhpSpreadsheet/Calculation/LookupRef/Lookup.php new file mode 100644 index 00000000..e21d35dc --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/LookupRef/Lookup.php @@ -0,0 +1,105 @@ + 1) || (!$hasResultVector && $lookupRows === 2 && $lookupColumns !== 2)) { + $lookupVector = LookupRef\Matrix::transpose($lookupVector); + $lookupRows = self::rowCount($lookupVector); + $lookupColumns = self::columnCount($lookupVector); + } + + $resultVector = self::verifyResultVector($lookupVector, $resultVector); + + if ($lookupRows === 2 && !$hasResultVector) { + $resultVector = array_pop($lookupVector); + $lookupVector = array_shift($lookupVector); + } + + if ($lookupColumns !== 2) { + $lookupVector = self::verifyLookupValues($lookupVector, $resultVector); + } + + return VLookup::lookup($lookupValue, $lookupVector, 2); + } + + private static function verifyLookupValues(array $lookupVector, array $resultVector): array + { + foreach ($lookupVector as &$value) { + if (is_array($value)) { + $k = array_keys($value); + $key1 = $key2 = array_shift($k); + ++$key2; + $dataValue1 = $value[$key1]; + } else { + $key1 = 0; + $key2 = 1; + $dataValue1 = $value; + } + + $dataValue2 = array_shift($resultVector); + if (is_array($dataValue2)) { + $dataValue2 = array_shift($dataValue2); + } + $value = [$key1 => $dataValue1, $key2 => $dataValue2]; + } + unset($value); + + return $lookupVector; + } + + private static function verifyResultVector(array $lookupVector, $resultVector) + { + if ($resultVector === null) { + $resultVector = $lookupVector; + } + + $resultRows = self::rowCount($resultVector); + $resultColumns = self::columnCount($resultVector); + + // we correctly orient our results + if ($resultRows === 1 && $resultColumns > 1) { + $resultVector = LookupRef\Matrix::transpose($resultVector); + } + + return $resultVector; + } + + private static function rowCount(array $dataArray): int + { + return count($dataArray); + } + + private static function columnCount(array $dataArray): int + { + $rowKeys = array_keys($dataArray); + $row = array_shift($rowKeys); + + return count($dataArray[$row]); + } +} diff --git a/src/PhpSpreadsheet/Calculation/LookupRef/LookupBase.php b/src/PhpSpreadsheet/Calculation/LookupRef/LookupBase.php new file mode 100644 index 00000000..80fc99ad --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/LookupRef/LookupBase.php @@ -0,0 +1,48 @@ +getMessage(); + } + + if (!is_array($matrix) || ($rowNum > count($matrix))) { + return Functions::REF(); + } + + $rowKeys = array_keys($matrix); + $columnKeys = @array_keys($matrix[$rowKeys[0]]); + + if ($columnNum > count($columnKeys)) { + return Functions::REF(); + } + + if ($columnNum === 0) { + return self::extractRowValue($matrix, $rowKeys, $rowNum); + } + + $columnNum = $columnKeys[--$columnNum]; + if ($rowNum === 0) { + return array_map( + function ($value) { + return [$value]; + }, + array_column($matrix, $columnNum) + ); + } + $rowNum = $rowKeys[--$rowNum]; + + return $matrix[$rowNum][$columnNum]; + } + + private static function extractRowValue(array $matrix, array $rowKeys, int $rowNum) + { + if ($rowNum === 0) { + return $matrix; + } + + $rowNum = $rowKeys[--$rowNum]; + $row = $matrix[$rowNum]; + if (is_array($row)) { + return [$rowNum => $row]; + } + + return $row; + } +} diff --git a/src/PhpSpreadsheet/Calculation/LookupRef/Offset.php b/src/PhpSpreadsheet/Calculation/LookupRef/Offset.php new file mode 100644 index 00000000..0e45831f --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/LookupRef/Offset.php @@ -0,0 +1,136 @@ +getParent() : null) + ->extractCellRange($cellAddress, $worksheet, false); + } + + private static function extractWorksheet($cellAddress, Cell $pCell): array + { + $sheetName = ''; + if (strpos($cellAddress, '!') !== false) { + [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); + $sheetName = trim($sheetName, "'"); + } + + $worksheet = ($sheetName !== '') + ? $pCell->getWorksheet()->getParent()->getSheetByName($sheetName) + : $pCell->getWorksheet(); + + return [$cellAddress, $worksheet]; + } + + private static function adjustEndCellColumnForWidth(string $endCellColumn, $width, int $startCellColumn, $columns) + { + $endCellColumn = Coordinate::columnIndexFromString($endCellColumn) - 1; + if (($width !== null) && (!is_object($width))) { + $endCellColumn = $startCellColumn + (int) $width - 1; + } else { + $endCellColumn += (int) $columns; + } + + return $endCellColumn; + } + + private static function adustEndCellRowForHeight($height, int $startCellRow, $rows, $endCellRow): int + { + if (($height !== null) && (!is_object($height))) { + $endCellRow = $startCellRow + (int) $height - 1; + } else { + $endCellRow += (int) $rows; + } + + return $endCellRow; + } +} diff --git a/src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php b/src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php new file mode 100644 index 00000000..02c9a79e --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php @@ -0,0 +1,209 @@ +getColumn()) : 1; + } + + /** + * COLUMN. + * + * Returns the column number of the given cell reference + * If the cell reference is a range of cells, COLUMN returns the column numbers of each column + * in the reference as a horizontal array. + * If cell reference is omitted, and the function is being called through the calculation engine, + * then it is assumed to be the reference of the cell in which the COLUMN function appears; + * otherwise this function returns 1. + * + * Excel Function: + * =COLUMN([cellAddress]) + * + * @param null|array|string $cellAddress A reference to a range of cells for which you want the column numbers + * + * @return int|int[] + */ + public static function COLUMN($cellAddress = null, ?Cell $pCell = null) + { + if (self::cellAddressNullOrWhitespace($cellAddress)) { + return self::cellColumn($pCell); + } + + if (is_array($cellAddress)) { + foreach ($cellAddress as $columnKey => $value) { + $columnKey = preg_replace('/[^a-z]/i', '', $columnKey); + + return (int) Coordinate::columnIndexFromString($columnKey); + } + + return self::cellColumn($pCell); + } + + $cellAddress = $cellAddress ?? ''; + if ($pCell != null) { + [,, $sheetName] = Helpers::extractWorksheet($cellAddress, $pCell); + [,, $cellAddress] = Helpers::extractCellAddresses($cellAddress, true, $pCell->getWorksheet(), $sheetName); + } + [, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); + if (strpos($cellAddress, ':') !== false) { + [$startAddress, $endAddress] = explode(':', $cellAddress); + $startAddress = preg_replace('/[^a-z]/i', '', $startAddress); + $endAddress = preg_replace('/[^a-z]/i', '', $endAddress); + + return range( + (int) Coordinate::columnIndexFromString($startAddress), + (int) Coordinate::columnIndexFromString($endAddress) + ); + } + + $cellAddress = preg_replace('/[^a-z]/i', '', $cellAddress); + + return (int) Coordinate::columnIndexFromString($cellAddress); + } + + /** + * COLUMNS. + * + * Returns the number of columns in an array or reference. + * + * Excel Function: + * =COLUMNS(cellAddress) + * + * @param null|array|string $cellAddress An array or array formula, or a reference to a range of cells + * for which you want the number of columns + * + * @return int|string The number of columns in cellAddress, or a string if arguments are invalid + */ + public static function COLUMNS($cellAddress = null) + { + if (self::cellAddressNullOrWhitespace($cellAddress)) { + return 1; + } + if (!is_array($cellAddress)) { + return Functions::VALUE(); + } + + reset($cellAddress); + $isMatrix = (is_numeric(key($cellAddress))); + [$columns, $rows] = Calculation::getMatrixDimensions($cellAddress); + + if ($isMatrix) { + return $rows; + } + + return $columns; + } + + private static function cellRow(?Cell $pCell): int + { + return ($pCell !== null) ? $pCell->getRow() : 1; + } + + /** + * ROW. + * + * Returns the row number of the given cell reference + * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference + * as a vertical array. + * If cell reference is omitted, and the function is being called through the calculation engine, + * then it is assumed to be the reference of the cell in which the ROW function appears; + * otherwise this function returns 1. + * + * Excel Function: + * =ROW([cellAddress]) + * + * @param null|array|string $cellAddress A reference to a range of cells for which you want the row numbers + * + * @return int|mixed[]|string + */ + public static function ROW($cellAddress = null, ?Cell $pCell = null) + { + if (self::cellAddressNullOrWhitespace($cellAddress)) { + return self::cellRow($pCell); + } + + if (is_array($cellAddress)) { + foreach ($cellAddress as $rowKey => $rowValue) { + foreach ($rowValue as $columnKey => $cellValue) { + return (int) preg_replace('/\D/', '', $rowKey); + } + } + + return self::cellRow($pCell); + } + + $cellAddress = $cellAddress ?? ''; + if ($pCell !== null) { + [,, $sheetName] = Helpers::extractWorksheet($cellAddress, $pCell); + [,, $cellAddress] = Helpers::extractCellAddresses($cellAddress, true, $pCell->getWorksheet(), $sheetName); + } + [, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); + if (strpos($cellAddress, ':') !== false) { + [$startAddress, $endAddress] = explode(':', $cellAddress); + $startAddress = preg_replace('/\D/', '', $startAddress); + $endAddress = preg_replace('/\D/', '', $endAddress); + + return array_map( + function ($value) { + return [$value]; + }, + range($startAddress, $endAddress) + ); + } + [$cellAddress] = explode(':', $cellAddress); + + return (int) preg_replace('/\D/', '', $cellAddress); + } + + /** + * ROWS. + * + * Returns the number of rows in an array or reference. + * + * Excel Function: + * =ROWS(cellAddress) + * + * @param null|array|string $cellAddress An array or array formula, or a reference to a range of cells + * for which you want the number of rows + * + * @return int|string The number of rows in cellAddress, or a string if arguments are invalid + */ + public static function ROWS($cellAddress = null) + { + if (self::cellAddressNullOrWhitespace($cellAddress)) { + return 1; + } + if (!is_array($cellAddress)) { + return Functions::VALUE(); + } + + reset($cellAddress); + $isMatrix = (is_numeric(key($cellAddress))); + [$columns, $rows] = Calculation::getMatrixDimensions($cellAddress); + + if ($isMatrix) { + return $columns; + } + + return $rows; + } +} diff --git a/src/PhpSpreadsheet/Calculation/LookupRef/Selection.php b/src/PhpSpreadsheet/Calculation/LookupRef/Selection.php new file mode 100644 index 00000000..6c18d73b --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/LookupRef/Selection.php @@ -0,0 +1,46 @@ + $entryCount)) { + return Functions::VALUE(); + } + + if (is_array($chooseArgs[$chosenEntry])) { + return Functions::flattenArray($chooseArgs[$chosenEntry]); + } + + return $chooseArgs[$chosenEntry]; + } +} diff --git a/src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php b/src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php new file mode 100644 index 00000000..ddd5d9ee --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php @@ -0,0 +1,105 @@ +getMessage(); + } + + $f = array_keys($lookupArray); + $firstRow = array_pop($f); + if ((!is_array($lookupArray[$firstRow])) || ($indexNumber > count($lookupArray[$firstRow]))) { + return Functions::REF(); + } + $columnKeys = array_keys($lookupArray[$firstRow]); + $returnColumn = $columnKeys[--$indexNumber]; + $firstColumn = array_shift($columnKeys); + + if (!$notExactMatch) { + uasort($lookupArray, ['self', 'vlookupSort']); + } + + $rowNumber = self::vLookupSearch($lookupValue, $lookupArray, $firstColumn, $notExactMatch); + + if ($rowNumber !== null) { + // return the appropriate value + return $lookupArray[$rowNumber][$returnColumn]; + } + + return Functions::NA(); + } + + private static function vlookupSort($a, $b) + { + reset($a); + $firstColumn = key($a); + $aLower = StringHelper::strToLower($a[$firstColumn]); + $bLower = StringHelper::strToLower($b[$firstColumn]); + + if ($aLower == $bLower) { + return 0; + } + + return ($aLower < $bLower) ? -1 : 1; + } + + private static function vLookupSearch($lookupValue, $lookupArray, $column, $notExactMatch) + { + $lookupLower = StringHelper::strToLower($lookupValue); + + $rowNumber = null; + foreach ($lookupArray as $rowKey => $rowData) { + $bothNumeric = is_numeric($lookupValue) && is_numeric($rowData[$column]); + $bothNotNumeric = !is_numeric($lookupValue) && !is_numeric($rowData[$column]); + $cellDataLower = StringHelper::strToLower($rowData[$column]); + + // break if we have passed possible keys + if ( + $notExactMatch && + (($bothNumeric && ($rowData[$column] > $lookupValue)) || + ($bothNotNumeric && ($cellDataLower > $lookupLower))) + ) { + break; + } + + $rowNumber = self::checkMatch( + $bothNumeric, + $bothNotNumeric, + $notExactMatch, + $rowKey, + $cellDataLower, + $lookupLower, + $rowNumber + ); + } + + return $rowNumber; + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig.php b/src/PhpSpreadsheet/Calculation/MathTrig.php index 823f6ef2..ec251f6d 100644 --- a/src/PhpSpreadsheet/Calculation/MathTrig.php +++ b/src/PhpSpreadsheet/Calculation/MathTrig.php @@ -2,43 +2,11 @@ namespace PhpOffice\PhpSpreadsheet\Calculation; -use Exception; -use Matrix\Exception as MatrixException; -use Matrix\Matrix; - +/** + * @deprecated 1.18.0 + */ class MathTrig { - // - // Private method to return an array of the factors of the input value - // - private static function factors($value) - { - $startVal = floor(sqrt($value)); - - $factorArray = []; - for ($i = $startVal; $i > 1; --$i) { - if (($value % $i) == 0) { - $factorArray = array_merge($factorArray, self::factors($value / $i)); - $factorArray = array_merge($factorArray, self::factors($i)); - if ($i <= sqrt($value)) { - break; - } - } - } - if (!empty($factorArray)) { - rsort($factorArray); - - return $factorArray; - } - - return [(int) $value]; - } - - private static function romanCut($num, $n) - { - return ($num - ($num % $n)) / $n; - } - /** * ARABIC. * @@ -47,75 +15,18 @@ class MathTrig * Excel Function: * ARABIC(text) * + * @Deprecated 1.18.0 + * + * @See MathTrig\Arabic::evaluate() + * Use the evaluate method in the MathTrig\Arabic class instead + * * @param string $roman * * @return int|string the arabic numberal contrived from the roman numeral */ public static function ARABIC($roman) { - // An empty string should return 0 - $roman = substr(trim(strtoupper((string) Functions::flattenSingleValue($roman))), 0, 255); - if ($roman === '') { - return 0; - } - - // Convert the roman numeral to an arabic number - $negativeNumber = $roman[0] === '-'; - if ($negativeNumber) { - $roman = substr($roman, 1); - } - - try { - $arabic = self::calculateArabic(str_split($roman)); - } catch (Exception $e) { - return Functions::VALUE(); // Invalid character detected - } - - if ($negativeNumber) { - $arabic *= -1; // The number should be negative - } - - return $arabic; - } - - /** - * Recursively calculate the arabic value of a roman numeral. - * - * @param int $sum - * @param int $subtract - * - * @return int - */ - protected static function calculateArabic(array $roman, &$sum = 0, $subtract = 0) - { - $lookup = [ - 'M' => 1000, - 'D' => 500, - 'C' => 100, - 'L' => 50, - 'X' => 10, - 'V' => 5, - 'I' => 1, - ]; - - $numeral = array_shift($roman); - if (!isset($lookup[$numeral])) { - throw new Exception('Invalid character detected'); - } - - $arabic = $lookup[$numeral]; - if (count($roman) > 0 && isset($lookup[$roman[0]]) && $arabic < $lookup[$roman[0]]) { - $subtract += $arabic; - } else { - $sum += ($arabic - $subtract); - $subtract = 0; - } - - if (count($roman) > 0) { - self::calculateArabic($roman, $sum, $subtract); - } - - return $sum; + return MathTrig\Arabic::evaluate($roman); } /** @@ -134,6 +45,11 @@ class MathTrig * Excel Function: * ATAN2(xCoordinate,yCoordinate) * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Tangent::atan2() + * Use the atan2 method in the MathTrig\Trig\Tangent class instead + * * @param float $xCoordinate the x-coordinate of the point * @param float $yCoordinate the y-coordinate of the point * @@ -141,27 +57,7 @@ class MathTrig */ public static function ATAN2($xCoordinate = null, $yCoordinate = null) { - $xCoordinate = Functions::flattenSingleValue($xCoordinate); - $yCoordinate = Functions::flattenSingleValue($yCoordinate); - - $xCoordinate = ($xCoordinate !== null) ? $xCoordinate : 0.0; - $yCoordinate = ($yCoordinate !== null) ? $yCoordinate : 0.0; - - if ( - ((is_numeric($xCoordinate)) || (is_bool($xCoordinate))) && - ((is_numeric($yCoordinate))) || (is_bool($yCoordinate)) - ) { - $xCoordinate = (float) $xCoordinate; - $yCoordinate = (float) $yCoordinate; - - if (($xCoordinate == 0) && ($yCoordinate == 0)) { - return Functions::DIV0(); - } - - return atan2($yCoordinate, $xCoordinate); - } - - return Functions::VALUE(); + return MathTrig\Trig\Tangent::atan2($xCoordinate, $yCoordinate); } /** @@ -172,6 +68,11 @@ class MathTrig * Excel Function: * BASE(Number, Radix [Min_length]) * + * @Deprecated 1.18.0 + * + * @See MathTrig\Base::evaluate() + * Use the evaluate method in the MathTrig\Base class instead + * * @param float $number * @param float $radix * @param int $minLength @@ -180,29 +81,7 @@ class MathTrig */ public static function BASE($number, $radix, $minLength = null) { - $number = Functions::flattenSingleValue($number); - $radix = Functions::flattenSingleValue($radix); - $minLength = Functions::flattenSingleValue($minLength); - - if (is_numeric($number) && is_numeric($radix) && ($minLength === null || is_numeric($minLength))) { - // Truncate to an integer - $number = (int) $number; - $radix = (int) $radix; - $minLength = (int) $minLength; - - if ($number < 0 || $number >= 2 ** 53 || $radix < 2 || $radix > 36) { - return Functions::NAN(); // Numeric range constraints - } - - $outcome = strtoupper((string) base_convert($number, 10, $radix)); - if ($minLength !== null) { - $outcome = str_pad($outcome, $minLength, '0', STR_PAD_LEFT); // String padding - } - - return $outcome; - } - - return Functions::VALUE(); + return MathTrig\Base::evaluate($number, $radix, $minLength); } /** @@ -216,34 +95,19 @@ class MathTrig * Excel Function: * CEILING(number[,significance]) * + * @Deprecated 1.17.0 + * * @param float $number the number you want to round * @param float $significance the multiple to which you want to round * * @return float|string Rounded Number, or a string containing an error + * + * @see MathTrig\Ceiling::ceiling() + * Use the ceiling() method in the MathTrig\Ceiling class instead */ public static function CEILING($number, $significance = null) { - $number = Functions::flattenSingleValue($number); - $significance = Functions::flattenSingleValue($significance); - - if ( - ($significance === null) && - (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) - ) { - $significance = $number / abs($number); - } - - if ((is_numeric($number)) && (is_numeric($significance))) { - if (($number == 0.0) || ($significance == 0.0)) { - return 0.0; - } elseif (self::SIGN($number) == self::SIGN($significance)) { - return ceil($number / $significance) * $significance; - } - - return Functions::NAN(); - } - - return Functions::VALUE(); + return MathTrig\Ceiling::ceiling($number, $significance); } /** @@ -255,27 +119,19 @@ class MathTrig * Excel Function: * COMBIN(numObjs,numInSet) * + * @Deprecated 1.18.0 + * + * @see MathTrig\Combinations::withoutRepetition() + * Use the withoutRepetition() method in the MathTrig\Combinations class instead + * * @param int $numObjs Number of different objects * @param int $numInSet Number of objects in each combination * - * @return int|string Number of combinations, or a string containing an error + * @return float|int|string Number of combinations, or a string containing an error */ public static function COMBIN($numObjs, $numInSet) { - $numObjs = Functions::flattenSingleValue($numObjs); - $numInSet = Functions::flattenSingleValue($numInSet); - - if ((is_numeric($numObjs)) && (is_numeric($numInSet))) { - if ($numObjs < $numInSet) { - return Functions::NAN(); - } elseif ($numInSet < 0) { - return Functions::NAN(); - } - - return round(self::FACT($numObjs) / self::FACT($numObjs - $numInSet)) / self::FACT($numInSet); - } - - return Functions::VALUE(); + return MathTrig\Combinations::withoutRepetition($numObjs, $numInSet); } /** @@ -290,27 +146,31 @@ class MathTrig * Excel Function: * EVEN(number) * + * @Deprecated 1.18.0 + * + * @see MathTrig\Round::even() + * Use the even() method in the MathTrig\Round class instead + * * @param float $number Number to round * - * @return int|string Rounded Number, or a string containing an error + * @return float|int|string Rounded Number, or a string containing an error */ public static function EVEN($number) { - $number = Functions::flattenSingleValue($number); + return MathTrig\Round::even($number); + } - if ($number === null) { - return 0; - } elseif (is_bool($number)) { - $number = (int) $number; - } - - if (is_numeric($number)) { - $significance = 2 * self::SIGN($number); - - return (int) self::CEILING($number, $significance); - } - - return Functions::VALUE(); + /** + * Helper function for Even. + * + * @Deprecated 1.18.0 + * + * @see MathTrig\Helpers::getEven() + * Use the evaluate() method in the MathTrig\Helpers class instead + */ + public static function getEven(float $number): int + { + return (int) MathTrig\Helpers::getEven($number); } /** @@ -322,35 +182,18 @@ class MathTrig * Excel Function: * FACT(factVal) * + * @Deprecated 1.18.0 + * * @param float $factVal Factorial Value * - * @return int|string Factorial, or a string containing an error + * @return float|int|string Factorial, or a string containing an error + * + *@see MathTrig\Factorial::fact() + * Use the fact() method in the MathTrig\Factorial class instead */ public static function FACT($factVal) { - $factVal = Functions::flattenSingleValue($factVal); - - if (is_numeric($factVal)) { - if ($factVal < 0) { - return Functions::NAN(); - } - $factLoop = floor($factVal); - if ( - (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) && - ($factVal > $factLoop) - ) { - return Functions::NAN(); - } - - $factorial = 1; - while ($factLoop > 1) { - $factorial *= $factLoop--; - } - - return $factorial; - } - - return Functions::VALUE(); + return MathTrig\Factorial::fact($factVal); } /** @@ -361,29 +204,18 @@ class MathTrig * Excel Function: * FACTDOUBLE(factVal) * + * @Deprecated 1.18.0 + * * @param float $factVal Factorial Value * - * @return int|string Double Factorial, or a string containing an error + * @return float|int|string Double Factorial, or a string containing an error + * + *@see MathTrig\Factorial::factDouble() + * Use the factDouble() method in the MathTrig\Factorial class instead */ public static function FACTDOUBLE($factVal) { - $factLoop = Functions::flattenSingleValue($factVal); - - if (is_numeric($factLoop)) { - $factLoop = floor($factLoop); - if ($factVal < 0) { - return Functions::NAN(); - } - $factorial = 1; - while ($factLoop > 1) { - $factorial *= $factLoop--; - --$factLoop; - } - - return $factorial; - } - - return Functions::VALUE(); + return MathTrig\Factorial::factDouble($factVal); } /** @@ -394,38 +226,19 @@ class MathTrig * Excel Function: * FLOOR(number[,significance]) * + * @Deprecated 1.17.0 + * * @param float $number Number to round * @param float $significance Significance * * @return float|string Rounded Number, or a string containing an error + * + *@see MathTrig\Floor::floor() + * Use the floor() method in the MathTrig\Floor class instead */ public static function FLOOR($number, $significance = null) { - $number = Functions::flattenSingleValue($number); - $significance = Functions::flattenSingleValue($significance); - - if ( - ($significance === null) && - (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) - ) { - $significance = $number / abs($number); - } - - if ((is_numeric($number)) && (is_numeric($significance))) { - if ($significance == 0.0) { - return Functions::DIV0(); - } elseif ($number == 0.0) { - return 0.0; - } elseif (self::SIGN($significance) == 1) { - return floor($number / $significance) * $significance; - } elseif (self::SIGN($number) == -1 && self::SIGN($significance) == -1) { - return floor($number / $significance) * $significance; - } - - return Functions::NAN(); - } - - return Functions::VALUE(); + return MathTrig\Floor::floor($number, $significance); } /** @@ -436,35 +249,20 @@ class MathTrig * Excel Function: * FLOOR.MATH(number[,significance[,mode]]) * + * @Deprecated 1.17.0 + * * @param float $number Number to round * @param float $significance Significance * @param int $mode direction to round negative numbers * * @return float|string Rounded Number, or a string containing an error + * + *@see MathTrig\Floor::math() + * Use the math() method in the MathTrig\Floor class instead */ public static function FLOORMATH($number, $significance = null, $mode = 0) { - $number = Functions::flattenSingleValue($number); - $significance = Functions::flattenSingleValue($significance); - $mode = Functions::flattenSingleValue($mode); - - if (is_numeric($number) && $significance === null) { - $significance = $number / abs($number); - } - - if (is_numeric($number) && is_numeric($significance) && is_numeric($mode)) { - if ($significance == 0.0) { - return Functions::DIV0(); - } elseif ($number == 0.0) { - return 0.0; - } elseif (self::SIGN($significance) == -1 || (self::SIGN($number) == -1 && !empty($mode))) { - return ceil($number / $significance) * $significance; - } - - return floor($number / $significance) * $significance; - } - - return Functions::VALUE(); + return MathTrig\Floor::math($number, $significance, $mode); } /** @@ -475,32 +273,41 @@ class MathTrig * Excel Function: * FLOOR.PRECISE(number[,significance]) * + * @Deprecated 1.17.0 + * * @param float $number Number to round * @param float $significance Significance * * @return float|string Rounded Number, or a string containing an error + * + *@see MathTrig\Floor::precise() + * Use the precise() method in the MathTrig\Floor class instead */ public static function FLOORPRECISE($number, $significance = 1) { - $number = Functions::flattenSingleValue($number); - $significance = Functions::flattenSingleValue($significance); - - if ((is_numeric($number)) && (is_numeric($significance))) { - if ($significance == 0.0) { - return Functions::DIV0(); - } elseif ($number == 0.0) { - return 0.0; - } - - return floor($number / abs($significance)) * abs($significance); - } - - return Functions::VALUE(); + return MathTrig\Floor::precise($number, $significance); } - private static function evaluateGCD($a, $b) + /** + * INT. + * + * Casts a floating point value to an integer + * + * Excel Function: + * INT(number) + * + * @Deprecated 1.17.0 + * + * @see MathTrig\IntClass::evaluate() + * Use the evaluate() method in the MathTrig\IntClass class instead + * + * @param float $number Number to cast to an integer + * + * @return int|string Integer value, or a string containing an error + */ + public static function INT($number) { - return $b ? self::evaluateGCD($b, $a % $b) : $a; + return MathTrig\IntClass::evaluate($number); } /** @@ -513,56 +320,18 @@ class MathTrig * Excel Function: * GCD(number1[,number2[, ...]]) * + * @Deprecated 1.18.0 + * + * @see MathTrig\Gcd::evaluate() + * Use the evaluate() method in the MathTrig\Gcd class instead + * * @param mixed ...$args Data values * * @return int|mixed|string Greatest Common Divisor, or a string containing an error */ public static function GCD(...$args) { - $args = Functions::flattenArray($args); - // Loop through arguments - foreach (Functions::flattenArray($args) as $value) { - if (!is_numeric($value)) { - return Functions::VALUE(); - } elseif ($value < 0) { - return Functions::NAN(); - } - } - - $gcd = (int) array_pop($args); - do { - $gcd = self::evaluateGCD($gcd, (int) array_pop($args)); - } while (!empty($args)); - - return $gcd; - } - - /** - * INT. - * - * Casts a floating point value to an integer - * - * Excel Function: - * INT(number) - * - * @param float $number Number to cast to an integer - * - * @return int|string Integer value, or a string containing an error - */ - public static function INT($number) - { - $number = Functions::flattenSingleValue($number); - - if ($number === null) { - return 0; - } elseif (is_bool($number)) { - return (int) $number; - } - if (is_numeric($number)) { - return (int) floor($number); - } - - return Functions::VALUE(); + return MathTrig\Gcd::evaluate(...$args); } /** @@ -576,45 +345,18 @@ class MathTrig * Excel Function: * LCM(number1[,number2[, ...]]) * + * @Deprecated 1.18.0 + * + * @see MathTrig\Lcm::evaluate() + * Use the evaluate() method in the MathTrig\Lcm class instead + * * @param mixed ...$args Data values * * @return int|string Lowest Common Multiplier, or a string containing an error */ public static function LCM(...$args) { - $returnValue = 1; - $allPoweredFactors = []; - // Loop through arguments - foreach (Functions::flattenArray($args) as $value) { - if (!is_numeric($value)) { - return Functions::VALUE(); - } - if ($value == 0) { - return 0; - } elseif ($value < 0) { - return Functions::NAN(); - } - $myFactors = self::factors(floor($value)); - $myCountedFactors = array_count_values($myFactors); - $myPoweredFactors = []; - foreach ($myCountedFactors as $myCountedFactor => $myCountedPower) { - $myPoweredFactors[$myCountedFactor] = $myCountedFactor ** $myCountedPower; - } - foreach ($myPoweredFactors as $myPoweredValue => $myPoweredFactor) { - if (isset($allPoweredFactors[$myPoweredValue])) { - if ($allPoweredFactors[$myPoweredValue] < $myPoweredFactor) { - $allPoweredFactors[$myPoweredValue] = $myPoweredFactor; - } - } else { - $allPoweredFactors[$myPoweredValue] = $myPoweredFactor; - } - } - } - foreach ($allPoweredFactors as $allPoweredFactor) { - $returnValue *= (int) $allPoweredFactor; - } - - return $returnValue; + return MathTrig\Lcm::evaluate(...$args); } /** @@ -625,24 +367,19 @@ class MathTrig * Excel Function: * LOG(number[,base]) * + * @Deprecated 1.18.0 + * + * @see MathTrig\Logarithms::withBase() + * Use the withBase() method in the MathTrig\Logarithms class instead + * * @param float $number The positive real number for which you want the logarithm * @param float $base The base of the logarithm. If base is omitted, it is assumed to be 10. * * @return float|string The result, or a string containing an error */ - public static function logBase($number = null, $base = 10) + public static function logBase($number, $base = 10) { - $number = Functions::flattenSingleValue($number); - $base = ($base === null) ? 10 : (float) Functions::flattenSingleValue($base); - - if ((!is_numeric($base)) || (!is_numeric($number))) { - return Functions::VALUE(); - } - if (($base <= 0) || ($number <= 0)) { - return Functions::NAN(); - } - - return log($number, $base); + return MathTrig\Logarithms::withBase($number, $base); } /** @@ -653,46 +390,18 @@ class MathTrig * Excel Function: * MDETERM(array) * + * @Deprecated 1.18.0 + * + * @see MathTrig\MatrixFunctions::determinant() + * Use the determinant() method in the MathTrig\MatrixFunctions class instead + * * @param array $matrixValues A matrix of values * * @return float|string The result, or a string containing an error */ public static function MDETERM($matrixValues) { - $matrixData = []; - if (!is_array($matrixValues)) { - $matrixValues = [[$matrixValues]]; - } - - $row = $maxColumn = 0; - foreach ($matrixValues as $matrixRow) { - if (!is_array($matrixRow)) { - $matrixRow = [$matrixRow]; - } - $column = 0; - foreach ($matrixRow as $matrixCell) { - if ((is_string($matrixCell)) || ($matrixCell === null)) { - return Functions::VALUE(); - } - $matrixData[$row][$column] = $matrixCell; - ++$column; - } - if ($column > $maxColumn) { - $maxColumn = $column; - } - ++$row; - } - - $matrix = new Matrix($matrixData); - if (!$matrix->isSquare()) { - return Functions::VALUE(); - } - - try { - return $matrix->determinant(); - } catch (MatrixException $ex) { - return Functions::VALUE(); - } + return MathTrig\MatrixFunctions::determinant($matrixValues); } /** @@ -703,55 +412,28 @@ class MathTrig * Excel Function: * MINVERSE(array) * + * @Deprecated 1.18.0 + * + * @see MathTrig\MatrixFunctions::inverse() + * Use the inverse() method in the MathTrig\MatrixFunctions class instead + * * @param array $matrixValues A matrix of values * * @return array|string The result, or a string containing an error */ public static function MINVERSE($matrixValues) { - $matrixData = []; - if (!is_array($matrixValues)) { - $matrixValues = [[$matrixValues]]; - } - - $row = $maxColumn = 0; - foreach ($matrixValues as $matrixRow) { - if (!is_array($matrixRow)) { - $matrixRow = [$matrixRow]; - } - $column = 0; - foreach ($matrixRow as $matrixCell) { - if ((is_string($matrixCell)) || ($matrixCell === null)) { - return Functions::VALUE(); - } - $matrixData[$row][$column] = $matrixCell; - ++$column; - } - if ($column > $maxColumn) { - $maxColumn = $column; - } - ++$row; - } - - $matrix = new Matrix($matrixData); - if (!$matrix->isSquare()) { - return Functions::VALUE(); - } - - if ($matrix->determinant() == 0.0) { - return Functions::NAN(); - } - - try { - return $matrix->inverse()->toArray(); - } catch (MatrixException $ex) { - return Functions::VALUE(); - } + return MathTrig\MatrixFunctions::inverse($matrixValues); } /** * MMULT. * + * @Deprecated 1.18.0 + * + * @see MathTrig\MatrixFunctions::multiply() + * Use the multiply() method in the MathTrig\MatrixFunctions class instead + * * @param array $matrixData1 A matrix of values * @param array $matrixData2 A matrix of values * @@ -759,80 +441,25 @@ class MathTrig */ public static function MMULT($matrixData1, $matrixData2) { - $matrixAData = $matrixBData = []; - if (!is_array($matrixData1)) { - $matrixData1 = [[$matrixData1]]; - } - if (!is_array($matrixData2)) { - $matrixData2 = [[$matrixData2]]; - } - - try { - $rowA = 0; - foreach ($matrixData1 as $matrixRow) { - if (!is_array($matrixRow)) { - $matrixRow = [$matrixRow]; - } - $columnA = 0; - foreach ($matrixRow as $matrixCell) { - if ((!is_numeric($matrixCell)) || ($matrixCell === null)) { - return Functions::VALUE(); - } - $matrixAData[$rowA][$columnA] = $matrixCell; - ++$columnA; - } - ++$rowA; - } - $matrixA = new Matrix($matrixAData); - $rowB = 0; - foreach ($matrixData2 as $matrixRow) { - if (!is_array($matrixRow)) { - $matrixRow = [$matrixRow]; - } - $columnB = 0; - foreach ($matrixRow as $matrixCell) { - if ((!is_numeric($matrixCell)) || ($matrixCell === null)) { - return Functions::VALUE(); - } - $matrixBData[$rowB][$columnB] = $matrixCell; - ++$columnB; - } - ++$rowB; - } - $matrixB = new Matrix($matrixBData); - - if ($columnA != $rowB) { - return Functions::VALUE(); - } - - return $matrixA->multiply($matrixB)->toArray(); - } catch (MatrixException $ex) { - return Functions::VALUE(); - } + return MathTrig\MatrixFunctions::multiply($matrixData1, $matrixData2); } /** * MOD. * + * @Deprecated 1.18.0 + * + * @see MathTrig\Operations::mod() + * Use the mod() method in the MathTrig\Operations class instead + * * @param int $a Dividend * @param int $b Divisor * - * @return int|string Remainder, or a string containing an error + * @return float|int|string Remainder, or a string containing an error */ public static function MOD($a = 1, $b = 1) { - $a = (float) Functions::flattenSingleValue($a); - $b = (float) Functions::flattenSingleValue($b); - - if ($b == 0.0) { - return Functions::DIV0(); - } elseif (($a < 0.0) && ($b > 0.0)) { - return $b - fmod(abs($a), $b); - } elseif (($a > 0.0) && ($b < 0.0)) { - return $b + fmod($a, abs($b)); - } - - return fmod($a, $b); + return MathTrig\Operations::mod($a, $b); } /** @@ -840,30 +467,19 @@ class MathTrig * * Rounds a number to the nearest multiple of a specified value * + * @Deprecated 1.17.0 + * * @param float $number Number to round * @param int $multiple Multiple to which you want to round $number * * @return float|string Rounded Number, or a string containing an error + * + *@see MathTrig\Round::multiple() + * Use the multiple() method in the MathTrig\Mround class instead */ public static function MROUND($number, $multiple) { - $number = Functions::flattenSingleValue($number); - $multiple = Functions::flattenSingleValue($multiple); - - if ((is_numeric($number)) && (is_numeric($multiple))) { - if ($multiple == 0) { - return 0; - } - if ((self::SIGN($number)) == (self::SIGN($multiple))) { - $multiplier = 1 / $multiple; - - return round($number * $multiplier) / $multiplier; - } - - return Functions::NAN(); - } - - return Functions::VALUE(); + return MathTrig\Round::multiple($number, $multiple); } /** @@ -871,36 +487,18 @@ class MathTrig * * Returns the ratio of the factorial of a sum of values to the product of factorials. * + * @Deprecated 1.18.0 + * + * @See MathTrig\Factorial::multinomial() + * Use the multinomial method in the MathTrig\Factorial class instead + * * @param mixed[] $args An array of mixed values for the Data Series * * @return float|string The result, or a string containing an error */ public static function MULTINOMIAL(...$args) { - $summer = 0; - $divisor = 1; - // Loop through arguments - foreach (Functions::flattenArray($args) as $arg) { - // Is it a numeric value? - if (is_numeric($arg)) { - if ($arg < 1) { - return Functions::NAN(); - } - $summer += floor($arg); - $divisor *= self::FACT($arg); - } else { - return Functions::VALUE(); - } - } - - // Return - if ($summer > 0) { - $summer = self::FACT($summer); - - return $summer / $divisor; - } - - return 0; + return MathTrig\Factorial::multinomial(...$args); } /** @@ -908,33 +506,18 @@ class MathTrig * * Returns number rounded up to the nearest odd integer. * + * @Deprecated 1.18.0 + * + * @See MathTrig\Round::odd() + * Use the odd method in the MathTrig\Round class instead + * * @param float $number Number to round * - * @return int|string Rounded Number, or a string containing an error + * @return float|int|string Rounded Number, or a string containing an error */ public static function ODD($number) { - $number = Functions::flattenSingleValue($number); - - if ($number === null) { - return 1; - } elseif (is_bool($number)) { - return 1; - } elseif (is_numeric($number)) { - $significance = self::SIGN($number); - if ($significance == 0) { - return 1; - } - - $result = self::CEILING($number, $significance); - if ($result == self::EVEN($result)) { - $result += $significance; - } - - return (int) $result; - } - - return Functions::VALUE(); + return MathTrig\Round::odd($number); } /** @@ -942,27 +525,19 @@ class MathTrig * * Computes x raised to the power y. * + * @Deprecated 1.18.0 + * + * @See MathTrig\Operations::power() + * Use the evaluate method in the MathTrig\Power class instead + * * @param float $x * @param float $y * - * @return float|string The result, or a string containing an error + * @return float|int|string The result, or a string containing an error */ public static function POWER($x = 0, $y = 2) { - $x = Functions::flattenSingleValue($x); - $y = Functions::flattenSingleValue($y); - - // Validate parameters - if ($x == 0.0 && $y == 0.0) { - return Functions::NAN(); - } elseif ($x == 0.0 && $y < 0.0) { - return Functions::DIV0(); - } - - // Return - $result = $x ** $y; - - return (!is_nan($result) && !is_infinite($result)) ? $result : Functions::NAN(); + return MathTrig\Operations::power($x, $y); } /** @@ -970,36 +545,21 @@ class MathTrig * * PRODUCT returns the product of all the values and cells referenced in the argument list. * + * @Deprecated 1.18.0 + * + * @See MathTrig\Operations::product() + * Use the product method in the MathTrig\Operations class instead + * * Excel Function: * PRODUCT(value1[,value2[, ...]]) * * @param mixed ...$args Data values * - * @return float + * @return float|string */ public static function PRODUCT(...$args) { - // Return value - $returnValue = null; - - // Loop through arguments - foreach (Functions::flattenArray($args) as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - if ($returnValue === null) { - $returnValue = $arg; - } else { - $returnValue *= $arg; - } - } - } - - // Return - if ($returnValue === null) { - return 0; - } - - return $returnValue; + return MathTrig\Operations::product(...$args); } /** @@ -1008,88 +568,60 @@ class MathTrig * QUOTIENT function returns the integer portion of a division. Numerator is the divided number * and denominator is the divisor. * + * @Deprecated 1.18.0 + * + * @See MathTrig\Operations::quotient() + * Use the quotient method in the MathTrig\Operations class instead + * * Excel Function: * QUOTIENT(value1[,value2[, ...]]) * - * @param mixed ...$args Data values + * @param mixed $numerator + * @param mixed $denominator * - * @return float + * @return int|string */ - public static function QUOTIENT(...$args) + public static function QUOTIENT($numerator, $denominator) { - // Return value - $returnValue = null; - - // Loop through arguments - foreach (Functions::flattenArray($args) as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - if ($returnValue === null) { - $returnValue = ($arg == 0) ? 0 : $arg; - } else { - if (($returnValue == 0) || ($arg == 0)) { - $returnValue = 0; - } else { - $returnValue /= $arg; - } - } - } - } - - // Return - return (int) $returnValue; + return MathTrig\Operations::quotient($numerator, $denominator); } /** - * RAND. + * RAND/RANDBETWEEN. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Random::randBetween() + * Use the randBetween or randBetween method in the MathTrig\Random class instead * * @param int $min Minimal value * @param int $max Maximal value * - * @return int Random number + * @return float|int|string Random number */ public static function RAND($min = 0, $max = 0) { - $min = Functions::flattenSingleValue($min); - $max = Functions::flattenSingleValue($max); - - if ($min == 0 && $max == 0) { - return (mt_rand(0, 10000000)) / 10000000; - } - - return mt_rand($min, $max); + return MathTrig\Random::randBetween($min, $max); } + /** + * ROMAN. + * + * Converts a number to Roman numeral + * + * @Deprecated 1.17.0 + * + * @Ssee MathTrig\Roman::evaluate() + * Use the evaluate() method in the MathTrig\Roman class instead + * + * @param mixed $aValue Number to convert + * @param mixed $style Number indicating one of five possible forms + * + * @return string Roman numeral, or a string containing an error + */ public static function ROMAN($aValue, $style = 0) { - $aValue = Functions::flattenSingleValue($aValue); - $style = ($style === null) ? 0 : (int) Functions::flattenSingleValue($style); - if ((!is_numeric($aValue)) || ($aValue < 0) || ($aValue >= 4000)) { - return Functions::VALUE(); - } - $aValue = (int) $aValue; - if ($aValue == 0) { - return ''; - } - - $mill = ['', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM']; - $cent = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM']; - $tens = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC']; - $ones = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']; - - $roman = ''; - while ($aValue > 5999) { - $roman .= 'M'; - $aValue -= 1000; - } - $m = self::romanCut($aValue, 1000); - $aValue %= 1000; - $c = self::romanCut($aValue, 100); - $aValue %= 100; - $t = self::romanCut($aValue, 10); - $aValue %= 10; - - return $roman . $mill[$m] . $cent[$c] . $tens[$t] . $ones[$aValue]; + return MathTrig\Roman::evaluate($aValue, $style); } /** @@ -1097,6 +629,11 @@ class MathTrig * * Rounds a number up to a specified number of decimal places * + * @Deprecated 1.17.0 + * + * @See MathTrig\Round::up() + * Use the up() method in the MathTrig\Round class instead + * * @param float $number Number to round * @param int $digits Number of digits to which you want to round $number * @@ -1104,22 +641,7 @@ class MathTrig */ public static function ROUNDUP($number, $digits) { - $number = Functions::flattenSingleValue($number); - $digits = Functions::flattenSingleValue($digits); - - if ((is_numeric($number)) && (is_numeric($digits))) { - if ($number == 0.0) { - return 0.0; - } - - if ($number < 0.0) { - return round($number - 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_DOWN); - } - - return round($number + 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_DOWN); - } - - return Functions::VALUE(); + return MathTrig\Round::up($number, $digits); } /** @@ -1127,6 +649,11 @@ class MathTrig * * Rounds a number down to a specified number of decimal places * + * @Deprecated 1.17.0 + * + * @See MathTrig\Round::down() + * Use the down() method in the MathTrig\Round class instead + * * @param float $number Number to round * @param int $digits Number of digits to which you want to round $number * @@ -1134,22 +661,7 @@ class MathTrig */ public static function ROUNDDOWN($number, $digits) { - $number = Functions::flattenSingleValue($number); - $digits = Functions::flattenSingleValue($digits); - - if ((is_numeric($number)) && (is_numeric($digits))) { - if ($number == 0.0) { - return 0.0; - } - - if ($number < 0.0) { - return round($number + 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_UP); - } - - return round($number - 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_UP); - } - - return Functions::VALUE(); + return MathTrig\Round::down($number, $digits); } /** @@ -1157,37 +669,21 @@ class MathTrig * * Returns the sum of a power series * - * @param mixed[] $args An array of mixed values for the Data Series + * @Deprecated 1.18.0 + * + * @See MathTrig\SeriesSum::evaluate() + * Use the evaluate method in the MathTrig\SeriesSum class instead + * + * @param mixed $x Input value + * @param mixed $n Initial power + * @param mixed $m Step + * @param mixed[] $args An array of coefficients for the Data Series * * @return float|string The result, or a string containing an error */ - public static function SERIESSUM(...$args) + public static function SERIESSUM($x, $n, $m, ...$args) { - $returnValue = 0; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - - $x = array_shift($aArgs); - $n = array_shift($aArgs); - $m = array_shift($aArgs); - - if ((is_numeric($x)) && (is_numeric($n)) && (is_numeric($m))) { - // Calculate - $i = 0; - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $returnValue += $arg * $x ** ($n + ($m * $i++)); - } else { - return Functions::VALUE(); - } - } - - return $returnValue; - } - - return Functions::VALUE(); + return MathTrig\SeriesSum::evaluate($x, $n, $m, ...$args); } /** @@ -1196,26 +692,31 @@ class MathTrig * Determines the sign of a number. Returns 1 if the number is positive, zero (0) * if the number is 0, and -1 if the number is negative. * + * @Deprecated 1.18.0 + * + * @See MathTrig\Sign::evaluate() + * Use the evaluate method in the MathTrig\Sign class instead + * * @param float $number Number to round * * @return int|string sign value, or a string containing an error */ public static function SIGN($number) { - $number = Functions::flattenSingleValue($number); + return MathTrig\Sign::evaluate($number); + } - if (is_bool($number)) { - return (int) $number; - } - if (is_numeric($number)) { - if ($number == 0.0) { - return 0; - } - - return $number / abs($number); - } - - return Functions::VALUE(); + /** + * returnSign = returns 0/-1/+1. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Helpers::returnSign() + * Use the returnSign method in the MathTrig\Helpers class instead + */ + public static function returnSign(float $number): int + { + return MathTrig\Helpers::returnSign($number); } /** @@ -1223,57 +724,18 @@ class MathTrig * * Returns the square root of (number * pi). * + * @Deprecated 1.18.0 + * + * @See MathTrig\Sqrt::sqrt() + * Use the pi method in the MathTrig\Sqrt class instead + * * @param float $number Number * * @return float|string Square Root of Number * Pi, or a string containing an error */ public static function SQRTPI($number) { - $number = Functions::flattenSingleValue($number); - - if (is_numeric($number)) { - if ($number < 0) { - return Functions::NAN(); - } - - return sqrt($number * M_PI); - } - - return Functions::VALUE(); - } - - protected static function filterHiddenArgs($cellReference, $args) - { - return array_filter( - $args, - function ($index) use ($cellReference) { - [, $row, $column] = explode('.', $index); - - return $cellReference->getWorksheet()->getRowDimension($row)->getVisible() && - $cellReference->getWorksheet()->getColumnDimension($column)->getVisible(); - }, - ARRAY_FILTER_USE_KEY - ); - } - - protected static function filterFormulaArgs($cellReference, $args) - { - return array_filter( - $args, - function ($index) use ($cellReference) { - [, $row, $column] = explode('.', $index); - if ($cellReference->getWorksheet()->cellExists($column . $row)) { - //take this cell out if it contains the SUBTOTAL or AGGREGATE functions in a formula - $isFormula = $cellReference->getWorksheet()->getCell($column . $row)->isFormula(); - $cellFormula = !preg_match('/^=.*\b(SUBTOTAL|AGGREGATE)\s*\(/i', $cellReference->getWorksheet()->getCell($column . $row)->getValue()); - - return !$isFormula || $cellFormula; - } - - return true; - }, - ARRAY_FILTER_USE_KEY - ); + return MathTrig\Sqrt::pi($number); } /** @@ -1281,6 +743,11 @@ class MathTrig * * Returns a subtotal in a list or database. * + * @Deprecated 1.18.0 + * + * @See MathTrig\Subtotal::evaluate() + * Use the evaluate method in the MathTrig\Subtotal class instead + * * @param int $functionType * A number 1 to 11 that specifies which function to * use in calculating subtotals within a range @@ -1294,45 +761,7 @@ class MathTrig */ public static function SUBTOTAL($functionType, ...$args) { - $cellReference = array_pop($args); - $aArgs = Functions::flattenArrayIndexed($args); - $subtotal = Functions::flattenSingleValue($functionType); - - // Calculate - if ((is_numeric($subtotal)) && (!is_string($subtotal))) { - if ($subtotal > 100) { - $aArgs = self::filterHiddenArgs($cellReference, $aArgs); - $subtotal -= 100; - } - - $aArgs = self::filterFormulaArgs($cellReference, $aArgs); - switch ($subtotal) { - case 1: - return Statistical::AVERAGE($aArgs); - case 2: - return Statistical::COUNT($aArgs); - case 3: - return Statistical::COUNTA($aArgs); - case 4: - return Statistical::MAX($aArgs); - case 5: - return Statistical::MIN($aArgs); - case 6: - return self::PRODUCT($aArgs); - case 7: - return Statistical::STDEV($aArgs); - case 8: - return Statistical::STDEVP($aArgs); - case 9: - return self::SUM($aArgs); - case 10: - return Statistical::VARFunc($aArgs); - case 11: - return Statistical::VARP($aArgs); - } - } - - return Functions::VALUE(); + return MathTrig\Subtotal::evaluate($functionType, ...$args); } /** @@ -1340,131 +769,67 @@ class MathTrig * * SUM computes the sum of all the values and cells referenced in the argument list. * + * @Deprecated 1.18.0 + * + * @See MathTrig\Sum::sumErroringStrings() + * Use the sumErroringStrings method in the MathTrig\Sum class instead + * * Excel Function: * SUM(value1[,value2[, ...]]) * * @param mixed ...$args Data values * - * @return float + * @return float|string */ public static function SUM(...$args) { - $returnValue = 0; - - // Loop through the arguments - foreach (Functions::flattenArray($args) as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $returnValue += $arg; - } elseif (Functions::isError($arg)) { - return $arg; - } - } - - return $returnValue; + return MathTrig\Sum::sumIgnoringStrings(...$args); } /** * SUMIF. * - * Counts the number of cells that contain numbers within the list of arguments + * Totals the values of cells that contain numbers within the list of arguments * * Excel Function: - * SUMIF(value1[,value2[, ...]],condition) + * SUMIF(range, criteria, [sum_range]) * - * @param mixed $aArgs Data values - * @param string $condition the criteria that defines which cells will be summed - * @param mixed $sumArgs + * @Deprecated 1.17.0 * - * @return float + * @see Statistical\Conditional::SUMIF() + * Use the SUMIF() method in the Statistical\Conditional class instead + * + * @param mixed $range Data values + * @param string $criteria the criteria that defines which cells will be summed + * @param mixed $sumRange + * + * @return float|string */ - public static function SUMIF($aArgs, $condition, $sumArgs = []) + public static function SUMIF($range, $criteria, $sumRange = []) { - $returnValue = 0; - - $aArgs = Functions::flattenArray($aArgs); - $sumArgs = Functions::flattenArray($sumArgs); - if (empty($sumArgs)) { - $sumArgs = $aArgs; - } - $condition = Functions::ifCondition($condition); - // Loop through arguments - foreach ($aArgs as $key => $arg) { - if (!is_numeric($arg)) { - $arg = str_replace('"', '""', $arg); - $arg = Calculation::wrapResult(strtoupper($arg)); - } - - $testCondition = '=' . $arg . $condition; - $sumValue = array_key_exists($key, $sumArgs) ? $sumArgs[$key] : 0; - - if ( - is_numeric($sumValue) && - Calculation::getInstance()->_calculateFormulaValue($testCondition) - ) { - // Is it a value within our criteria and only numeric can be added to the result - $returnValue += $sumValue; - } - } - - return $returnValue; + return Statistical\Conditional::SUMIF($range, $criteria, $sumRange); } /** * SUMIFS. * - * Counts the number of cells that contain numbers within the list of arguments + * Totals the values of cells that contain numbers within the list of arguments * * Excel Function: - * SUMIFS(value1[,value2[, ...]],condition) + * SUMIFS(sum_range, criteria_range1, criteria1, [criteria_range2, criteria2], ...) + * + * @Deprecated 1.17.0 + * + * @see Statistical\Conditional::SUMIFS() + * Use the SUMIFS() method in the Statistical\Conditional class instead * * @param mixed $args Data values * - * @return float + * @return null|float|string */ public static function SUMIFS(...$args) { - $arrayList = $args; - - // Return value - $returnValue = 0; - - $sumArgs = Functions::flattenArray(array_shift($arrayList)); - $aArgsArray = []; - $conditions = []; - - while (count($arrayList) > 0) { - $aArgsArray[] = Functions::flattenArray(array_shift($arrayList)); - $conditions[] = Functions::ifCondition(array_shift($arrayList)); - } - - // Loop through each sum and see if arguments and conditions are true - foreach ($sumArgs as $index => $value) { - $valid = true; - - foreach ($conditions as $cidx => $condition) { - $arg = $aArgsArray[$cidx][$index]; - - // Loop through arguments - if (!is_numeric($arg)) { - $arg = Calculation::wrapResult(strtoupper($arg)); - } - $testCondition = '=' . $arg . $condition; - if (!Calculation::getInstance()->_calculateFormulaValue($testCondition)) { - // Is not a value within our criteria - $valid = false; - - break; // if false found, don't need to check other conditions - } - } - - if ($valid) { - $returnValue += $value; - } - } - - // Return - return $returnValue; + return Statistical\Conditional::SUMIFS(...$args); } /** @@ -1473,39 +838,18 @@ class MathTrig * Excel Function: * SUMPRODUCT(value1[,value2[, ...]]) * + * @Deprecated 1.18.0 + * + * @See MathTrig\Sum::product() + * Use the product method in the MathTrig\Sum class instead + * * @param mixed ...$args Data values * * @return float|string The result, or a string containing an error */ public static function SUMPRODUCT(...$args) { - $arrayList = $args; - - $wrkArray = Functions::flattenArray(array_shift($arrayList)); - $wrkCellCount = count($wrkArray); - - for ($i = 0; $i < $wrkCellCount; ++$i) { - if ((!is_numeric($wrkArray[$i])) || (is_string($wrkArray[$i]))) { - $wrkArray[$i] = 0; - } - } - - foreach ($arrayList as $matrixData) { - $array2 = Functions::flattenArray($matrixData); - $count = count($array2); - if ($wrkCellCount != $count) { - return Functions::VALUE(); - } - - foreach ($array2 as $i => $val) { - if ((!is_numeric($val)) || (is_string($val))) { - $val = 0; - } - $wrkArray[$i] *= $val; - } - } - - return array_sum($wrkArray); + return MathTrig\Sum::product(...$args); } /** @@ -1513,107 +857,75 @@ class MathTrig * * SUMSQ returns the sum of the squares of the arguments * + * @Deprecated 1.18.0 + * + * @See MathTrig\SumSquares::sumSquare() + * Use the sumSquare method in the MathTrig\SumSquares class instead + * * Excel Function: * SUMSQ(value1[,value2[, ...]]) * * @param mixed ...$args Data values * - * @return float + * @return float|string */ public static function SUMSQ(...$args) { - $returnValue = 0; - - // Loop through arguments - foreach (Functions::flattenArray($args) as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $returnValue += ($arg * $arg); - } - } - - return $returnValue; + return MathTrig\SumSquares::sumSquare(...$args); } /** * SUMX2MY2. * + * @Deprecated 1.18.0 + * + * @See MathTrig\SumSquares::sumXSquaredMinusYSquared() + * Use the sumXSquaredMinusYSquared method in the MathTrig\SumSquares class instead + * * @param mixed[] $matrixData1 Matrix #1 * @param mixed[] $matrixData2 Matrix #2 * - * @return float + * @return float|string */ public static function SUMX2MY2($matrixData1, $matrixData2) { - $array1 = Functions::flattenArray($matrixData1); - $array2 = Functions::flattenArray($matrixData2); - $count = min(count($array1), count($array2)); - - $result = 0; - for ($i = 0; $i < $count; ++$i) { - if ( - ((is_numeric($array1[$i])) && (!is_string($array1[$i]))) && - ((is_numeric($array2[$i])) && (!is_string($array2[$i]))) - ) { - $result += ($array1[$i] * $array1[$i]) - ($array2[$i] * $array2[$i]); - } - } - - return $result; + return MathTrig\SumSquares::sumXSquaredMinusYSquared($matrixData1, $matrixData2); } /** * SUMX2PY2. * + * @Deprecated 1.18.0 + * + * @See MathTrig\SumSquares::sumXSquaredPlusYSquared() + * Use the sumXSquaredPlusYSquared method in the MathTrig\SumSquares class instead + * * @param mixed[] $matrixData1 Matrix #1 * @param mixed[] $matrixData2 Matrix #2 * - * @return float + * @return float|string */ public static function SUMX2PY2($matrixData1, $matrixData2) { - $array1 = Functions::flattenArray($matrixData1); - $array2 = Functions::flattenArray($matrixData2); - $count = min(count($array1), count($array2)); - - $result = 0; - for ($i = 0; $i < $count; ++$i) { - if ( - ((is_numeric($array1[$i])) && (!is_string($array1[$i]))) && - ((is_numeric($array2[$i])) && (!is_string($array2[$i]))) - ) { - $result += ($array1[$i] * $array1[$i]) + ($array2[$i] * $array2[$i]); - } - } - - return $result; + return MathTrig\SumSquares::sumXSquaredPlusYSquared($matrixData1, $matrixData2); } /** * SUMXMY2. * + * @Deprecated 1.18.0 + * + * @See MathTrig\SumSquares::sumXMinusYSquared() + * Use the sumXMinusYSquared method in the MathTrig\SumSquares class instead + * * @param mixed[] $matrixData1 Matrix #1 * @param mixed[] $matrixData2 Matrix #2 * - * @return float + * @return float|string */ public static function SUMXMY2($matrixData1, $matrixData2) { - $array1 = Functions::flattenArray($matrixData1); - $array2 = Functions::flattenArray($matrixData2); - $count = min(count($array1), count($array2)); - - $result = 0; - for ($i = 0; $i < $count; ++$i) { - if ( - ((is_numeric($array1[$i])) && (!is_string($array1[$i]))) && - ((is_numeric($array2[$i])) && (!is_string($array2[$i]))) - ) { - $result += ($array1[$i] - $array2[$i]) * ($array1[$i] - $array2[$i]); - } - } - - return $result; + return MathTrig\SumSquares::sumXMinusYSquared($matrixData1, $matrixData2); } /** @@ -1621,6 +933,11 @@ class MathTrig * * Truncates value to the number of fractional digits by number_digits. * + * @Deprecated 1.17.0 + * + * @see MathTrig\Trunc::evaluate() + * Use the evaluate() method in the MathTrig\Trunc class instead + * * @param float $value * @param int $digits * @@ -1628,23 +945,7 @@ class MathTrig */ public static function TRUNC($value = 0, $digits = 0) { - $value = Functions::flattenSingleValue($value); - $digits = Functions::flattenSingleValue($digits); - - // Validate parameters - if ((!is_numeric($value)) || (!is_numeric($digits))) { - return Functions::VALUE(); - } - $digits = floor($digits); - - // Truncate - $adjust = 10 ** $digits; - - if (($digits > 0) && (rtrim((int) ((abs($value) - abs((int) $value)) * $adjust), '0') < $adjust / 10)) { - return $value; - } - - return ((int) ($value * $adjust)) / $adjust; + return MathTrig\Trunc::evaluate($value, $digits); } /** @@ -1652,21 +953,18 @@ class MathTrig * * Returns the secant of an angle. * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Secant::sec() + * Use the sec method in the MathTrig\Trig\Secant class instead + * * @param float $angle Number * * @return float|string The secant of the angle */ public static function SEC($angle) { - $angle = Functions::flattenSingleValue($angle); - - if (!is_numeric($angle)) { - return Functions::VALUE(); - } - - $result = cos($angle); - - return ($result == 0.0) ? Functions::DIV0() : 1 / $result; + return MathTrig\Trig\Secant::sec($angle); } /** @@ -1674,21 +972,18 @@ class MathTrig * * Returns the hyperbolic secant of an angle. * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Secant::sech() + * Use the sech method in the MathTrig\Trig\Secant class instead + * * @param float $angle Number * * @return float|string The hyperbolic secant of the angle */ public static function SECH($angle) { - $angle = Functions::flattenSingleValue($angle); - - if (!is_numeric($angle)) { - return Functions::VALUE(); - } - - $result = cosh($angle); - - return ($result == 0.0) ? Functions::DIV0() : 1 / $result; + return MathTrig\Trig\Secant::sech($angle); } /** @@ -1696,21 +991,18 @@ class MathTrig * * Returns the cosecant of an angle. * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Cosecant::csc() + * Use the csc method in the MathTrig\Trig\Cosecant class instead + * * @param float $angle Number * * @return float|string The cosecant of the angle */ public static function CSC($angle) { - $angle = Functions::flattenSingleValue($angle); - - if (!is_numeric($angle)) { - return Functions::VALUE(); - } - - $result = sin($angle); - - return ($result == 0.0) ? Functions::DIV0() : 1 / $result; + return MathTrig\Trig\Cosecant::csc($angle); } /** @@ -1718,21 +1010,18 @@ class MathTrig * * Returns the hyperbolic cosecant of an angle. * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Cosecant::csch() + * Use the csch method in the MathTrig\Trig\Cosecant class instead + * * @param float $angle Number * * @return float|string The hyperbolic cosecant of the angle */ public static function CSCH($angle) { - $angle = Functions::flattenSingleValue($angle); - - if (!is_numeric($angle)) { - return Functions::VALUE(); - } - - $result = sinh($angle); - - return ($result == 0.0) ? Functions::DIV0() : 1 / $result; + return MathTrig\Trig\Cosecant::csch($angle); } /** @@ -1740,21 +1029,18 @@ class MathTrig * * Returns the cotangent of an angle. * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Cotangent::cot() + * Use the cot method in the MathTrig\Trig\Cotangent class instead + * * @param float $angle Number * * @return float|string The cotangent of the angle */ public static function COT($angle) { - $angle = Functions::flattenSingleValue($angle); - - if (!is_numeric($angle)) { - return Functions::VALUE(); - } - - $result = tan($angle); - - return ($result == 0.0) ? Functions::DIV0() : 1 / $result; + return MathTrig\Trig\Cotangent::cot($angle); } /** @@ -1762,21 +1048,18 @@ class MathTrig * * Returns the hyperbolic cotangent of an angle. * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Cotangent::coth() + * Use the coth method in the MathTrig\Trig\Cotangent class instead + * * @param float $angle Number * * @return float|string The hyperbolic cotangent of the angle */ public static function COTH($angle) { - $angle = Functions::flattenSingleValue($angle); - - if (!is_numeric($angle)) { - return Functions::VALUE(); - } - - $result = tanh($angle); - - return ($result == 0.0) ? Functions::DIV0() : 1 / $result; + return MathTrig\Trig\Cotangent::coth($angle); } /** @@ -1784,19 +1067,35 @@ class MathTrig * * Returns the arccotangent of a number. * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Cotangent::acot() + * Use the acot method in the MathTrig\Trig\Cotangent class instead + * * @param float $number Number * * @return float|string The arccotangent of the number */ public static function ACOT($number) { - $number = Functions::flattenSingleValue($number); + return MathTrig\Trig\Cotangent::acot($number); + } - if (!is_numeric($number)) { - return Functions::VALUE(); - } - - return (M_PI / 2) - atan($number); + /** + * Return NAN or value depending on argument. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Helpers::numberOrNan() + * Use the numberOrNan method in the MathTrig\Helpers class instead + * + * @param float $result Number + * + * @return float|string + */ + public static function numberOrNan($result) + { + return MathTrig\Helpers::numberOrNan($result); } /** @@ -1804,20 +1103,418 @@ class MathTrig * * Returns the hyperbolic arccotangent of a number. * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Cotangent::acoth() + * Use the acoth method in the MathTrig\Trig\Cotangent class instead + * * @param float $number Number * * @return float|string The hyperbolic arccotangent of the number */ public static function ACOTH($number) + { + return MathTrig\Trig\Cotangent::acoth($number); + } + + /** + * ROUND. + * + * Returns the result of builtin function round after validating args. + * + * @Deprecated 1.17.0 + * + * @See MathTrig\Round::round() + * Use the round() method in the MathTrig\Round class instead + * + * @param mixed $number Should be numeric + * @param mixed $precision Should be int + * + * @return float|string Rounded number + */ + public static function builtinROUND($number, $precision) + { + return MathTrig\Round::round($number, $precision); + } + + /** + * ABS. + * + * Returns the result of builtin function abs after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Absolute::evaluate() + * Use the evaluate method in the MathTrig\Absolute class instead + * + * @param mixed $number Should be numeric + * + * @return float|int|string Rounded number + */ + public static function builtinABS($number) + { + return MathTrig\Absolute::evaluate($number); + } + + /** + * ACOS. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Cosine::acos() + * Use the acos method in the MathTrig\Trig\Cosine class instead + * + * Returns the result of builtin function acos after validating args. + * + * @param mixed $number Should be numeric + * + * @return float|string Rounded number + */ + public static function builtinACOS($number) + { + return MathTrig\Trig\Cosine::acos($number); + } + + /** + * ACOSH. + * + * Returns the result of builtin function acosh after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Cosine::acosh() + * Use the acosh method in the MathTrig\Trig\Cosine class instead + * + * @param mixed $number Should be numeric + * + * @return float|string Rounded number + */ + public static function builtinACOSH($number) + { + return MathTrig\Trig\Cosine::acosh($number); + } + + /** + * ASIN. + * + * Returns the result of builtin function asin after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Sine::asin() + * Use the asin method in the MathTrig\Trig\Sine class instead + * + * @param mixed $number Should be numeric + * + * @return float|string Rounded number + */ + public static function builtinASIN($number) + { + return MathTrig\Trig\Sine::asin($number); + } + + /** + * ASINH. + * + * Returns the result of builtin function asinh after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Sine::asinh() + * Use the asinh method in the MathTrig\Trig\Sine class instead + * + * @param mixed $number Should be numeric + * + * @return float|string Rounded number + */ + public static function builtinASINH($number) + { + return MathTrig\Trig\Sine::asinh($number); + } + + /** + * ATAN. + * + * Returns the result of builtin function atan after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Tangent::atan() + * Use the atan method in the MathTrig\Trig\Tangent class instead + * + * @param mixed $number Should be numeric + * + * @return float|string Rounded number + */ + public static function builtinATAN($number) + { + return MathTrig\Trig\Tangent::atan($number); + } + + /** + * ATANH. + * + * Returns the result of builtin function atanh after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Tangent::atanh() + * Use the atanh method in the MathTrig\Trig\Tangent class instead + * + * @param mixed $number Should be numeric + * + * @return float|string Rounded number + */ + public static function builtinATANH($number) + { + return MathTrig\Trig\Tangent::atanh($number); + } + + /** + * COS. + * + * Returns the result of builtin function cos after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Cosine::cos() + * Use the cos method in the MathTrig\Trig\Cosine class instead + * + * @param mixed $number Should be numeric + * + * @return float|string Rounded number + */ + public static function builtinCOS($number) + { + return MathTrig\Trig\Cosine::cos($number); + } + + /** + * COSH. + * + * Returns the result of builtin function cos after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Cosine::cosh() + * Use the cosh method in the MathTrig\Trig\Cosine class instead + * + * @param mixed $number Should be numeric + * + * @return float|string Rounded number + */ + public static function builtinCOSH($number) + { + return MathTrig\Trig\Cosine::cosh($number); + } + + /** + * DEGREES. + * + * Returns the result of builtin function rad2deg after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Angle::toDegrees() + * Use the toDegrees method in the MathTrig\Angle class instead + * + * @param mixed $number Should be numeric + * + * @return float|string Rounded number + */ + public static function builtinDEGREES($number) + { + return MathTrig\Angle::toDegrees($number); + } + + /** + * EXP. + * + * Returns the result of builtin function exp after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Exp::evaluate() + * Use the evaluate method in the MathTrig\Exp class instead + * + * @param mixed $number Should be numeric + * + * @return float|string Rounded number + */ + public static function builtinEXP($number) + { + return MathTrig\Exp::evaluate($number); + } + + /** + * LN. + * + * Returns the result of builtin function log after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Logarithms::natural() + * Use the natural method in the MathTrig\Logarithms class instead + * + * @param mixed $number Should be numeric + * + * @return float|string Rounded number + */ + public static function builtinLN($number) + { + return MathTrig\Logarithms::natural($number); + } + + /** + * LOG10. + * + * Returns the result of builtin function log after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Logarithms::base10() + * Use the natural method in the MathTrig\Logarithms class instead + * + * @param mixed $number Should be numeric + * + * @return float|string Rounded number + */ + public static function builtinLOG10($number) + { + return MathTrig\Logarithms::base10($number); + } + + /** + * RADIANS. + * + * Returns the result of builtin function deg2rad after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Angle::toRadians() + * Use the toRadians method in the MathTrig\Angle class instead + * + * @param mixed $number Should be numeric + * + * @return float|string Rounded number + */ + public static function builtinRADIANS($number) + { + return MathTrig\Angle::toRadians($number); + } + + /** + * SIN. + * + * Returns the result of builtin function sin after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Sine::evaluate() + * Use the sin method in the MathTrig\Trig\Sine class instead + * + * @param mixed $number Should be numeric + * + * @return float|string sine + */ + public static function builtinSIN($number) + { + return MathTrig\Trig\Sine::sin($number); + } + + /** + * SINH. + * + * Returns the result of builtin function sinh after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Sine::sinh() + * Use the sinh method in the MathTrig\Trig\Sine class instead + * + * @param mixed $number Should be numeric + * + * @return float|string Rounded number + */ + public static function builtinSINH($number) + { + return MathTrig\Trig\Sine::sinh($number); + } + + /** + * SQRT. + * + * Returns the result of builtin function sqrt after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Sqrt::sqrt() + * Use the sqrt method in the MathTrig\Sqrt class instead + * + * @param mixed $number Should be numeric + * + * @return float|string Rounded number + */ + public static function builtinSQRT($number) + { + return MathTrig\Sqrt::sqrt($number); + } + + /** + * TAN. + * + * Returns the result of builtin function tan after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Tangent::tan() + * Use the tan method in the MathTrig\Trig\Tangent class instead + * + * @param mixed $number Should be numeric + * + * @return float|string Rounded number + */ + public static function builtinTAN($number) + { + return MathTrig\Trig\Tangent::tan($number); + } + + /** + * TANH. + * + * Returns the result of builtin function sinh after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Tangent::tanh() + * Use the tanh method in the MathTrig\Trig\Tangent class instead + * + * @param mixed $number Should be numeric + * + * @return float|string Rounded number + */ + public static function builtinTANH($number) + { + return MathTrig\Trig\Tangent::tanh($number); + } + + /** + * Many functions accept null/false/true argument treated as 0/0/1. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Helpers::validateNumericNullBool() + * Use the validateNumericNullBool method in the MathTrig\Helpers class instead + * + * @param mixed $number + */ + public static function nullFalseTrueToNumber(&$number): void { $number = Functions::flattenSingleValue($number); - - if (!is_numeric($number)) { - return Functions::VALUE(); + if ($number === null) { + $number = 0; + } elseif (is_bool($number)) { + $number = (int) $number; } - - $result = log(($number + 1) / ($number - 1)) / 2; - - return is_nan($result) ? Functions::NAN() : $result; } } diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Absolute.php b/src/PhpSpreadsheet/Calculation/MathTrig/Absolute.php new file mode 100644 index 00000000..9f1bd804 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Absolute.php @@ -0,0 +1,28 @@ +getMessage(); + } + + return abs($number); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Angle.php b/src/PhpSpreadsheet/Calculation/MathTrig/Angle.php new file mode 100644 index 00000000..3062481f --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Angle.php @@ -0,0 +1,48 @@ +getMessage(); + } + + return rad2deg($number); + } + + /** + * RADIANS. + * + * Returns the result of builtin function deg2rad after validating args. + * + * @param mixed $number Should be numeric + * + * @return float|string Rounded number + */ + public static function toRadians($number) + { + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return deg2rad($number); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Arabic.php b/src/PhpSpreadsheet/Calculation/MathTrig/Arabic.php new file mode 100644 index 00000000..b852eeac --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Arabic.php @@ -0,0 +1,103 @@ + 1000, + 'D' => 500, + 'C' => 100, + 'L' => 50, + 'X' => 10, + 'V' => 5, + 'I' => 1, + ]; + + /** + * Recursively calculate the arabic value of a roman numeral. + * + * @param int $sum + * @param int $subtract + * + * @return int + */ + private static function calculateArabic(array $roman, &$sum = 0, $subtract = 0) + { + $numeral = array_shift($roman); + if (!isset(self::ROMAN_LOOKUP[$numeral])) { + throw new Exception('Invalid character detected'); + } + + $arabic = self::ROMAN_LOOKUP[$numeral]; + if (count($roman) > 0 && isset(self::ROMAN_LOOKUP[$roman[0]]) && $arabic < self::ROMAN_LOOKUP[$roman[0]]) { + $subtract += $arabic; + } else { + $sum += ($arabic - $subtract); + $subtract = 0; + } + + if (count($roman) > 0) { + self::calculateArabic($roman, $sum, $subtract); + } + + return $sum; + } + + /** + * @param mixed $value + */ + private static function mollifyScrutinizer($value): array + { + return is_array($value) ? $value : []; + } + + private static function strSplit(string $roman): array + { + $rslt = str_split($roman); + + return self::mollifyScrutinizer($rslt); + } + + /** + * ARABIC. + * + * Converts a Roman numeral to an Arabic numeral. + * + * Excel Function: + * ARABIC(text) + * + * @param string $roman + * + * @return int|string the arabic numberal contrived from the roman numeral + */ + public static function evaluate($roman) + { + // An empty string should return 0 + $roman = substr(trim(strtoupper((string) Functions::flattenSingleValue($roman))), 0, 255); + if ($roman === '') { + return 0; + } + + // Convert the roman numeral to an arabic number + $negativeNumber = $roman[0] === '-'; + if ($negativeNumber) { + $roman = substr($roman, 1); + } + + try { + $arabic = self::calculateArabic(self::strSplit($roman)); + } catch (Exception $e) { + return Functions::VALUE(); // Invalid character detected + } + + if ($negativeNumber) { + $arabic *= -1; // The number should be negative + } + + return $arabic; + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Base.php b/src/PhpSpreadsheet/Calculation/MathTrig/Base.php new file mode 100644 index 00000000..4be7b7c7 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Base.php @@ -0,0 +1,49 @@ +getMessage(); + } + $minLength = Functions::flattenSingleValue($minLength); + + if ($minLength === null || is_numeric($minLength)) { + if ($number < 0 || $number >= 2 ** 53 || $radix < 2 || $radix > 36) { + return Functions::NAN(); // Numeric range constraints + } + + $outcome = strtoupper((string) base_convert("$number", 10, $radix)); + if ($minLength !== null) { + $outcome = str_pad($outcome, (int) $minLength, '0', STR_PAD_LEFT); // String padding + } + + return $outcome; + } + + return Functions::VALUE(); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Ceiling.php b/src/PhpSpreadsheet/Calculation/MathTrig/Ceiling.php new file mode 100644 index 00000000..73f54a52 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Ceiling.php @@ -0,0 +1,138 @@ +getMessage(); + } + + return self::argumentsOk((float) $number, (float) $significance); + } + + /** + * CEILING.MATH. + * + * Round a number down to the nearest integer or to the nearest multiple of significance. + * + * Excel Function: + * CEILING.MATH(number[,significance[,mode]]) + * + * @param mixed $number Number to round + * @param mixed $significance Significance + * @param int $mode direction to round negative numbers + * + * @return float|string Rounded Number, or a string containing an error + */ + public static function math($number, $significance = null, $mode = 0) + { + try { + $number = Helpers::validateNumericNullBool($number); + $significance = Helpers::validateNumericNullSubstitution($significance, ($number < 0) ? -1 : 1); + $mode = Helpers::validateNumericNullSubstitution($mode, null); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (empty($significance * $number)) { + return 0.0; + } + if (self::ceilingMathTest((float) $significance, (float) $number, (int) $mode)) { + return floor($number / $significance) * $significance; + } + + return ceil($number / $significance) * $significance; + } + + /** + * CEILING.PRECISE. + * + * Rounds number up, away from zero, to the nearest multiple of significance. + * + * Excel Function: + * CEILING.PRECISE(number[,significance]) + * + * @param mixed $number the number you want to round + * @param float $significance the multiple to which you want to round + * + * @return float|string Rounded Number, or a string containing an error + */ + public static function precise($number, $significance = 1) + { + try { + $number = Helpers::validateNumericNullBool($number); + $significance = Helpers::validateNumericNullSubstitution($significance, null); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (!$significance) { + return 0.0; + } + $result = $number / abs($significance); + + return ceil($result) * $significance * (($significance < 0) ? -1 : 1); + } + + /** + * Let CEILINGMATH complexity pass Scrutinizer. + */ + private static function ceilingMathTest(float $significance, float $number, int $mode): bool + { + return ((float) $significance < 0) || ((float) $number < 0 && !empty($mode)); + } + + /** + * Avoid Scrutinizer problems concerning complexity. + * + * @return float|string + */ + private static function argumentsOk(float $number, float $significance) + { + if (empty($number * $significance)) { + return 0.0; + } + if (Helpers::returnSign($number) == Helpers::returnSign($significance)) { + return ceil($number / $significance) * $significance; + } + + return Functions::NAN(); + } + + private static function floorCheck1Arg(): void + { + $compatibility = Functions::getCompatibilityMode(); + if ($compatibility === Functions::COMPATIBILITY_EXCEL) { + throw new Exception('Excel requires 2 arguments for CEILING'); + } + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Combinations.php b/src/PhpSpreadsheet/Calculation/MathTrig/Combinations.php new file mode 100644 index 00000000..97508bb1 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Combinations.php @@ -0,0 +1,74 @@ +getMessage(); + } + + return round(Factorial::fact($numObjs) / Factorial::fact($numObjs - $numInSet)) / Factorial::fact($numInSet); + } + + /** + * COMBIN. + * + * Returns the number of combinations for a given number of items. Use COMBIN to + * determine the total possible number of groups for a given number of items. + * + * Excel Function: + * COMBIN(numObjs,numInSet) + * + * @param mixed $numObjs Number of different objects + * @param mixed $numInSet Number of objects in each combination + * + * @return float|int|string Number of combinations, or a string containing an error + */ + public static function withRepetition($numObjs, $numInSet) + { + try { + $numObjs = Helpers::validateNumericNullSubstitution($numObjs, null); + $numInSet = Helpers::validateNumericNullSubstitution($numInSet, null); + Helpers::validateNotNegative($numInSet); + Helpers::validateNotNegative($numObjs); + $numObjs = (int) $numObjs; + $numInSet = (int) $numInSet; + // Microsoft documentation says following is true, but Excel + // does not enforce this restriction. + //Helpers::validateNotNegative($numObjs - $numInSet); + if ($numObjs === 0) { + Helpers::validateNotNegative(-$numInSet); + + return 1; + } + } catch (Exception $e) { + return $e->getMessage(); + } + + return round(Factorial::fact($numObjs + $numInSet - 1) / Factorial::fact($numObjs - 1)) / Factorial::fact($numInSet); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Exp.php b/src/PhpSpreadsheet/Calculation/MathTrig/Exp.php new file mode 100644 index 00000000..ce930a83 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Exp.php @@ -0,0 +1,28 @@ +getMessage(); + } + + return exp($number); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Factorial.php b/src/PhpSpreadsheet/Calculation/MathTrig/Factorial.php new file mode 100644 index 00000000..f443f8e5 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Factorial.php @@ -0,0 +1,110 @@ +getMessage(); + } + + $factLoop = floor($factVal); + if ($factVal > $factLoop) { + if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { + return Statistical\Distributions\Gamma::gammaValue($factVal + 1); + } + } + + $factorial = 1; + while ($factLoop > 1) { + $factorial *= $factLoop--; + } + + return $factorial; + } + + /** + * FACTDOUBLE. + * + * Returns the double factorial of a number. + * + * Excel Function: + * FACTDOUBLE(factVal) + * + * @param float $factVal Factorial Value + * + * @return float|int|string Double Factorial, or a string containing an error + */ + public static function factDouble($factVal) + { + try { + $factVal = Helpers::validateNumericNullSubstitution($factVal, 0); + Helpers::validateNotNegative($factVal); + } catch (Exception $e) { + return $e->getMessage(); + } + + $factLoop = floor($factVal); + $factorial = 1; + while ($factLoop > 1) { + $factorial *= $factLoop; + $factLoop -= 2; + } + + return $factorial; + } + + /** + * MULTINOMIAL. + * + * Returns the ratio of the factorial of a sum of values to the product of factorials. + * + * @param mixed[] $args An array of mixed values for the Data Series + * + * @return float|string The result, or a string containing an error + */ + public static function multinomial(...$args) + { + $summer = 0; + $divisor = 1; + + try { + // Loop through arguments + foreach (Functions::flattenArray($args) as $argx) { + $arg = Helpers::validateNumericNullSubstitution($argx, null); + Helpers::validateNotNegative($arg); + $arg = (int) $arg; + $summer += $arg; + $divisor *= self::fact($arg); + } + } catch (Exception $e) { + return $e->getMessage(); + } + + $summer = self::fact($summer); + + return $summer / $divisor; + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Floor.php b/src/PhpSpreadsheet/Calculation/MathTrig/Floor.php new file mode 100644 index 00000000..04e12205 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Floor.php @@ -0,0 +1,166 @@ +getMessage(); + } + + return self::argumentsOk((float) $number, (float) $significance); + } + + /** + * FLOOR.MATH. + * + * Round a number down to the nearest integer or to the nearest multiple of significance. + * + * Excel Function: + * FLOOR.MATH(number[,significance[,mode]]) + * + * @param mixed $number Number to round + * @param mixed $significance Significance + * @param mixed $mode direction to round negative numbers + * + * @return float|string Rounded Number, or a string containing an error + */ + public static function math($number, $significance = null, $mode = 0) + { + try { + $number = Helpers::validateNumericNullBool($number); + $significance = Helpers::validateNumericNullSubstitution($significance, ($number < 0) ? -1 : 1); + $mode = Helpers::validateNumericNullSubstitution($mode, null); + } catch (Exception $e) { + return $e->getMessage(); + } + + return self::argsOk((float) $number, (float) $significance, (int) $mode); + } + + /** + * FLOOR.PRECISE. + * + * Rounds number down, toward zero, to the nearest multiple of significance. + * + * Excel Function: + * FLOOR.PRECISE(number[,significance]) + * + * @param float $number Number to round + * @param float $significance Significance + * + * @return float|string Rounded Number, or a string containing an error + */ + public static function precise($number, $significance = 1) + { + try { + $number = Helpers::validateNumericNullBool($number); + $significance = Helpers::validateNumericNullSubstitution($significance, null); + } catch (Exception $e) { + return $e->getMessage(); + } + + return self::argumentsOkPrecise((float) $number, (float) $significance); + } + + /** + * Avoid Scrutinizer problems concerning complexity. + * + * @return float|string + */ + private static function argumentsOkPrecise(float $number, float $significance) + { + if ($significance == 0.0) { + return Functions::DIV0(); + } + if ($number == 0.0) { + return 0.0; + } + + return floor($number / abs($significance)) * abs($significance); + } + + /** + * Avoid Scrutinizer complexity problems. + * + * @return float|string Rounded Number, or a string containing an error + */ + private static function argsOk(float $number, float $significance, int $mode) + { + if (!$significance) { + return Functions::DIV0(); + } + if (!$number) { + return 0.0; + } + if (self::floorMathTest($number, $significance, $mode)) { + return ceil($number / $significance) * $significance; + } + + return floor($number / $significance) * $significance; + } + + /** + * Let FLOORMATH complexity pass Scrutinizer. + */ + private static function floorMathTest(float $number, float $significance, int $mode): bool + { + return Helpers::returnSign($significance) == -1 || (Helpers::returnSign($number) == -1 && !empty($mode)); + } + + /** + * Avoid Scrutinizer problems concerning complexity. + * + * @return float|string + */ + private static function argumentsOk(float $number, float $significance) + { + if ($significance == 0.0) { + return Functions::DIV0(); + } + if ($number == 0.0) { + return 0.0; + } + if (Helpers::returnSign($significance) == 1) { + return floor($number / $significance) * $significance; + } + if (Helpers::returnSign($number) == -1 && Helpers::returnSign($significance) == -1) { + return floor($number / $significance) * $significance; + } + + return Functions::NAN(); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Gcd.php b/src/PhpSpreadsheet/Calculation/MathTrig/Gcd.php new file mode 100644 index 00000000..1dd52faa --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Gcd.php @@ -0,0 +1,69 @@ +getMessage(); + } + + if (count($arrayArgs) <= 0) { + return Functions::VALUE(); + } + $gcd = (int) array_pop($arrayArgs); + do { + $gcd = self::evaluateGCD($gcd, (int) array_pop($arrayArgs)); + } while (!empty($arrayArgs)); + + return $gcd; + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Helpers.php b/src/PhpSpreadsheet/Calculation/MathTrig/Helpers.php new file mode 100644 index 00000000..b89644a9 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Helpers.php @@ -0,0 +1,129 @@ += 0. + * + * @param float|int $number + */ + public static function validateNotNegative($number, ?string $except = null): void + { + if ($number >= 0) { + return; + } + + throw new Exception($except ?? Functions::NAN()); + } + + /** + * Confirm number > 0. + * + * @param float|int $number + */ + public static function validatePositive($number, ?string $except = null): void + { + if ($number > 0) { + return; + } + + throw new Exception($except ?? Functions::NAN()); + } + + /** + * Confirm number != 0. + * + * @param float|int $number + */ + public static function validateNotZero($number): void + { + if ($number) { + return; + } + + throw new Exception(Functions::DIV0()); + } + + public static function returnSign(float $number): int + { + return $number ? (($number > 0) ? 1 : -1) : 0; + } + + public static function getEven(float $number): float + { + $significance = 2 * self::returnSign($number); + + return $significance ? (ceil($number / $significance) * $significance) : 0; + } + + /** + * Return NAN or value depending on argument. + * + * @param float $result Number + * + * @return float|string + */ + public static function numberOrNan($result) + { + return is_nan($result) ? Functions::NAN() : $result; + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/IntClass.php b/src/PhpSpreadsheet/Calculation/MathTrig/IntClass.php new file mode 100644 index 00000000..7aa3d06a --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/IntClass.php @@ -0,0 +1,31 @@ +getMessage(); + } + + return (int) floor($number); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Lcm.php b/src/PhpSpreadsheet/Calculation/MathTrig/Lcm.php new file mode 100644 index 00000000..46e9816d --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Lcm.php @@ -0,0 +1,110 @@ + 1; --$i) { + if (($value % $i) == 0) { + $factorArray = array_merge($factorArray, self::factors($value / $i)); + $factorArray = array_merge($factorArray, self::factors($i)); + if ($i <= sqrt($value)) { + break; + } + } + } + if (!empty($factorArray)) { + rsort($factorArray); + + return $factorArray; + } + + return [(int) $value]; + } + + /** + * LCM. + * + * Returns the lowest common multiplier of a series of numbers + * The least common multiple is the smallest positive integer that is a multiple + * of all integer arguments number1, number2, and so on. Use LCM to add fractions + * with different denominators. + * + * Excel Function: + * LCM(number1[,number2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return int|string Lowest Common Multiplier, or a string containing an error + */ + public static function evaluate(...$args) + { + try { + $arrayArgs = []; + $anyZeros = 0; + $anyNonNulls = 0; + foreach (Functions::flattenArray($args) as $value1) { + $anyNonNulls += (int) ($value1 !== null); + $value = Helpers::validateNumericNullSubstitution($value1, 1); + Helpers::validateNotNegative($value); + $arrayArgs[] = (int) $value; + $anyZeros += (int) !((bool) $value); + } + self::testNonNulls($anyNonNulls); + if ($anyZeros) { + return 0; + } + } catch (Exception $e) { + return $e->getMessage(); + } + + $returnValue = 1; + $allPoweredFactors = []; + // Loop through arguments + foreach ($arrayArgs as $value) { + $myFactors = self::factors(floor($value)); + $myCountedFactors = array_count_values($myFactors); + $myPoweredFactors = []; + foreach ($myCountedFactors as $myCountedFactor => $myCountedPower) { + $myPoweredFactors[$myCountedFactor] = $myCountedFactor ** $myCountedPower; + } + self::processPoweredFactors($allPoweredFactors, $myPoweredFactors); + } + foreach ($allPoweredFactors as $allPoweredFactor) { + $returnValue *= (int) $allPoweredFactor; + } + + return $returnValue; + } + + private static function processPoweredFactors(array &$allPoweredFactors, array &$myPoweredFactors): void + { + foreach ($myPoweredFactors as $myPoweredValue => $myPoweredFactor) { + if (isset($allPoweredFactors[$myPoweredValue])) { + if ($allPoweredFactors[$myPoweredValue] < $myPoweredFactor) { + $allPoweredFactors[$myPoweredValue] = $myPoweredFactor; + } + } else { + $allPoweredFactors[$myPoweredValue] = $myPoweredFactor; + } + } + } + + private static function testNonNulls(int $anyNonNulls): void + { + if (!$anyNonNulls) { + throw new Exception(Functions::VALUE()); + } + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Logarithms.php b/src/PhpSpreadsheet/Calculation/MathTrig/Logarithms.php new file mode 100644 index 00000000..d6878d88 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Logarithms.php @@ -0,0 +1,77 @@ +getMessage(); + } + + return log($number, $base); + } + + /** + * LOG10. + * + * Returns the result of builtin function log after validating args. + * + * @param mixed $number Should be numeric + * + * @return float|string Rounded number + */ + public static function base10($number) + { + try { + $number = Helpers::validateNumericNullBool($number); + Helpers::validatePositive($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return log10($number); + } + + /** + * LN. + * + * Returns the result of builtin function log after validating args. + * + * @param mixed $number Should be numeric + * + * @return float|string Rounded number + */ + public static function natural($number) + { + try { + $number = Helpers::validateNumericNullBool($number); + Helpers::validatePositive($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return log($number); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/MatrixFunctions.php b/src/PhpSpreadsheet/Calculation/MathTrig/MatrixFunctions.php new file mode 100644 index 00000000..92e1ff8e --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/MatrixFunctions.php @@ -0,0 +1,138 @@ +determinant(); + } catch (MatrixException $ex) { + return Functions::VALUE(); + } catch (Exception $e) { + return $e->getMessage(); + } + } + + /** + * MINVERSE. + * + * Returns the inverse matrix for the matrix stored in an array. + * + * Excel Function: + * MINVERSE(array) + * + * @param mixed $matrixValues A matrix of values + * + * @return array|string The result, or a string containing an error + */ + public static function inverse($matrixValues) + { + try { + $matrix = self::getMatrix($matrixValues); + + return $matrix->inverse()->toArray(); + } catch (MatrixDiv0Exception $e) { + return Functions::NAN(); + } catch (MatrixException $e) { + return Functions::VALUE(); + } catch (Exception $e) { + return $e->getMessage(); + } + } + + /** + * MMULT. + * + * @param mixed $matrixData1 A matrix of values + * @param mixed $matrixData2 A matrix of values + * + * @return array|string The result, or a string containing an error + */ + public static function multiply($matrixData1, $matrixData2) + { + try { + $matrixA = self::getMatrix($matrixData1); + $matrixB = self::getMatrix($matrixData2); + + return $matrixA->multiply($matrixB)->toArray(); + } catch (MatrixException $ex) { + return Functions::VALUE(); + } catch (Exception $e) { + return $e->getMessage(); + } + } + + /** + * MUnit. + * + * @param mixed $dimension Number of rows and columns + * + * @return array|string The result, or a string containing an error + */ + public static function identity($dimension) + { + try { + $dimension = (int) Helpers::validateNumericNullBool($dimension); + Helpers::validatePositive($dimension, Functions::VALUE()); + $matrix = Builder::createIdentityMatrix($dimension, 0)->toArray(); + + return $matrix; + } catch (Exception $e) { + return $e->getMessage(); + } + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Operations.php b/src/PhpSpreadsheet/Calculation/MathTrig/Operations.php new file mode 100644 index 00000000..595c7fdc --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Operations.php @@ -0,0 +1,136 @@ +getMessage(); + } + + if (($dividend < 0.0) && ($divisor > 0.0)) { + return $divisor - fmod(abs($dividend), $divisor); + } + if (($dividend > 0.0) && ($divisor < 0.0)) { + return $divisor + fmod($dividend, abs($divisor)); + } + + return fmod($dividend, $divisor); + } + + /** + * POWER. + * + * Computes x raised to the power y. + * + * @param float|int $x + * @param float|int $y + * + * @return float|int|string The result, or a string containing an error + */ + public static function power($x, $y) + { + try { + $x = Helpers::validateNumericNullBool($x); + $y = Helpers::validateNumericNullBool($y); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Validate parameters + if (!$x && !$y) { + return Functions::NAN(); + } + if (!$x && $y < 0.0) { + return Functions::DIV0(); + } + + // Return + $result = $x ** $y; + + return Helpers::numberOrNan($result); + } + + /** + * PRODUCT. + * + * PRODUCT returns the product of all the values and cells referenced in the argument list. + * + * Excel Function: + * PRODUCT(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float|string + */ + public static function product(...$args) + { + // Return value + $returnValue = null; + + // Loop through arguments + foreach (Functions::flattenArray($args) as $arg) { + // Is it a numeric value? + if (is_numeric($arg)) { + if ($returnValue === null) { + $returnValue = $arg; + } else { + $returnValue *= $arg; + } + } else { + return Functions::VALUE(); + } + } + + // Return + if ($returnValue === null) { + return 0; + } + + return $returnValue; + } + + /** + * QUOTIENT. + * + * QUOTIENT function returns the integer portion of a division. Numerator is the divided number + * and denominator is the divisor. + * + * Excel Function: + * QUOTIENT(value1,value2) + * + * @param mixed $numerator Expect float|int + * @param mixed $denominator Expect float|int + * + * @return int|string + */ + public static function quotient($numerator, $denominator) + { + try { + $numerator = Helpers::validateNumericNullSubstitution($numerator, 0); + $denominator = Helpers::validateNumericNullSubstitution($denominator, 0); + Helpers::validateNotZero($denominator); + } catch (Exception $e) { + return $e->getMessage(); + } + + return (int) ($numerator / $denominator); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Random.php b/src/PhpSpreadsheet/Calculation/MathTrig/Random.php new file mode 100644 index 00000000..963a789a --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Random.php @@ -0,0 +1,39 @@ +getMessage(); + } + + return mt_rand($min, $max); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Roman.php b/src/PhpSpreadsheet/Calculation/MathTrig/Roman.php new file mode 100644 index 00000000..71a6df3a --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Roman.php @@ -0,0 +1,835 @@ + ['VL'], + 46 => ['VLI'], + 47 => ['VLII'], + 48 => ['VLIII'], + 49 => ['VLIV', 'IL'], + 95 => ['VC'], + 96 => ['VCI'], + 97 => ['VCII'], + 98 => ['VCIII'], + 99 => ['VCIV', 'IC'], + 145 => ['CVL'], + 146 => ['CVLI'], + 147 => ['CVLII'], + 148 => ['CVLIII'], + 149 => ['CVLIV', 'CIL'], + 195 => ['CVC'], + 196 => ['CVCI'], + 197 => ['CVCII'], + 198 => ['CVCIII'], + 199 => ['CVCIV', 'CIC'], + 245 => ['CCVL'], + 246 => ['CCVLI'], + 247 => ['CCVLII'], + 248 => ['CCVLIII'], + 249 => ['CCVLIV', 'CCIL'], + 295 => ['CCVC'], + 296 => ['CCVCI'], + 297 => ['CCVCII'], + 298 => ['CCVCIII'], + 299 => ['CCVCIV', 'CCIC'], + 345 => ['CCCVL'], + 346 => ['CCCVLI'], + 347 => ['CCCVLII'], + 348 => ['CCCVLIII'], + 349 => ['CCCVLIV', 'CCCIL'], + 395 => ['CCCVC'], + 396 => ['CCCVCI'], + 397 => ['CCCVCII'], + 398 => ['CCCVCIII'], + 399 => ['CCCVCIV', 'CCCIC'], + 445 => ['CDVL'], + 446 => ['CDVLI'], + 447 => ['CDVLII'], + 448 => ['CDVLIII'], + 449 => ['CDVLIV', 'CDIL'], + 450 => ['LD'], + 451 => ['LDI'], + 452 => ['LDII'], + 453 => ['LDIII'], + 454 => ['LDIV'], + 455 => ['LDV'], + 456 => ['LDVI'], + 457 => ['LDVII'], + 458 => ['LDVIII'], + 459 => ['LDIX'], + 460 => ['LDX'], + 461 => ['LDXI'], + 462 => ['LDXII'], + 463 => ['LDXIII'], + 464 => ['LDXIV'], + 465 => ['LDXV'], + 466 => ['LDXVI'], + 467 => ['LDXVII'], + 468 => ['LDXVIII'], + 469 => ['LDXIX'], + 470 => ['LDXX'], + 471 => ['LDXXI'], + 472 => ['LDXXII'], + 473 => ['LDXXIII'], + 474 => ['LDXXIV'], + 475 => ['LDXXV'], + 476 => ['LDXXVI'], + 477 => ['LDXXVII'], + 478 => ['LDXXVIII'], + 479 => ['LDXXIX'], + 480 => ['LDXXX'], + 481 => ['LDXXXI'], + 482 => ['LDXXXII'], + 483 => ['LDXXXIII'], + 484 => ['LDXXXIV'], + 485 => ['LDXXXV'], + 486 => ['LDXXXVI'], + 487 => ['LDXXXVII'], + 488 => ['LDXXXVIII'], + 489 => ['LDXXXIX'], + 490 => ['LDXL', 'XD'], + 491 => ['LDXLI', 'XDI'], + 492 => ['LDXLII', 'XDII'], + 493 => ['LDXLIII', 'XDIII'], + 494 => ['LDXLIV', 'XDIV'], + 495 => ['LDVL', 'XDV', 'VD'], + 496 => ['LDVLI', 'XDVI', 'VDI'], + 497 => ['LDVLII', 'XDVII', 'VDII'], + 498 => ['LDVLIII', 'XDVIII', 'VDIII'], + 499 => ['LDVLIV', 'XDIX', 'VDIV', 'ID'], + 545 => ['DVL'], + 546 => ['DVLI'], + 547 => ['DVLII'], + 548 => ['DVLIII'], + 549 => ['DVLIV', 'DIL'], + 595 => ['DVC'], + 596 => ['DVCI'], + 597 => ['DVCII'], + 598 => ['DVCIII'], + 599 => ['DVCIV', 'DIC'], + 645 => ['DCVL'], + 646 => ['DCVLI'], + 647 => ['DCVLII'], + 648 => ['DCVLIII'], + 649 => ['DCVLIV', 'DCIL'], + 695 => ['DCVC'], + 696 => ['DCVCI'], + 697 => ['DCVCII'], + 698 => ['DCVCIII'], + 699 => ['DCVCIV', 'DCIC'], + 745 => ['DCCVL'], + 746 => ['DCCVLI'], + 747 => ['DCCVLII'], + 748 => ['DCCVLIII'], + 749 => ['DCCVLIV', 'DCCIL'], + 795 => ['DCCVC'], + 796 => ['DCCVCI'], + 797 => ['DCCVCII'], + 798 => ['DCCVCIII'], + 799 => ['DCCVCIV', 'DCCIC'], + 845 => ['DCCCVL'], + 846 => ['DCCCVLI'], + 847 => ['DCCCVLII'], + 848 => ['DCCCVLIII'], + 849 => ['DCCCVLIV', 'DCCCIL'], + 895 => ['DCCCVC'], + 896 => ['DCCCVCI'], + 897 => ['DCCCVCII'], + 898 => ['DCCCVCIII'], + 899 => ['DCCCVCIV', 'DCCCIC'], + 945 => ['CMVL'], + 946 => ['CMVLI'], + 947 => ['CMVLII'], + 948 => ['CMVLIII'], + 949 => ['CMVLIV', 'CMIL'], + 950 => ['LM'], + 951 => ['LMI'], + 952 => ['LMII'], + 953 => ['LMIII'], + 954 => ['LMIV'], + 955 => ['LMV'], + 956 => ['LMVI'], + 957 => ['LMVII'], + 958 => ['LMVIII'], + 959 => ['LMIX'], + 960 => ['LMX'], + 961 => ['LMXI'], + 962 => ['LMXII'], + 963 => ['LMXIII'], + 964 => ['LMXIV'], + 965 => ['LMXV'], + 966 => ['LMXVI'], + 967 => ['LMXVII'], + 968 => ['LMXVIII'], + 969 => ['LMXIX'], + 970 => ['LMXX'], + 971 => ['LMXXI'], + 972 => ['LMXXII'], + 973 => ['LMXXIII'], + 974 => ['LMXXIV'], + 975 => ['LMXXV'], + 976 => ['LMXXVI'], + 977 => ['LMXXVII'], + 978 => ['LMXXVIII'], + 979 => ['LMXXIX'], + 980 => ['LMXXX'], + 981 => ['LMXXXI'], + 982 => ['LMXXXII'], + 983 => ['LMXXXIII'], + 984 => ['LMXXXIV'], + 985 => ['LMXXXV'], + 986 => ['LMXXXVI'], + 987 => ['LMXXXVII'], + 988 => ['LMXXXVIII'], + 989 => ['LMXXXIX'], + 990 => ['LMXL', 'XM'], + 991 => ['LMXLI', 'XMI'], + 992 => ['LMXLII', 'XMII'], + 993 => ['LMXLIII', 'XMIII'], + 994 => ['LMXLIV', 'XMIV'], + 995 => ['LMVL', 'XMV', 'VM'], + 996 => ['LMVLI', 'XMVI', 'VMI'], + 997 => ['LMVLII', 'XMVII', 'VMII'], + 998 => ['LMVLIII', 'XMVIII', 'VMIII'], + 999 => ['LMVLIV', 'XMIX', 'VMIV', 'IM'], + 1045 => ['MVL'], + 1046 => ['MVLI'], + 1047 => ['MVLII'], + 1048 => ['MVLIII'], + 1049 => ['MVLIV', 'MIL'], + 1095 => ['MVC'], + 1096 => ['MVCI'], + 1097 => ['MVCII'], + 1098 => ['MVCIII'], + 1099 => ['MVCIV', 'MIC'], + 1145 => ['MCVL'], + 1146 => ['MCVLI'], + 1147 => ['MCVLII'], + 1148 => ['MCVLIII'], + 1149 => ['MCVLIV', 'MCIL'], + 1195 => ['MCVC'], + 1196 => ['MCVCI'], + 1197 => ['MCVCII'], + 1198 => ['MCVCIII'], + 1199 => ['MCVCIV', 'MCIC'], + 1245 => ['MCCVL'], + 1246 => ['MCCVLI'], + 1247 => ['MCCVLII'], + 1248 => ['MCCVLIII'], + 1249 => ['MCCVLIV', 'MCCIL'], + 1295 => ['MCCVC'], + 1296 => ['MCCVCI'], + 1297 => ['MCCVCII'], + 1298 => ['MCCVCIII'], + 1299 => ['MCCVCIV', 'MCCIC'], + 1345 => ['MCCCVL'], + 1346 => ['MCCCVLI'], + 1347 => ['MCCCVLII'], + 1348 => ['MCCCVLIII'], + 1349 => ['MCCCVLIV', 'MCCCIL'], + 1395 => ['MCCCVC'], + 1396 => ['MCCCVCI'], + 1397 => ['MCCCVCII'], + 1398 => ['MCCCVCIII'], + 1399 => ['MCCCVCIV', 'MCCCIC'], + 1445 => ['MCDVL'], + 1446 => ['MCDVLI'], + 1447 => ['MCDVLII'], + 1448 => ['MCDVLIII'], + 1449 => ['MCDVLIV', 'MCDIL'], + 1450 => ['MLD'], + 1451 => ['MLDI'], + 1452 => ['MLDII'], + 1453 => ['MLDIII'], + 1454 => ['MLDIV'], + 1455 => ['MLDV'], + 1456 => ['MLDVI'], + 1457 => ['MLDVII'], + 1458 => ['MLDVIII'], + 1459 => ['MLDIX'], + 1460 => ['MLDX'], + 1461 => ['MLDXI'], + 1462 => ['MLDXII'], + 1463 => ['MLDXIII'], + 1464 => ['MLDXIV'], + 1465 => ['MLDXV'], + 1466 => ['MLDXVI'], + 1467 => ['MLDXVII'], + 1468 => ['MLDXVIII'], + 1469 => ['MLDXIX'], + 1470 => ['MLDXX'], + 1471 => ['MLDXXI'], + 1472 => ['MLDXXII'], + 1473 => ['MLDXXIII'], + 1474 => ['MLDXXIV'], + 1475 => ['MLDXXV'], + 1476 => ['MLDXXVI'], + 1477 => ['MLDXXVII'], + 1478 => ['MLDXXVIII'], + 1479 => ['MLDXXIX'], + 1480 => ['MLDXXX'], + 1481 => ['MLDXXXI'], + 1482 => ['MLDXXXII'], + 1483 => ['MLDXXXIII'], + 1484 => ['MLDXXXIV'], + 1485 => ['MLDXXXV'], + 1486 => ['MLDXXXVI'], + 1487 => ['MLDXXXVII'], + 1488 => ['MLDXXXVIII'], + 1489 => ['MLDXXXIX'], + 1490 => ['MLDXL', 'MXD'], + 1491 => ['MLDXLI', 'MXDI'], + 1492 => ['MLDXLII', 'MXDII'], + 1493 => ['MLDXLIII', 'MXDIII'], + 1494 => ['MLDXLIV', 'MXDIV'], + 1495 => ['MLDVL', 'MXDV', 'MVD'], + 1496 => ['MLDVLI', 'MXDVI', 'MVDI'], + 1497 => ['MLDVLII', 'MXDVII', 'MVDII'], + 1498 => ['MLDVLIII', 'MXDVIII', 'MVDIII'], + 1499 => ['MLDVLIV', 'MXDIX', 'MVDIV', 'MID'], + 1545 => ['MDVL'], + 1546 => ['MDVLI'], + 1547 => ['MDVLII'], + 1548 => ['MDVLIII'], + 1549 => ['MDVLIV', 'MDIL'], + 1595 => ['MDVC'], + 1596 => ['MDVCI'], + 1597 => ['MDVCII'], + 1598 => ['MDVCIII'], + 1599 => ['MDVCIV', 'MDIC'], + 1645 => ['MDCVL'], + 1646 => ['MDCVLI'], + 1647 => ['MDCVLII'], + 1648 => ['MDCVLIII'], + 1649 => ['MDCVLIV', 'MDCIL'], + 1695 => ['MDCVC'], + 1696 => ['MDCVCI'], + 1697 => ['MDCVCII'], + 1698 => ['MDCVCIII'], + 1699 => ['MDCVCIV', 'MDCIC'], + 1745 => ['MDCCVL'], + 1746 => ['MDCCVLI'], + 1747 => ['MDCCVLII'], + 1748 => ['MDCCVLIII'], + 1749 => ['MDCCVLIV', 'MDCCIL'], + 1795 => ['MDCCVC'], + 1796 => ['MDCCVCI'], + 1797 => ['MDCCVCII'], + 1798 => ['MDCCVCIII'], + 1799 => ['MDCCVCIV', 'MDCCIC'], + 1845 => ['MDCCCVL'], + 1846 => ['MDCCCVLI'], + 1847 => ['MDCCCVLII'], + 1848 => ['MDCCCVLIII'], + 1849 => ['MDCCCVLIV', 'MDCCCIL'], + 1895 => ['MDCCCVC'], + 1896 => ['MDCCCVCI'], + 1897 => ['MDCCCVCII'], + 1898 => ['MDCCCVCIII'], + 1899 => ['MDCCCVCIV', 'MDCCCIC'], + 1945 => ['MCMVL'], + 1946 => ['MCMVLI'], + 1947 => ['MCMVLII'], + 1948 => ['MCMVLIII'], + 1949 => ['MCMVLIV', 'MCMIL'], + 1950 => ['MLM'], + 1951 => ['MLMI'], + 1952 => ['MLMII'], + 1953 => ['MLMIII'], + 1954 => ['MLMIV'], + 1955 => ['MLMV'], + 1956 => ['MLMVI'], + 1957 => ['MLMVII'], + 1958 => ['MLMVIII'], + 1959 => ['MLMIX'], + 1960 => ['MLMX'], + 1961 => ['MLMXI'], + 1962 => ['MLMXII'], + 1963 => ['MLMXIII'], + 1964 => ['MLMXIV'], + 1965 => ['MLMXV'], + 1966 => ['MLMXVI'], + 1967 => ['MLMXVII'], + 1968 => ['MLMXVIII'], + 1969 => ['MLMXIX'], + 1970 => ['MLMXX'], + 1971 => ['MLMXXI'], + 1972 => ['MLMXXII'], + 1973 => ['MLMXXIII'], + 1974 => ['MLMXXIV'], + 1975 => ['MLMXXV'], + 1976 => ['MLMXXVI'], + 1977 => ['MLMXXVII'], + 1978 => ['MLMXXVIII'], + 1979 => ['MLMXXIX'], + 1980 => ['MLMXXX'], + 1981 => ['MLMXXXI'], + 1982 => ['MLMXXXII'], + 1983 => ['MLMXXXIII'], + 1984 => ['MLMXXXIV'], + 1985 => ['MLMXXXV'], + 1986 => ['MLMXXXVI'], + 1987 => ['MLMXXXVII'], + 1988 => ['MLMXXXVIII'], + 1989 => ['MLMXXXIX'], + 1990 => ['MLMXL', 'MXM'], + 1991 => ['MLMXLI', 'MXMI'], + 1992 => ['MLMXLII', 'MXMII'], + 1993 => ['MLMXLIII', 'MXMIII'], + 1994 => ['MLMXLIV', 'MXMIV'], + 1995 => ['MLMVL', 'MXMV', 'MVM'], + 1996 => ['MLMVLI', 'MXMVI', 'MVMI'], + 1997 => ['MLMVLII', 'MXMVII', 'MVMII'], + 1998 => ['MLMVLIII', 'MXMVIII', 'MVMIII'], + 1999 => ['MLMVLIV', 'MXMIX', 'MVMIV', 'MIM'], + 2045 => ['MMVL'], + 2046 => ['MMVLI'], + 2047 => ['MMVLII'], + 2048 => ['MMVLIII'], + 2049 => ['MMVLIV', 'MMIL'], + 2095 => ['MMVC'], + 2096 => ['MMVCI'], + 2097 => ['MMVCII'], + 2098 => ['MMVCIII'], + 2099 => ['MMVCIV', 'MMIC'], + 2145 => ['MMCVL'], + 2146 => ['MMCVLI'], + 2147 => ['MMCVLII'], + 2148 => ['MMCVLIII'], + 2149 => ['MMCVLIV', 'MMCIL'], + 2195 => ['MMCVC'], + 2196 => ['MMCVCI'], + 2197 => ['MMCVCII'], + 2198 => ['MMCVCIII'], + 2199 => ['MMCVCIV', 'MMCIC'], + 2245 => ['MMCCVL'], + 2246 => ['MMCCVLI'], + 2247 => ['MMCCVLII'], + 2248 => ['MMCCVLIII'], + 2249 => ['MMCCVLIV', 'MMCCIL'], + 2295 => ['MMCCVC'], + 2296 => ['MMCCVCI'], + 2297 => ['MMCCVCII'], + 2298 => ['MMCCVCIII'], + 2299 => ['MMCCVCIV', 'MMCCIC'], + 2345 => ['MMCCCVL'], + 2346 => ['MMCCCVLI'], + 2347 => ['MMCCCVLII'], + 2348 => ['MMCCCVLIII'], + 2349 => ['MMCCCVLIV', 'MMCCCIL'], + 2395 => ['MMCCCVC'], + 2396 => ['MMCCCVCI'], + 2397 => ['MMCCCVCII'], + 2398 => ['MMCCCVCIII'], + 2399 => ['MMCCCVCIV', 'MMCCCIC'], + 2445 => ['MMCDVL'], + 2446 => ['MMCDVLI'], + 2447 => ['MMCDVLII'], + 2448 => ['MMCDVLIII'], + 2449 => ['MMCDVLIV', 'MMCDIL'], + 2450 => ['MMLD'], + 2451 => ['MMLDI'], + 2452 => ['MMLDII'], + 2453 => ['MMLDIII'], + 2454 => ['MMLDIV'], + 2455 => ['MMLDV'], + 2456 => ['MMLDVI'], + 2457 => ['MMLDVII'], + 2458 => ['MMLDVIII'], + 2459 => ['MMLDIX'], + 2460 => ['MMLDX'], + 2461 => ['MMLDXI'], + 2462 => ['MMLDXII'], + 2463 => ['MMLDXIII'], + 2464 => ['MMLDXIV'], + 2465 => ['MMLDXV'], + 2466 => ['MMLDXVI'], + 2467 => ['MMLDXVII'], + 2468 => ['MMLDXVIII'], + 2469 => ['MMLDXIX'], + 2470 => ['MMLDXX'], + 2471 => ['MMLDXXI'], + 2472 => ['MMLDXXII'], + 2473 => ['MMLDXXIII'], + 2474 => ['MMLDXXIV'], + 2475 => ['MMLDXXV'], + 2476 => ['MMLDXXVI'], + 2477 => ['MMLDXXVII'], + 2478 => ['MMLDXXVIII'], + 2479 => ['MMLDXXIX'], + 2480 => ['MMLDXXX'], + 2481 => ['MMLDXXXI'], + 2482 => ['MMLDXXXII'], + 2483 => ['MMLDXXXIII'], + 2484 => ['MMLDXXXIV'], + 2485 => ['MMLDXXXV'], + 2486 => ['MMLDXXXVI'], + 2487 => ['MMLDXXXVII'], + 2488 => ['MMLDXXXVIII'], + 2489 => ['MMLDXXXIX'], + 2490 => ['MMLDXL', 'MMXD'], + 2491 => ['MMLDXLI', 'MMXDI'], + 2492 => ['MMLDXLII', 'MMXDII'], + 2493 => ['MMLDXLIII', 'MMXDIII'], + 2494 => ['MMLDXLIV', 'MMXDIV'], + 2495 => ['MMLDVL', 'MMXDV', 'MMVD'], + 2496 => ['MMLDVLI', 'MMXDVI', 'MMVDI'], + 2497 => ['MMLDVLII', 'MMXDVII', 'MMVDII'], + 2498 => ['MMLDVLIII', 'MMXDVIII', 'MMVDIII'], + 2499 => ['MMLDVLIV', 'MMXDIX', 'MMVDIV', 'MMID'], + 2545 => ['MMDVL'], + 2546 => ['MMDVLI'], + 2547 => ['MMDVLII'], + 2548 => ['MMDVLIII'], + 2549 => ['MMDVLIV', 'MMDIL'], + 2595 => ['MMDVC'], + 2596 => ['MMDVCI'], + 2597 => ['MMDVCII'], + 2598 => ['MMDVCIII'], + 2599 => ['MMDVCIV', 'MMDIC'], + 2645 => ['MMDCVL'], + 2646 => ['MMDCVLI'], + 2647 => ['MMDCVLII'], + 2648 => ['MMDCVLIII'], + 2649 => ['MMDCVLIV', 'MMDCIL'], + 2695 => ['MMDCVC'], + 2696 => ['MMDCVCI'], + 2697 => ['MMDCVCII'], + 2698 => ['MMDCVCIII'], + 2699 => ['MMDCVCIV', 'MMDCIC'], + 2745 => ['MMDCCVL'], + 2746 => ['MMDCCVLI'], + 2747 => ['MMDCCVLII'], + 2748 => ['MMDCCVLIII'], + 2749 => ['MMDCCVLIV', 'MMDCCIL'], + 2795 => ['MMDCCVC'], + 2796 => ['MMDCCVCI'], + 2797 => ['MMDCCVCII'], + 2798 => ['MMDCCVCIII'], + 2799 => ['MMDCCVCIV', 'MMDCCIC'], + 2845 => ['MMDCCCVL'], + 2846 => ['MMDCCCVLI'], + 2847 => ['MMDCCCVLII'], + 2848 => ['MMDCCCVLIII'], + 2849 => ['MMDCCCVLIV', 'MMDCCCIL'], + 2895 => ['MMDCCCVC'], + 2896 => ['MMDCCCVCI'], + 2897 => ['MMDCCCVCII'], + 2898 => ['MMDCCCVCIII'], + 2899 => ['MMDCCCVCIV', 'MMDCCCIC'], + 2945 => ['MMCMVL'], + 2946 => ['MMCMVLI'], + 2947 => ['MMCMVLII'], + 2948 => ['MMCMVLIII'], + 2949 => ['MMCMVLIV', 'MMCMIL'], + 2950 => ['MMLM'], + 2951 => ['MMLMI'], + 2952 => ['MMLMII'], + 2953 => ['MMLMIII'], + 2954 => ['MMLMIV'], + 2955 => ['MMLMV'], + 2956 => ['MMLMVI'], + 2957 => ['MMLMVII'], + 2958 => ['MMLMVIII'], + 2959 => ['MMLMIX'], + 2960 => ['MMLMX'], + 2961 => ['MMLMXI'], + 2962 => ['MMLMXII'], + 2963 => ['MMLMXIII'], + 2964 => ['MMLMXIV'], + 2965 => ['MMLMXV'], + 2966 => ['MMLMXVI'], + 2967 => ['MMLMXVII'], + 2968 => ['MMLMXVIII'], + 2969 => ['MMLMXIX'], + 2970 => ['MMLMXX'], + 2971 => ['MMLMXXI'], + 2972 => ['MMLMXXII'], + 2973 => ['MMLMXXIII'], + 2974 => ['MMLMXXIV'], + 2975 => ['MMLMXXV'], + 2976 => ['MMLMXXVI'], + 2977 => ['MMLMXXVII'], + 2978 => ['MMLMXXVIII'], + 2979 => ['MMLMXXIX'], + 2980 => ['MMLMXXX'], + 2981 => ['MMLMXXXI'], + 2982 => ['MMLMXXXII'], + 2983 => ['MMLMXXXIII'], + 2984 => ['MMLMXXXIV'], + 2985 => ['MMLMXXXV'], + 2986 => ['MMLMXXXVI'], + 2987 => ['MMLMXXXVII'], + 2988 => ['MMLMXXXVIII'], + 2989 => ['MMLMXXXIX'], + 2990 => ['MMLMXL', 'MMXM'], + 2991 => ['MMLMXLI', 'MMXMI'], + 2992 => ['MMLMXLII', 'MMXMII'], + 2993 => ['MMLMXLIII', 'MMXMIII'], + 2994 => ['MMLMXLIV', 'MMXMIV'], + 2995 => ['MMLMVL', 'MMXMV', 'MMVM'], + 2996 => ['MMLMVLI', 'MMXMVI', 'MMVMI'], + 2997 => ['MMLMVLII', 'MMXMVII', 'MMVMII'], + 2998 => ['MMLMVLIII', 'MMXMVIII', 'MMVMIII'], + 2999 => ['MMLMVLIV', 'MMXMIX', 'MMVMIV', 'MMIM'], + 3045 => ['MMMVL'], + 3046 => ['MMMVLI'], + 3047 => ['MMMVLII'], + 3048 => ['MMMVLIII'], + 3049 => ['MMMVLIV', 'MMMIL'], + 3095 => ['MMMVC'], + 3096 => ['MMMVCI'], + 3097 => ['MMMVCII'], + 3098 => ['MMMVCIII'], + 3099 => ['MMMVCIV', 'MMMIC'], + 3145 => ['MMMCVL'], + 3146 => ['MMMCVLI'], + 3147 => ['MMMCVLII'], + 3148 => ['MMMCVLIII'], + 3149 => ['MMMCVLIV', 'MMMCIL'], + 3195 => ['MMMCVC'], + 3196 => ['MMMCVCI'], + 3197 => ['MMMCVCII'], + 3198 => ['MMMCVCIII'], + 3199 => ['MMMCVCIV', 'MMMCIC'], + 3245 => ['MMMCCVL'], + 3246 => ['MMMCCVLI'], + 3247 => ['MMMCCVLII'], + 3248 => ['MMMCCVLIII'], + 3249 => ['MMMCCVLIV', 'MMMCCIL'], + 3295 => ['MMMCCVC'], + 3296 => ['MMMCCVCI'], + 3297 => ['MMMCCVCII'], + 3298 => ['MMMCCVCIII'], + 3299 => ['MMMCCVCIV', 'MMMCCIC'], + 3345 => ['MMMCCCVL'], + 3346 => ['MMMCCCVLI'], + 3347 => ['MMMCCCVLII'], + 3348 => ['MMMCCCVLIII'], + 3349 => ['MMMCCCVLIV', 'MMMCCCIL'], + 3395 => ['MMMCCCVC'], + 3396 => ['MMMCCCVCI'], + 3397 => ['MMMCCCVCII'], + 3398 => ['MMMCCCVCIII'], + 3399 => ['MMMCCCVCIV', 'MMMCCCIC'], + 3445 => ['MMMCDVL'], + 3446 => ['MMMCDVLI'], + 3447 => ['MMMCDVLII'], + 3448 => ['MMMCDVLIII'], + 3449 => ['MMMCDVLIV', 'MMMCDIL'], + 3450 => ['MMMLD'], + 3451 => ['MMMLDI'], + 3452 => ['MMMLDII'], + 3453 => ['MMMLDIII'], + 3454 => ['MMMLDIV'], + 3455 => ['MMMLDV'], + 3456 => ['MMMLDVI'], + 3457 => ['MMMLDVII'], + 3458 => ['MMMLDVIII'], + 3459 => ['MMMLDIX'], + 3460 => ['MMMLDX'], + 3461 => ['MMMLDXI'], + 3462 => ['MMMLDXII'], + 3463 => ['MMMLDXIII'], + 3464 => ['MMMLDXIV'], + 3465 => ['MMMLDXV'], + 3466 => ['MMMLDXVI'], + 3467 => ['MMMLDXVII'], + 3468 => ['MMMLDXVIII'], + 3469 => ['MMMLDXIX'], + 3470 => ['MMMLDXX'], + 3471 => ['MMMLDXXI'], + 3472 => ['MMMLDXXII'], + 3473 => ['MMMLDXXIII'], + 3474 => ['MMMLDXXIV'], + 3475 => ['MMMLDXXV'], + 3476 => ['MMMLDXXVI'], + 3477 => ['MMMLDXXVII'], + 3478 => ['MMMLDXXVIII'], + 3479 => ['MMMLDXXIX'], + 3480 => ['MMMLDXXX'], + 3481 => ['MMMLDXXXI'], + 3482 => ['MMMLDXXXII'], + 3483 => ['MMMLDXXXIII'], + 3484 => ['MMMLDXXXIV'], + 3485 => ['MMMLDXXXV'], + 3486 => ['MMMLDXXXVI'], + 3487 => ['MMMLDXXXVII'], + 3488 => ['MMMLDXXXVIII'], + 3489 => ['MMMLDXXXIX'], + 3490 => ['MMMLDXL', 'MMMXD'], + 3491 => ['MMMLDXLI', 'MMMXDI'], + 3492 => ['MMMLDXLII', 'MMMXDII'], + 3493 => ['MMMLDXLIII', 'MMMXDIII'], + 3494 => ['MMMLDXLIV', 'MMMXDIV'], + 3495 => ['MMMLDVL', 'MMMXDV', 'MMMVD'], + 3496 => ['MMMLDVLI', 'MMMXDVI', 'MMMVDI'], + 3497 => ['MMMLDVLII', 'MMMXDVII', 'MMMVDII'], + 3498 => ['MMMLDVLIII', 'MMMXDVIII', 'MMMVDIII'], + 3499 => ['MMMLDVLIV', 'MMMXDIX', 'MMMVDIV', 'MMMID'], + 3545 => ['MMMDVL'], + 3546 => ['MMMDVLI'], + 3547 => ['MMMDVLII'], + 3548 => ['MMMDVLIII'], + 3549 => ['MMMDVLIV', 'MMMDIL'], + 3595 => ['MMMDVC'], + 3596 => ['MMMDVCI'], + 3597 => ['MMMDVCII'], + 3598 => ['MMMDVCIII'], + 3599 => ['MMMDVCIV', 'MMMDIC'], + 3645 => ['MMMDCVL'], + 3646 => ['MMMDCVLI'], + 3647 => ['MMMDCVLII'], + 3648 => ['MMMDCVLIII'], + 3649 => ['MMMDCVLIV', 'MMMDCIL'], + 3695 => ['MMMDCVC'], + 3696 => ['MMMDCVCI'], + 3697 => ['MMMDCVCII'], + 3698 => ['MMMDCVCIII'], + 3699 => ['MMMDCVCIV', 'MMMDCIC'], + 3745 => ['MMMDCCVL'], + 3746 => ['MMMDCCVLI'], + 3747 => ['MMMDCCVLII'], + 3748 => ['MMMDCCVLIII'], + 3749 => ['MMMDCCVLIV', 'MMMDCCIL'], + 3795 => ['MMMDCCVC'], + 3796 => ['MMMDCCVCI'], + 3797 => ['MMMDCCVCII'], + 3798 => ['MMMDCCVCIII'], + 3799 => ['MMMDCCVCIV', 'MMMDCCIC'], + 3845 => ['MMMDCCCVL'], + 3846 => ['MMMDCCCVLI'], + 3847 => ['MMMDCCCVLII'], + 3848 => ['MMMDCCCVLIII'], + 3849 => ['MMMDCCCVLIV', 'MMMDCCCIL'], + 3895 => ['MMMDCCCVC'], + 3896 => ['MMMDCCCVCI'], + 3897 => ['MMMDCCCVCII'], + 3898 => ['MMMDCCCVCIII'], + 3899 => ['MMMDCCCVCIV', 'MMMDCCCIC'], + 3945 => ['MMMCMVL'], + 3946 => ['MMMCMVLI'], + 3947 => ['MMMCMVLII'], + 3948 => ['MMMCMVLIII'], + 3949 => ['MMMCMVLIV', 'MMMCMIL'], + 3950 => ['MMMLM'], + 3951 => ['MMMLMI'], + 3952 => ['MMMLMII'], + 3953 => ['MMMLMIII'], + 3954 => ['MMMLMIV'], + 3955 => ['MMMLMV'], + 3956 => ['MMMLMVI'], + 3957 => ['MMMLMVII'], + 3958 => ['MMMLMVIII'], + 3959 => ['MMMLMIX'], + 3960 => ['MMMLMX'], + 3961 => ['MMMLMXI'], + 3962 => ['MMMLMXII'], + 3963 => ['MMMLMXIII'], + 3964 => ['MMMLMXIV'], + 3965 => ['MMMLMXV'], + 3966 => ['MMMLMXVI'], + 3967 => ['MMMLMXVII'], + 3968 => ['MMMLMXVIII'], + 3969 => ['MMMLMXIX'], + 3970 => ['MMMLMXX'], + 3971 => ['MMMLMXXI'], + 3972 => ['MMMLMXXII'], + 3973 => ['MMMLMXXIII'], + 3974 => ['MMMLMXXIV'], + 3975 => ['MMMLMXXV'], + 3976 => ['MMMLMXXVI'], + 3977 => ['MMMLMXXVII'], + 3978 => ['MMMLMXXVIII'], + 3979 => ['MMMLMXXIX'], + 3980 => ['MMMLMXXX'], + 3981 => ['MMMLMXXXI'], + 3982 => ['MMMLMXXXII'], + 3983 => ['MMMLMXXXIII'], + 3984 => ['MMMLMXXXIV'], + 3985 => ['MMMLMXXXV'], + 3986 => ['MMMLMXXXVI'], + 3987 => ['MMMLMXXXVII'], + 3988 => ['MMMLMXXXVIII'], + 3989 => ['MMMLMXXXIX'], + 3990 => ['MMMLMXL', 'MMMXM'], + 3991 => ['MMMLMXLI', 'MMMXMI'], + 3992 => ['MMMLMXLII', 'MMMXMII'], + 3993 => ['MMMLMXLIII', 'MMMXMIII'], + 3994 => ['MMMLMXLIV', 'MMMXMIV'], + 3995 => ['MMMLMVL', 'MMMXMV', 'MMMVM'], + 3996 => ['MMMLMVLI', 'MMMXMVI', 'MMMVMI'], + 3997 => ['MMMLMVLII', 'MMMXMVII', 'MMMVMII'], + 3998 => ['MMMLMVLIII', 'MMMXMVIII', 'MMMVMIII'], + 3999 => ['MMMLMVLIV', 'MMMXMIX', 'MMMVMIV', 'MMMIM'], + ]; + + private const THOUSANDS = ['', 'M', 'MM', 'MMM']; + private const HUNDREDS = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM']; + private const TENS = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC']; + private const ONES = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']; + const MAX_ROMAN_VALUE = 3999; + const MAX_ROMAN_STYLE = 4; + + private static function valueOk(int $aValue, int $style): string + { + $origValue = $aValue; + $m = \intdiv($aValue, 1000); + $aValue %= 1000; + $c = \intdiv($aValue, 100); + $aValue %= 100; + $t = \intdiv($aValue, 10); + $aValue %= 10; + $result = self::THOUSANDS[$m] . self::HUNDREDS[$c] . self::TENS[$t] . self::ONES[$aValue]; + if ($style > 0) { + if (array_key_exists($origValue, self::VALUES)) { + $arr = self::VALUES[$origValue]; + $idx = min($style, count($arr)) - 1; + $result = $arr[$idx]; + } + } + + return $result; + } + + private static function styleOk(int $aValue, int $style): string + { + return ($aValue < 0 || $aValue > self::MAX_ROMAN_VALUE) ? Functions::VALUE() : self::valueOk($aValue, $style); + } + + public static function calculateRoman(int $aValue, int $style): string + { + return ($style < 0 || $style > self::MAX_ROMAN_STYLE) ? Functions::VALUE() : self::styleOk($aValue, $style); + } + + /** + * ROMAN. + * + * Converts a number to Roman numeral + * + * @param mixed $aValue Number to convert + * @param mixed $style Number indicating one of five possible forms + * + * @return string Roman numeral, or a string containing an error + */ + public static function evaluate($aValue, $style = 0) + { + try { + $aValue = Helpers::validateNumericNullBool($aValue); + if (is_bool($style)) { + $style = $style ? 0 : 4; + } + $style = Helpers::validateNumericNullSubstitution($style, null); + } catch (Exception $e) { + return $e->getMessage(); + } + + return self::calculateRoman((int) $aValue, (int) $style); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Round.php b/src/PhpSpreadsheet/Calculation/MathTrig/Round.php new file mode 100644 index 00000000..2ddde900 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Round.php @@ -0,0 +1,179 @@ +getMessage(); + } + + return round($number, (int) $precision); + } + + /** + * ROUNDUP. + * + * Rounds a number up to a specified number of decimal places + * + * @param float $number Number to round + * @param int $digits Number of digits to which you want to round $number + * + * @return float|string Rounded Number, or a string containing an error + */ + public static function up($number, $digits) + { + try { + $number = Helpers::validateNumericNullBool($number); + $digits = (int) Helpers::validateNumericNullSubstitution($digits, null); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($number == 0.0) { + return 0.0; + } + + if ($number < 0.0) { + return round($number - 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_DOWN); + } + + return round($number + 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_DOWN); + } + + /** + * ROUNDDOWN. + * + * Rounds a number down to a specified number of decimal places + * + * @param float $number Number to round + * @param int $digits Number of digits to which you want to round $number + * + * @return float|string Rounded Number, or a string containing an error + */ + public static function down($number, $digits) + { + try { + $number = Helpers::validateNumericNullBool($number); + $digits = (int) Helpers::validateNumericNullSubstitution($digits, null); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($number == 0.0) { + return 0.0; + } + + if ($number < 0.0) { + return round($number + 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_UP); + } + + return round($number - 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_UP); + } + + /** + * MROUND. + * + * Rounds a number to the nearest multiple of a specified value + * + * @param mixed $number Expect float. Number to round. + * @param mixed $multiple Expect int. Multiple to which you want to round. + * + * @return float|string Rounded Number, or a string containing an error + */ + public static function multiple($number, $multiple) + { + try { + $number = Helpers::validateNumericNullSubstitution($number, 0); + $multiple = Helpers::validateNumericNullSubstitution($multiple, null); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($number == 0 || $multiple == 0) { + return 0; + } + if ((Helpers::returnSign($number)) == (Helpers::returnSign($multiple))) { + $multiplier = 1 / $multiple; + + return round($number * $multiplier) / $multiplier; + } + + return Functions::NAN(); + } + + /** + * EVEN. + * + * Returns number rounded up to the nearest even integer. + * You can use this function for processing items that come in twos. For example, + * a packing crate accepts rows of one or two items. The crate is full when + * the number of items, rounded up to the nearest two, matches the crate's + * capacity. + * + * Excel Function: + * EVEN(number) + * + * @param float $number Number to round + * + * @return float|string Rounded Number, or a string containing an error + */ + public static function even($number) + { + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return Helpers::getEven($number); + } + + /** + * ODD. + * + * Returns number rounded up to the nearest odd integer. + * + * @param float $number Number to round + * + * @return float|string Rounded Number, or a string containing an error + */ + public static function odd($number) + { + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + $significance = Helpers::returnSign($number); + if ($significance == 0) { + return 1; + } + + $result = ceil($number / $significance) * $significance; + if ($result == Helpers::getEven($result)) { + $result += $significance; + } + + return $result; + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/SeriesSum.php b/src/PhpSpreadsheet/Calculation/MathTrig/SeriesSum.php new file mode 100644 index 00000000..2ada9df4 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/SeriesSum.php @@ -0,0 +1,46 @@ +getMessage(); + } + + return $returnValue; + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Sign.php b/src/PhpSpreadsheet/Calculation/MathTrig/Sign.php new file mode 100644 index 00000000..a48cf0f9 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Sign.php @@ -0,0 +1,29 @@ +getMessage(); + } + + return Helpers::returnSign($number); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Sqrt.php b/src/PhpSpreadsheet/Calculation/MathTrig/Sqrt.php new file mode 100644 index 00000000..8ead578e --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Sqrt.php @@ -0,0 +1,49 @@ +getMessage(); + } + + return Helpers::numberOrNan(sqrt($number)); + } + + /** + * SQRTPI. + * + * Returns the square root of (number * pi). + * + * @param float $number Number + * + * @return float|string Square Root of Number * Pi, or a string containing an error + */ + public static function pi($number) + { + try { + $number = Helpers::validateNumericNullSubstitution($number, 0); + Helpers::validateNotNegative($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return sqrt($number * M_PI); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Subtotal.php b/src/PhpSpreadsheet/Calculation/MathTrig/Subtotal.php new file mode 100644 index 00000000..2edb86f7 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Subtotal.php @@ -0,0 +1,111 @@ +getWorksheet()->getRowDimension($row)->getVisible(); + }, + ARRAY_FILTER_USE_KEY + ); + } + + /** + * @param mixed $cellReference + * @param mixed $args + */ + protected static function filterFormulaArgs($cellReference, $args): array + { + return array_filter( + $args, + function ($index) use ($cellReference) { + [, $row, $column] = explode('.', $index); + $retVal = true; + if ($cellReference->getWorksheet()->cellExists($column . $row)) { + //take this cell out if it contains the SUBTOTAL or AGGREGATE functions in a formula + $isFormula = $cellReference->getWorksheet()->getCell($column . $row)->isFormula(); + $cellFormula = !preg_match('/^=.*\b(SUBTOTAL|AGGREGATE)\s*\(/i', $cellReference->getWorksheet()->getCell($column . $row)->getValue()); + + $retVal = !$isFormula || $cellFormula; + } + + return $retVal; + }, + ARRAY_FILTER_USE_KEY + ); + } + + /** @var callable[] */ + private const CALL_FUNCTIONS = [ + 1 => [Statistical\Averages::class, 'average'], + [Statistical\Counts::class, 'COUNT'], // 2 + [Statistical\Counts::class, 'COUNTA'], // 3 + [Statistical\Maximum::class, 'max'], // 4 + [Statistical\Minimum::class, 'min'], // 5 + [Operations::class, 'product'], // 6 + [Statistical\StandardDeviations::class, 'STDEV'], // 7 + [Statistical\StandardDeviations::class, 'STDEVP'], // 8 + [Sum::class, 'sumIgnoringStrings'], // 9 + [Statistical\Variances::class, 'VAR'], // 10 + [Statistical\Variances::class, 'VARP'], // 11 + ]; + + /** + * SUBTOTAL. + * + * Returns a subtotal in a list or database. + * + * @param mixed $functionType + * A number 1 to 11 that specifies which function to + * use in calculating subtotals within a range + * list + * Numbers 101 to 111 shadow the functions of 1 to 11 + * but ignore any values in the range that are + * in hidden rows + * @param mixed[] $args A mixed data series of values + * + * @return float|string + */ + public static function evaluate($functionType, ...$args) + { + $cellReference = array_pop($args); + $aArgs = Functions::flattenArrayIndexed($args); + + try { + $subtotal = (int) Helpers::validateNumericNullBool($functionType); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Calculate + if ($subtotal > 100) { + $aArgs = self::filterHiddenArgs($cellReference, $aArgs); + $subtotal -= 100; + } + + $aArgs = self::filterFormulaArgs($cellReference, $aArgs); + if (array_key_exists($subtotal, self::CALL_FUNCTIONS)) { + /** @var callable */ + $call = self::CALL_FUNCTIONS[$subtotal]; + + return call_user_func_array($call, $aArgs); + } + + return Functions::VALUE(); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Sum.php b/src/PhpSpreadsheet/Calculation/MathTrig/Sum.php new file mode 100644 index 00000000..741734d9 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Sum.php @@ -0,0 +1,115 @@ + $arg) { + // Is it a numeric value? + if (is_numeric($arg) || empty($arg)) { + if (is_string($arg)) { + $arg = (int) $arg; + } + $returnValue += $arg; + } elseif (is_bool($arg)) { + $returnValue += (int) $arg; + } elseif (Functions::isError($arg)) { + return $arg; + // ignore non-numerics from cell, but fail as literals (except null) + } elseif ($arg !== null && !Functions::isCellValue($k)) { + return Functions::VALUE(); + } + } + + return $returnValue; + } + + /** + * SUMPRODUCT. + * + * Excel Function: + * SUMPRODUCT(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float|string The result, or a string containing an error + */ + public static function product(...$args) + { + $arrayList = $args; + + $wrkArray = Functions::flattenArray(array_shift($arrayList)); + $wrkCellCount = count($wrkArray); + + for ($i = 0; $i < $wrkCellCount; ++$i) { + if ((!is_numeric($wrkArray[$i])) || (is_string($wrkArray[$i]))) { + $wrkArray[$i] = 0; + } + } + + foreach ($arrayList as $matrixData) { + $array2 = Functions::flattenArray($matrixData); + $count = count($array2); + if ($wrkCellCount != $count) { + return Functions::VALUE(); + } + + foreach ($array2 as $i => $val) { + if ((!is_numeric($val)) || (is_string($val))) { + $val = 0; + } + $wrkArray[$i] *= $val; + } + } + + return array_sum($wrkArray); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/SumSquares.php b/src/PhpSpreadsheet/Calculation/MathTrig/SumSquares.php new file mode 100644 index 00000000..49fa6381 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/SumSquares.php @@ -0,0 +1,142 @@ +getMessage(); + } + + return $returnValue; + } + + private static function getCount(array $array1, array $array2): int + { + $count = count($array1); + if ($count !== count($array2)) { + throw new Exception(Functions::NA()); + } + + return $count; + } + + /** + * These functions accept only numeric arguments, not even strings which are numeric. + * + * @param mixed $item + */ + private static function numericNotString($item): bool + { + return is_numeric($item) && !is_string($item); + } + + /** + * SUMX2MY2. + * + * @param mixed[] $matrixData1 Matrix #1 + * @param mixed[] $matrixData2 Matrix #2 + * + * @return float|string + */ + public static function sumXSquaredMinusYSquared($matrixData1, $matrixData2) + { + try { + $array1 = Functions::flattenArray($matrixData1); + $array2 = Functions::flattenArray($matrixData2); + $count = self::getCount($array1, $array2); + + $result = 0; + for ($i = 0; $i < $count; ++$i) { + if (self::numericNotString($array1[$i]) && self::numericNotString($array2[$i])) { + $result += ($array1[$i] * $array1[$i]) - ($array2[$i] * $array2[$i]); + } + } + } catch (Exception $e) { + return $e->getMessage(); + } + + return $result; + } + + /** + * SUMX2PY2. + * + * @param mixed[] $matrixData1 Matrix #1 + * @param mixed[] $matrixData2 Matrix #2 + * + * @return float|string + */ + public static function sumXSquaredPlusYSquared($matrixData1, $matrixData2) + { + try { + $array1 = Functions::flattenArray($matrixData1); + $array2 = Functions::flattenArray($matrixData2); + $count = self::getCount($array1, $array2); + + $result = 0; + for ($i = 0; $i < $count; ++$i) { + if (self::numericNotString($array1[$i]) && self::numericNotString($array2[$i])) { + $result += ($array1[$i] * $array1[$i]) + ($array2[$i] * $array2[$i]); + } + } + } catch (Exception $e) { + return $e->getMessage(); + } + + return $result; + } + + /** + * SUMXMY2. + * + * @param mixed[] $matrixData1 Matrix #1 + * @param mixed[] $matrixData2 Matrix #2 + * + * @return float|string + */ + public static function sumXMinusYSquared($matrixData1, $matrixData2) + { + try { + $array1 = Functions::flattenArray($matrixData1); + $array2 = Functions::flattenArray($matrixData2); + $count = self::getCount($array1, $array2); + + $result = 0; + for ($i = 0; $i < $count; ++$i) { + if (self::numericNotString($array1[$i]) && self::numericNotString($array2[$i])) { + $result += ($array1[$i] - $array2[$i]) * ($array1[$i] - $array2[$i]); + } + } + } catch (Exception $e) { + return $e->getMessage(); + } + + return $result; + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosecant.php b/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosecant.php new file mode 100644 index 00000000..3038e6cc --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosecant.php @@ -0,0 +1,49 @@ +getMessage(); + } + + return Helpers::verySmallDenominator(1.0, sin($angle)); + } + + /** + * CSCH. + * + * Returns the hyperbolic cosecant of an angle. + * + * @param float $angle Number + * + * @return float|string The hyperbolic cosecant of the angle + */ + public static function csch($angle) + { + try { + $angle = Helpers::validateNumericNullBool($angle); + } catch (Exception $e) { + return $e->getMessage(); + } + + return Helpers::verySmallDenominator(1.0, sinh($angle)); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosine.php b/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosine.php new file mode 100644 index 00000000..6c69e126 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosine.php @@ -0,0 +1,89 @@ +getMessage(); + } + + return cos($number); + } + + /** + * COSH. + * + * Returns the result of builtin function cosh after validating args. + * + * @param mixed $number Should be numeric + * + * @return float|string hyperbolic cosine + */ + public static function cosh($number) + { + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return cosh($number); + } + + /** + * ACOS. + * + * Returns the arccosine of a number. + * + * @param float $number Number + * + * @return float|string The arccosine of the number + */ + public static function acos($number) + { + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return Helpers::numberOrNan(acos($number)); + } + + /** + * ACOSH. + * + * Returns the arc inverse hyperbolic cosine of a number. + * + * @param float $number Number + * + * @return float|string The inverse hyperbolic cosine of the number, or an error string + */ + public static function acosh($number) + { + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return Helpers::numberOrNan(acosh($number)); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cotangent.php b/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cotangent.php new file mode 100644 index 00000000..1b796f50 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cotangent.php @@ -0,0 +1,91 @@ +getMessage(); + } + + return Helpers::verySmallDenominator(cos($angle), sin($angle)); + } + + /** + * COTH. + * + * Returns the hyperbolic cotangent of an angle. + * + * @param float $angle Number + * + * @return float|string The hyperbolic cotangent of the angle + */ + public static function coth($angle) + { + try { + $angle = Helpers::validateNumericNullBool($angle); + } catch (Exception $e) { + return $e->getMessage(); + } + + return Helpers::verySmallDenominator(1.0, tanh($angle)); + } + + /** + * ACOT. + * + * Returns the arccotangent of a number. + * + * @param float $number Number + * + * @return float|string The arccotangent of the number + */ + public static function acot($number) + { + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return (M_PI / 2) - atan($number); + } + + /** + * ACOTH. + * + * Returns the hyperbolic arccotangent of a number. + * + * @param float $number Number + * + * @return float|string The hyperbolic arccotangent of the number + */ + public static function acoth($number) + { + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + $result = ($number === 1) ? NAN : (log(($number + 1) / ($number - 1)) / 2); + + return Helpers::numberOrNan($result); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Secant.php b/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Secant.php new file mode 100644 index 00000000..70299cb7 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Secant.php @@ -0,0 +1,49 @@ +getMessage(); + } + + return Helpers::verySmallDenominator(1.0, cos($angle)); + } + + /** + * SECH. + * + * Returns the hyperbolic secant of an angle. + * + * @param float $angle Number + * + * @return float|string The hyperbolic secant of the angle + */ + public static function sech($angle) + { + try { + $angle = Helpers::validateNumericNullBool($angle); + } catch (Exception $e) { + return $e->getMessage(); + } + + return Helpers::verySmallDenominator(1.0, cosh($angle)); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Sine.php b/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Sine.php new file mode 100644 index 00000000..2c6a8a07 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Sine.php @@ -0,0 +1,89 @@ +getMessage(); + } + + return sin($angle); + } + + /** + * SINH. + * + * Returns the result of builtin function sinh after validating args. + * + * @param mixed $angle Should be numeric + * + * @return float|string hyperbolic sine + */ + public static function sinh($angle) + { + try { + $angle = Helpers::validateNumericNullBool($angle); + } catch (Exception $e) { + return $e->getMessage(); + } + + return sinh($angle); + } + + /** + * ASIN. + * + * Returns the arcsine of a number. + * + * @param float $number Number + * + * @return float|string The arcsine of the number + */ + public static function asin($number) + { + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return Helpers::numberOrNan(asin($number)); + } + + /** + * ASINH. + * + * Returns the inverse hyperbolic sine of a number. + * + * @param float $number Number + * + * @return float|string The inverse hyperbolic sine of the number + */ + public static function asinh($number) + { + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return Helpers::numberOrNan(asinh($number)); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Tangent.php b/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Tangent.php new file mode 100644 index 00000000..6cd235fb --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Tangent.php @@ -0,0 +1,127 @@ +getMessage(); + } + + return Helpers::verySmallDenominator(sin($angle), cos($angle)); + } + + /** + * TANH. + * + * Returns the result of builtin function sinh after validating args. + * + * @param mixed $angle Should be numeric + * + * @return float|string hyperbolic tangent + */ + public static function tanh($angle) + { + try { + $angle = Helpers::validateNumericNullBool($angle); + } catch (Exception $e) { + return $e->getMessage(); + } + + return tanh($angle); + } + + /** + * ATAN. + * + * Returns the arctangent of a number. + * + * @param float $number Number + * + * @return float|string The arctangent of the number + */ + public static function atan($number) + { + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return Helpers::numberOrNan(atan($number)); + } + + /** + * ATANH. + * + * Returns the inverse hyperbolic tangent of a number. + * + * @param float $number Number + * + * @return float|string The inverse hyperbolic tangent of the number + */ + public static function atanh($number) + { + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return Helpers::numberOrNan(atanh($number)); + } + + /** + * ATAN2. + * + * This function calculates the arc tangent of the two variables x and y. It is similar to + * calculating the arc tangent of y ÷ x, except that the signs of both arguments are used + * to determine the quadrant of the result. + * The arctangent is the angle from the x-axis to a line containing the origin (0, 0) and a + * point with coordinates (xCoordinate, yCoordinate). The angle is given in radians between + * -pi and pi, excluding -pi. + * + * Note that the Excel ATAN2() function accepts its arguments in the reverse order to the standard + * PHP atan2() function, so we need to reverse them here before calling the PHP atan() function. + * + * Excel Function: + * ATAN2(xCoordinate,yCoordinate) + * + * @param mixed $xCoordinate should be float, the x-coordinate of the point + * @param mixed $yCoordinate should be float, the y-coordinate of the point + * + * @return float|string the inverse tangent of the specified x- and y-coordinates, or a string containing an error + */ + public static function atan2($xCoordinate, $yCoordinate) + { + try { + $xCoordinate = Helpers::validateNumericNullBool($xCoordinate); + $yCoordinate = Helpers::validateNumericNullBool($yCoordinate); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (($xCoordinate == 0) && ($yCoordinate == 0)) { + return Functions::DIV0(); + } + + return atan2($yCoordinate, $xCoordinate); + } +} diff --git a/src/PhpSpreadsheet/Calculation/MathTrig/Trunc.php b/src/PhpSpreadsheet/Calculation/MathTrig/Trunc.php new file mode 100644 index 00000000..4b3670f6 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/MathTrig/Trunc.php @@ -0,0 +1,39 @@ +getMessage(); + } + + $digits = floor($digits); + + // Truncate + $adjust = 10 ** $digits; + + if (($digits > 0) && (rtrim((string) (int) ((abs($value) - abs((int) $value)) * $adjust), '0') < $adjust / 10)) { + return $value; + } + + return ((int) ($value * $adjust)) / $adjust; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical.php b/src/PhpSpreadsheet/Calculation/Statistical.php index 19f40f2d..d43a85f9 100644 --- a/src/PhpSpreadsheet/Calculation/Statistical.php +++ b/src/PhpSpreadsheet/Calculation/Statistical.php @@ -2,564 +2,27 @@ namespace PhpOffice\PhpSpreadsheet\Calculation; -use PhpOffice\PhpSpreadsheet\Shared\Trend\Trend; +use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages; +use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional; +use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Confidence; +use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts; +use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Maximum; +use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Minimum; +use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Permutations; +use PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations; +use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends; +use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances; +/** + * @deprecated 1.18.0 + */ class Statistical { const LOG_GAMMA_X_MAX_VALUE = 2.55e305; - const XMININ = 2.23e-308; const EPS = 2.22e-16; const MAX_VALUE = 1.2e308; - const MAX_ITERATIONS = 256; const SQRT2PI = 2.5066282746310005024157652848110452530069867406099; - private static function checkTrendArrays(&$array1, &$array2) - { - if (!is_array($array1)) { - $array1 = [$array1]; - } - if (!is_array($array2)) { - $array2 = [$array2]; - } - - $array1 = Functions::flattenArray($array1); - $array2 = Functions::flattenArray($array2); - foreach ($array1 as $key => $value) { - if ((is_bool($value)) || (is_string($value)) || ($value === null)) { - unset($array1[$key], $array2[$key]); - } - } - foreach ($array2 as $key => $value) { - if ((is_bool($value)) || (is_string($value)) || ($value === null)) { - unset($array1[$key], $array2[$key]); - } - } - $array1 = array_merge($array1); - $array2 = array_merge($array2); - - return true; - } - - /** - * Incomplete beta function. - * - * @author Jaco van Kooten - * @author Paul Meagher - * - * The computation is based on formulas from Numerical Recipes, Chapter 6.4 (W.H. Press et al, 1992). - * - * @param mixed $x require 0<=x<=1 - * @param mixed $p require p>0 - * @param mixed $q require q>0 - * - * @return float 0 if x<0, p<=0, q<=0 or p+q>2.55E305 and 1 if x>1 to avoid errors and over/underflow - */ - private static function incompleteBeta($x, $p, $q) - { - if ($x <= 0.0) { - return 0.0; - } elseif ($x >= 1.0) { - return 1.0; - } elseif (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > self::LOG_GAMMA_X_MAX_VALUE)) { - return 0.0; - } - $beta_gam = exp((0 - self::logBeta($p, $q)) + $p * log($x) + $q * log(1.0 - $x)); - if ($x < ($p + 1.0) / ($p + $q + 2.0)) { - return $beta_gam * self::betaFraction($x, $p, $q) / $p; - } - - return 1.0 - ($beta_gam * self::betaFraction(1 - $x, $q, $p) / $q); - } - - // Function cache for logBeta function - private static $logBetaCacheP = 0.0; - - private static $logBetaCacheQ = 0.0; - - private static $logBetaCacheResult = 0.0; - - /** - * The natural logarithm of the beta function. - * - * @param mixed $p require p>0 - * @param mixed $q require q>0 - * - * @return float 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow - * - * @author Jaco van Kooten - */ - private static function logBeta($p, $q) - { - if ($p != self::$logBetaCacheP || $q != self::$logBetaCacheQ) { - self::$logBetaCacheP = $p; - self::$logBetaCacheQ = $q; - if (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > self::LOG_GAMMA_X_MAX_VALUE)) { - self::$logBetaCacheResult = 0.0; - } else { - self::$logBetaCacheResult = self::logGamma($p) + self::logGamma($q) - self::logGamma($p + $q); - } - } - - return self::$logBetaCacheResult; - } - - /** - * Evaluates of continued fraction part of incomplete beta function. - * Based on an idea from Numerical Recipes (W.H. Press et al, 1992). - * - * @author Jaco van Kooten - * - * @param mixed $x - * @param mixed $p - * @param mixed $q - * - * @return float - */ - private static function betaFraction($x, $p, $q) - { - $c = 1.0; - $sum_pq = $p + $q; - $p_plus = $p + 1.0; - $p_minus = $p - 1.0; - $h = 1.0 - $sum_pq * $x / $p_plus; - if (abs($h) < self::XMININ) { - $h = self::XMININ; - } - $h = 1.0 / $h; - $frac = $h; - $m = 1; - $delta = 0.0; - while ($m <= self::MAX_ITERATIONS && abs($delta - 1.0) > Functions::PRECISION) { - $m2 = 2 * $m; - // even index for d - $d = $m * ($q - $m) * $x / (($p_minus + $m2) * ($p + $m2)); - $h = 1.0 + $d * $h; - if (abs($h) < self::XMININ) { - $h = self::XMININ; - } - $h = 1.0 / $h; - $c = 1.0 + $d / $c; - if (abs($c) < self::XMININ) { - $c = self::XMININ; - } - $frac *= $h * $c; - // odd index for d - $d = -($p + $m) * ($sum_pq + $m) * $x / (($p + $m2) * ($p_plus + $m2)); - $h = 1.0 + $d * $h; - if (abs($h) < self::XMININ) { - $h = self::XMININ; - } - $h = 1.0 / $h; - $c = 1.0 + $d / $c; - if (abs($c) < self::XMININ) { - $c = self::XMININ; - } - $delta = $h * $c; - $frac *= $delta; - ++$m; - } - - return $frac; - } - - /** - * logGamma function. - * - * @version 1.1 - * - * @author Jaco van Kooten - * - * Original author was Jaco van Kooten. Ported to PHP by Paul Meagher. - * - * The natural logarithm of the gamma function.
- * Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz
- * Applied Mathematics Division
- * Argonne National Laboratory
- * Argonne, IL 60439
- *

- * References: - *

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

- *

- * From the original documentation: - *

- *

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

- *

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

- * - * @return float MAX_VALUE for x < 0.0 or when overflow would occur, i.e. x > 2.55E305 - */ - - // Function cache for logGamma - private static $logGammaCacheResult = 0.0; - - private static $logGammaCacheX = 0.0; - - private static function logGamma($x) - { - // Log Gamma related constants - static $lg_d1 = -0.5772156649015328605195174; - static $lg_d2 = 0.4227843350984671393993777; - static $lg_d4 = 1.791759469228055000094023; - - static $lg_p1 = [ - 4.945235359296727046734888, - 201.8112620856775083915565, - 2290.838373831346393026739, - 11319.67205903380828685045, - 28557.24635671635335736389, - 38484.96228443793359990269, - 26377.48787624195437963534, - 7225.813979700288197698961, - ]; - static $lg_p2 = [ - 4.974607845568932035012064, - 542.4138599891070494101986, - 15506.93864978364947665077, - 184793.2904445632425417223, - 1088204.76946882876749847, - 3338152.967987029735917223, - 5106661.678927352456275255, - 3074109.054850539556250927, - ]; - static $lg_p4 = [ - 14745.02166059939948905062, - 2426813.369486704502836312, - 121475557.4045093227939592, - 2663432449.630976949898078, - 29403789566.34553899906876, - 170266573776.5398868392998, - 492612579337.743088758812, - 560625185622.3951465078242, - ]; - static $lg_q1 = [ - 67.48212550303777196073036, - 1113.332393857199323513008, - 7738.757056935398733233834, - 27639.87074403340708898585, - 54993.10206226157329794414, - 61611.22180066002127833352, - 36351.27591501940507276287, - 8785.536302431013170870835, - ]; - static $lg_q2 = [ - 183.0328399370592604055942, - 7765.049321445005871323047, - 133190.3827966074194402448, - 1136705.821321969608938755, - 5267964.117437946917577538, - 13467014.54311101692290052, - 17827365.30353274213975932, - 9533095.591844353613395747, - ]; - static $lg_q4 = [ - 2690.530175870899333379843, - 639388.5654300092398984238, - 41355999.30241388052042842, - 1120872109.61614794137657, - 14886137286.78813811542398, - 101680358627.2438228077304, - 341747634550.7377132798597, - 446315818741.9713286462081, - ]; - static $lg_c = [ - -0.001910444077728, - 8.4171387781295e-4, - -5.952379913043012e-4, - 7.93650793500350248e-4, - -0.002777777777777681622553, - 0.08333333333333333331554247, - 0.0057083835261, - ]; - - // Rough estimate of the fourth root of logGamma_xBig - static $lg_frtbig = 2.25e76; - static $pnt68 = 0.6796875; - - if ($x == self::$logGammaCacheX) { - return self::$logGammaCacheResult; - } - $y = $x; - if ($y > 0.0 && $y <= self::LOG_GAMMA_X_MAX_VALUE) { - if ($y <= self::EPS) { - $res = -log($y); - } elseif ($y <= 1.5) { - // --------------------- - // EPS .LT. X .LE. 1.5 - // --------------------- - if ($y < $pnt68) { - $corr = -log($y); - $xm1 = $y; - } else { - $corr = 0.0; - $xm1 = $y - 1.0; - } - if ($y <= 0.5 || $y >= $pnt68) { - $xden = 1.0; - $xnum = 0.0; - for ($i = 0; $i < 8; ++$i) { - $xnum = $xnum * $xm1 + $lg_p1[$i]; - $xden = $xden * $xm1 + $lg_q1[$i]; - } - $res = $corr + $xm1 * ($lg_d1 + $xm1 * ($xnum / $xden)); - } else { - $xm2 = $y - 1.0; - $xden = 1.0; - $xnum = 0.0; - for ($i = 0; $i < 8; ++$i) { - $xnum = $xnum * $xm2 + $lg_p2[$i]; - $xden = $xden * $xm2 + $lg_q2[$i]; - } - $res = $corr + $xm2 * ($lg_d2 + $xm2 * ($xnum / $xden)); - } - } elseif ($y <= 4.0) { - // --------------------- - // 1.5 .LT. X .LE. 4.0 - // --------------------- - $xm2 = $y - 2.0; - $xden = 1.0; - $xnum = 0.0; - for ($i = 0; $i < 8; ++$i) { - $xnum = $xnum * $xm2 + $lg_p2[$i]; - $xden = $xden * $xm2 + $lg_q2[$i]; - } - $res = $xm2 * ($lg_d2 + $xm2 * ($xnum / $xden)); - } elseif ($y <= 12.0) { - // ---------------------- - // 4.0 .LT. X .LE. 12.0 - // ---------------------- - $xm4 = $y - 4.0; - $xden = -1.0; - $xnum = 0.0; - for ($i = 0; $i < 8; ++$i) { - $xnum = $xnum * $xm4 + $lg_p4[$i]; - $xden = $xden * $xm4 + $lg_q4[$i]; - } - $res = $lg_d4 + $xm4 * ($xnum / $xden); - } else { - // --------------------------------- - // Evaluate for argument .GE. 12.0 - // --------------------------------- - $res = 0.0; - if ($y <= $lg_frtbig) { - $res = $lg_c[6]; - $ysq = $y * $y; - for ($i = 0; $i < 6; ++$i) { - $res = $res / $ysq + $lg_c[$i]; - } - $res /= $y; - $corr = log($y); - $res = $res + log(self::SQRT2PI) - 0.5 * $corr; - $res += $y * ($corr - 1.0); - } - } - } else { - // -------------------------- - // Return for bad arguments - // -------------------------- - $res = self::MAX_VALUE; - } - // ------------------------------ - // Final adjustments and return - // ------------------------------ - self::$logGammaCacheX = $x; - self::$logGammaCacheResult = $res; - - return $res; - } - - // - // Private implementation of the incomplete Gamma function - // - private static function incompleteGamma($a, $x) - { - static $max = 32; - $summer = 0; - for ($n = 0; $n <= $max; ++$n) { - $divisor = $a; - for ($i = 1; $i <= $n; ++$i) { - $divisor *= ($a + $i); - } - $summer += ($x ** $n / $divisor); - } - - return $x ** $a * exp(0 - $x) * $summer; - } - - // - // Private implementation of the Gamma function - // - private static function gamma($data) - { - if ($data == 0.0) { - return 0; - } - - static $p0 = 1.000000000190015; - static $p = [ - 1 => 76.18009172947146, - 2 => -86.50532032941677, - 3 => 24.01409824083091, - 4 => -1.231739572450155, - 5 => 1.208650973866179e-3, - 6 => -5.395239384953e-6, - ]; - - $y = $x = $data; - $tmp = $x + 5.5; - $tmp -= ($x + 0.5) * log($tmp); - - $summer = $p0; - for ($j = 1; $j <= 6; ++$j) { - $summer += ($p[$j] / ++$y); - } - - return exp(0 - $tmp + log(self::SQRT2PI * $summer / $x)); - } - - /* - * inverse_ncdf.php - * ------------------- - * begin : Friday, January 16, 2004 - * copyright : (C) 2004 Michael Nickerson - * email : nickersonm@yahoo.com - * - */ - private static function inverseNcdf($p) - { - // Inverse ncdf approximation by Peter J. Acklam, implementation adapted to - // PHP by Michael Nickerson, using Dr. Thomas Ziegler's C implementation as - // a guide. http://home.online.no/~pjacklam/notes/invnorm/index.html - // I have not checked the accuracy of this implementation. Be aware that PHP - // will truncate the coeficcients to 14 digits. - - // You have permission to use and distribute this function freely for - // whatever purpose you want, but please show common courtesy and give credit - // where credit is due. - - // Input paramater is $p - probability - where 0 < p < 1. - - // Coefficients in rational approximations - static $a = [ - 1 => -3.969683028665376e+01, - 2 => 2.209460984245205e+02, - 3 => -2.759285104469687e+02, - 4 => 1.383577518672690e+02, - 5 => -3.066479806614716e+01, - 6 => 2.506628277459239e+00, - ]; - - static $b = [ - 1 => -5.447609879822406e+01, - 2 => 1.615858368580409e+02, - 3 => -1.556989798598866e+02, - 4 => 6.680131188771972e+01, - 5 => -1.328068155288572e+01, - ]; - - static $c = [ - 1 => -7.784894002430293e-03, - 2 => -3.223964580411365e-01, - 3 => -2.400758277161838e+00, - 4 => -2.549732539343734e+00, - 5 => 4.374664141464968e+00, - 6 => 2.938163982698783e+00, - ]; - - static $d = [ - 1 => 7.784695709041462e-03, - 2 => 3.224671290700398e-01, - 3 => 2.445134137142996e+00, - 4 => 3.754408661907416e+00, - ]; - - // Define lower and upper region break-points. - $p_low = 0.02425; //Use lower region approx. below this - $p_high = 1 - $p_low; //Use upper region approx. above this - - if (0 < $p && $p < $p_low) { - // Rational approximation for lower region. - $q = sqrt(-2 * log($p)); - - return ((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) / - (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1); - } elseif ($p_low <= $p && $p <= $p_high) { - // Rational approximation for central region. - $q = $p - 0.5; - $r = $q * $q; - - return ((((($a[1] * $r + $a[2]) * $r + $a[3]) * $r + $a[4]) * $r + $a[5]) * $r + $a[6]) * $q / - ((((($b[1] * $r + $b[2]) * $r + $b[3]) * $r + $b[4]) * $r + $b[5]) * $r + 1); - } elseif ($p_high < $p && $p < 1) { - // Rational approximation for upper region. - $q = sqrt(-2 * log(1 - $p)); - - return -((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) / - (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1); - } - // If 0 < p < 1, return a null value - return Functions::NULL(); - } - - /** - * MS Excel does not count Booleans if passed as cell values, but they are counted if passed as literals. - * OpenOffice Calc always counts Booleans. - * Gnumeric never counts Booleans. - * - * @param mixed $arg - * @param mixed $k - * - * @return int|mixed - */ - private static function testAcceptedBoolean($arg, $k) - { - if ( - (is_bool($arg)) && - ((!Functions::isCellValue($k) && (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_EXCEL)) || - (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE)) - ) { - $arg = (int) $arg; - } - - return $arg; - } - - /** - * @param mixed $arg - * @param mixed $k - * - * @return bool - */ - private static function isAcceptedCountable($arg, $k) - { - if ( - ((is_numeric($arg)) && (!is_string($arg))) || - ((is_numeric($arg)) && (!Functions::isCellValue($k)) && - (Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_GNUMERIC)) - ) { - return true; - } - - return false; - } - /** * AVEDEV. * @@ -569,45 +32,18 @@ class Statistical * Excel Function: * AVEDEV(value1[,value2[, ...]]) * + * @Deprecated 1.17.0 + * + * @see Statistical\Averages::averageDeviations() + * Use the averageDeviations() method in the Statistical\Averages class instead + * * @param mixed ...$args Data values * * @return float|string */ public static function AVEDEV(...$args) { - $aArgs = Functions::flattenArrayIndexed($args); - - // Return value - $returnValue = 0; - - $aMean = self::AVERAGE(...$args); - if ($aMean === Functions::DIV0()) { - return Functions::NAN(); - } elseif ($aMean === Functions::VALUE()) { - return Functions::VALUE(); - } - - $aCount = 0; - foreach ($aArgs as $k => $arg) { - $arg = self::testAcceptedBoolean($arg, $k); - // Is it a numeric value? - // Strings containing numeric values are only counted if they are string literals (not cell values) - // and then only in MS Excel and in Open Office, not in Gnumeric - if ((is_string($arg)) && (!is_numeric($arg)) && (!Functions::isCellValue($k))) { - return Functions::VALUE(); - } - if (self::isAcceptedCountable($arg, $k)) { - $returnValue += abs($arg - $aMean); - ++$aCount; - } - } - - // Return - if ($aCount === 0) { - return Functions::DIV0(); - } - - return $returnValue / $aCount; + return Averages::averageDeviations(...$args); } /** @@ -618,35 +54,18 @@ class Statistical * Excel Function: * AVERAGE(value1[,value2[, ...]]) * + * @Deprecated 1.17.0 + * + * @see Statistical\Averages::average() + * Use the average() method in the Statistical\Averages class instead + * * @param mixed ...$args Data values * * @return float|string */ public static function AVERAGE(...$args) { - $returnValue = $aCount = 0; - - // Loop through arguments - foreach (Functions::flattenArrayIndexed($args) as $k => $arg) { - $arg = self::testAcceptedBoolean($arg, $k); - // Is it a numeric value? - // Strings containing numeric values are only counted if they are string literals (not cell values) - // and then only in MS Excel and in Open Office, not in Gnumeric - if ((is_string($arg)) && (!is_numeric($arg)) && (!Functions::isCellValue($k))) { - return Functions::VALUE(); - } - if (self::isAcceptedCountable($arg, $k)) { - $returnValue += $arg; - ++$aCount; - } - } - - // Return - if ($aCount > 0) { - return $returnValue / $aCount; - } - - return Functions::DIV0(); + return Averages::average(...$args); } /** @@ -657,39 +76,18 @@ class Statistical * Excel Function: * AVERAGEA(value1[,value2[, ...]]) * + * @Deprecated 1.17.0 + * + * @see Statistical\Averages::averageA() + * Use the averageA() method in the Statistical\Averages class instead + * * @param mixed ...$args Data values * * @return float|string */ public static function AVERAGEA(...$args) { - $returnValue = null; - - $aCount = 0; - // Loop through arguments - foreach (Functions::flattenArrayIndexed($args) as $k => $arg) { - if ( - (is_bool($arg)) && - (!Functions::isMatrixValue($k)) - ) { - } else { - if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { - if (is_bool($arg)) { - $arg = (int) $arg; - } elseif (is_string($arg)) { - $arg = 0; - } - $returnValue += $arg; - ++$aCount; - } - } - } - - if ($aCount > 0) { - return $returnValue / $aCount; - } - - return Functions::DIV0(); + return Averages::averageA(...$args); } /** @@ -700,47 +98,20 @@ class Statistical * Excel Function: * AVERAGEIF(value1[,value2[, ...]],condition) * - * @param mixed $aArgs Data values - * @param string $condition the criteria that defines which cells will be checked - * @param mixed[] $averageArgs Data values + * @Deprecated 1.17.0 * - * @return float|string + * @see Statistical\Conditional::AVERAGEIF() + * Use the AVERAGEIF() method in the Statistical\Conditional class instead + * + * @param mixed $range Data values + * @param string $condition the criteria that defines which cells will be checked + * @param mixed[] $averageRange Data values + * + * @return null|float|string */ - public static function AVERAGEIF($aArgs, $condition, $averageArgs = []) + public static function AVERAGEIF($range, $condition, $averageRange = []) { - $returnValue = 0; - - $aArgs = Functions::flattenArray($aArgs); - $averageArgs = Functions::flattenArray($averageArgs); - if (empty($averageArgs)) { - $averageArgs = $aArgs; - } - $condition = Functions::ifCondition($condition); - $conditionIsNumeric = strpos($condition, '"') === false; - - // Loop through arguments - $aCount = 0; - foreach ($aArgs as $key => $arg) { - if (!is_numeric($arg)) { - if ($conditionIsNumeric) { - continue; - } - $arg = Calculation::wrapResult(strtoupper($arg)); - } elseif (!$conditionIsNumeric) { - continue; - } - $testCondition = '=' . $arg . $condition; - if (Calculation::getInstance()->_calculateFormulaValue($testCondition)) { - $returnValue += $averageArgs[$key]; - ++$aCount; - } - } - - if ($aCount > 0) { - return $returnValue / $aCount; - } - - return Functions::DIV0(); + return Conditional::AVERAGEIF($range, $condition, $averageRange); } /** @@ -748,6 +119,11 @@ class Statistical * * Returns the beta distribution. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Beta::distribution() + * Use the distribution() method in the Statistical\Distributions\Beta class instead + * * @param float $value Value at which you want to evaluate the distribution * @param float $alpha Parameter to the distribution * @param float $beta Parameter to the distribution @@ -758,28 +134,7 @@ class Statistical */ public static function BETADIST($value, $alpha, $beta, $rMin = 0, $rMax = 1) { - $value = Functions::flattenSingleValue($value); - $alpha = Functions::flattenSingleValue($alpha); - $beta = Functions::flattenSingleValue($beta); - $rMin = Functions::flattenSingleValue($rMin); - $rMax = Functions::flattenSingleValue($rMax); - - if ((is_numeric($value)) && (is_numeric($alpha)) && (is_numeric($beta)) && (is_numeric($rMin)) && (is_numeric($rMax))) { - if (($value < $rMin) || ($value > $rMax) || ($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax)) { - return Functions::NAN(); - } - if ($rMin > $rMax) { - $tmp = $rMin; - $rMin = $rMax; - $rMax = $tmp; - } - $value -= $rMin; - $value /= ($rMax - $rMin); - - return self::incompleteBeta($value, $alpha, $beta); - } - - return Functions::VALUE(); + return Statistical\Distributions\Beta::distribution($value, $alpha, $beta, $rMin, $rMax); } /** @@ -787,6 +142,11 @@ class Statistical * * Returns the inverse of the Beta distribution. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Beta::inverse() + * Use the inverse() method in the Statistical\Distributions\Beta class instead + * * @param float $probability Probability at which you want to evaluate the distribution * @param float $alpha Parameter to the distribution * @param float $beta Parameter to the distribution @@ -797,44 +157,7 @@ class Statistical */ public static function BETAINV($probability, $alpha, $beta, $rMin = 0, $rMax = 1) { - $probability = Functions::flattenSingleValue($probability); - $alpha = Functions::flattenSingleValue($alpha); - $beta = Functions::flattenSingleValue($beta); - $rMin = Functions::flattenSingleValue($rMin); - $rMax = Functions::flattenSingleValue($rMax); - - if ((is_numeric($probability)) && (is_numeric($alpha)) && (is_numeric($beta)) && (is_numeric($rMin)) && (is_numeric($rMax))) { - if (($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax) || ($probability <= 0) || ($probability > 1)) { - return Functions::NAN(); - } - if ($rMin > $rMax) { - $tmp = $rMin; - $rMin = $rMax; - $rMax = $tmp; - } - $a = 0; - $b = 2; - - $i = 0; - while ((($b - $a) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) { - $guess = ($a + $b) / 2; - $result = self::BETADIST($guess, $alpha, $beta); - if (($result == $probability) || ($result == 0)) { - $b = $a; - } elseif ($result > $probability) { - $b = $guess; - } else { - $a = $guess; - } - } - if ($i == self::MAX_ITERATIONS) { - return Functions::NA(); - } - - return round($rMin + $guess * ($rMax - $rMin), 12); - } - - return Functions::VALUE(); + return Statistical\Distributions\Beta::inverse($probability, $alpha, $beta, $rMin, $rMax); } /** @@ -846,43 +169,21 @@ class Statistical * experiment. For example, BINOMDIST can calculate the probability that two of the next three * babies born are male. * - * @param float $value Number of successes in trials - * @param float $trials Number of trials - * @param float $probability Probability of success on each trial - * @param bool $cumulative + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Binomial::distribution() + * Use the distribution() method in the Statistical\Distributions\Binomial class instead + * + * @param mixed $value Number of successes in trials + * @param mixed $trials Number of trials + * @param mixed $probability Probability of success on each trial + * @param mixed $cumulative * * @return float|string */ public static function BINOMDIST($value, $trials, $probability, $cumulative) { - $value = Functions::flattenSingleValue($value); - $trials = Functions::flattenSingleValue($trials); - $probability = Functions::flattenSingleValue($probability); - - if ((is_numeric($value)) && (is_numeric($trials)) && (is_numeric($probability))) { - $value = floor($value); - $trials = floor($trials); - if (($value < 0) || ($value > $trials)) { - return Functions::NAN(); - } - if (($probability < 0) || ($probability > 1)) { - return Functions::NAN(); - } - if ((is_numeric($cumulative)) || (is_bool($cumulative))) { - if ($cumulative) { - $summer = 0; - for ($i = 0; $i <= $value; ++$i) { - $summer += MathTrig::COMBIN($trials, $i) * $probability ** $i * (1 - $probability) ** ($trials - $i); - } - - return $summer; - } - - return MathTrig::COMBIN($trials, $value) * $probability ** $value * (1 - $probability) ** ($trials - $value); - } - } - - return Functions::VALUE(); + return Statistical\Distributions\Binomial::distribution($value, $trials, $probability, $cumulative); } /** @@ -890,6 +191,11 @@ class Statistical * * Returns the one-tailed probability of the chi-squared distribution. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\ChiSquared::distributionRightTail() + * Use the distributionRightTail() method in the Statistical\Distributions\ChiSquared class instead + * * @param float $value Value for the function * @param float $degrees degrees of freedom * @@ -897,26 +203,7 @@ class Statistical */ public static function CHIDIST($value, $degrees) { - $value = Functions::flattenSingleValue($value); - $degrees = Functions::flattenSingleValue($degrees); - - if ((is_numeric($value)) && (is_numeric($degrees))) { - $degrees = floor($degrees); - if ($degrees < 1) { - return Functions::NAN(); - } - if ($value < 0) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { - return 1; - } - - return Functions::NAN(); - } - - return 1 - (self::incompleteGamma($degrees / 2, $value / 2) / self::gamma($degrees / 2)); - } - - return Functions::VALUE(); + return Statistical\Distributions\ChiSquared::distributionRightTail($value, $degrees); } /** @@ -924,6 +211,11 @@ class Statistical * * Returns the one-tailed probability of the chi-squared distribution. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\ChiSquared::inverseRightTail() + * Use the inverseRightTail() method in the Statistical\Distributions\ChiSquared class instead + * * @param float $probability Probability for the function * @param float $degrees degrees of freedom * @@ -931,52 +223,7 @@ class Statistical */ public static function CHIINV($probability, $degrees) { - $probability = Functions::flattenSingleValue($probability); - $degrees = Functions::flattenSingleValue($degrees); - - if ((is_numeric($probability)) && (is_numeric($degrees))) { - $degrees = floor($degrees); - - $xLo = 100; - $xHi = 0; - - $x = $xNew = 1; - $dx = 1; - $i = 0; - - while ((abs($dx) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) { - // Apply Newton-Raphson step - $result = 1 - (self::incompleteGamma($degrees / 2, $x / 2) / self::gamma($degrees / 2)); - $error = $result - $probability; - if ($error == 0.0) { - $dx = 0; - } elseif ($error < 0.0) { - $xLo = $x; - } else { - $xHi = $x; - } - // Avoid division by zero - if ($result != 0.0) { - $dx = $error / $result; - $xNew = $x - $dx; - } - // If the NR fails to converge (which for example may be the - // case if the initial guess is too rough) we apply a bisection - // step to determine a more narrow interval around the root. - if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) { - $xNew = ($xLo + $xHi) / 2; - $dx = $xNew - $x; - } - $x = $xNew; - } - if ($i == self::MAX_ITERATIONS) { - return Functions::NA(); - } - - return round($x, 12); - } - - return Functions::VALUE(); + return Statistical\Distributions\ChiSquared::inverseRightTail($probability, $degrees); } /** @@ -984,6 +231,11 @@ class Statistical * * Returns the confidence interval for a population mean * + * @Deprecated 1.18.0 + * + * @see Statistical\Confidence::CONFIDENCE() + * Use the CONFIDENCE() method in the Statistical\Confidence class instead + * * @param float $alpha * @param float $stdDev Standard Deviation * @param float $size @@ -992,23 +244,7 @@ class Statistical */ public static function CONFIDENCE($alpha, $stdDev, $size) { - $alpha = Functions::flattenSingleValue($alpha); - $stdDev = Functions::flattenSingleValue($stdDev); - $size = Functions::flattenSingleValue($size); - - if ((is_numeric($alpha)) && (is_numeric($stdDev)) && (is_numeric($size))) { - $size = floor($size); - if (($alpha <= 0) || ($alpha >= 1)) { - return Functions::NAN(); - } - if (($stdDev <= 0) || ($size < 1)) { - return Functions::NAN(); - } - - return self::NORMSINV(1 - $alpha / 2) * $stdDev / sqrt($size); - } - - return Functions::VALUE(); + return Confidence::CONFIDENCE($alpha, $stdDev, $size); } /** @@ -1016,6 +252,11 @@ class Statistical * * Returns covariance, the average of the products of deviations for each data point pair. * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::CORREL() + * Use the CORREL() method in the Statistical\Trends class instead + * * @param mixed $yValues array of mixed Data Series Y * @param null|mixed $xValues array of mixed Data Series X * @@ -1023,24 +264,7 @@ class Statistical */ public static function CORREL($yValues, $xValues = null) { - if (($xValues === null) || (!is_array($yValues)) || (!is_array($xValues))) { - return Functions::VALUE(); - } - if (!self::checkTrendArrays($yValues, $xValues)) { - return Functions::VALUE(); - } - $yValueCount = count($yValues); - $xValueCount = count($xValues); - - if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { - return Functions::NA(); - } elseif ($yValueCount == 1) { - return Functions::DIV0(); - } - - $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); - - return $bestFitLinear->getCorrelation(); + return Trends::CORREL($xValues, $yValues); } /** @@ -1051,27 +275,18 @@ class Statistical * Excel Function: * COUNT(value1[,value2[, ...]]) * + * @Deprecated 1.17.0 + * + * @see Statistical\Counts::COUNT() + * Use the COUNT() method in the Statistical\Counts class instead + * * @param mixed ...$args Data values * * @return int */ public static function COUNT(...$args) { - $returnValue = 0; - - // Loop through arguments - $aArgs = Functions::flattenArrayIndexed($args); - foreach ($aArgs as $k => $arg) { - $arg = self::testAcceptedBoolean($arg, $k); - // Is it a numeric value? - // Strings containing numeric values are only counted if they are string literals (not cell values) - // and then only in MS Excel and in Open Office, not in Gnumeric - if (self::isAcceptedCountable($arg, $k)) { - ++$returnValue; - } - } - - return $returnValue; + return Counts::COUNT(...$args); } /** @@ -1082,24 +297,18 @@ class Statistical * Excel Function: * COUNTA(value1[,value2[, ...]]) * + * @Deprecated 1.17.0 + * + * @see Statistical\Counts::COUNTA() + * Use the COUNTA() method in the Statistical\Counts class instead + * * @param mixed ...$args Data values * * @return int */ public static function COUNTA(...$args) { - $returnValue = 0; - - // Loop through arguments - $aArgs = Functions::flattenArrayIndexed($args); - foreach ($aArgs as $k => $arg) { - // Nulls are counted if literals, but not if cell values - if ($arg !== null || (!Functions::isCellValue($k))) { - ++$returnValue; - } - } - - return $returnValue; + return Counts::COUNTA(...$args); } /** @@ -1110,24 +319,18 @@ class Statistical * Excel Function: * COUNTBLANK(value1[,value2[, ...]]) * + * @Deprecated 1.17.0 + * + * @see Statistical\Counts::COUNTBLANK() + * Use the COUNTBLANK() method in the Statistical\Counts class instead + * * @param mixed ...$args Data values * * @return int */ public static function COUNTBLANK(...$args) { - $returnValue = 0; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - foreach ($aArgs as $arg) { - // Is it a blank cell? - if (($arg === null) || ((is_string($arg)) && ($arg == ''))) { - ++$returnValue; - } - } - - return $returnValue; + return Counts::COUNTBLANK(...$args); } /** @@ -1136,38 +339,21 @@ class Statistical * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: - * COUNTIF(value1[,value2[, ...]],condition) + * COUNTIF(range,condition) * - * @param mixed $aArgs Data values + * @Deprecated 1.17.0 + * + * @see Statistical\Conditional::COUNTIF() + * Use the COUNTIF() method in the Statistical\Conditional class instead + * + * @param mixed $range Data values * @param string $condition the criteria that defines which cells will be counted * * @return int */ - public static function COUNTIF($aArgs, $condition) + public static function COUNTIF($range, $condition) { - $returnValue = 0; - - $aArgs = Functions::flattenArray($aArgs); - $condition = Functions::ifCondition($condition); - $conditionIsNumeric = strpos($condition, '"') === false; - // Loop through arguments - foreach ($aArgs as $arg) { - if (!is_numeric($arg)) { - if ($conditionIsNumeric) { - continue; - } - $arg = Calculation::wrapResult(strtoupper($arg)); - } elseif (!$conditionIsNumeric) { - continue; - } - $testCondition = '=' . $arg . $condition; - if (Calculation::getInstance()->_calculateFormulaValue($testCondition)) { - // Is it a value within our criteria - ++$returnValue; - } - } - - return $returnValue; + return Conditional::COUNTIF($range, $condition); } /** @@ -1178,66 +364,18 @@ class Statistical * Excel Function: * COUNTIFS(criteria_range1, criteria1, [criteria_range2, criteria2]…) * - * @param mixed $args Criterias + * @Deprecated 1.17.0 + * + * @see Statistical\Conditional::COUNTIFS() + * Use the COUNTIFS() method in the Statistical\Conditional class instead + * + * @param mixed $args Pairs of Ranges and Criteria * * @return int */ public static function COUNTIFS(...$args) { - $arrayList = $args; - - // Return value - $returnValue = 0; - - if (empty($arrayList)) { - return $returnValue; - } - - $aArgsArray = []; - $conditions = []; - - while (count($arrayList) > 0) { - $aArgsArray[] = Functions::flattenArray(array_shift($arrayList)); - $conditions[] = Functions::ifCondition(array_shift($arrayList)); - } - - // Loop through each arg and see if arguments and conditions are true - foreach (array_keys($aArgsArray[0]) as $index) { - $valid = true; - - foreach ($conditions as $cidx => $condition) { - $conditionIsNumeric = strpos($condition, '"') === false; - $arg = $aArgsArray[$cidx][$index]; - - // Loop through arguments - if (!is_numeric($arg)) { - if ($conditionIsNumeric) { - $valid = false; - - break; // if false found, don't need to check other conditions - } - $arg = Calculation::wrapResult(strtoupper($arg)); - } elseif (!$conditionIsNumeric) { - $valid = false; - - break; // if false found, don't need to check other conditions - } - $testCondition = '=' . $arg . $condition; - if (!Calculation::getInstance()->_calculateFormulaValue($testCondition)) { - // Is not a value within our criteria - $valid = false; - - break; // if false found, don't need to check other conditions - } - } - - if ($valid) { - ++$returnValue; - } - } - - // Return - return $returnValue; + return Conditional::COUNTIFS(...$args); } /** @@ -1245,6 +383,11 @@ class Statistical * * Returns covariance, the average of the products of deviations for each data point pair. * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::COVAR() + * Use the COVAR() method in the Statistical\Trends class instead + * * @param mixed $yValues array of mixed Data Series Y * @param mixed $xValues array of mixed Data Series X * @@ -1252,21 +395,7 @@ class Statistical */ public static function COVAR($yValues, $xValues) { - if (!self::checkTrendArrays($yValues, $xValues)) { - return Functions::VALUE(); - } - $yValueCount = count($yValues); - $xValueCount = count($xValues); - - if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { - return Functions::NA(); - } elseif ($yValueCount == 1) { - return Functions::DIV0(); - } - - $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); - - return $bestFitLinear->getCovariance(); + return Trends::COVAR($yValues, $xValues); } /** @@ -1277,123 +406,20 @@ class Statistical * * See https://support.microsoft.com/en-us/help/828117/ for details of the algorithm used * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Binomial::inverse() + * Use the inverse() method in the Statistical\Distributions\Binomial class instead + * * @param float $trials number of Bernoulli trials * @param float $probability probability of a success on each trial * @param float $alpha criterion value * * @return int|string - * - * @TODO Warning. This implementation differs from the algorithm detailed on the MS - * web site in that $CumPGuessMinus1 = $CumPGuess - 1 rather than $CumPGuess - $PGuess - * This eliminates a potential endless loop error, but may have an adverse affect on the - * accuracy of the function (although all my tests have so far returned correct results). */ public static function CRITBINOM($trials, $probability, $alpha) { - $trials = floor(Functions::flattenSingleValue($trials)); - $probability = Functions::flattenSingleValue($probability); - $alpha = Functions::flattenSingleValue($alpha); - - if ((is_numeric($trials)) && (is_numeric($probability)) && (is_numeric($alpha))) { - $trials = (int) $trials; - if ($trials < 0) { - return Functions::NAN(); - } elseif (($probability < 0.0) || ($probability > 1.0)) { - return Functions::NAN(); - } elseif (($alpha < 0.0) || ($alpha > 1.0)) { - return Functions::NAN(); - } - - if ($alpha <= 0.5) { - $t = sqrt(log(1 / ($alpha * $alpha))); - $trialsApprox = 0 - ($t + (2.515517 + 0.802853 * $t + 0.010328 * $t * $t) / (1 + 1.432788 * $t + 0.189269 * $t * $t + 0.001308 * $t * $t * $t)); - } else { - $t = sqrt(log(1 / (1 - $alpha) ** 2)); - $trialsApprox = $t - (2.515517 + 0.802853 * $t + 0.010328 * $t * $t) / (1 + 1.432788 * $t + 0.189269 * $t * $t + 0.001308 * $t * $t * $t); - } - - $Guess = floor($trials * $probability + $trialsApprox * sqrt($trials * $probability * (1 - $probability))); - if ($Guess < 0) { - $Guess = 0; - } elseif ($Guess > $trials) { - $Guess = $trials; - } - - $TotalUnscaledProbability = $UnscaledPGuess = $UnscaledCumPGuess = 0.0; - $EssentiallyZero = 10e-12; - - $m = floor($trials * $probability); - ++$TotalUnscaledProbability; - if ($m == $Guess) { - ++$UnscaledPGuess; - } - if ($m <= $Guess) { - ++$UnscaledCumPGuess; - } - - $PreviousValue = 1; - $Done = false; - $k = $m + 1; - while ((!$Done) && ($k <= $trials)) { - $CurrentValue = $PreviousValue * ($trials - $k + 1) * $probability / ($k * (1 - $probability)); - $TotalUnscaledProbability += $CurrentValue; - if ($k == $Guess) { - $UnscaledPGuess += $CurrentValue; - } - if ($k <= $Guess) { - $UnscaledCumPGuess += $CurrentValue; - } - if ($CurrentValue <= $EssentiallyZero) { - $Done = true; - } - $PreviousValue = $CurrentValue; - ++$k; - } - - $PreviousValue = 1; - $Done = false; - $k = $m - 1; - while ((!$Done) && ($k >= 0)) { - $CurrentValue = $PreviousValue * $k + 1 * (1 - $probability) / (($trials - $k) * $probability); - $TotalUnscaledProbability += $CurrentValue; - if ($k == $Guess) { - $UnscaledPGuess += $CurrentValue; - } - if ($k <= $Guess) { - $UnscaledCumPGuess += $CurrentValue; - } - if ($CurrentValue <= $EssentiallyZero) { - $Done = true; - } - $PreviousValue = $CurrentValue; - --$k; - } - - $PGuess = $UnscaledPGuess / $TotalUnscaledProbability; - $CumPGuess = $UnscaledCumPGuess / $TotalUnscaledProbability; - - $CumPGuessMinus1 = $CumPGuess - 1; - - while (true) { - if (($CumPGuessMinus1 < $alpha) && ($CumPGuess >= $alpha)) { - return $Guess; - } elseif (($CumPGuessMinus1 < $alpha) && ($CumPGuess < $alpha)) { - $PGuessPlus1 = $PGuess * ($trials - $Guess) * $probability / $Guess / (1 - $probability); - $CumPGuessMinus1 = $CumPGuess; - $CumPGuess = $CumPGuess + $PGuessPlus1; - $PGuess = $PGuessPlus1; - ++$Guess; - } elseif (($CumPGuessMinus1 >= $alpha) && ($CumPGuess >= $alpha)) { - $PGuessMinus1 = $PGuess * $Guess * (1 - $probability) / ($trials - $Guess + 1) / $probability; - $CumPGuess = $CumPGuessMinus1; - $CumPGuessMinus1 = $CumPGuessMinus1 - $PGuess; - $PGuess = $PGuessMinus1; - --$Guess; - } - } - } - - return Functions::VALUE(); + return Statistical\Distributions\Binomial::inverse($trials, $probability, $alpha); } /** @@ -1404,48 +430,18 @@ class Statistical * Excel Function: * DEVSQ(value1[,value2[, ...]]) * + * @Deprecated 1.18.0 + * + * @see Statistical\Deviations::sumSquares() + * Use the sumSquares() method in the Statistical\Deviations class instead + * * @param mixed ...$args Data values * * @return float|string */ public static function DEVSQ(...$args) { - $aArgs = Functions::flattenArrayIndexed($args); - - // Return value - $returnValue = null; - - $aMean = self::AVERAGE($aArgs); - if ($aMean != Functions::DIV0()) { - $aCount = -1; - foreach ($aArgs as $k => $arg) { - // Is it a numeric value? - if ( - (is_bool($arg)) && - ((!Functions::isCellValue($k)) || - (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE)) - ) { - $arg = (int) $arg; - } - if ((is_numeric($arg)) && (!is_string($arg))) { - if ($returnValue === null) { - $returnValue = ($arg - $aMean) ** 2; - } else { - $returnValue += ($arg - $aMean) ** 2; - } - ++$aCount; - } - } - - // Return - if ($returnValue === null) { - return Functions::NAN(); - } - - return $returnValue; - } - - return Functions::NA(); + return Statistical\Deviations::sumSquares(...$args); } /** @@ -1455,6 +451,11 @@ class Statistical * such as how long an automated bank teller takes to deliver cash. For example, you can * use EXPONDIST to determine the probability that the process takes at most 1 minute. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Exponential::distribution() + * Use the distribution() method in the Statistical\Distributions\Exponential class instead + * * @param float $value Value of the function * @param float $lambda The parameter value * @param bool $cumulative @@ -1463,34 +464,7 @@ class Statistical */ public static function EXPONDIST($value, $lambda, $cumulative) { - $value = Functions::flattenSingleValue($value); - $lambda = Functions::flattenSingleValue($lambda); - $cumulative = Functions::flattenSingleValue($cumulative); - - if ((is_numeric($value)) && (is_numeric($lambda))) { - if (($value < 0) || ($lambda < 0)) { - return Functions::NAN(); - } - if ((is_numeric($cumulative)) || (is_bool($cumulative))) { - if ($cumulative) { - return 1 - exp(0 - $value * $lambda); - } - - return $lambda * exp(0 - $value * $lambda); - } - } - - return Functions::VALUE(); - } - - private static function betaFunction($a, $b) - { - return (self::gamma($a) * self::gamma($b)) / self::gamma($a + $b); - } - - private static function regularizedIncompleteBeta($value, $a, $b) - { - return self::incompleteBeta($value, $a, $b) / self::betaFunction($a, $b); + return Statistical\Distributions\Exponential::distribution($value, $lambda, $cumulative); } /** @@ -1501,6 +475,11 @@ class Statistical * For example, you can examine the test scores of men and women entering high school, and determine * if the variability in the females is different from that found in the males. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\F::distribution() + * Use the distribution() method in the Statistical\Distributions\Exponential class instead + * * @param float $value Value of the function * @param int $u The numerator degrees of freedom * @param int $v The denominator degrees of freedom @@ -1511,32 +490,7 @@ class Statistical */ public static function FDIST2($value, $u, $v, $cumulative) { - $value = Functions::flattenSingleValue($value); - $u = Functions::flattenSingleValue($u); - $v = Functions::flattenSingleValue($v); - $cumulative = Functions::flattenSingleValue($cumulative); - - if (is_numeric($value) && is_numeric($u) && is_numeric($v)) { - if ($value < 0 || $u < 1 || $v < 1) { - return Functions::NAN(); - } - - $cumulative = (bool) $cumulative; - $u = (int) $u; - $v = (int) $v; - - if ($cumulative) { - $adjustedValue = ($u * $value) / ($u * $value + $v); - - return self::incompleteBeta($adjustedValue, $u / 2, $v / 2); - } - - return (self::gamma(($v + $u) / 2) / (self::gamma($u / 2) * self::gamma($v / 2))) * - (($u / $v) ** ($u / 2)) * - (($value ** (($u - 2) / 2)) / ((1 + ($u / $v) * $value) ** (($u + $v) / 2))); - } - - return Functions::VALUE(); + return Statistical\Distributions\F::distribution($value, $u, $v, $cumulative); } /** @@ -1546,23 +500,18 @@ class Statistical * is normally distributed rather than skewed. Use this function to perform hypothesis * testing on the correlation coefficient. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Fisher::distribution() + * Use the distribution() method in the Statistical\Distributions\Fisher class instead + * * @param float $value * * @return float|string */ public static function FISHER($value) { - $value = Functions::flattenSingleValue($value); - - if (is_numeric($value)) { - if (($value <= -1) || ($value >= 1)) { - return Functions::NAN(); - } - - return 0.5 * log((1 + $value) / (1 - $value)); - } - - return Functions::VALUE(); + return Statistical\Distributions\Fisher::distribution($value); } /** @@ -1572,19 +521,18 @@ class Statistical * analyzing correlations between ranges or arrays of data. If y = FISHER(x), then * FISHERINV(y) = x. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Fisher::inverse() + * Use the inverse() method in the Statistical\Distributions\Fisher class instead + * * @param float $value * * @return float|string */ public static function FISHERINV($value) { - $value = Functions::flattenSingleValue($value); - - if (is_numeric($value)) { - return (exp(2 * $value) - 1) / (exp(2 * $value) + 1); - } - - return Functions::VALUE(); + return Statistical\Distributions\Fisher::inverse($value); } /** @@ -1592,6 +540,11 @@ class Statistical * * Calculates, or predicts, a future value by using existing values. The predicted value is a y-value for a given x-value. * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::FORECAST() + * Use the FORECAST() method in the Statistical\Trends class instead + * * @param float $xValue Value of X for which we want to find Y * @param mixed $yValues array of mixed Data Series Y * @param mixed $xValues of mixed Data Series X @@ -1600,30 +553,18 @@ class Statistical */ public static function FORECAST($xValue, $yValues, $xValues) { - $xValue = Functions::flattenSingleValue($xValue); - if (!is_numeric($xValue)) { - return Functions::VALUE(); - } elseif (!self::checkTrendArrays($yValues, $xValues)) { - return Functions::VALUE(); - } - $yValueCount = count($yValues); - $xValueCount = count($xValues); - - if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { - return Functions::NA(); - } elseif ($yValueCount == 1) { - return Functions::DIV0(); - } - - $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); - - return $bestFitLinear->getValueOfYForX($xValue); + return Trends::FORECAST($xValue, $yValues, $xValues); } /** * GAMMA. * - * Return the gamma function value. + * Returns the gamma function value. + * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Gamma::gamma() + * Use the gamma() method in the Statistical\Distributions\Gamma class instead * * @param float $value * @@ -1631,14 +572,7 @@ class Statistical */ public static function GAMMAFunction($value) { - $value = Functions::flattenSingleValue($value); - if (!is_numeric($value)) { - return Functions::VALUE(); - } elseif ((((int) $value) == ((float) $value)) && $value <= 0.0) { - return Functions::NAN(); - } - - return self::gamma($value); + return Statistical\Distributions\Gamma::gamma($value); } /** @@ -1646,6 +580,11 @@ class Statistical * * Returns the gamma distribution. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Gamma::distribution() + * Use the distribution() method in the Statistical\Distributions\Gamma class instead + * * @param float $value Value at which you want to evaluate the distribution * @param float $a Parameter to the distribution * @param float $b Parameter to the distribution @@ -1655,24 +594,7 @@ class Statistical */ public static function GAMMADIST($value, $a, $b, $cumulative) { - $value = Functions::flattenSingleValue($value); - $a = Functions::flattenSingleValue($a); - $b = Functions::flattenSingleValue($b); - - if ((is_numeric($value)) && (is_numeric($a)) && (is_numeric($b))) { - if (($value < 0) || ($a <= 0) || ($b <= 0)) { - return Functions::NAN(); - } - if ((is_numeric($cumulative)) || (is_bool($cumulative))) { - if ($cumulative) { - return self::incompleteGamma($a, $value / $b) / self::gamma($a); - } - - return (1 / ($b ** $a * self::gamma($a))) * $value ** ($a - 1) * exp(0 - ($value / $b)); - } - } - - return Functions::VALUE(); + return Statistical\Distributions\Gamma::distribution($value, $a, $b, $cumulative); } /** @@ -1680,6 +602,11 @@ class Statistical * * Returns the inverse of the Gamma distribution. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Gamma::inverse() + * Use the inverse() method in the Statistical\Distributions\Gamma class instead + * * @param float $probability Probability at which you want to evaluate the distribution * @param float $alpha Parameter to the distribution * @param float $beta Parameter to the distribution @@ -1688,53 +615,7 @@ class Statistical */ public static function GAMMAINV($probability, $alpha, $beta) { - $probability = Functions::flattenSingleValue($probability); - $alpha = Functions::flattenSingleValue($alpha); - $beta = Functions::flattenSingleValue($beta); - - if ((is_numeric($probability)) && (is_numeric($alpha)) && (is_numeric($beta))) { - if (($alpha <= 0) || ($beta <= 0) || ($probability < 0) || ($probability > 1)) { - return Functions::NAN(); - } - - $xLo = 0; - $xHi = $alpha * $beta * 5; - - $x = $xNew = 1; - $dx = 1024; - $i = 0; - - while ((abs($dx) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) { - // Apply Newton-Raphson step - $error = self::GAMMADIST($x, $alpha, $beta, true) - $probability; - if ($error < 0.0) { - $xLo = $x; - } else { - $xHi = $x; - } - $pdf = self::GAMMADIST($x, $alpha, $beta, false); - // Avoid division by zero - if ($pdf != 0.0) { - $dx = $error / $pdf; - $xNew = $x - $dx; - } - // If the NR fails to converge (which for example may be the - // case if the initial guess is too rough) we apply a bisection - // step to determine a more narrow interval around the root. - if (($xNew < $xLo) || ($xNew > $xHi) || ($pdf == 0.0)) { - $xNew = ($xLo + $xHi) / 2; - $dx = $xNew - $x; - } - $x = $xNew; - } - if ($i == self::MAX_ITERATIONS) { - return Functions::NA(); - } - - return $x; - } - - return Functions::VALUE(); + return Statistical\Distributions\Gamma::inverse($probability, $alpha, $beta); } /** @@ -1742,23 +623,18 @@ class Statistical * * Returns the natural logarithm of the gamma function. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Gamma::ln() + * Use the ln() method in the Statistical\Distributions\Gamma class instead + * * @param float $value * * @return float|string */ public static function GAMMALN($value) { - $value = Functions::flattenSingleValue($value); - - if (is_numeric($value)) { - if ($value <= 0) { - return Functions::NAN(); - } - - return log(self::gamma($value)); - } - - return Functions::VALUE(); + return Statistical\Distributions\Gamma::ln($value); } /** @@ -1767,18 +643,18 @@ class Statistical * Calculates the probability that a member of a standard normal population will fall between * the mean and z standard deviations from the mean. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\StandardNormal::gauss() + * Use the gauss() method in the Statistical\Distributions\StandardNormal class instead + * * @param float $value * * @return float|string The result, or a string containing an error */ public static function GAUSS($value) { - $value = Functions::flattenSingleValue($value); - if (!is_numeric($value)) { - return Functions::VALUE(); - } - - return self::NORMDIST($value, 0, 1, true) - 0.5; + return Statistical\Distributions\StandardNormal::gauss($value); } /** @@ -1791,23 +667,18 @@ class Statistical * Excel Function: * GEOMEAN(value1[,value2[, ...]]) * + * @Deprecated 1.18.0 + * + * @see Statistical\Averages\Mean::geometric() + * Use the geometric() method in the Statistical\Averages\Mean class instead + * * @param mixed ...$args Data values * * @return float|string */ public static function GEOMEAN(...$args) { - $aArgs = Functions::flattenArray($args); - - $aMean = MathTrig::PRODUCT($aArgs); - if (is_numeric($aMean) && ($aMean > 0)) { - $aCount = self::COUNT($aArgs); - if (self::MIN($aArgs) > 0) { - return $aMean ** (1 / $aCount); - } - } - - return Functions::NAN(); + return Statistical\Averages\Mean::geometric(...$args); } /** @@ -1815,31 +686,21 @@ class Statistical * * Returns values along a predicted exponential Trend * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::GROWTH() + * Use the GROWTH() method in the Statistical\Trends class instead + * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * @param mixed[] $newValues Values of X for which we want to find Y * @param bool $const a logical value specifying whether to force the intersect to equal 0 * - * @return array of float + * @return float[] */ public static function GROWTH($yValues, $xValues = [], $newValues = [], $const = true) { - $yValues = Functions::flattenArray($yValues); - $xValues = Functions::flattenArray($xValues); - $newValues = Functions::flattenArray($newValues); - $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); - - $bestFitExponential = Trend::calculate(Trend::TREND_EXPONENTIAL, $yValues, $xValues, $const); - if (empty($newValues)) { - $newValues = $bestFitExponential->getXValues(); - } - - $returnArray = []; - foreach ($newValues as $xValue) { - $returnArray[0][] = $bestFitExponential->getValueOfYForX($xValue); - } - - return $returnArray; + return Trends::GROWTH($yValues, $xValues, $newValues, $const); } /** @@ -1851,38 +712,18 @@ class Statistical * Excel Function: * HARMEAN(value1[,value2[, ...]]) * + * @Deprecated 1.18.0 + * + * @see Statistical\Averages\Mean::harmonic() + * Use the harmonic() method in the Statistical\Averages\Mean class instead + * * @param mixed ...$args Data values * * @return float|string */ public static function HARMEAN(...$args) { - // Return value - $returnValue = 0; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - if (self::MIN($aArgs) < 0) { - return Functions::NAN(); - } - $aCount = 0; - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - if ($arg <= 0) { - return Functions::NAN(); - } - $returnValue += (1 / $arg); - ++$aCount; - } - } - - // Return - if ($aCount > 0) { - return 1 / ($returnValue / $aCount); - } - - return Functions::NA(); + return Statistical\Averages\Mean::harmonic(...$args); } /** @@ -1891,42 +732,26 @@ class Statistical * Returns the hypergeometric distribution. HYPGEOMDIST returns the probability of a given number of * sample successes, given the sample size, population successes, and population size. * - * @param float $sampleSuccesses Number of successes in the sample - * @param float $sampleNumber Size of the sample - * @param float $populationSuccesses Number of successes in the population - * @param float $populationNumber Population size + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\HyperGeometric::distribution() + * Use the distribution() method in the Statistical\Distributions\HyperGeometric class instead + * + * @param mixed $sampleSuccesses Number of successes in the sample + * @param mixed $sampleNumber Size of the sample + * @param mixed $populationSuccesses Number of successes in the population + * @param mixed $populationNumber Population size * * @return float|string */ public static function HYPGEOMDIST($sampleSuccesses, $sampleNumber, $populationSuccesses, $populationNumber) { - $sampleSuccesses = Functions::flattenSingleValue($sampleSuccesses); - $sampleNumber = Functions::flattenSingleValue($sampleNumber); - $populationSuccesses = Functions::flattenSingleValue($populationSuccesses); - $populationNumber = Functions::flattenSingleValue($populationNumber); - - if ((is_numeric($sampleSuccesses)) && (is_numeric($sampleNumber)) && (is_numeric($populationSuccesses)) && (is_numeric($populationNumber))) { - $sampleSuccesses = floor($sampleSuccesses); - $sampleNumber = floor($sampleNumber); - $populationSuccesses = floor($populationSuccesses); - $populationNumber = floor($populationNumber); - - if (($sampleSuccesses < 0) || ($sampleSuccesses > $sampleNumber) || ($sampleSuccesses > $populationSuccesses)) { - return Functions::NAN(); - } - if (($sampleNumber <= 0) || ($sampleNumber > $populationNumber)) { - return Functions::NAN(); - } - if (($populationSuccesses <= 0) || ($populationSuccesses > $populationNumber)) { - return Functions::NAN(); - } - - return MathTrig::COMBIN($populationSuccesses, $sampleSuccesses) * - MathTrig::COMBIN($populationNumber - $populationSuccesses, $sampleNumber - $sampleSuccesses) / - MathTrig::COMBIN($populationNumber, $sampleNumber); - } - - return Functions::VALUE(); + return Statistical\Distributions\HyperGeometric::distribution( + $sampleSuccesses, + $sampleNumber, + $populationSuccesses, + $populationNumber + ); } /** @@ -1934,6 +759,11 @@ class Statistical * * Calculates the point at which a line will intersect the y-axis by using existing x-values and y-values. * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::INTERCEPT() + * Use the INTERCEPT() method in the Statistical\Trends class instead + * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * @@ -1941,21 +771,7 @@ class Statistical */ public static function INTERCEPT($yValues, $xValues) { - if (!self::checkTrendArrays($yValues, $xValues)) { - return Functions::VALUE(); - } - $yValueCount = count($yValues); - $xValueCount = count($xValues); - - if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { - return Functions::NA(); - } elseif ($yValueCount == 1) { - return Functions::DIV0(); - } - - $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); - - return $bestFitLinear->getIntersect(); + return Trends::INTERCEPT($yValues, $xValues); } /** @@ -1966,40 +782,18 @@ class Statistical * kurtosis indicates a relatively peaked distribution. Negative kurtosis indicates a * relatively flat distribution. * + * @Deprecated 1.18.0 + * + * @see Statistical\Deviations::kurtosis() + * Use the kurtosis() method in the Statistical\Deviations class instead + * * @param array ...$args Data Series * * @return float|string */ public static function KURT(...$args) { - $aArgs = Functions::flattenArrayIndexed($args); - $mean = self::AVERAGE($aArgs); - $stdDev = self::STDEV($aArgs); - - if ($stdDev > 0) { - $count = $summer = 0; - // Loop through arguments - foreach ($aArgs as $k => $arg) { - if ( - (is_bool($arg)) && - (!Functions::isMatrixValue($k)) - ) { - } else { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $summer += (($arg - $mean) / $stdDev) ** 4; - ++$count; - } - } - } - - // Return - if ($count > 3) { - return $summer * ($count * ($count + 1) / (($count - 1) * ($count - 2) * ($count - 3))) - (3 * ($count - 1) ** 2 / (($count - 2) * ($count - 3))); - } - } - - return Functions::DIV0(); + return Statistical\Deviations::kurtosis(...$args); } /** @@ -2011,37 +805,18 @@ class Statistical * Excel Function: * LARGE(value1[,value2[, ...]],entry) * + * @Deprecated 1.18.0 + * + * @see Statistical\Size::large() + * Use the large() method in the Statistical\Size class instead + * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function LARGE(...$args) { - $aArgs = Functions::flattenArray($args); - $entry = array_pop($aArgs); - - if ((is_numeric($entry)) && (!is_string($entry))) { - $entry = (int) floor($entry); - - // Calculate - $mArgs = []; - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $mArgs[] = $arg; - } - } - $count = self::COUNT($mArgs); - --$entry; - if (($entry < 0) || ($entry >= $count) || ($count == 0)) { - return Functions::NAN(); - } - rsort($mArgs); - - return $mArgs[$entry]; - } - - return Functions::VALUE(); + return Statistical\Size::large(...$args); } /** @@ -2050,6 +825,11 @@ class Statistical * Calculates the statistics for a line by using the "least squares" method to calculate a straight line that best fits your data, * and then returns an array that describes the line. * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::LINEST() + * Use the LINEST() method in the Statistical\Trends class instead + * * @param mixed[] $yValues Data Series Y * @param null|mixed[] $xValues Data Series X * @param bool $const a logical value specifying whether to force the intersect to equal 0 @@ -2059,48 +839,7 @@ class Statistical */ public static function LINEST($yValues, $xValues = null, $const = true, $stats = false) { - $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); - $stats = ($stats === null) ? false : (bool) Functions::flattenSingleValue($stats); - if ($xValues === null) { - $xValues = range(1, count(Functions::flattenArray($yValues))); - } - - if (!self::checkTrendArrays($yValues, $xValues)) { - return Functions::VALUE(); - } - $yValueCount = count($yValues); - $xValueCount = count($xValues); - - if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { - return Functions::NA(); - } elseif ($yValueCount == 1) { - return 0; - } - - $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues, $const); - if ($stats) { - return [ - [ - $bestFitLinear->getSlope(), - $bestFitLinear->getSlopeSE(), - $bestFitLinear->getGoodnessOfFit(), - $bestFitLinear->getF(), - $bestFitLinear->getSSRegression(), - ], - [ - $bestFitLinear->getIntersect(), - $bestFitLinear->getIntersectSE(), - $bestFitLinear->getStdevOfResiduals(), - $bestFitLinear->getDFResiduals(), - $bestFitLinear->getSSResiduals(), - ], - ]; - } - - return [ - $bestFitLinear->getSlope(), - $bestFitLinear->getIntersect(), - ]; + return Trends::LINEST($yValues, $xValues, $const, $stats); } /** @@ -2109,6 +848,11 @@ class Statistical * Calculates an exponential curve that best fits the X and Y data series, * and then returns an array that describes the line. * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::LOGEST() + * Use the LOGEST() method in the Statistical\Trends class instead + * * @param mixed[] $yValues Data Series Y * @param null|mixed[] $xValues Data Series X * @param bool $const a logical value specifying whether to force the intersect to equal 0 @@ -2118,54 +862,7 @@ class Statistical */ public static function LOGEST($yValues, $xValues = null, $const = true, $stats = false) { - $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); - $stats = ($stats === null) ? false : (bool) Functions::flattenSingleValue($stats); - if ($xValues === null) { - $xValues = range(1, count(Functions::flattenArray($yValues))); - } - - if (!self::checkTrendArrays($yValues, $xValues)) { - return Functions::VALUE(); - } - $yValueCount = count($yValues); - $xValueCount = count($xValues); - - foreach ($yValues as $value) { - if ($value <= 0.0) { - return Functions::NAN(); - } - } - - if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { - return Functions::NA(); - } elseif ($yValueCount == 1) { - return 1; - } - - $bestFitExponential = Trend::calculate(Trend::TREND_EXPONENTIAL, $yValues, $xValues, $const); - if ($stats) { - return [ - [ - $bestFitExponential->getSlope(), - $bestFitExponential->getSlopeSE(), - $bestFitExponential->getGoodnessOfFit(), - $bestFitExponential->getF(), - $bestFitExponential->getSSRegression(), - ], - [ - $bestFitExponential->getIntersect(), - $bestFitExponential->getIntersectSE(), - $bestFitExponential->getStdevOfResiduals(), - $bestFitExponential->getDFResiduals(), - $bestFitExponential->getSSResiduals(), - ], - ]; - } - - return [ - $bestFitExponential->getSlope(), - $bestFitExponential->getIntersect(), - ]; + return Trends::LOGEST($yValues, $xValues, $const, $stats); } /** @@ -2173,6 +870,11 @@ class Statistical * * Returns the inverse of the normal cumulative distribution * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\LogNormal::inverse() + * Use the inverse() method in the Statistical\Distributions\LogNormal class instead + * * @param float $probability * @param float $mean * @param float $stdDev @@ -2185,19 +887,7 @@ class Statistical */ public static function LOGINV($probability, $mean, $stdDev) { - $probability = Functions::flattenSingleValue($probability); - $mean = Functions::flattenSingleValue($mean); - $stdDev = Functions::flattenSingleValue($stdDev); - - if ((is_numeric($probability)) && (is_numeric($mean)) && (is_numeric($stdDev))) { - if (($probability < 0) || ($probability > 1) || ($stdDev <= 0)) { - return Functions::NAN(); - } - - return exp($mean + $stdDev * self::NORMSINV($probability)); - } - - return Functions::VALUE(); + return Statistical\Distributions\LogNormal::inverse($probability, $mean, $stdDev); } /** @@ -2206,6 +896,11 @@ class Statistical * Returns the cumulative lognormal distribution of x, where ln(x) is normally distributed * with parameters mean and standard_dev. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\LogNormal::cumulative() + * Use the cumulative() method in the Statistical\Distributions\LogNormal class instead + * * @param float $value * @param float $mean * @param float $stdDev @@ -2214,19 +909,7 @@ class Statistical */ public static function LOGNORMDIST($value, $mean, $stdDev) { - $value = Functions::flattenSingleValue($value); - $mean = Functions::flattenSingleValue($mean); - $stdDev = Functions::flattenSingleValue($stdDev); - - if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) { - if (($value <= 0) || ($stdDev <= 0)) { - return Functions::NAN(); - } - - return self::NORMSDIST((log($value) - $mean) / $stdDev); - } - - return Functions::VALUE(); + return Statistical\Distributions\LogNormal::cumulative($value, $mean, $stdDev); } /** @@ -2235,6 +918,11 @@ class Statistical * Returns the lognormal distribution of x, where ln(x) is normally distributed * with parameters mean and standard_dev. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\LogNormal::distribution() + * Use the distribution() method in the Statistical\Distributions\LogNormal class instead + * * @param float $value * @param float $mean * @param float $stdDev @@ -2244,25 +932,7 @@ class Statistical */ public static function LOGNORMDIST2($value, $mean, $stdDev, $cumulative = false) { - $value = Functions::flattenSingleValue($value); - $mean = Functions::flattenSingleValue($mean); - $stdDev = Functions::flattenSingleValue($stdDev); - $cumulative = (bool) Functions::flattenSingleValue($cumulative); - - if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) { - if (($value <= 0) || ($stdDev <= 0)) { - return Functions::NAN(); - } - - if ($cumulative === true) { - return self::NORMSDIST2((log($value) - $mean) / $stdDev, true); - } - - return (1 / (sqrt(2 * M_PI) * $stdDev * $value)) * - exp(0 - ((log($value) - $mean) ** 2 / (2 * $stdDev ** 2))); - } - - return Functions::VALUE(); + return Statistical\Distributions\LogNormal::distribution($value, $mean, $stdDev, $cumulative); } /** @@ -2272,32 +942,20 @@ class Statistical * with negative numbers considered smaller than positive numbers. * * Excel Function: - * MAX(value1[,value2[, ...]]) + * max(value1[,value2[, ...]]) + * + * @Deprecated 1.17.0 * * @param mixed ...$args Data values * * @return float + * + *@see Statistical\Maximum::max() + * Use the MAX() method in the Statistical\Maximum class instead */ public static function MAX(...$args) { - $returnValue = null; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - if (($returnValue === null) || ($arg > $returnValue)) { - $returnValue = $arg; - } - } - } - - if ($returnValue === null) { - return 0; - } - - return $returnValue; + return Maximum::max(...$args); } /** @@ -2306,37 +964,20 @@ class Statistical * Returns the greatest value in a list of arguments, including numbers, text, and logical values * * Excel Function: - * MAXA(value1[,value2[, ...]]) + * maxA(value1[,value2[, ...]]) + * + * @Deprecated 1.17.0 * * @param mixed ...$args Data values * * @return float + * + *@see Statistical\Maximum::maxA() + * Use the MAXA() method in the Statistical\Maximum class instead */ public static function MAXA(...$args) { - $returnValue = null; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { - if (is_bool($arg)) { - $arg = (int) $arg; - } elseif (is_string($arg)) { - $arg = 0; - } - if (($returnValue === null) || ($arg > $returnValue)) { - $returnValue = $arg; - } - } - } - - if ($returnValue === null) { - return 0; - } - - return $returnValue; + return Maximum::maxA(...$args); } /** @@ -2347,53 +988,18 @@ class Statistical * Excel Function: * MAXIFS(max_range, criteria_range1, criteria1, [criteria_range2, criteria2], ...) * + * @Deprecated 1.17.0 + * + * @see Statistical\Conditional::MAXIFS() + * Use the MAXIFS() method in the Statistical\Conditional class instead + * * @param mixed $args Data range and criterias * * @return float */ public static function MAXIFS(...$args) { - $arrayList = $args; - - // Return value - $returnValue = null; - - $maxArgs = Functions::flattenArray(array_shift($arrayList)); - $aArgsArray = []; - $conditions = []; - - while (count($arrayList) > 0) { - $aArgsArray[] = Functions::flattenArray(array_shift($arrayList)); - $conditions[] = Functions::ifCondition(array_shift($arrayList)); - } - - // Loop through each arg and see if arguments and conditions are true - foreach ($maxArgs as $index => $value) { - $valid = true; - - foreach ($conditions as $cidx => $condition) { - $arg = $aArgsArray[$cidx][$index]; - - // Loop through arguments - if (!is_numeric($arg)) { - $arg = Calculation::wrapResult(strtoupper($arg)); - } - $testCondition = '=' . $arg . $condition; - if (!Calculation::getInstance()->_calculateFormulaValue($testCondition)) { - // Is not a value within our criteria - $valid = false; - - break; // if false found, don't need to check other conditions - } - } - - if ($valid) { - $returnValue = $returnValue === null ? $value : max($value, $returnValue); - } - } - - // Return - return $returnValue; + return Conditional::MAXIFS(...$args); } /** @@ -2404,37 +1010,18 @@ class Statistical * Excel Function: * MEDIAN(value1[,value2[, ...]]) * + * @Deprecated 1.18.0 + * + * @see Statistical\Averages::median() + * Use the median() method in the Statistical\Averages class instead + * * @param mixed ...$args Data values * * @return float|string The result, or a string containing an error */ public static function MEDIAN(...$args) { - $returnValue = Functions::NAN(); - - $mArgs = []; - // Loop through arguments - $aArgs = Functions::flattenArray($args); - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $mArgs[] = $arg; - } - } - - $mValueCount = count($mArgs); - if ($mValueCount > 0) { - sort($mArgs, SORT_NUMERIC); - $mValueCount = $mValueCount / 2; - if ($mValueCount == floor($mValueCount)) { - $returnValue = ($mArgs[$mValueCount--] + $mArgs[$mValueCount]) / 2; - } else { - $mValueCount = floor($mValueCount); - $returnValue = $mArgs[$mValueCount]; - } - } - - return $returnValue; + return Statistical\Averages::median(...$args); } /** @@ -2446,30 +1033,18 @@ class Statistical * Excel Function: * MIN(value1[,value2[, ...]]) * + * @Deprecated 1.17.0 + * * @param mixed ...$args Data values * * @return float + * + *@see Statistical\Minimum::min() + * Use the min() method in the Statistical\Minimum class instead */ public static function MIN(...$args) { - $returnValue = null; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - if (($returnValue === null) || ($arg < $returnValue)) { - $returnValue = $arg; - } - } - } - - if ($returnValue === null) { - return 0; - } - - return $returnValue; + return Minimum::min(...$args); } /** @@ -2480,35 +1055,18 @@ class Statistical * Excel Function: * MINA(value1[,value2[, ...]]) * + * @Deprecated 1.17.0 + * * @param mixed ...$args Data values * * @return float + * + *@see Statistical\Minimum::minA() + * Use the minA() method in the Statistical\Minimum class instead */ public static function MINA(...$args) { - $returnValue = null; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { - if (is_bool($arg)) { - $arg = (int) $arg; - } elseif (is_string($arg)) { - $arg = 0; - } - if (($returnValue === null) || ($arg < $returnValue)) { - $returnValue = $arg; - } - } - } - - if ($returnValue === null) { - return 0; - } - - return $returnValue; + return Minimum::minA(...$args); } /** @@ -2519,102 +1077,18 @@ class Statistical * Excel Function: * MINIFS(min_range, criteria_range1, criteria1, [criteria_range2, criteria2], ...) * + * @Deprecated 1.17.0 + * + * @see Statistical\Conditional::MINIFS() + * Use the MINIFS() method in the Statistical\Conditional class instead + * * @param mixed $args Data range and criterias * * @return float */ public static function MINIFS(...$args) { - $arrayList = $args; - - // Return value - $returnValue = null; - - $minArgs = Functions::flattenArray(array_shift($arrayList)); - $aArgsArray = []; - $conditions = []; - - while (count($arrayList) > 0) { - $aArgsArray[] = Functions::flattenArray(array_shift($arrayList)); - $conditions[] = Functions::ifCondition(array_shift($arrayList)); - } - - // Loop through each arg and see if arguments and conditions are true - foreach ($minArgs as $index => $value) { - $valid = true; - - foreach ($conditions as $cidx => $condition) { - $arg = $aArgsArray[$cidx][$index]; - - // Loop through arguments - if (!is_numeric($arg)) { - $arg = Calculation::wrapResult(strtoupper($arg)); - } - $testCondition = '=' . $arg . $condition; - if (!Calculation::getInstance()->_calculateFormulaValue($testCondition)) { - // Is not a value within our criteria - $valid = false; - - break; // if false found, don't need to check other conditions - } - } - - if ($valid) { - $returnValue = $returnValue === null ? $value : min($value, $returnValue); - } - } - - // Return - return $returnValue; - } - - // - // Special variant of array_count_values that isn't limited to strings and integers, - // but can work with floating point numbers as values - // - private static function modeCalc($data) - { - $frequencyArray = []; - $index = 0; - $maxfreq = 0; - $maxfreqkey = ''; - $maxfreqdatum = ''; - foreach ($data as $datum) { - $found = false; - ++$index; - foreach ($frequencyArray as $key => $value) { - if ((string) $value['value'] == (string) $datum) { - ++$frequencyArray[$key]['frequency']; - $freq = $frequencyArray[$key]['frequency']; - if ($freq > $maxfreq) { - $maxfreq = $freq; - $maxfreqkey = $key; - $maxfreqdatum = $datum; - } elseif ($freq == $maxfreq) { - if ($frequencyArray[$key]['index'] < $frequencyArray[$maxfreqkey]['index']) { - $maxfreqkey = $key; - $maxfreqdatum = $datum; - } - } - $found = true; - - break; - } - } - if (!$found) { - $frequencyArray[] = [ - 'value' => $datum, - 'frequency' => 1, - 'index' => $index, - ]; - } - } - - if ($maxfreq <= 1) { - return Functions::NA(); - } - - return $maxfreqdatum; + return Conditional::MINIFS(...$args); } /** @@ -2625,30 +1099,18 @@ class Statistical * Excel Function: * MODE(value1[,value2[, ...]]) * + * @Deprecated 1.18.0 + * + * @see Statistical\Averages::mode() + * Use the mode() method in the Statistical\Averages class instead + * * @param mixed ...$args Data values * * @return float|string The result, or a string containing an error */ public static function MODE(...$args) { - $returnValue = Functions::NA(); - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - - $mArgs = []; - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $mArgs[] = $arg; - } - } - - if (!empty($mArgs)) { - return self::modeCalc($mArgs); - } - - return $returnValue; + return Statistical\Averages::mode(...$args); } /** @@ -2660,34 +1122,20 @@ class Statistical * distribution, except that the number of successes is fixed, and the number of trials is * variable. Like the binomial, trials are assumed to be independent. * - * @param float $failures Number of Failures - * @param float $successes Threshold number of Successes - * @param float $probability Probability of success on each trial + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Binomial::negative() + * Use the negative() method in the Statistical\Distributions\Binomial class instead + * + * @param mixed $failures Number of Failures + * @param mixed $successes Threshold number of Successes + * @param mixed $probability Probability of success on each trial * * @return float|string The result, or a string containing an error */ public static function NEGBINOMDIST($failures, $successes, $probability) { - $failures = floor(Functions::flattenSingleValue($failures)); - $successes = floor(Functions::flattenSingleValue($successes)); - $probability = Functions::flattenSingleValue($probability); - - if ((is_numeric($failures)) && (is_numeric($successes)) && (is_numeric($probability))) { - if (($failures < 0) || ($successes < 1)) { - return Functions::NAN(); - } elseif (($probability < 0) || ($probability > 1)) { - return Functions::NAN(); - } - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { - if (($failures + $successes - 1) <= 0) { - return Functions::NAN(); - } - } - - return (MathTrig::COMBIN($failures + $successes - 1, $successes - 1)) * ($probability ** $successes) * ((1 - $probability) ** $failures); - } - - return Functions::VALUE(); + return Statistical\Distributions\Binomial::negative($failures, $successes, $probability); } /** @@ -2697,33 +1145,21 @@ class Statistical * function has a very wide range of applications in statistics, including hypothesis * testing. * - * @param float $value - * @param float $mean Mean Value - * @param float $stdDev Standard Deviation - * @param bool $cumulative + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Normal::distribution() + * Use the distribution() method in the Statistical\Distributions\Normal class instead + * + * @param mixed $value + * @param mixed $mean Mean Value + * @param mixed $stdDev Standard Deviation + * @param mixed $cumulative * * @return float|string The result, or a string containing an error */ public static function NORMDIST($value, $mean, $stdDev, $cumulative) { - $value = Functions::flattenSingleValue($value); - $mean = Functions::flattenSingleValue($mean); - $stdDev = Functions::flattenSingleValue($stdDev); - - if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) { - if ($stdDev < 0) { - return Functions::NAN(); - } - if ((is_numeric($cumulative)) || (is_bool($cumulative))) { - if ($cumulative) { - return 0.5 * (1 + Engineering::erfVal(($value - $mean) / ($stdDev * sqrt(2)))); - } - - return (1 / (self::SQRT2PI * $stdDev)) * exp(0 - (($value - $mean) ** 2 / (2 * ($stdDev * $stdDev)))); - } - } - - return Functions::VALUE(); + return Statistical\Distributions\Normal::distribution($value, $mean, $stdDev, $cumulative); } /** @@ -2731,30 +1167,20 @@ class Statistical * * Returns the inverse of the normal cumulative distribution for the specified mean and standard deviation. * - * @param float $probability - * @param float $mean Mean Value - * @param float $stdDev Standard Deviation + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Normal::inverse() + * Use the inverse() method in the Statistical\Distributions\Normal class instead + * + * @param mixed $probability + * @param mixed $mean Mean Value + * @param mixed $stdDev Standard Deviation * * @return float|string The result, or a string containing an error */ public static function NORMINV($probability, $mean, $stdDev) { - $probability = Functions::flattenSingleValue($probability); - $mean = Functions::flattenSingleValue($mean); - $stdDev = Functions::flattenSingleValue($stdDev); - - if ((is_numeric($probability)) && (is_numeric($mean)) && (is_numeric($stdDev))) { - if (($probability < 0) || ($probability > 1)) { - return Functions::NAN(); - } - if ($stdDev < 0) { - return Functions::NAN(); - } - - return (self::inverseNcdf($probability) * $stdDev) + $mean; - } - - return Functions::VALUE(); + return Statistical\Distributions\Normal::inverse($probability, $mean, $stdDev); } /** @@ -2764,18 +1190,18 @@ class Statistical * a mean of 0 (zero) and a standard deviation of one. Use this function in place of a * table of standard normal curve areas. * - * @param float $value + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\StandardNormal::cumulative() + * Use the cumulative() method in the Statistical\Distributions\StandardNormal class instead + * + * @param mixed $value * * @return float|string The result, or a string containing an error */ public static function NORMSDIST($value) { - $value = Functions::flattenSingleValue($value); - if (!is_numeric($value)) { - return Functions::VALUE(); - } - - return self::NORMDIST($value, 0, 1, true); + return Statistical\Distributions\StandardNormal::cumulative($value); } /** @@ -2785,20 +1211,19 @@ class Statistical * a mean of 0 (zero) and a standard deviation of one. Use this function in place of a * table of standard normal curve areas. * - * @param float $value - * @param bool $cumulative + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\StandardNormal::distribution() + * Use the distribution() method in the Statistical\Distributions\StandardNormal class instead + * + * @param mixed $value + * @param mixed $cumulative * * @return float|string The result, or a string containing an error */ public static function NORMSDIST2($value, $cumulative) { - $value = Functions::flattenSingleValue($value); - if (!is_numeric($value)) { - return Functions::VALUE(); - } - $cumulative = (bool) Functions::flattenSingleValue($cumulative); - - return self::NORMDIST($value, 0, 1, $cumulative); + return Statistical\Distributions\StandardNormal::distribution($value, $cumulative); } /** @@ -2806,13 +1231,18 @@ class Statistical * * Returns the inverse of the standard normal cumulative distribution * - * @param float $value + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\StandardNormal::inverse() + * Use the inverse() method in the Statistical\Distributions\StandardNormal class instead + * + * @param mixed $value * * @return float|string The result, or a string containing an error */ public static function NORMSINV($value) { - return self::NORMINV($value, 0, 1); + return Statistical\Distributions\StandardNormal::inverse($value); } /** @@ -2823,92 +1253,42 @@ class Statistical * Excel Function: * PERCENTILE(value1[,value2[, ...]],entry) * + * @Deprecated 1.18.0 + * + * @see Statistical\Percentiles::PERCENTILE() + * Use the PERCENTILE() method in the Statistical\Percentiles class instead + * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function PERCENTILE(...$args) { - $aArgs = Functions::flattenArray($args); - - // Calculate - $entry = array_pop($aArgs); - - if ((is_numeric($entry)) && (!is_string($entry))) { - if (($entry < 0) || ($entry > 1)) { - return Functions::NAN(); - } - $mArgs = []; - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $mArgs[] = $arg; - } - } - $mValueCount = count($mArgs); - if ($mValueCount > 0) { - sort($mArgs); - $count = self::COUNT($mArgs); - $index = $entry * ($count - 1); - $iBase = floor($index); - if ($index == $iBase) { - return $mArgs[$index]; - } - $iNext = $iBase + 1; - $iProportion = $index - $iBase; - - return $mArgs[$iBase] + (($mArgs[$iNext] - $mArgs[$iBase]) * $iProportion); - } - } - - return Functions::VALUE(); + return Statistical\Percentiles::PERCENTILE(...$args); } /** * PERCENTRANK. * * Returns the rank of a value in a data set as a percentage of the data set. + * Note that the returned rank is simply rounded to the appropriate significant digits, + * rather than floored (as MS Excel), so value 3 for a value set of 1, 2, 3, 4 will return + * 0.667 rather than 0.666 * - * @param float[] $valueSet An array of, or a reference to, a list of numbers - * @param int $value the number whose rank you want to find - * @param int $significance the number of significant digits for the returned percentage value + * @Deprecated 1.18.0 + * + * @see Statistical\Percentiles::PERCENTRANK() + * Use the PERCENTRANK() method in the Statistical\Percentiles class instead + * + * @param mixed $valueSet An array of, or a reference to, a list of numbers + * @param mixed $value the number whose rank you want to find + * @param mixed $significance the number of significant digits for the returned percentage value * * @return float|string (string if result is an error) */ public static function PERCENTRANK($valueSet, $value, $significance = 3) { - $valueSet = Functions::flattenArray($valueSet); - $value = Functions::flattenSingleValue($value); - $significance = ($significance === null) ? 3 : (int) Functions::flattenSingleValue($significance); - - foreach ($valueSet as $key => $valueEntry) { - if (!is_numeric($valueEntry)) { - unset($valueSet[$key]); - } - } - sort($valueSet, SORT_NUMERIC); - $valueCount = count($valueSet); - if ($valueCount == 0) { - return Functions::NAN(); - } - - $valueAdjustor = $valueCount - 1; - if (($value < $valueSet[0]) || ($value > $valueSet[$valueAdjustor])) { - return Functions::NA(); - } - - $pos = array_search($value, $valueSet); - if ($pos === false) { - $pos = 0; - $testValue = $valueSet[0]; - while ($testValue < $value) { - $testValue = $valueSet[++$pos]; - } - --$pos; - $pos += (($value - $valueSet[$pos]) / ($testValue - $valueSet[$pos])); - } - - return round($pos / $valueAdjustor, $significance); + return Statistical\Percentiles::PERCENTRANK($valueSet, $value, $significance); } /** @@ -2920,26 +1300,19 @@ class Statistical * combinations, for which the internal order is not significant. Use this function * for lottery-style probability calculations. * + * @Deprecated 1.17.0 + * + * @see Statistical\Permutations::PERMUT() + * Use the PERMUT() method in the Statistical\Permutations class instead + * * @param int $numObjs Number of different objects * @param int $numInSet Number of objects in each permutation * - * @return int|string Number of permutations, or a string containing an error + * @return float|int|string Number of permutations, or a string containing an error */ public static function PERMUT($numObjs, $numInSet) { - $numObjs = Functions::flattenSingleValue($numObjs); - $numInSet = Functions::flattenSingleValue($numInSet); - - if ((is_numeric($numObjs)) && (is_numeric($numInSet))) { - $numInSet = floor($numInSet); - if ($numObjs < $numInSet) { - return Functions::NAN(); - } - - return round(MathTrig::FACT($numObjs) / MathTrig::FACT($numObjs - $numInSet)); - } - - return Functions::VALUE(); + return Permutations::PERMUT($numObjs, $numInSet); } /** @@ -2949,37 +1322,20 @@ class Statistical * is predicting the number of events over a specific time, such as the number of * cars arriving at a toll plaza in 1 minute. * - * @param float $value - * @param float $mean Mean Value - * @param bool $cumulative + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Poisson::distribution() + * Use the distribution() method in the Statistical\Distributions\Poisson class instead + * + * @param mixed $value + * @param mixed $mean Mean Value + * @param mixed $cumulative * * @return float|string The result, or a string containing an error */ public static function POISSON($value, $mean, $cumulative) { - $value = Functions::flattenSingleValue($value); - $mean = Functions::flattenSingleValue($mean); - - if ((is_numeric($value)) && (is_numeric($mean))) { - if (($value < 0) || ($mean <= 0)) { - return Functions::NAN(); - } - if ((is_numeric($cumulative)) || (is_bool($cumulative))) { - if ($cumulative) { - $summer = 0; - $floor = floor($value); - for ($i = 0; $i <= $floor; ++$i) { - $summer += $mean ** $i / MathTrig::FACT($i); - } - - return exp(0 - $mean) * $summer; - } - - return (exp(0 - $mean) * $mean ** $value) / MathTrig::FACT($value); - } - } - - return Functions::VALUE(); + return Statistical\Distributions\Poisson::distribution($value, $mean, $cumulative); } /** @@ -2990,27 +1346,18 @@ class Statistical * Excel Function: * QUARTILE(value1[,value2[, ...]],entry) * + * @Deprecated 1.18.0 + * + * @see Statistical\Percentiles::QUARTILE() + * Use the QUARTILE() method in the Statistical\Percentiles class instead + * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function QUARTILE(...$args) { - $aArgs = Functions::flattenArray($args); - - // Calculate - $entry = floor(array_pop($aArgs)); - - if ((is_numeric($entry)) && (!is_string($entry))) { - $entry /= 4; - if (($entry < 0) || ($entry > 1)) { - return Functions::NAN(); - } - - return self::PERCENTILE($aArgs, $entry); - } - - return Functions::VALUE(); + return Statistical\Percentiles::QUARTILE(...$args); } /** @@ -3018,35 +1365,20 @@ class Statistical * * Returns the rank of a number in a list of numbers. * - * @param int $value the number whose rank you want to find - * @param float[] $valueSet An array of, or a reference to, a list of numbers - * @param int $order Order to sort the values in the value set + * @Deprecated 1.18.0 + * + * @see Statistical\Percentiles::RANK() + * Use the RANK() method in the Statistical\Percentiles class instead + * + * @param mixed $value the number whose rank you want to find + * @param mixed $valueSet An array of, or a reference to, a list of numbers + * @param mixed $order Order to sort the values in the value set * * @return float|string The result, or a string containing an error */ public static function RANK($value, $valueSet, $order = 0) { - $value = Functions::flattenSingleValue($value); - $valueSet = Functions::flattenArray($valueSet); - $order = ($order === null) ? 0 : (int) Functions::flattenSingleValue($order); - - foreach ($valueSet as $key => $valueEntry) { - if (!is_numeric($valueEntry)) { - unset($valueSet[$key]); - } - } - - if ($order == 0) { - rsort($valueSet, SORT_NUMERIC); - } else { - sort($valueSet, SORT_NUMERIC); - } - $pos = array_search($value, $valueSet); - if ($pos === false) { - return Functions::NA(); - } - - return ++$pos; + return Statistical\Percentiles::RANK($value, $valueSet, $order); } /** @@ -3054,6 +1386,11 @@ class Statistical * * Returns the square of the Pearson product moment correlation coefficient through data points in known_y's and known_x's. * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::RSQ() + * Use the RSQ() method in the Statistical\Trends class instead + * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * @@ -3061,21 +1398,7 @@ class Statistical */ public static function RSQ($yValues, $xValues) { - if (!self::checkTrendArrays($yValues, $xValues)) { - return Functions::VALUE(); - } - $yValueCount = count($yValues); - $xValueCount = count($xValues); - - if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { - return Functions::NA(); - } elseif ($yValueCount == 1) { - return Functions::DIV0(); - } - - $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); - - return $bestFitLinear->getGoodnessOfFit(); + return Trends::RSQ($yValues, $xValues); } /** @@ -3086,37 +1409,18 @@ class Statistical * asymmetric tail extending toward more positive values. Negative skewness indicates a * distribution with an asymmetric tail extending toward more negative values. * + * @Deprecated 1.18.0 + * + * @see Statistical\Deviations::skew() + * Use the skew() method in the Statistical\Deviations class instead + * * @param array ...$args Data Series * * @return float|string The result, or a string containing an error */ public static function SKEW(...$args) { - $aArgs = Functions::flattenArrayIndexed($args); - $mean = self::AVERAGE($aArgs); - $stdDev = self::STDEV($aArgs); - - $count = $summer = 0; - // Loop through arguments - foreach ($aArgs as $k => $arg) { - if ( - (is_bool($arg)) && - (!Functions::isMatrixValue($k)) - ) { - } else { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $summer += (($arg - $mean) / $stdDev) ** 3; - ++$count; - } - } - } - - if ($count > 2) { - return $summer * ($count / (($count - 1) * ($count - 2))); - } - - return Functions::DIV0(); + return Statistical\Deviations::skew(...$args); } /** @@ -3124,6 +1428,11 @@ class Statistical * * Returns the slope of the linear regression line through data points in known_y's and known_x's. * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::SLOPE() + * Use the SLOPE() method in the Statistical\Trends class instead + * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * @@ -3131,21 +1440,7 @@ class Statistical */ public static function SLOPE($yValues, $xValues) { - if (!self::checkTrendArrays($yValues, $xValues)) { - return Functions::VALUE(); - } - $yValueCount = count($yValues); - $xValueCount = count($xValues); - - if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { - return Functions::NA(); - } elseif ($yValueCount == 1) { - return Functions::DIV0(); - } - - $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); - - return $bestFitLinear->getSlope(); + return Trends::SLOPE($yValues, $xValues); } /** @@ -3157,38 +1452,18 @@ class Statistical * Excel Function: * SMALL(value1[,value2[, ...]],entry) * + * @Deprecated 1.18.0 + * + * @see Statistical\Size::small() + * Use the small() method in the Statistical\Size class instead + * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function SMALL(...$args) { - $aArgs = Functions::flattenArray($args); - - // Calculate - $entry = array_pop($aArgs); - - if ((is_numeric($entry)) && (!is_string($entry))) { - $entry = (int) floor($entry); - - $mArgs = []; - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $mArgs[] = $arg; - } - } - $count = self::COUNT($mArgs); - --$entry; - if (($entry < 0) || ($entry >= $count) || ($count == 0)) { - return Functions::NAN(); - } - sort($mArgs); - - return $mArgs[$entry]; - } - - return Functions::VALUE(); + return Statistical\Size::small(...$args); } /** @@ -3196,6 +1471,11 @@ class Statistical * * Returns a normalized value from a distribution characterized by mean and standard_dev. * + * @Deprecated 1.18.0 + * + * @see Statistical\Standardize::execute() + * Use the execute() method in the Statistical\Standardize class instead + * * @param float $value Value to normalize * @param float $mean Mean Value * @param float $stdDev Standard Deviation @@ -3204,19 +1484,7 @@ class Statistical */ public static function STANDARDIZE($value, $mean, $stdDev) { - $value = Functions::flattenSingleValue($value); - $mean = Functions::flattenSingleValue($mean); - $stdDev = Functions::flattenSingleValue($stdDev); - - if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) { - if ($stdDev <= 0) { - return Functions::NAN(); - } - - return ($value - $mean) / $stdDev; - } - - return Functions::VALUE(); + return Statistical\Standardize::execute($value, $mean, $stdDev); } /** @@ -3228,45 +1496,18 @@ class Statistical * Excel Function: * STDEV(value1[,value2[, ...]]) * + * @Deprecated 1.17.0 + * + * @see Statistical\StandardDeviations::STDEV() + * Use the STDEV() method in the Statistical\StandardDeviations class instead + * * @param mixed ...$args Data values * * @return float|string The result, or a string containing an error */ public static function STDEV(...$args) { - $aArgs = Functions::flattenArrayIndexed($args); - - // Return value - $returnValue = null; - - $aMean = self::AVERAGE($aArgs); - if ($aMean !== null) { - $aCount = -1; - foreach ($aArgs as $k => $arg) { - if ( - (is_bool($arg)) && - ((!Functions::isCellValue($k)) || (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE)) - ) { - $arg = (int) $arg; - } - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - if ($returnValue === null) { - $returnValue = ($arg - $aMean) ** 2; - } else { - $returnValue += ($arg - $aMean) ** 2; - } - ++$aCount; - } - } - - // Return - if (($aCount > 0) && ($returnValue >= 0)) { - return sqrt($returnValue / $aCount); - } - } - - return Functions::DIV0(); + return StandardDeviations::STDEV(...$args); } /** @@ -3277,48 +1518,18 @@ class Statistical * Excel Function: * STDEVA(value1[,value2[, ...]]) * + * @Deprecated 1.17.0 + * + * @see Statistical\StandardDeviations::STDEVA() + * Use the STDEVA() method in the Statistical\StandardDeviations class instead + * * @param mixed ...$args Data values * * @return float|string */ public static function STDEVA(...$args) { - $aArgs = Functions::flattenArrayIndexed($args); - - $returnValue = null; - - $aMean = self::AVERAGEA($aArgs); - if ($aMean !== null) { - $aCount = -1; - foreach ($aArgs as $k => $arg) { - if ( - (is_bool($arg)) && - (!Functions::isMatrixValue($k)) - ) { - } else { - // Is it a numeric value? - if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) { - if (is_bool($arg)) { - $arg = (int) $arg; - } elseif (is_string($arg)) { - $arg = 0; - } - if ($returnValue === null) { - $returnValue = ($arg - $aMean) ** 2; - } else { - $returnValue += ($arg - $aMean) ** 2; - } - ++$aCount; - } - } - } - - if (($aCount > 0) && ($returnValue >= 0)) { - return sqrt($returnValue / $aCount); - } - } - - return Functions::DIV0(); + return StandardDeviations::STDEVA(...$args); } /** @@ -3329,43 +1540,18 @@ class Statistical * Excel Function: * STDEVP(value1[,value2[, ...]]) * + * @Deprecated 1.17.0 + * + * @see Statistical\StandardDeviations::STDEVP() + * Use the STDEVP() method in the Statistical\StandardDeviations class instead + * * @param mixed ...$args Data values * * @return float|string */ public static function STDEVP(...$args) { - $aArgs = Functions::flattenArrayIndexed($args); - - $returnValue = null; - - $aMean = self::AVERAGE($aArgs); - if ($aMean !== null) { - $aCount = 0; - foreach ($aArgs as $k => $arg) { - if ( - (is_bool($arg)) && - ((!Functions::isCellValue($k)) || (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE)) - ) { - $arg = (int) $arg; - } - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - if ($returnValue === null) { - $returnValue = ($arg - $aMean) ** 2; - } else { - $returnValue += ($arg - $aMean) ** 2; - } - ++$aCount; - } - } - - if (($aCount > 0) && ($returnValue >= 0)) { - return sqrt($returnValue / $aCount); - } - } - - return Functions::DIV0(); + return StandardDeviations::STDEVP(...$args); } /** @@ -3376,53 +1562,28 @@ class Statistical * Excel Function: * STDEVPA(value1[,value2[, ...]]) * + * @Deprecated 1.17.0 + * + * @see Statistical\StandardDeviations::STDEVPA() + * Use the STDEVPA() method in the Statistical\StandardDeviations class instead + * * @param mixed ...$args Data values * * @return float|string */ public static function STDEVPA(...$args) { - $aArgs = Functions::flattenArrayIndexed($args); - - $returnValue = null; - - $aMean = self::AVERAGEA($aArgs); - if ($aMean !== null) { - $aCount = 0; - foreach ($aArgs as $k => $arg) { - if ( - (is_bool($arg)) && - (!Functions::isMatrixValue($k)) - ) { - } else { - // Is it a numeric value? - if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) { - if (is_bool($arg)) { - $arg = (int) $arg; - } elseif (is_string($arg)) { - $arg = 0; - } - if ($returnValue === null) { - $returnValue = ($arg - $aMean) ** 2; - } else { - $returnValue += ($arg - $aMean) ** 2; - } - ++$aCount; - } - } - } - - if (($aCount > 0) && ($returnValue >= 0)) { - return sqrt($returnValue / $aCount); - } - } - - return Functions::DIV0(); + return StandardDeviations::STDEVPA(...$args); } /** * STEYX. * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::STEYX() + * Use the STEYX() method in the Statistical\Trends class instead + * * Returns the standard error of the predicted y-value for each x in the regression. * * @param mixed[] $yValues Data Series Y @@ -3432,21 +1593,7 @@ class Statistical */ public static function STEYX($yValues, $xValues) { - if (!self::checkTrendArrays($yValues, $xValues)) { - return Functions::VALUE(); - } - $yValueCount = count($yValues); - $xValueCount = count($xValues); - - if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { - return Functions::NA(); - } elseif ($yValueCount == 1) { - return Functions::DIV0(); - } - - $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); - - return $bestFitLinear->getStdevOfResiduals(); + return Trends::STEYX($yValues, $xValues); } /** @@ -3454,6 +1601,11 @@ class Statistical * * Returns the probability of Student's T distribution. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\StudentT::distribution() + * Use the distribution() method in the Statistical\Distributions\StudentT class instead + * * @param float $value Value for the function * @param float $degrees degrees of freedom * @param float $tails number of tails (1 or 2) @@ -3462,61 +1614,18 @@ class Statistical */ public static function TDIST($value, $degrees, $tails) { - $value = Functions::flattenSingleValue($value); - $degrees = floor(Functions::flattenSingleValue($degrees)); - $tails = floor(Functions::flattenSingleValue($tails)); - - if ((is_numeric($value)) && (is_numeric($degrees)) && (is_numeric($tails))) { - if (($value < 0) || ($degrees < 1) || ($tails < 1) || ($tails > 2)) { - return Functions::NAN(); - } - // tdist, which finds the probability that corresponds to a given value - // of t with k degrees of freedom. This algorithm is translated from a - // pascal function on p81 of "Statistical Computing in Pascal" by D - // Cooke, A H Craven & G M Clark (1985: Edward Arnold (Pubs.) Ltd: - // London). The above Pascal algorithm is itself a translation of the - // fortran algoritm "AS 3" by B E Cooper of the Atlas Computer - // Laboratory as reported in (among other places) "Applied Statistics - // Algorithms", editied by P Griffiths and I D Hill (1985; Ellis - // Horwood Ltd.; W. Sussex, England). - $tterm = $degrees; - $ttheta = atan2($value, sqrt($tterm)); - $tc = cos($ttheta); - $ts = sin($ttheta); - - if (($degrees % 2) == 1) { - $ti = 3; - $tterm = $tc; - } else { - $ti = 2; - $tterm = 1; - } - - $tsum = $tterm; - while ($ti < $degrees) { - $tterm *= $tc * $tc * ($ti - 1) / $ti; - $tsum += $tterm; - $ti += 2; - } - $tsum *= $ts; - if (($degrees % 2) == 1) { - $tsum = Functions::M_2DIVPI * ($tsum + $ttheta); - } - $tValue = 0.5 * (1 + $tsum); - if ($tails == 1) { - return 1 - abs($tValue); - } - - return 1 - abs((1 - $tValue) - $tValue); - } - - return Functions::VALUE(); + return Statistical\Distributions\StudentT::distribution($value, $degrees, $tails); } /** * TINV. * - * Returns the one-tailed probability of the chi-squared distribution. + * Returns the one-tailed probability of the Student-T distribution. + * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\StudentT::inverse() + * Use the inverse() method in the Statistical\Distributions\StudentT class instead * * @param float $probability Probability for the function * @param float $degrees degrees of freedom @@ -3525,50 +1634,7 @@ class Statistical */ public static function TINV($probability, $degrees) { - $probability = Functions::flattenSingleValue($probability); - $degrees = floor(Functions::flattenSingleValue($degrees)); - - if ((is_numeric($probability)) && (is_numeric($degrees))) { - $xLo = 100; - $xHi = 0; - - $x = $xNew = 1; - $dx = 1; - $i = 0; - - while ((abs($dx) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) { - // Apply Newton-Raphson step - $result = self::TDIST($x, $degrees, 2); - $error = $result - $probability; - if ($error == 0.0) { - $dx = 0; - } elseif ($error < 0.0) { - $xLo = $x; - } else { - $xHi = $x; - } - // Avoid division by zero - if ($result != 0.0) { - $dx = $error / $result; - $xNew = $x - $dx; - } - // If the NR fails to converge (which for example may be the - // case if the initial guess is too rough) we apply a bisection - // step to determine a more narrow interval around the root. - if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) { - $xNew = ($xLo + $xHi) / 2; - $dx = $xNew - $x; - } - $x = $xNew; - } - if ($i == self::MAX_ITERATIONS) { - return Functions::NA(); - } - - return round($x, 12); - } - - return Functions::VALUE(); + return Statistical\Distributions\StudentT::inverse($probability, $degrees); } /** @@ -3576,31 +1642,21 @@ class Statistical * * Returns values along a linear Trend * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::TREND() + * Use the TREND() method in the Statistical\Trends class instead + * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * @param mixed[] $newValues Values of X for which we want to find Y * @param bool $const a logical value specifying whether to force the intersect to equal 0 * - * @return array of float + * @return float[] */ public static function TREND($yValues, $xValues = [], $newValues = [], $const = true) { - $yValues = Functions::flattenArray($yValues); - $xValues = Functions::flattenArray($xValues); - $newValues = Functions::flattenArray($newValues); - $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); - - $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues, $const); - if (empty($newValues)) { - $newValues = $bestFitLinear->getXValues(); - } - - $returnArray = []; - foreach ($newValues as $xValue) { - $returnArray[0][] = $bestFitLinear->getValueOfYForX($xValue); - } - - return $returnArray; + return Trends::TREND($yValues, $xValues, $newValues, $const); } /** @@ -3613,39 +1669,18 @@ class Statistical * Excel Function: * TRIMEAN(value1[,value2[, ...]], $discard) * + * @Deprecated 1.18.0 + * + *@see Statistical\Averages\Mean::trim() + * Use the trim() method in the Statistical\Averages\Mean class instead + * * @param mixed $args Data values * * @return float|string */ public static function TRIMMEAN(...$args) { - $aArgs = Functions::flattenArray($args); - - // Calculate - $percent = array_pop($aArgs); - - if ((is_numeric($percent)) && (!is_string($percent))) { - if (($percent < 0) || ($percent > 1)) { - return Functions::NAN(); - } - $mArgs = []; - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $mArgs[] = $arg; - } - } - $discard = floor(self::COUNT($mArgs) * $percent / 2); - sort($mArgs); - for ($i = 0; $i < $discard; ++$i) { - array_pop($mArgs); - array_shift($mArgs); - } - - return self::AVERAGE($mArgs); - } - - return Functions::VALUE(); + return Statistical\Averages\Mean::trim(...$args); } /** @@ -3656,38 +1691,18 @@ class Statistical * Excel Function: * VAR(value1[,value2[, ...]]) * + * @Deprecated 1.17.0 + * + *@see Statistical\Variances::VAR() + * Use the VAR() method in the Statistical\Variances class instead + * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VARFunc(...$args) { - $returnValue = Functions::DIV0(); - - $summerA = $summerB = 0; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - $aCount = 0; - foreach ($aArgs as $arg) { - if (is_bool($arg)) { - $arg = (int) $arg; - } - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $summerA += ($arg * $arg); - $summerB += $arg; - ++$aCount; - } - } - - if ($aCount > 1) { - $summerA *= $aCount; - $summerB *= $summerB; - $returnValue = ($summerA - $summerB) / ($aCount * ($aCount - 1)); - } - - return $returnValue; + return Variances::VAR(...$args); } /** @@ -3698,51 +1713,18 @@ class Statistical * Excel Function: * VARA(value1[,value2[, ...]]) * + * @Deprecated 1.17.0 + * + * @see Statistical\Variances::VARA() + * Use the VARA() method in the Statistical\Variances class instead + * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VARA(...$args) { - $returnValue = Functions::DIV0(); - - $summerA = $summerB = 0; - - // Loop through arguments - $aArgs = Functions::flattenArrayIndexed($args); - $aCount = 0; - foreach ($aArgs as $k => $arg) { - if ( - (is_string($arg)) && - (Functions::isValue($k)) - ) { - return Functions::VALUE(); - } elseif ( - (is_string($arg)) && - (!Functions::isMatrixValue($k)) - ) { - } else { - // Is it a numeric value? - if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) { - if (is_bool($arg)) { - $arg = (int) $arg; - } elseif (is_string($arg)) { - $arg = 0; - } - $summerA += ($arg * $arg); - $summerB += $arg; - ++$aCount; - } - } - } - - if ($aCount > 1) { - $summerA *= $aCount; - $summerB *= $summerB; - $returnValue = ($summerA - $summerB) / ($aCount * ($aCount - 1)); - } - - return $returnValue; + return Variances::VARA(...$args); } /** @@ -3753,39 +1735,18 @@ class Statistical * Excel Function: * VARP(value1[,value2[, ...]]) * + * @Deprecated 1.17.0 + * + * @see Statistical\Variances::VARP() + * Use the VARP() method in the Statistical\Variances class instead + * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VARP(...$args) { - // Return value - $returnValue = Functions::DIV0(); - - $summerA = $summerB = 0; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - $aCount = 0; - foreach ($aArgs as $arg) { - if (is_bool($arg)) { - $arg = (int) $arg; - } - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $summerA += ($arg * $arg); - $summerB += $arg; - ++$aCount; - } - } - - if ($aCount > 0) { - $summerA *= $aCount; - $summerB *= $summerB; - $returnValue = ($summerA - $summerB) / ($aCount * $aCount); - } - - return $returnValue; + return Variances::VARP(...$args); } /** @@ -3796,51 +1757,18 @@ class Statistical * Excel Function: * VARPA(value1[,value2[, ...]]) * + * @Deprecated 1.17.0 + * + * @see Statistical\Variances::VARPA() + * Use the VARPA() method in the Statistical\Variances class instead + * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VARPA(...$args) { - $returnValue = Functions::DIV0(); - - $summerA = $summerB = 0; - - // Loop through arguments - $aArgs = Functions::flattenArrayIndexed($args); - $aCount = 0; - foreach ($aArgs as $k => $arg) { - if ( - (is_string($arg)) && - (Functions::isValue($k)) - ) { - return Functions::VALUE(); - } elseif ( - (is_string($arg)) && - (!Functions::isMatrixValue($k)) - ) { - } else { - // Is it a numeric value? - if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) { - if (is_bool($arg)) { - $arg = (int) $arg; - } elseif (is_string($arg)) { - $arg = 0; - } - $summerA += ($arg * $arg); - $summerB += $arg; - ++$aCount; - } - } - } - - if ($aCount > 0) { - $summerA *= $aCount; - $summerB *= $summerB; - $returnValue = ($summerA - $summerB) / ($aCount * $aCount); - } - - return $returnValue; + return Variances::VARPA(...$args); } /** @@ -3849,6 +1777,11 @@ class Statistical * Returns the Weibull distribution. Use this distribution in reliability * analysis, such as calculating a device's mean time to failure. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Weibull::distribution() + * Use the distribution() method in the Statistical\Distributions\Weibull class instead + * * @param float $value * @param float $alpha Alpha Parameter * @param float $beta Beta Parameter @@ -3858,31 +1791,21 @@ class Statistical */ public static function WEIBULL($value, $alpha, $beta, $cumulative) { - $value = Functions::flattenSingleValue($value); - $alpha = Functions::flattenSingleValue($alpha); - $beta = Functions::flattenSingleValue($beta); - - if ((is_numeric($value)) && (is_numeric($alpha)) && (is_numeric($beta))) { - if (($value < 0) || ($alpha <= 0) || ($beta <= 0)) { - return Functions::NAN(); - } - if ((is_numeric($cumulative)) || (is_bool($cumulative))) { - if ($cumulative) { - return 1 - exp(0 - ($value / $beta) ** $alpha); - } - - return ($alpha / $beta ** $alpha) * $value ** ($alpha - 1) * exp(0 - ($value / $beta) ** $alpha); - } - } - - return Functions::VALUE(); + return Statistical\Distributions\Weibull::distribution($value, $alpha, $beta, $cumulative); } /** * ZTEST. * - * Returns the Weibull distribution. Use this distribution in reliability - * analysis, such as calculating a device's mean time to failure. + * Returns the one-tailed P-value of a z-test. + * + * For a given hypothesized population mean, x, Z.TEST returns the probability that the sample mean would be + * greater than the average of observations in the data set (array) — that is, the observed sample mean. + * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\StandardNormal::zTest() + * Use the zTest() method in the Statistical\Distributions\StandardNormal class instead * * @param float $dataSet * @param float $m0 Alpha Parameter @@ -3892,15 +1815,6 @@ class Statistical */ public static function ZTEST($dataSet, $m0, $sigma = null) { - $dataSet = Functions::flattenArrayIndexed($dataSet); - $m0 = Functions::flattenSingleValue($m0); - $sigma = Functions::flattenSingleValue($sigma); - - if ($sigma === null) { - $sigma = self::STDEV($dataSet); - } - $n = count($dataSet); - - return 1 - self::NORMSDIST((self::AVERAGE($dataSet) - $m0) / ($sigma / sqrt($n))); + return Statistical\Distributions\StandardNormal::zTest($dataSet, $m0, $sigma); } } diff --git a/src/PhpSpreadsheet/Calculation/Statistical/AggregateBase.php b/src/PhpSpreadsheet/Calculation/Statistical/AggregateBase.php new file mode 100644 index 00000000..75c012dc --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/AggregateBase.php @@ -0,0 +1,50 @@ + $arg) { + $arg = self::testAcceptedBoolean($arg, $k); + // Is it a numeric value? + // Strings containing numeric values are only counted if they are string literals (not cell values) + // and then only in MS Excel and in Open Office, not in Gnumeric + if ((is_string($arg)) && (!is_numeric($arg)) && (!Functions::isCellValue($k))) { + return Functions::VALUE(); + } + if (self::isAcceptedCountable($arg, $k)) { + $returnValue += abs($arg - $aMean); + ++$aCount; + } + } + + // Return + if ($aCount === 0) { + return Functions::DIV0(); + } + + return $returnValue / $aCount; + } + + /** + * AVERAGE. + * + * Returns the average (arithmetic mean) of the arguments + * + * Excel Function: + * AVERAGE(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float|string (string if result is an error) + */ + public static function average(...$args) + { + $returnValue = $aCount = 0; + + // Loop through arguments + foreach (Functions::flattenArrayIndexed($args) as $k => $arg) { + $arg = self::testAcceptedBoolean($arg, $k); + // Is it a numeric value? + // Strings containing numeric values are only counted if they are string literals (not cell values) + // and then only in MS Excel and in Open Office, not in Gnumeric + if ((is_string($arg)) && (!is_numeric($arg)) && (!Functions::isCellValue($k))) { + return Functions::VALUE(); + } + if (self::isAcceptedCountable($arg, $k)) { + $returnValue += $arg; + ++$aCount; + } + } + + // Return + if ($aCount > 0) { + return $returnValue / $aCount; + } + + return Functions::DIV0(); + } + + /** + * AVERAGEA. + * + * Returns the average of its arguments, including numbers, text, and logical values + * + * Excel Function: + * AVERAGEA(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float|string (string if result is an error) + */ + public static function averageA(...$args) + { + $returnValue = null; + + $aCount = 0; + // Loop through arguments + foreach (Functions::flattenArrayIndexed($args) as $k => $arg) { + if ((is_bool($arg)) && (!Functions::isMatrixValue($k))) { + } else { + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { + if (is_bool($arg)) { + $arg = (int) $arg; + } elseif (is_string($arg)) { + $arg = 0; + } + $returnValue += $arg; + ++$aCount; + } + } + } + + if ($aCount > 0) { + return $returnValue / $aCount; + } + + return Functions::DIV0(); + } + + /** + * MEDIAN. + * + * Returns the median of the given numbers. The median is the number in the middle of a set of numbers. + * + * Excel Function: + * MEDIAN(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float|string The result, or a string containing an error + */ + public static function median(...$args) + { + $aArgs = Functions::flattenArray($args); + + $returnValue = Functions::NAN(); + + $aArgs = self::filterArguments($aArgs); + $valueCount = count($aArgs); + if ($valueCount > 0) { + sort($aArgs, SORT_NUMERIC); + $valueCount = $valueCount / 2; + if ($valueCount == floor($valueCount)) { + $returnValue = ($aArgs[$valueCount--] + $aArgs[$valueCount]) / 2; + } else { + $valueCount = floor($valueCount); + $returnValue = $aArgs[$valueCount]; + } + } + + return $returnValue; + } + + /** + * MODE. + * + * Returns the most frequently occurring, or repetitive, value in an array or range of data + * + * Excel Function: + * MODE(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float|string The result, or a string containing an error + */ + public static function mode(...$args) + { + $returnValue = Functions::NA(); + + // Loop through arguments + $aArgs = Functions::flattenArray($args); + $aArgs = self::filterArguments($aArgs); + + if (!empty($aArgs)) { + return self::modeCalc($aArgs); + } + + return $returnValue; + } + + protected static function filterArguments($args) + { + return array_filter( + $args, + function ($value) { + // Is it a numeric value? + return (is_numeric($value)) && (!is_string($value)); + } + ); + } + + // + // Special variant of array_count_values that isn't limited to strings and integers, + // but can work with floating point numbers as values + // + private static function modeCalc($data) + { + $frequencyArray = []; + $index = 0; + $maxfreq = 0; + $maxfreqkey = ''; + $maxfreqdatum = ''; + foreach ($data as $datum) { + $found = false; + ++$index; + foreach ($frequencyArray as $key => $value) { + if ((string) $value['value'] == (string) $datum) { + ++$frequencyArray[$key]['frequency']; + $freq = $frequencyArray[$key]['frequency']; + if ($freq > $maxfreq) { + $maxfreq = $freq; + $maxfreqkey = $key; + $maxfreqdatum = $datum; + } elseif ($freq == $maxfreq) { + if ($frequencyArray[$key]['index'] < $frequencyArray[$maxfreqkey]['index']) { + $maxfreqkey = $key; + $maxfreqdatum = $datum; + } + } + $found = true; + + break; + } + } + + if ($found === false) { + $frequencyArray[] = [ + 'value' => $datum, + 'frequency' => 1, + 'index' => $index, + ]; + } + } + + if ($maxfreq <= 1) { + return Functions::NA(); + } + + return $maxfreqdatum; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Averages/Mean.php b/src/PhpSpreadsheet/Calculation/Statistical/Averages/Mean.php new file mode 100644 index 00000000..d4d0c7ee --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Averages/Mean.php @@ -0,0 +1,131 @@ + 0)) { + $aCount = Counts::COUNT($aArgs); + if (Minimum::min($aArgs) > 0) { + return $aMean ** (1 / $aCount); + } + } + + return Functions::NAN(); + } + + /** + * HARMEAN. + * + * Returns the harmonic mean of a data set. The harmonic mean is the reciprocal of the + * arithmetic mean of reciprocals. + * + * Excel Function: + * HARMEAN(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float|string + */ + public static function harmonic(...$args) + { + // Loop through arguments + $aArgs = Functions::flattenArray($args); + if (Minimum::min($aArgs) < 0) { + return Functions::NAN(); + } + + $returnValue = 0; + $aCount = 0; + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + if ($arg <= 0) { + return Functions::NAN(); + } + $returnValue += (1 / $arg); + ++$aCount; + } + } + + // Return + if ($aCount > 0) { + return 1 / ($returnValue / $aCount); + } + + return Functions::NA(); + } + + /** + * TRIMMEAN. + * + * Returns the mean of the interior of a data set. TRIMMEAN calculates the mean + * taken by excluding a percentage of data points from the top and bottom tails + * of a data set. + * + * Excel Function: + * TRIMEAN(value1[,value2[, ...]], $discard) + * + * @param mixed $args Data values + * + * @return float|string + */ + public static function trim(...$args) + { + $aArgs = Functions::flattenArray($args); + + // Calculate + $percent = array_pop($aArgs); + + if ((is_numeric($percent)) && (!is_string($percent))) { + if (($percent < 0) || ($percent > 1)) { + return Functions::NAN(); + } + + $mArgs = []; + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $mArgs[] = $arg; + } + } + + $discard = floor(Counts::COUNT($mArgs) * $percent / 2); + sort($mArgs); + + for ($i = 0; $i < $discard; ++$i) { + array_pop($mArgs); + array_shift($mArgs); + } + + return Averages::average($mArgs); + } + + return Functions::VALUE(); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Conditional.php b/src/PhpSpreadsheet/Calculation/Statistical/Conditional.php new file mode 100644 index 00000000..51e6b004 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Conditional.php @@ -0,0 +1,304 @@ +getMessage(); + } + + if (($alpha <= 0) || ($alpha >= 1) || ($stdDev <= 0) || ($size < 1)) { + return Functions::NAN(); + } + + return Distributions\StandardNormal::inverse(1 - $alpha / 2) * $stdDev / sqrt($size); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Counts.php b/src/PhpSpreadsheet/Calculation/Statistical/Counts.php new file mode 100644 index 00000000..13e7af79 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Counts.php @@ -0,0 +1,95 @@ + $arg) { + $arg = self::testAcceptedBoolean($arg, $k); + // Is it a numeric value? + // Strings containing numeric values are only counted if they are string literals (not cell values) + // and then only in MS Excel and in Open Office, not in Gnumeric + if (self::isAcceptedCountable($arg, $k)) { + ++$returnValue; + } + } + + return $returnValue; + } + + /** + * COUNTA. + * + * Counts the number of cells that are not empty within the list of arguments + * + * Excel Function: + * COUNTA(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return int + */ + public static function COUNTA(...$args) + { + $returnValue = 0; + + // Loop through arguments + $aArgs = Functions::flattenArrayIndexed($args); + foreach ($aArgs as $k => $arg) { + // Nulls are counted if literals, but not if cell values + if ($arg !== null || (!Functions::isCellValue($k))) { + ++$returnValue; + } + } + + return $returnValue; + } + + /** + * COUNTBLANK. + * + * Counts the number of empty cells within the list of arguments + * + * Excel Function: + * COUNTBLANK(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return int + */ + public static function COUNTBLANK(...$args) + { + $returnValue = 0; + + // Loop through arguments + $aArgs = Functions::flattenArray($args); + foreach ($aArgs as $arg) { + // Is it a blank cell? + if (($arg === null) || ((is_string($arg)) && ($arg == ''))) { + ++$returnValue; + } + } + + return $returnValue; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Deviations.php b/src/PhpSpreadsheet/Calculation/Statistical/Deviations.php new file mode 100644 index 00000000..55da9f1d --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Deviations.php @@ -0,0 +1,141 @@ + $arg) { + // Is it a numeric value? + if ( + (is_bool($arg)) && + ((!Functions::isCellValue($k)) || + (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE)) + ) { + $arg = (int) $arg; + } + if ((is_numeric($arg)) && (!is_string($arg))) { + $returnValue += ($arg - $aMean) ** 2; + ++$aCount; + } + } + + return $aCount === 0 ? Functions::VALUE() : $returnValue; + } + + /** + * KURT. + * + * Returns the kurtosis of a data set. Kurtosis characterizes the relative peakedness + * or flatness of a distribution compared with the normal distribution. Positive + * kurtosis indicates a relatively peaked distribution. Negative kurtosis indicates a + * relatively flat distribution. + * + * @param array ...$args Data Series + * + * @return float|string + */ + public static function kurtosis(...$args) + { + $aArgs = Functions::flattenArrayIndexed($args); + $mean = Averages::average($aArgs); + if (!is_numeric($mean)) { + return Functions::DIV0(); + } + $stdDev = StandardDeviations::STDEV($aArgs); + + if ($stdDev > 0) { + $count = $summer = 0; + + foreach ($aArgs as $k => $arg) { + if ((is_bool($arg)) && (!Functions::isMatrixValue($k))) { + } else { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $summer += (($arg - $mean) / $stdDev) ** 4; + ++$count; + } + } + } + + if ($count > 3) { + return $summer * ($count * ($count + 1) / + (($count - 1) * ($count - 2) * ($count - 3))) - (3 * ($count - 1) ** 2 / + (($count - 2) * ($count - 3))); + } + } + + return Functions::DIV0(); + } + + /** + * SKEW. + * + * Returns the skewness of a distribution. Skewness characterizes the degree of asymmetry + * of a distribution around its mean. Positive skewness indicates a distribution with an + * asymmetric tail extending toward more positive values. Negative skewness indicates a + * distribution with an asymmetric tail extending toward more negative values. + * + * @param array ...$args Data Series + * + * @return float|int|string The result, or a string containing an error + */ + public static function skew(...$args) + { + $aArgs = Functions::flattenArrayIndexed($args); + $mean = Averages::average($aArgs); + if (!is_numeric($mean)) { + return Functions::DIV0(); + } + $stdDev = StandardDeviations::STDEV($aArgs); + if ($stdDev === 0.0 || is_string($stdDev)) { + return Functions::DIV0(); + } + + $count = $summer = 0; + // Loop through arguments + foreach ($aArgs as $k => $arg) { + if ((is_bool($arg)) && (!Functions::isMatrixValue($k))) { + } elseif (!is_numeric($arg)) { + return Functions::VALUE(); + } else { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $summer += (($arg - $mean) / $stdDev) ** 3; + ++$count; + } + } + } + + if ($count > 2) { + return $summer * ($count / (($count - 1) * ($count - 2))); + } + + return Functions::DIV0(); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Beta.php b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Beta.php new file mode 100644 index 00000000..63e6eb4d --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Beta.php @@ -0,0 +1,260 @@ +getMessage(); + } + + if ($rMin > $rMax) { + $tmp = $rMin; + $rMin = $rMax; + $rMax = $tmp; + } + if (($value < $rMin) || ($value > $rMax) || ($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax)) { + return Functions::NAN(); + } + + $value -= $rMin; + $value /= ($rMax - $rMin); + + return self::incompleteBeta($value, $alpha, $beta); + } + + /** + * BETAINV. + * + * Returns the inverse of the Beta distribution. + * + * @param mixed $probability Float probability at which you want to evaluate the distribution + * @param mixed $alpha Parameter to the distribution as a float + * @param mixed $beta Parameter to the distribution as a float + * @param mixed $rMin Minimum value as a float + * @param mixed $rMax Maximum value as a float + * + * @return float|string + */ + public static function inverse($probability, $alpha, $beta, $rMin = 0.0, $rMax = 1.0) + { + $probability = Functions::flattenSingleValue($probability); + $alpha = Functions::flattenSingleValue($alpha); + $beta = Functions::flattenSingleValue($beta); + $rMin = ($rMin === null) ? 0.0 : Functions::flattenSingleValue($rMin); + $rMax = ($rMax === null) ? 1.0 : Functions::flattenSingleValue($rMax); + + try { + $probability = DistributionValidations::validateProbability($probability); + $alpha = DistributionValidations::validateFloat($alpha); + $beta = DistributionValidations::validateFloat($beta); + $rMax = DistributionValidations::validateFloat($rMax); + $rMin = DistributionValidations::validateFloat($rMin); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($rMin > $rMax) { + $tmp = $rMin; + $rMin = $rMax; + $rMax = $tmp; + } + if (($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax) || ($probability <= 0.0)) { + return Functions::NAN(); + } + + return self::calculateInverse($probability, $alpha, $beta, $rMin, $rMax); + } + + /** + * @return float|string + */ + private static function calculateInverse(float $probability, float $alpha, float $beta, float $rMin, float $rMax) + { + $a = 0; + $b = 2; + + $i = 0; + while ((($b - $a) > Functions::PRECISION) && (++$i <= self::MAX_ITERATIONS)) { + $guess = ($a + $b) / 2; + $result = self::distribution($guess, $alpha, $beta); + if (($result === $probability) || ($result === 0.0)) { + $b = $a; + } elseif ($result > $probability) { + $b = $guess; + } else { + $a = $guess; + } + } + + if ($i === self::MAX_ITERATIONS) { + return Functions::NA(); + } + + return round($rMin + $guess * ($rMax - $rMin), 12); + } + + /** + * Incomplete beta function. + * + * @author Jaco van Kooten + * @author Paul Meagher + * + * The computation is based on formulas from Numerical Recipes, Chapter 6.4 (W.H. Press et al, 1992). + * + * @param float $x require 0<=x<=1 + * @param float $p require p>0 + * @param float $q require q>0 + * + * @return float 0 if x<0, p<=0, q<=0 or p+q>2.55E305 and 1 if x>1 to avoid errors and over/underflow + */ + public static function incompleteBeta(float $x, float $p, float $q): float + { + if ($x <= 0.0) { + return 0.0; + } elseif ($x >= 1.0) { + return 1.0; + } elseif (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > self::LOG_GAMMA_X_MAX_VALUE)) { + return 0.0; + } + + $beta_gam = exp((0 - self::logBeta($p, $q)) + $p * log($x) + $q * log(1.0 - $x)); + if ($x < ($p + 1.0) / ($p + $q + 2.0)) { + return $beta_gam * self::betaFraction($x, $p, $q) / $p; + } + + return 1.0 - ($beta_gam * self::betaFraction(1 - $x, $q, $p) / $q); + } + + // Function cache for logBeta function + private static $logBetaCacheP = 0.0; + + private static $logBetaCacheQ = 0.0; + + private static $logBetaCacheResult = 0.0; + + /** + * The natural logarithm of the beta function. + * + * @param float $p require p>0 + * @param float $q require q>0 + * + * @return float 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow + * + * @author Jaco van Kooten + */ + private static function logBeta(float $p, float $q): float + { + if ($p != self::$logBetaCacheP || $q != self::$logBetaCacheQ) { + self::$logBetaCacheP = $p; + self::$logBetaCacheQ = $q; + if (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > self::LOG_GAMMA_X_MAX_VALUE)) { + self::$logBetaCacheResult = 0.0; + } else { + self::$logBetaCacheResult = Gamma::logGamma($p) + Gamma::logGamma($q) - Gamma::logGamma($p + $q); + } + } + + return self::$logBetaCacheResult; + } + + /** + * Evaluates of continued fraction part of incomplete beta function. + * Based on an idea from Numerical Recipes (W.H. Press et al, 1992). + * + * @author Jaco van Kooten + */ + private static function betaFraction(float $x, float $p, float $q): float + { + $c = 1.0; + $sum_pq = $p + $q; + $p_plus = $p + 1.0; + $p_minus = $p - 1.0; + $h = 1.0 - $sum_pq * $x / $p_plus; + if (abs($h) < self::XMININ) { + $h = self::XMININ; + } + $h = 1.0 / $h; + $frac = $h; + $m = 1; + $delta = 0.0; + while ($m <= self::MAX_ITERATIONS && abs($delta - 1.0) > Functions::PRECISION) { + $m2 = 2 * $m; + // even index for d + $d = $m * ($q - $m) * $x / (($p_minus + $m2) * ($p + $m2)); + $h = 1.0 + $d * $h; + if (abs($h) < self::XMININ) { + $h = self::XMININ; + } + $h = 1.0 / $h; + $c = 1.0 + $d / $c; + if (abs($c) < self::XMININ) { + $c = self::XMININ; + } + $frac *= $h * $c; + // odd index for d + $d = -($p + $m) * ($sum_pq + $m) * $x / (($p + $m2) * ($p_plus + $m2)); + $h = 1.0 + $d * $h; + if (abs($h) < self::XMININ) { + $h = self::XMININ; + } + $h = 1.0 / $h; + $c = 1.0 + $d / $c; + if (abs($c) < self::XMININ) { + $c = self::XMININ; + } + $delta = $h * $c; + $frac *= $delta; + ++$m; + } + + return $frac; + } + + private static function betaValue(float $a, float $b): float + { + return (Gamma::gammaValue($a) * Gamma::gammaValue($b)) / + Gamma::gammaValue($a + $b); + } + + private static function regularizedIncompleteBeta(float $value, float $a, float $b): float + { + return self::incompleteBeta($value, $a, $b) / self::betaValue($a, $b); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Binomial.php b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Binomial.php new file mode 100644 index 00000000..9631236a --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Binomial.php @@ -0,0 +1,202 @@ +getMessage(); + } + + if (($value < 0) || ($value > $trials)) { + return Functions::NAN(); + } + + if ($cumulative) { + return self::calculateCumulativeBinomial($value, $trials, $probability); + } + + return Combinations::withoutRepetition($trials, $value) * $probability ** $value + * (1 - $probability) ** ($trials - $value); + } + + /** + * BINOM.DIST.RANGE. + * + * Returns returns the Binomial Distribution probability for the number of successes from a specified number + * of trials falling into a specified range. + * + * @param mixed $trials Integer number of trials + * @param mixed $probability Probability of success on each trial as a float + * @param mixed $successes The integer number of successes in trials + * @param mixed $limit Upper limit for successes in trials as null, or an integer + * If null, then this will indicate the same as the number of Successes + * + * @return float|string + */ + public static function range($trials, $probability, $successes, $limit = null) + { + $trials = Functions::flattenSingleValue($trials); + $probability = Functions::flattenSingleValue($probability); + $successes = Functions::flattenSingleValue($successes); + $limit = ($limit === null) ? $successes : Functions::flattenSingleValue($limit); + + try { + $trials = DistributionValidations::validateInt($trials); + $probability = DistributionValidations::validateProbability($probability); + $successes = DistributionValidations::validateInt($successes); + $limit = DistributionValidations::validateInt($limit); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (($successes < 0) || ($successes > $trials)) { + return Functions::NAN(); + } + if (($limit < 0) || ($limit > $trials) || $limit < $successes) { + return Functions::NAN(); + } + + $summer = 0; + for ($i = $successes; $i <= $limit; ++$i) { + $summer += Combinations::withoutRepetition($trials, $i) * $probability ** $i + * (1 - $probability) ** ($trials - $i); + } + + return $summer; + } + + /** + * NEGBINOMDIST. + * + * Returns the negative binomial distribution. NEGBINOMDIST returns the probability that + * there will be number_f failures before the number_s-th success, when the constant + * probability of a success is probability_s. This function is similar to the binomial + * distribution, except that the number of successes is fixed, and the number of trials is + * variable. Like the binomial, trials are assumed to be independent. + * + * @param mixed $failures Number of Failures as an integer + * @param mixed $successes Threshold number of Successes as an integer + * @param mixed $probability Probability of success on each trial as a float + * + * @return float|string The result, or a string containing an error + * + * TODO Add support for the cumulative flag not present for NEGBINOMDIST, but introduced for NEGBINOM.DIST + * The cumulative default should be false to reflect the behaviour of NEGBINOMDIST + */ + public static function negative($failures, $successes, $probability) + { + $failures = Functions::flattenSingleValue($failures); + $successes = Functions::flattenSingleValue($successes); + $probability = Functions::flattenSingleValue($probability); + + try { + $failures = DistributionValidations::validateInt($failures); + $successes = DistributionValidations::validateInt($successes); + $probability = DistributionValidations::validateProbability($probability); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (($failures < 0) || ($successes < 1)) { + return Functions::NAN(); + } + if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { + if (($failures + $successes - 1) <= 0) { + return Functions::NAN(); + } + } + + return (Combinations::withoutRepetition($failures + $successes - 1, $successes - 1)) + * ($probability ** $successes) * ((1 - $probability) ** $failures); + } + + /** + * CRITBINOM. + * + * Returns the smallest value for which the cumulative binomial distribution is greater + * than or equal to a criterion value + * + * @param mixed $trials number of Bernoulli trials as an integer + * @param mixed $probability probability of a success on each trial as a float + * @param mixed $alpha criterion value as a float + * + * @return int|string + */ + public static function inverse($trials, $probability, $alpha) + { + $trials = Functions::flattenSingleValue($trials); + $probability = Functions::flattenSingleValue($probability); + $alpha = Functions::flattenSingleValue($alpha); + + try { + $trials = DistributionValidations::validateInt($trials); + $probability = DistributionValidations::validateProbability($probability); + $alpha = DistributionValidations::validateFloat($alpha); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($trials < 0) { + return Functions::NAN(); + } elseif (($alpha < 0.0) || ($alpha > 1.0)) { + return Functions::NAN(); + } + + $successes = 0; + while ($successes <= $trials) { + $result = self::calculateCumulativeBinomial($successes, $trials, $probability); + if ($result >= $alpha) { + break; + } + ++$successes; + } + + return $successes; + } + + /** + * @return float|int + */ + private static function calculateCumulativeBinomial(int $value, int $trials, float $probability) + { + $summer = 0; + for ($i = 0; $i <= $value; ++$i) { + $summer += Combinations::withoutRepetition($trials, $i) * $probability ** $i + * (1 - $probability) ** ($trials - $i); + } + + return $summer; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php new file mode 100644 index 00000000..5165d639 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php @@ -0,0 +1,311 @@ +getMessage(); + } + + if ($degrees < 1) { + return Functions::NAN(); + } + if ($value < 0) { + if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { + return 1; + } + + return Functions::NAN(); + } + + return 1 - (Gamma::incompleteGamma($degrees / 2, $value / 2) / Gamma::gammaValue($degrees / 2)); + } + + /** + * CHIDIST. + * + * Returns the one-tailed probability of the chi-squared distribution. + * + * @param mixed $value Float value for which we want the probability + * @param mixed $degrees Integer degrees of freedom + * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) + * + * @return float|string + */ + public static function distributionLeftTail($value, $degrees, $cumulative) + { + $value = Functions::flattenSingleValue($value); + $degrees = Functions::flattenSingleValue($degrees); + $cumulative = Functions::flattenSingleValue($cumulative); + + try { + $value = DistributionValidations::validateFloat($value); + $degrees = DistributionValidations::validateInt($degrees); + $cumulative = DistributionValidations::validateBool($cumulative); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($degrees < 1) { + return Functions::NAN(); + } + if ($value < 0) { + if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { + return 1; + } + + return Functions::NAN(); + } + + if ($cumulative === true) { + return 1 - self::distributionRightTail($value, $degrees); + } + + return (($value ** (($degrees / 2) - 1) * exp(-$value / 2))) / + ((2 ** ($degrees / 2)) * Gamma::gammaValue($degrees / 2)); + } + + /** + * CHIINV. + * + * Returns the inverse of the right-tailed probability of the chi-squared distribution. + * + * @param mixed $probability Float probability at which you want to evaluate the distribution + * @param mixed $degrees Integer degrees of freedom + * + * @return float|string + */ + public static function inverseRightTail($probability, $degrees) + { + $probability = Functions::flattenSingleValue($probability); + $degrees = Functions::flattenSingleValue($degrees); + + try { + $probability = DistributionValidations::validateProbability($probability); + $degrees = DistributionValidations::validateInt($degrees); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($degrees < 1) { + return Functions::NAN(); + } + + $callback = function ($value) use ($degrees) { + return 1 - (Gamma::incompleteGamma($degrees / 2, $value / 2) + / Gamma::gammaValue($degrees / 2)); + }; + + $newtonRaphson = new NewtonRaphson($callback); + + return $newtonRaphson->execute($probability); + } + + /** + * CHIINV. + * + * Returns the inverse of the left-tailed probability of the chi-squared distribution. + * + * @param mixed $probability Float probability at which you want to evaluate the distribution + * @param mixed $degrees Integer degrees of freedom + * + * @return float|string + */ + public static function inverseLeftTail($probability, $degrees) + { + $probability = Functions::flattenSingleValue($probability); + $degrees = Functions::flattenSingleValue($degrees); + + try { + $probability = DistributionValidations::validateProbability($probability); + $degrees = DistributionValidations::validateInt($degrees); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($degrees < 1) { + return Functions::NAN(); + } + + return self::inverseLeftTailCalculation($probability, $degrees); + } + + /** + * CHITEST. + * + * Uses the chi-square test to calculate the probability that the differences between two supplied data sets + * (of observed and expected frequencies), are likely to be simply due to sampling error, + * or if they are likely to be real. + * + * @param mixed $actual an array of observed frequencies + * @param mixed $expected an array of expected frequencies + * + * @return float|string + */ + public static function test($actual, $expected) + { + $rows = count($actual); + $actual = Functions::flattenArray($actual); + $expected = Functions::flattenArray($expected); + $columns = count($actual) / $rows; + + $countActuals = count($actual); + $countExpected = count($expected); + if ($countActuals !== $countExpected || $countActuals === 1) { + return Functions::NAN(); + } + + $result = 0.0; + for ($i = 0; $i < $countActuals; ++$i) { + if ($expected[$i] == 0.0) { + return Functions::DIV0(); + } elseif ($expected[$i] < 0.0) { + return Functions::NAN(); + } + $result += (($actual[$i] - $expected[$i]) ** 2) / $expected[$i]; + } + + $degrees = self::degrees($rows, $columns); + + $result = self::distributionRightTail($result, $degrees); + + return $result; + } + + protected static function degrees(int $rows, int $columns): int + { + if ($rows === 1) { + return $columns - 1; + } elseif ($columns === 1) { + return $rows - 1; + } + + return ($columns - 1) * ($rows - 1); + } + + private static function inverseLeftTailCalculation(float $probability, int $degrees): float + { + // bracket the root + $min = 0; + $sd = sqrt(2.0 * $degrees); + $max = 2 * $sd; + $s = -1; + + while ($s * self::pchisq($max, $degrees) > $probability * $s) { + $min = $max; + $max += 2 * $sd; + } + + // Find root using bisection + $chi2 = 0.5 * ($min + $max); + + while (($max - $min) > self::EPS * $chi2) { + if ($s * self::pchisq($chi2, $degrees) > $probability * $s) { + $min = $chi2; + } else { + $max = $chi2; + } + $chi2 = 0.5 * ($min + $max); + } + + return $chi2; + } + + private static function pchisq($chi2, $degrees) + { + return self::gammp($degrees, 0.5 * $chi2); + } + + private static function gammp($n, $x) + { + if ($x < 0.5 * $n + 1) { + return self::gser($n, $x); + } + + return 1 - self::gcf($n, $x); + } + + // Return the incomplete gamma function P(n/2,x) evaluated by + // series representation. Algorithm from numerical recipe. + // Assume that n is a positive integer and x>0, won't check arguments. + // Relative error controlled by the eps parameter + private static function gser($n, $x) + { + $gln = Gamma::ln($n / 2); + $a = 0.5 * $n; + $ap = $a; + $sum = 1.0 / $a; + $del = $sum; + for ($i = 1; $i < 101; ++$i) { + ++$ap; + $del = $del * $x / $ap; + $sum += $del; + if ($del < $sum * self::EPS) { + break; + } + } + + return $sum * exp(-$x + $a * log($x) - $gln); + } + + // Return the incomplete gamma function Q(n/2,x) evaluated by + // its continued fraction representation. Algorithm from numerical recipe. + // Assume that n is a postive integer and x>0, won't check arguments. + // Relative error controlled by the eps parameter + private static function gcf($n, $x) + { + $gln = Gamma::ln($n / 2); + $a = 0.5 * $n; + $b = $x + 1 - $a; + $fpmin = 1.e-300; + $c = 1 / $fpmin; + $d = 1 / $b; + $h = $d; + for ($i = 1; $i < 101; ++$i) { + $an = -$i * ($i - $a); + $b += 2; + $d = $an * $d + $b; + if (abs($d) < $fpmin) { + $d = $fpmin; + } + $c = $b + $an / $c; + if (abs($c) < $fpmin) { + $c = $fpmin; + } + $d = 1 / $d; + $del = $d * $c; + $h = $h * $del; + if (abs($del - 1) < self::EPS) { + break; + } + } + + return $h * exp(-$x + $a * log($x) - $gln); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Distributions/DistributionValidations.php b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/DistributionValidations.php new file mode 100644 index 00000000..57ef00af --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/DistributionValidations.php @@ -0,0 +1,24 @@ + 1.0) { + throw new Exception(Functions::NAN()); + } + + return $probability; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Exponential.php b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Exponential.php new file mode 100644 index 00000000..b3fd9460 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Exponential.php @@ -0,0 +1,47 @@ +getMessage(); + } + + if (($value < 0) || ($lambda < 0)) { + return Functions::NAN(); + } + + if ($cumulative === true) { + return 1 - exp(0 - $value * $lambda); + } + + return $lambda * exp(0 - $value * $lambda); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Distributions/F.php b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/F.php new file mode 100644 index 00000000..54b1950d --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/F.php @@ -0,0 +1,56 @@ +getMessage(); + } + + if ($value < 0 || $u < 1 || $v < 1) { + return Functions::NAN(); + } + + if ($cumulative) { + $adjustedValue = ($u * $value) / ($u * $value + $v); + + return Beta::incompleteBeta($adjustedValue, $u / 2, $v / 2); + } + + return (Gamma::gammaValue(($v + $u) / 2) / + (Gamma::gammaValue($u / 2) * Gamma::gammaValue($v / 2))) * + (($u / $v) ** ($u / 2)) * + (($value ** (($u - 2) / 2)) / ((1 + ($u / $v) * $value) ** (($u + $v) / 2))); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Fisher.php b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Fisher.php new file mode 100644 index 00000000..923bf02d --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Fisher.php @@ -0,0 +1,61 @@ +getMessage(); + } + + if (($value <= -1) || ($value >= 1)) { + return Functions::NAN(); + } + + return 0.5 * log((1 + $value) / (1 - $value)); + } + + /** + * FISHERINV. + * + * Returns the inverse of the Fisher transformation. Use this transformation when + * analyzing correlations between ranges or arrays of data. If y = FISHER(x), then + * FISHERINV(y) = x. + * + * @param mixed $probability Float probability at which you want to evaluate the distribution + * + * @return float|string + */ + public static function inverse($probability) + { + $probability = Functions::flattenSingleValue($probability); + + try { + DistributionValidations::validateFloat($probability); + } catch (Exception $e) { + return $e->getMessage(); + } + + return (exp(2 * $probability) - 1) / (exp(2 * $probability) + 1); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Gamma.php b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Gamma.php new file mode 100644 index 00000000..2c6ed670 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Gamma.php @@ -0,0 +1,127 @@ +getMessage(); + } + + if ((((int) $value) == ((float) $value)) && $value <= 0.0) { + return Functions::NAN(); + } + + return self::gammaValue($value); + } + + /** + * GAMMADIST. + * + * Returns the gamma distribution. + * + * @param mixed $value Float Value at which you want to evaluate the distribution + * @param mixed $a Parameter to the distribution as a float + * @param mixed $b Parameter to the distribution as a float + * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) + * + * @return float|string + */ + public static function distribution($value, $a, $b, $cumulative) + { + $value = Functions::flattenSingleValue($value); + $a = Functions::flattenSingleValue($a); + $b = Functions::flattenSingleValue($b); + + try { + $value = DistributionValidations::validateFloat($value); + $a = DistributionValidations::validateFloat($a); + $b = DistributionValidations::validateFloat($b); + $cumulative = DistributionValidations::validateBool($cumulative); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (($value < 0) || ($a <= 0) || ($b <= 0)) { + return Functions::NAN(); + } + + return self::calculateDistribution($value, $a, $b, $cumulative); + } + + /** + * GAMMAINV. + * + * Returns the inverse of the Gamma distribution. + * + * @param mixed $probability Float probability at which you want to evaluate the distribution + * @param mixed $alpha Parameter to the distribution as a float + * @param mixed $beta Parameter to the distribution as a float + * + * @return float|string + */ + public static function inverse($probability, $alpha, $beta) + { + $probability = Functions::flattenSingleValue($probability); + $alpha = Functions::flattenSingleValue($alpha); + $beta = Functions::flattenSingleValue($beta); + + try { + $probability = DistributionValidations::validateProbability($probability); + $alpha = DistributionValidations::validateFloat($alpha); + $beta = DistributionValidations::validateFloat($beta); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (($alpha <= 0.0) || ($beta <= 0.0)) { + return Functions::NAN(); + } + + return self::calculateInverse($probability, $alpha, $beta); + } + + /** + * GAMMALN. + * + * Returns the natural logarithm of the gamma function. + * + * @param mixed $value Float Value at which you want to evaluate the distribution + * + * @return float|string + */ + public static function ln($value) + { + $value = Functions::flattenSingleValue($value); + + try { + $value = DistributionValidations::validateFloat($value); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($value <= 0) { + return Functions::NAN(); + } + + return log(self::gammaValue($value)); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php new file mode 100644 index 00000000..89170f7c --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php @@ -0,0 +1,381 @@ + Functions::PRECISION) && (++$i <= self::MAX_ITERATIONS)) { + // Apply Newton-Raphson step + $result = self::calculateDistribution($x, $alpha, $beta, true); + $error = $result - $probability; + + if ($error == 0.0) { + $dx = 0; + } elseif ($error < 0.0) { + $xLo = $x; + } else { + $xHi = $x; + } + + $pdf = self::calculateDistribution($x, $alpha, $beta, false); + // Avoid division by zero + if ($pdf !== 0.0) { + $dx = $error / $pdf; + $xNew = $x - $dx; + } + + // If the NR fails to converge (which for example may be the + // case if the initial guess is too rough) we apply a bisection + // step to determine a more narrow interval around the root. + if (($xNew < $xLo) || ($xNew > $xHi) || ($pdf == 0.0)) { + $xNew = ($xLo + $xHi) / 2; + $dx = $xNew - $x; + } + $x = $xNew; + } + + if ($i === self::MAX_ITERATIONS) { + return Functions::NA(); + } + + return $x; + } + + // + // Implementation of the incomplete Gamma function + // + public static function incompleteGamma(float $a, float $x): float + { + static $max = 32; + $summer = 0; + for ($n = 0; $n <= $max; ++$n) { + $divisor = $a; + for ($i = 1; $i <= $n; ++$i) { + $divisor *= ($a + $i); + } + $summer += ($x ** $n / $divisor); + } + + return $x ** $a * exp(0 - $x) * $summer; + } + + // + // Implementation of the Gamma function + // + public static function gammaValue(float $value): float + { + if ($value == 0.0) { + return 0; + } + + static $p0 = 1.000000000190015; + static $p = [ + 1 => 76.18009172947146, + 2 => -86.50532032941677, + 3 => 24.01409824083091, + 4 => -1.231739572450155, + 5 => 1.208650973866179e-3, + 6 => -5.395239384953e-6, + ]; + + $y = $x = $value; + $tmp = $x + 5.5; + $tmp -= ($x + 0.5) * log($tmp); + + $summer = $p0; + for ($j = 1; $j <= 6; ++$j) { + $summer += ($p[$j] / ++$y); + } + + return exp(0 - $tmp + log(self::SQRT2PI * $summer / $x)); + } + + /** + * logGamma function. + * + * @version 1.1 + * + * @author Jaco van Kooten + * + * Original author was Jaco van Kooten. Ported to PHP by Paul Meagher. + * + * The natural logarithm of the gamma function.
+ * Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz
+ * Applied Mathematics Division
+ * Argonne National Laboratory
+ * Argonne, IL 60439
+ *

+ * References: + *

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

+ *

+ * From the original documentation: + *

+ *

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

+ *

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

+ * + * @return float MAX_VALUE for x < 0.0 or when overflow would occur, i.e. x > 2.55E305 + */ + + // Log Gamma related constants + private const LG_D1 = -0.5772156649015328605195174; + + private const LG_D2 = 0.4227843350984671393993777; + + private const LG_D4 = 1.791759469228055000094023; + + private const LG_P1 = [ + 4.945235359296727046734888, + 201.8112620856775083915565, + 2290.838373831346393026739, + 11319.67205903380828685045, + 28557.24635671635335736389, + 38484.96228443793359990269, + 26377.48787624195437963534, + 7225.813979700288197698961, + ]; + + private const LG_P2 = [ + 4.974607845568932035012064, + 542.4138599891070494101986, + 15506.93864978364947665077, + 184793.2904445632425417223, + 1088204.76946882876749847, + 3338152.967987029735917223, + 5106661.678927352456275255, + 3074109.054850539556250927, + ]; + + private const LG_P4 = [ + 14745.02166059939948905062, + 2426813.369486704502836312, + 121475557.4045093227939592, + 2663432449.630976949898078, + 29403789566.34553899906876, + 170266573776.5398868392998, + 492612579337.743088758812, + 560625185622.3951465078242, + ]; + + private const LG_Q1 = [ + 67.48212550303777196073036, + 1113.332393857199323513008, + 7738.757056935398733233834, + 27639.87074403340708898585, + 54993.10206226157329794414, + 61611.22180066002127833352, + 36351.27591501940507276287, + 8785.536302431013170870835, + ]; + + private const LG_Q2 = [ + 183.0328399370592604055942, + 7765.049321445005871323047, + 133190.3827966074194402448, + 1136705.821321969608938755, + 5267964.117437946917577538, + 13467014.54311101692290052, + 17827365.30353274213975932, + 9533095.591844353613395747, + ]; + + private const LG_Q4 = [ + 2690.530175870899333379843, + 639388.5654300092398984238, + 41355999.30241388052042842, + 1120872109.61614794137657, + 14886137286.78813811542398, + 101680358627.2438228077304, + 341747634550.7377132798597, + 446315818741.9713286462081, + ]; + + private const LG_C = [ + -0.001910444077728, + 8.4171387781295e-4, + -5.952379913043012e-4, + 7.93650793500350248e-4, + -0.002777777777777681622553, + 0.08333333333333333331554247, + 0.0057083835261, + ]; + + // Rough estimate of the fourth root of logGamma_xBig + private const LG_FRTBIG = 2.25e76; + + private const PNT68 = 0.6796875; + + // Function cache for logGamma + private static $logGammaCacheResult = 0.0; + + private static $logGammaCacheX = 0.0; + + public static function logGamma(float $x): float + { + if ($x == self::$logGammaCacheX) { + return self::$logGammaCacheResult; + } + + $y = $x; + if ($y > 0.0 && $y <= self::LOG_GAMMA_X_MAX_VALUE) { + if ($y <= self::EPS) { + $res = -log($y); + } elseif ($y <= 1.5) { + $res = self::logGamma1($y); + } elseif ($y <= 4.0) { + $res = self::logGamma2($y); + } elseif ($y <= 12.0) { + $res = self::logGamma3($y); + } else { + $res = self::logGamma4($y); + } + } else { + // -------------------------- + // Return for bad arguments + // -------------------------- + $res = self::MAX_VALUE; + } + + // ------------------------------ + // Final adjustments and return + // ------------------------------ + self::$logGammaCacheX = $x; + self::$logGammaCacheResult = $res; + + return $res; + } + + private static function logGamma1(float $y) + { + // --------------------- + // EPS .LT. X .LE. 1.5 + // --------------------- + if ($y < self::PNT68) { + $corr = -log($y); + $xm1 = $y; + } else { + $corr = 0.0; + $xm1 = $y - 1.0; + } + + $xden = 1.0; + $xnum = 0.0; + if ($y <= 0.5 || $y >= self::PNT68) { + for ($i = 0; $i < 8; ++$i) { + $xnum = $xnum * $xm1 + self::LG_P1[$i]; + $xden = $xden * $xm1 + self::LG_Q1[$i]; + } + + return $corr + $xm1 * (self::LG_D1 + $xm1 * ($xnum / $xden)); + } + + $xm2 = $y - 1.0; + for ($i = 0; $i < 8; ++$i) { + $xnum = $xnum * $xm2 + self::LG_P2[$i]; + $xden = $xden * $xm2 + self::LG_Q2[$i]; + } + + return $corr + $xm2 * (self::LG_D2 + $xm2 * ($xnum / $xden)); + } + + private static function logGamma2(float $y) + { + // --------------------- + // 1.5 .LT. X .LE. 4.0 + // --------------------- + $xm2 = $y - 2.0; + $xden = 1.0; + $xnum = 0.0; + for ($i = 0; $i < 8; ++$i) { + $xnum = $xnum * $xm2 + self::LG_P2[$i]; + $xden = $xden * $xm2 + self::LG_Q2[$i]; + } + + return $xm2 * (self::LG_D2 + $xm2 * ($xnum / $xden)); + } + + protected static function logGamma3(float $y) + { + // ---------------------- + // 4.0 .LT. X .LE. 12.0 + // ---------------------- + $xm4 = $y - 4.0; + $xden = -1.0; + $xnum = 0.0; + for ($i = 0; $i < 8; ++$i) { + $xnum = $xnum * $xm4 + self::LG_P4[$i]; + $xden = $xden * $xm4 + self::LG_Q4[$i]; + } + + return self::LG_D4 + $xm4 * ($xnum / $xden); + } + + protected static function logGamma4(float $y) + { + // --------------------------------- + // Evaluate for argument .GE. 12.0 + // --------------------------------- + $res = 0.0; + if ($y <= self::LG_FRTBIG) { + $res = self::LG_C[6]; + $ysq = $y * $y; + for ($i = 0; $i < 6; ++$i) { + $res = $res / $ysq + self::LG_C[$i]; + } + $res /= $y; + $corr = log($y); + $res = $res + log(self::SQRT2PI) - 0.5 * $corr; + $res += $y * ($corr - 1.0); + } + + return $res; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Distributions/HyperGeometric.php b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/HyperGeometric.php new file mode 100644 index 00000000..fe30c087 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/HyperGeometric.php @@ -0,0 +1,59 @@ +getMessage(); + } + + if (($sampleSuccesses < 0) || ($sampleSuccesses > $sampleNumber) || ($sampleSuccesses > $populationSuccesses)) { + return Functions::NAN(); + } + if (($sampleNumber <= 0) || ($sampleNumber > $populationNumber)) { + return Functions::NAN(); + } + if (($populationSuccesses <= 0) || ($populationSuccesses > $populationNumber)) { + return Functions::NAN(); + } + + $successesPopulationAndSample = (float) Combinations::withoutRepetition($populationSuccesses, $sampleSuccesses); + $numbersPopulationAndSample = (float) Combinations::withoutRepetition($populationNumber, $sampleNumber); + $adjustedPopulationAndSample = (float) Combinations::withoutRepetition( + $populationNumber - $populationSuccesses, + $sampleNumber - $sampleSuccesses + ); + + return $successesPopulationAndSample * $adjustedPopulationAndSample / $numbersPopulationAndSample; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Distributions/LogNormal.php b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/LogNormal.php new file mode 100644 index 00000000..e1523773 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/LogNormal.php @@ -0,0 +1,119 @@ +getMessage(); + } + + if (($value <= 0) || ($stdDev <= 0)) { + return Functions::NAN(); + } + + return StandardNormal::cumulative((log($value) - $mean) / $stdDev); + } + + /** + * LOGNORM.DIST. + * + * Returns the lognormal distribution of x, where ln(x) is normally distributed + * with parameters mean and standard_dev. + * + * @param mixed $value Float value for which we want the probability + * @param mixed $mean Mean value as a float + * @param mixed $stdDev Standard Deviation as a float + * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) + * + * @return float|string The result, or a string containing an error + */ + public static function distribution($value, $mean, $stdDev, $cumulative = false) + { + $value = Functions::flattenSingleValue($value); + $mean = Functions::flattenSingleValue($mean); + $stdDev = Functions::flattenSingleValue($stdDev); + $cumulative = Functions::flattenSingleValue($cumulative); + + try { + $value = DistributionValidations::validateFloat($value); + $mean = DistributionValidations::validateFloat($mean); + $stdDev = DistributionValidations::validateFloat($stdDev); + $cumulative = DistributionValidations::validateBool($cumulative); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (($value <= 0) || ($stdDev <= 0)) { + return Functions::NAN(); + } + + if ($cumulative === true) { + return StandardNormal::distribution((log($value) - $mean) / $stdDev, true); + } + + return (1 / (sqrt(2 * M_PI) * $stdDev * $value)) * + exp(0 - ((log($value) - $mean) ** 2 / (2 * $stdDev ** 2))); + } + + /** + * LOGINV. + * + * Returns the inverse of the lognormal cumulative distribution + * + * @param mixed $probability Float probability for which we want the value + * @param mixed $mean Mean Value as a float + * @param mixed $stdDev Standard Deviation as a float + * + * @return float|string The result, or a string containing an error + * + * @TODO Try implementing P J Acklam's refinement algorithm for greater + * accuracy if I can get my head round the mathematics + * (as described at) http://home.online.no/~pjacklam/notes/invnorm/ + */ + public static function inverse($probability, $mean, $stdDev) + { + $probability = Functions::flattenSingleValue($probability); + $mean = Functions::flattenSingleValue($mean); + $stdDev = Functions::flattenSingleValue($stdDev); + + try { + $probability = DistributionValidations::validateProbability($probability); + $mean = DistributionValidations::validateFloat($mean); + $stdDev = DistributionValidations::validateFloat($stdDev); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($stdDev <= 0) { + return Functions::NAN(); + } + + return exp($mean + $stdDev * StandardNormal::inverse($probability)); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Distributions/NewtonRaphson.php b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/NewtonRaphson.php new file mode 100644 index 00000000..26211672 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/NewtonRaphson.php @@ -0,0 +1,62 @@ +callback = $callback; + } + + public function execute(float $probability) + { + $xLo = 100; + $xHi = 0; + + $dx = 1; + $x = $xNew = 1; + $i = 0; + + while ((abs($dx) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) { + // Apply Newton-Raphson step + $result = call_user_func($this->callback, $x); + $error = $result - $probability; + + if ($error == 0.0) { + $dx = 0; + } elseif ($error < 0.0) { + $xLo = $x; + } else { + $xHi = $x; + } + + // Avoid division by zero + if ($result != 0.0) { + $dx = $error / $result; + $xNew = $x - $dx; + } + + // If the NR fails to converge (which for example may be the + // case if the initial guess is too rough) we apply a bisection + // step to determine a more narrow interval around the root. + if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) { + $xNew = ($xLo + $xHi) / 2; + $dx = $xNew - $x; + } + $x = $xNew; + } + + if ($i == self::MAX_ITERATIONS) { + return Functions::NA(); + } + + return $x; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Normal.php b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Normal.php new file mode 100644 index 00000000..4d158b8c --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Normal.php @@ -0,0 +1,166 @@ +getMessage(); + } + + if ($stdDev < 0) { + return Functions::NAN(); + } + + if ($cumulative) { + return 0.5 * (1 + Engineering\Erf::erfValue(($value - $mean) / ($stdDev * sqrt(2)))); + } + + return (1 / (self::SQRT2PI * $stdDev)) * exp(0 - (($value - $mean) ** 2 / (2 * ($stdDev * $stdDev)))); + } + + /** + * NORMINV. + * + * Returns the inverse of the normal cumulative distribution for the specified mean and standard deviation. + * + * @param mixed $probability Float probability for which we want the value + * @param mixed $mean Mean Value as a float + * @param mixed $stdDev Standard Deviation as a float + * + * @return float|string The result, or a string containing an error + */ + public static function inverse($probability, $mean, $stdDev) + { + $probability = Functions::flattenSingleValue($probability); + $mean = Functions::flattenSingleValue($mean); + $stdDev = Functions::flattenSingleValue($stdDev); + + try { + $probability = DistributionValidations::validateProbability($probability); + $mean = DistributionValidations::validateFloat($mean); + $stdDev = DistributionValidations::validateFloat($stdDev); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($stdDev < 0) { + return Functions::NAN(); + } + + return (self::inverseNcdf($probability) * $stdDev) + $mean; + } + + /* + * inverse_ncdf.php + * ------------------- + * begin : Friday, January 16, 2004 + * copyright : (C) 2004 Michael Nickerson + * email : nickersonm@yahoo.com + * + */ + private static function inverseNcdf($p) + { + // Inverse ncdf approximation by Peter J. Acklam, implementation adapted to + // PHP by Michael Nickerson, using Dr. Thomas Ziegler's C implementation as + // a guide. http://home.online.no/~pjacklam/notes/invnorm/index.html + // I have not checked the accuracy of this implementation. Be aware that PHP + // will truncate the coeficcients to 14 digits. + + // You have permission to use and distribute this function freely for + // whatever purpose you want, but please show common courtesy and give credit + // where credit is due. + + // Input paramater is $p - probability - where 0 < p < 1. + + // Coefficients in rational approximations + static $a = [ + 1 => -3.969683028665376e+01, + 2 => 2.209460984245205e+02, + 3 => -2.759285104469687e+02, + 4 => 1.383577518672690e+02, + 5 => -3.066479806614716e+01, + 6 => 2.506628277459239e+00, + ]; + + static $b = [ + 1 => -5.447609879822406e+01, + 2 => 1.615858368580409e+02, + 3 => -1.556989798598866e+02, + 4 => 6.680131188771972e+01, + 5 => -1.328068155288572e+01, + ]; + + static $c = [ + 1 => -7.784894002430293e-03, + 2 => -3.223964580411365e-01, + 3 => -2.400758277161838e+00, + 4 => -2.549732539343734e+00, + 5 => 4.374664141464968e+00, + 6 => 2.938163982698783e+00, + ]; + + static $d = [ + 1 => 7.784695709041462e-03, + 2 => 3.224671290700398e-01, + 3 => 2.445134137142996e+00, + 4 => 3.754408661907416e+00, + ]; + + // Define lower and upper region break-points. + $p_low = 0.02425; //Use lower region approx. below this + $p_high = 1 - $p_low; //Use upper region approx. above this + + if (0 < $p && $p < $p_low) { + // Rational approximation for lower region. + $q = sqrt(-2 * log($p)); + + return ((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) / + (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1); + } elseif ($p_high < $p && $p < 1) { + // Rational approximation for upper region. + $q = sqrt(-2 * log(1 - $p)); + + return -((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) / + (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1); + } + + // Rational approximation for central region. + $q = $p - 0.5; + $r = $q * $q; + + return ((((($a[1] * $r + $a[2]) * $r + $a[3]) * $r + $a[4]) * $r + $a[5]) * $r + $a[6]) * $q / + ((((($b[1] * $r + $b[2]) * $r + $b[3]) * $r + $b[4]) * $r + $b[5]) * $r + 1); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Poisson.php b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Poisson.php new file mode 100644 index 00000000..e7252e02 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Poisson.php @@ -0,0 +1,53 @@ +getMessage(); + } + + if (($value < 0) || ($mean < 0)) { + return Functions::NAN(); + } + + if ($cumulative) { + $summer = 0; + $floor = floor($value); + for ($i = 0; $i <= $floor; ++$i) { + $summer += $mean ** $i / MathTrig\Factorial::fact($i); + } + + return exp(0 - $mean) * $summer; + } + + return (exp(0 - $mean) * $mean ** $value) / MathTrig\Factorial::fact($value); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Distributions/StandardNormal.php b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/StandardNormal.php new file mode 100644 index 00000000..d10f02a5 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/StandardNormal.php @@ -0,0 +1,110 @@ +getMessage(); + } + + if (($value < 0) || ($degrees < 1) || ($tails < 1) || ($tails > 2)) { + return Functions::NAN(); + } + + return self::calculateDistribution($value, $degrees, $tails); + } + + /** + * TINV. + * + * Returns the one-tailed probability of the chi-squared distribution. + * + * @param mixed $probability Float probability for the function + * @param mixed $degrees Integer value for degrees of freedom + * + * @return float|string The result, or a string containing an error + */ + public static function inverse($probability, $degrees) + { + $probability = Functions::flattenSingleValue($probability); + $degrees = Functions::flattenSingleValue($degrees); + + try { + $probability = DistributionValidations::validateProbability($probability); + $degrees = DistributionValidations::validateInt($degrees); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($degrees <= 0) { + return Functions::NAN(); + } + + $callback = function ($value) use ($degrees) { + return self::distribution($value, $degrees, 2); + }; + + $newtonRaphson = new NewtonRaphson($callback); + + return $newtonRaphson->execute($probability); + } + + /** + * @return float + */ + private static function calculateDistribution(float $value, int $degrees, int $tails) + { + // tdist, which finds the probability that corresponds to a given value + // of t with k degrees of freedom. This algorithm is translated from a + // pascal function on p81 of "Statistical Computing in Pascal" by D + // Cooke, A H Craven & G M Clark (1985: Edward Arnold (Pubs.) Ltd: + // London). The above Pascal algorithm is itself a translation of the + // fortran algoritm "AS 3" by B E Cooper of the Atlas Computer + // Laboratory as reported in (among other places) "Applied Statistics + // Algorithms", editied by P Griffiths and I D Hill (1985; Ellis + // Horwood Ltd.; W. Sussex, England). + $tterm = $degrees; + $ttheta = atan2($value, sqrt($tterm)); + $tc = cos($ttheta); + $ts = sin($ttheta); + + if (($degrees % 2) === 1) { + $ti = 3; + $tterm = $tc; + } else { + $ti = 2; + $tterm = 1; + } + + $tsum = $tterm; + while ($ti < $degrees) { + $tterm *= $tc * $tc * ($ti - 1) / $ti; + $tsum += $tterm; + $ti += 2; + } + + $tsum *= $ts; + if (($degrees % 2) == 1) { + $tsum = Functions::M_2DIVPI * ($tsum + $ttheta); + } + + $tValue = 0.5 * (1 + $tsum); + if ($tails == 1) { + return 1 - abs($tValue); + } + + return 1 - abs((1 - $tValue) - $tValue); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Weibull.php b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Weibull.php new file mode 100644 index 00000000..ecec8a85 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Weibull.php @@ -0,0 +1,49 @@ +getMessage(); + } + + if (($value < 0) || ($alpha <= 0) || ($beta <= 0)) { + return Functions::NAN(); + } + + if ($cumulative) { + return 1 - exp(0 - ($value / $beta) ** $alpha); + } + + return ($alpha / $beta ** $alpha) * $value ** ($alpha - 1) * exp(0 - ($value / $beta) ** $alpha); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php b/src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php new file mode 100644 index 00000000..bd17b062 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php @@ -0,0 +1,17 @@ + $returnValue)) { + $returnValue = $arg; + } + } + } + + if ($returnValue === null) { + return 0; + } + + return $returnValue; + } + + /** + * MAXA. + * + * Returns the greatest value in a list of arguments, including numbers, text, and logical values + * + * Excel Function: + * MAXA(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float + */ + public static function maxA(...$args) + { + $returnValue = null; + + // Loop through arguments + $aArgs = Functions::flattenArray($args); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { + $arg = self::datatypeAdjustmentAllowStrings($arg); + if (($returnValue === null) || ($arg > $returnValue)) { + $returnValue = $arg; + } + } + } + + if ($returnValue === null) { + return 0; + } + + return $returnValue; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Minimum.php b/src/PhpSpreadsheet/Calculation/Statistical/Minimum.php new file mode 100644 index 00000000..596aad78 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Minimum.php @@ -0,0 +1,78 @@ +getMessage(); + } + + if (($entry < 0) || ($entry > 1)) { + return Functions::NAN(); + } + + $mArgs = self::percentileFilterValues($aArgs); + $mValueCount = count($mArgs); + if ($mValueCount > 0) { + sort($mArgs); + $count = Counts::COUNT($mArgs); + $index = $entry * ($count - 1); + $iBase = floor($index); + if ($index == $iBase) { + return $mArgs[$index]; + } + $iNext = $iBase + 1; + $iProportion = $index - $iBase; + + return $mArgs[$iBase] + (($mArgs[$iNext] - $mArgs[$iBase]) * $iProportion); + } + + return Functions::NAN(); + } + + /** + * PERCENTRANK. + * + * Returns the rank of a value in a data set as a percentage of the data set. + * Note that the returned rank is simply rounded to the appropriate significant digits, + * rather than floored (as MS Excel), so value 3 for a value set of 1, 2, 3, 4 will return + * 0.667 rather than 0.666 + * + * @param mixed $valueSet An array of (float) values, or a reference to, a list of numbers + * @param mixed $value The number whose rank you want to find + * @param mixed $significance The (integer) number of significant digits for the returned percentage value + * + * @return float|string (string if result is an error) + */ + public static function PERCENTRANK($valueSet, $value, $significance = 3) + { + $valueSet = Functions::flattenArray($valueSet); + $value = Functions::flattenSingleValue($value); + $significance = ($significance === null) ? 3 : Functions::flattenSingleValue($significance); + + try { + $value = StatisticalValidations::validateFloat($value); + $significance = StatisticalValidations::validateInt($significance); + } catch (Exception $e) { + return $e->getMessage(); + } + + $valueSet = self::rankFilterValues($valueSet); + $valueCount = count($valueSet); + if ($valueCount == 0) { + return Functions::NA(); + } + sort($valueSet, SORT_NUMERIC); + + $valueAdjustor = $valueCount - 1; + if (($value < $valueSet[0]) || ($value > $valueSet[$valueAdjustor])) { + return Functions::NA(); + } + + $pos = array_search($value, $valueSet); + if ($pos === false) { + $pos = 0; + $testValue = $valueSet[0]; + while ($testValue < $value) { + $testValue = $valueSet[++$pos]; + } + --$pos; + $pos += (($value - $valueSet[$pos]) / ($testValue - $valueSet[$pos])); + } + + return round($pos / $valueAdjustor, $significance); + } + + /** + * QUARTILE. + * + * Returns the quartile of a data set. + * + * Excel Function: + * QUARTILE(value1[,value2[, ...]],entry) + * + * @param mixed $args Data values + * + * @return float|string The result, or a string containing an error + */ + public static function QUARTILE(...$args) + { + $aArgs = Functions::flattenArray($args); + $entry = array_pop($aArgs); + + try { + $entry = StatisticalValidations::validateFloat($entry); + } catch (Exception $e) { + return $e->getMessage(); + } + + $entry = floor($entry); + $entry /= 4; + if (($entry < 0) || ($entry > 1)) { + return Functions::NAN(); + } + + return self::PERCENTILE($aArgs, $entry); + } + + /** + * RANK. + * + * Returns the rank of a number in a list of numbers. + * + * @param mixed $value The number whose rank you want to find + * @param mixed $valueSet An array of float values, or a reference to, a list of numbers + * @param mixed $order Order to sort the values in the value set + * + * @return float|string The result, or a string containing an error (0 = Descending, 1 = Ascending) + */ + public static function RANK($value, $valueSet, $order = self::RANK_SORT_DESCENDING) + { + $value = Functions::flattenSingleValue($value); + $valueSet = Functions::flattenArray($valueSet); + $order = ($order === null) ? self::RANK_SORT_DESCENDING : Functions::flattenSingleValue($order); + + try { + $value = StatisticalValidations::validateFloat($value); + $order = StatisticalValidations::validateInt($order); + } catch (Exception $e) { + return $e->getMessage(); + } + + $valueSet = self::rankFilterValues($valueSet); + if ($order === self::RANK_SORT_DESCENDING) { + rsort($valueSet, SORT_NUMERIC); + } else { + sort($valueSet, SORT_NUMERIC); + } + + $pos = array_search($value, $valueSet); + if ($pos === false) { + return Functions::NA(); + } + + return ++$pos; + } + + protected static function percentileFilterValues(array $dataSet) + { + return array_filter( + $dataSet, + function ($value): bool { + return is_numeric($value) && !is_string($value); + } + ); + } + + protected static function rankFilterValues(array $dataSet) + { + return array_filter( + $dataSet, + function ($value): bool { + return is_numeric($value); + } + ); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Permutations.php b/src/PhpSpreadsheet/Calculation/Statistical/Permutations.php new file mode 100644 index 00000000..272a8a53 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Permutations.php @@ -0,0 +1,77 @@ +getMessage(); + } + + if ($numObjs < $numInSet) { + return Functions::NAN(); + } + $result = round(MathTrig\Factorial::fact($numObjs) / MathTrig\Factorial::fact($numObjs - $numInSet)); + + return IntOrFloat::evaluate($result); + } + + /** + * PERMUTATIONA. + * + * Returns the number of permutations for a given number of objects (with repetitions) + * that can be selected from the total objects. + * + * @param mixed $numObjs Integer number of different objects + * @param mixed $numInSet Integer number of objects in each permutation + * + * @return float|int|string Number of permutations, or a string containing an error + */ + public static function PERMUTATIONA($numObjs, $numInSet) + { + $numObjs = Functions::flattenSingleValue($numObjs); + $numInSet = Functions::flattenSingleValue($numInSet); + + try { + $numObjs = StatisticalValidations::validateInt($numObjs); + $numInSet = StatisticalValidations::validateInt($numInSet); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($numObjs < 0 || $numInSet < 0) { + return Functions::NAN(); + } + + $result = $numObjs ** $numInSet; + + return IntOrFloat::evaluate($result); + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/Size.php b/src/PhpSpreadsheet/Calculation/Statistical/Size.php new file mode 100644 index 00000000..de4b6d6c --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/Size.php @@ -0,0 +1,96 @@ += $count) || ($count == 0)) { + return Functions::NAN(); + } + rsort($mArgs); + + return $mArgs[$entry]; + } + + return Functions::VALUE(); + } + + /** + * SMALL. + * + * Returns the nth smallest value in a data set. You can use this function to + * select a value based on its relative standing. + * + * Excel Function: + * SMALL(value1[,value2[, ...]],entry) + * + * @param mixed $args Data values + * + * @return float|string The result, or a string containing an error + */ + public static function small(...$args) + { + $aArgs = Functions::flattenArray($args); + + $entry = array_pop($aArgs); + + if ((is_numeric($entry)) && (!is_string($entry))) { + $entry = (int) floor($entry); + + $mArgs = self::filter($aArgs); + $count = Counts::COUNT($mArgs); + --$entry; + if (($entry < 0) || ($entry >= $count) || ($count == 0)) { + return Functions::NAN(); + } + sort($mArgs); + + return $mArgs[$entry]; + } + + return Functions::VALUE(); + } + + /** + * @param mixed[] $args Data values + */ + protected static function filter(array $args): array + { + $mArgs = []; + + foreach ($args as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $mArgs[] = $arg; + } + } + + return $mArgs; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/StandardDeviations.php b/src/PhpSpreadsheet/Calculation/Statistical/StandardDeviations.php new file mode 100644 index 00000000..af271205 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/StandardDeviations.php @@ -0,0 +1,95 @@ +getMessage(); + } + + if ($stdDev <= 0) { + return Functions::NAN(); + } + + return ($value - $mean) / $stdDev; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/StatisticalValidations.php b/src/PhpSpreadsheet/Calculation/Statistical/StatisticalValidations.php new file mode 100644 index 00000000..5b315da4 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/StatisticalValidations.php @@ -0,0 +1,45 @@ + $value) { + if ((is_bool($value)) || (is_string($value)) || ($value === null)) { + unset($array1[$key], $array2[$key]); + } + } + } + + private static function checkTrendArrays(&$array1, &$array2): void + { + if (!is_array($array1)) { + $array1 = [$array1]; + } + if (!is_array($array2)) { + $array2 = [$array2]; + } + + $array1 = Functions::flattenArray($array1); + $array2 = Functions::flattenArray($array2); + + self::filterTrendValues($array1, $array2); + self::filterTrendValues($array2, $array1); + + // Reset the array indexes + $array1 = array_merge($array1); + $array2 = array_merge($array2); + } + + protected static function validateTrendArrays(array $yValues, array $xValues): void + { + $yValueCount = count($yValues); + $xValueCount = count($xValues); + + if (($yValueCount === 0) || ($yValueCount !== $xValueCount)) { + throw new Exception(Functions::NA()); + } elseif ($yValueCount === 1) { + throw new Exception(Functions::DIV0()); + } + } + + /** + * CORREL. + * + * Returns covariance, the average of the products of deviations for each data point pair. + * + * @param mixed $yValues array of mixed Data Series Y + * @param null|mixed $xValues array of mixed Data Series X + * + * @return float|string + */ + public static function CORREL($yValues, $xValues = null) + { + if (($xValues === null) || (!is_array($yValues)) || (!is_array($xValues))) { + return Functions::VALUE(); + } + + try { + self::checkTrendArrays($yValues, $xValues); + self::validateTrendArrays($yValues, $xValues); + } catch (Exception $e) { + return $e->getMessage(); + } + + $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); + + return $bestFitLinear->getCorrelation(); + } + + /** + * COVAR. + * + * Returns covariance, the average of the products of deviations for each data point pair. + * + * @param mixed $yValues array of mixed Data Series Y + * @param mixed $xValues array of mixed Data Series X + * + * @return float|string + */ + public static function COVAR($yValues, $xValues) + { + try { + self::checkTrendArrays($yValues, $xValues); + self::validateTrendArrays($yValues, $xValues); + } catch (Exception $e) { + return $e->getMessage(); + } + + $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); + + return $bestFitLinear->getCovariance(); + } + + /** + * FORECAST. + * + * Calculates, or predicts, a future value by using existing values. + * The predicted value is a y-value for a given x-value. + * + * @param mixed $xValue Float value of X for which we want to find Y + * @param mixed $yValues array of mixed Data Series Y + * @param mixed $xValues of mixed Data Series X + * + * @return bool|float|string + */ + public static function FORECAST($xValue, $yValues, $xValues) + { + $xValue = Functions::flattenSingleValue($xValue); + + try { + $xValue = StatisticalValidations::validateFloat($xValue); + self::checkTrendArrays($yValues, $xValues); + self::validateTrendArrays($yValues, $xValues); + } catch (Exception $e) { + return $e->getMessage(); + } + + $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); + + return $bestFitLinear->getValueOfYForX($xValue); + } + + /** + * GROWTH. + * + * Returns values along a predicted exponential Trend + * + * @param mixed[] $yValues Data Series Y + * @param mixed[] $xValues Data Series X + * @param mixed[] $newValues Values of X for which we want to find Y + * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not + * + * @return float[] + */ + public static function GROWTH($yValues, $xValues = [], $newValues = [], $const = true) + { + $yValues = Functions::flattenArray($yValues); + $xValues = Functions::flattenArray($xValues); + $newValues = Functions::flattenArray($newValues); + $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); + + $bestFitExponential = Trend::calculate(Trend::TREND_EXPONENTIAL, $yValues, $xValues, $const); + if (empty($newValues)) { + $newValues = $bestFitExponential->getXValues(); + } + + $returnArray = []; + foreach ($newValues as $xValue) { + $returnArray[0][] = [$bestFitExponential->getValueOfYForX($xValue)]; + } + + return $returnArray; + } + + /** + * INTERCEPT. + * + * Calculates the point at which a line will intersect the y-axis by using existing x-values and y-values. + * + * @param mixed[] $yValues Data Series Y + * @param mixed[] $xValues Data Series X + * + * @return float|string + */ + public static function INTERCEPT($yValues, $xValues) + { + try { + self::checkTrendArrays($yValues, $xValues); + self::validateTrendArrays($yValues, $xValues); + } catch (Exception $e) { + return $e->getMessage(); + } + + $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); + + return $bestFitLinear->getIntersect(); + } + + /** + * LINEST. + * + * Calculates the statistics for a line by using the "least squares" method to calculate a straight line + * that best fits your data, and then returns an array that describes the line. + * + * @param mixed[] $yValues Data Series Y + * @param null|mixed[] $xValues Data Series X + * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not + * @param mixed $stats A logical (boolean) value specifying whether to return additional regression statistics + * + * @return array|int|string The result, or a string containing an error + */ + public static function LINEST($yValues, $xValues = null, $const = true, $stats = false) + { + $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); + $stats = ($stats === null) ? false : (bool) Functions::flattenSingleValue($stats); + if ($xValues === null) { + $xValues = $yValues; + } + + try { + self::checkTrendArrays($yValues, $xValues); + self::validateTrendArrays($yValues, $xValues); + } catch (Exception $e) { + return $e->getMessage(); + } + + $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues, $const); + + if ($stats === true) { + return [ + [ + $bestFitLinear->getSlope(), + $bestFitLinear->getIntersect(), + ], + [ + $bestFitLinear->getSlopeSE(), + ($const === false) ? Functions::NA() : $bestFitLinear->getIntersectSE(), + ], + [ + $bestFitLinear->getGoodnessOfFit(), + $bestFitLinear->getStdevOfResiduals(), + ], + [ + $bestFitLinear->getF(), + $bestFitLinear->getDFResiduals(), + ], + [ + $bestFitLinear->getSSRegression(), + $bestFitLinear->getSSResiduals(), + ], + ]; + } + + return [ + $bestFitLinear->getSlope(), + $bestFitLinear->getIntersect(), + ]; + } + + /** + * LOGEST. + * + * Calculates an exponential curve that best fits the X and Y data series, + * and then returns an array that describes the line. + * + * @param mixed[] $yValues Data Series Y + * @param null|mixed[] $xValues Data Series X + * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not + * @param mixed $stats A logical (boolean) value specifying whether to return additional regression statistics + * + * @return array|int|string The result, or a string containing an error + */ + public static function LOGEST($yValues, $xValues = null, $const = true, $stats = false) + { + $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); + $stats = ($stats === null) ? false : (bool) Functions::flattenSingleValue($stats); + if ($xValues === null) { + $xValues = $yValues; + } + + try { + self::checkTrendArrays($yValues, $xValues); + self::validateTrendArrays($yValues, $xValues); + } catch (Exception $e) { + return $e->getMessage(); + } + + foreach ($yValues as $value) { + if ($value < 0.0) { + return Functions::NAN(); + } + } + + $bestFitExponential = Trend::calculate(Trend::TREND_EXPONENTIAL, $yValues, $xValues, $const); + + if ($stats === true) { + return [ + [ + $bestFitExponential->getSlope(), + $bestFitExponential->getIntersect(), + ], + [ + $bestFitExponential->getSlopeSE(), + ($const === false) ? Functions::NA() : $bestFitExponential->getIntersectSE(), + ], + [ + $bestFitExponential->getGoodnessOfFit(), + $bestFitExponential->getStdevOfResiduals(), + ], + [ + $bestFitExponential->getF(), + $bestFitExponential->getDFResiduals(), + ], + [ + $bestFitExponential->getSSRegression(), + $bestFitExponential->getSSResiduals(), + ], + ]; + } + + return [ + $bestFitExponential->getSlope(), + $bestFitExponential->getIntersect(), + ]; + } + + /** + * RSQ. + * + * Returns the square of the Pearson product moment correlation coefficient through data points + * in known_y's and known_x's. + * + * @param mixed[] $yValues Data Series Y + * @param mixed[] $xValues Data Series X + * + * @return float|string The result, or a string containing an error + */ + public static function RSQ($yValues, $xValues) + { + try { + self::checkTrendArrays($yValues, $xValues); + self::validateTrendArrays($yValues, $xValues); + } catch (Exception $e) { + return $e->getMessage(); + } + + $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); + + return $bestFitLinear->getGoodnessOfFit(); + } + + /** + * SLOPE. + * + * Returns the slope of the linear regression line through data points in known_y's and known_x's. + * + * @param mixed[] $yValues Data Series Y + * @param mixed[] $xValues Data Series X + * + * @return float|string The result, or a string containing an error + */ + public static function SLOPE($yValues, $xValues) + { + try { + self::checkTrendArrays($yValues, $xValues); + self::validateTrendArrays($yValues, $xValues); + } catch (Exception $e) { + return $e->getMessage(); + } + + $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); + + return $bestFitLinear->getSlope(); + } + + /** + * STEYX. + * + * Returns the standard error of the predicted y-value for each x in the regression. + * + * @param mixed[] $yValues Data Series Y + * @param mixed[] $xValues Data Series X + * + * @return float|string + */ + public static function STEYX($yValues, $xValues) + { + try { + self::checkTrendArrays($yValues, $xValues); + self::validateTrendArrays($yValues, $xValues); + } catch (Exception $e) { + return $e->getMessage(); + } + + $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); + + return $bestFitLinear->getStdevOfResiduals(); + } + + /** + * TREND. + * + * Returns values along a linear Trend + * + * @param mixed[] $yValues Data Series Y + * @param mixed[] $xValues Data Series X + * @param mixed[] $newValues Values of X for which we want to find Y + * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not + * + * @return float[] + */ + public static function TREND($yValues, $xValues = [], $newValues = [], $const = true) + { + $yValues = Functions::flattenArray($yValues); + $xValues = Functions::flattenArray($xValues); + $newValues = Functions::flattenArray($newValues); + $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); + + $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues, $const); + if (empty($newValues)) { + $newValues = $bestFitLinear->getXValues(); + } + + $returnArray = []; + foreach ($newValues as $xValue) { + $returnArray[0][] = [$bestFitLinear->getValueOfYForX($xValue)]; + } + + return $returnArray; + } +} diff --git a/src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php b/src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php new file mode 100644 index 00000000..e5334671 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php @@ -0,0 +1,28 @@ + 1) { + $summerA *= $aCount; + $summerB *= $summerB; + + return ($summerA - $summerB) / ($aCount * ($aCount - 1)); + } + + return $returnValue; + } + + /** + * VARA. + * + * Estimates variance based on a sample, including numbers, text, and logical values + * + * Excel Function: + * VARA(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float|string (string if result is an error) + */ + public static function VARA(...$args) + { + $returnValue = Functions::DIV0(); + + $summerA = $summerB = 0.0; + + // Loop through arguments + $aArgs = Functions::flattenArrayIndexed($args); + $aCount = 0; + foreach ($aArgs as $k => $arg) { + if ((is_string($arg)) && (Functions::isValue($k))) { + return Functions::VALUE(); + } elseif ((is_string($arg)) && (!Functions::isMatrixValue($k))) { + } else { + // Is it a numeric value? + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) { + $arg = self::datatypeAdjustmentAllowStrings($arg); + $summerA += ($arg * $arg); + $summerB += $arg; + ++$aCount; + } + } + } + + if ($aCount > 1) { + $summerA *= $aCount; + $summerB *= $summerB; + + return ($summerA - $summerB) / ($aCount * ($aCount - 1)); + } + + return $returnValue; + } + + /** + * VARP. + * + * Calculates variance based on the entire population + * + * Excel Function: + * VARP(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float|string (string if result is an error) + */ + public static function VARP(...$args) + { + // Return value + $returnValue = Functions::DIV0(); + + $summerA = $summerB = 0.0; + + // Loop through arguments + $aArgs = Functions::flattenArray($args); + $aCount = 0; + foreach ($aArgs as $arg) { + $arg = self::datatypeAdjustmentBooleans($arg); + + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $summerA += ($arg * $arg); + $summerB += $arg; + ++$aCount; + } + } + + if ($aCount > 0) { + $summerA *= $aCount; + $summerB *= $summerB; + + return ($summerA - $summerB) / ($aCount * $aCount); + } + + return $returnValue; + } + + /** + * VARPA. + * + * Calculates variance based on the entire population, including numbers, text, and logical values + * + * Excel Function: + * VARPA(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float|string (string if result is an error) + */ + public static function VARPA(...$args) + { + $returnValue = Functions::DIV0(); + + $summerA = $summerB = 0.0; + + // Loop through arguments + $aArgs = Functions::flattenArrayIndexed($args); + $aCount = 0; + foreach ($aArgs as $k => $arg) { + if ((is_string($arg)) && (Functions::isValue($k))) { + return Functions::VALUE(); + } elseif ((is_string($arg)) && (!Functions::isMatrixValue($k))) { + } else { + // Is it a numeric value? + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) { + $arg = self::datatypeAdjustmentAllowStrings($arg); + $summerA += ($arg * $arg); + $summerB += $arg; + ++$aCount; + } + } + } + + if ($aCount > 0) { + $summerA *= $aCount; + $summerB *= $summerB; + + return ($summerA - $summerB) / ($aCount * $aCount); + } + + return $returnValue; + } +} diff --git a/src/PhpSpreadsheet/Calculation/TextData.php b/src/PhpSpreadsheet/Calculation/TextData.php index f8974402..0bde3b7f 100644 --- a/src/PhpSpreadsheet/Calculation/TextData.php +++ b/src/PhpSpreadsheet/Calculation/TextData.php @@ -3,141 +3,88 @@ namespace PhpOffice\PhpSpreadsheet\Calculation; use DateTimeInterface; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PhpOffice\PhpSpreadsheet\Shared\StringHelper; -use PhpOffice\PhpSpreadsheet\Style\NumberFormat; +/** + * @deprecated 1.18.0 + */ class TextData { - private static $invalidChars; - - private static function unicodeToOrd($character) - { - return unpack('V', iconv('UTF-8', 'UCS-4LE', $character))[1]; - } - /** * CHARACTER. * + * @Deprecated 1.18.0 + * + * @see Use the character() method in the TextData\CharacterConvert class instead + * * @param string $character Value * * @return string */ public static function CHARACTER($character) { - $character = Functions::flattenSingleValue($character); - - if (!is_numeric($character)) { - return Functions::VALUE(); - } - $character = (int) $character; - if ($character < 1 || $character > 255) { - return Functions::VALUE(); - } - - return iconv('UCS-4LE', 'UTF-8', pack('V', $character)); + return TextData\CharacterConvert::character($character); } /** * TRIMNONPRINTABLE. * + * @Deprecated 1.18.0 + * + * @see Use the nonPrintable() method in the TextData\Trim class instead + * * @param mixed $stringValue Value to check * * @return string */ public static function TRIMNONPRINTABLE($stringValue = '') { - $stringValue = Functions::flattenSingleValue($stringValue); - - if (is_bool($stringValue)) { - return ($stringValue) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - if (self::$invalidChars === null) { - self::$invalidChars = range(chr(0), chr(31)); - } - - if (is_string($stringValue) || is_numeric($stringValue)) { - return str_replace(self::$invalidChars, '', trim($stringValue, "\x00..\x1F")); - } - - return null; + return TextData\Trim::nonPrintable($stringValue); } /** * TRIMSPACES. * + * @Deprecated 1.18.0 + * + * @see Use the spaces() method in the TextData\Trim class instead + * * @param mixed $stringValue Value to check * * @return string */ public static function TRIMSPACES($stringValue = '') { - $stringValue = Functions::flattenSingleValue($stringValue); - if (is_bool($stringValue)) { - return ($stringValue) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - if (is_string($stringValue) || is_numeric($stringValue)) { - return trim(preg_replace('/ +/', ' ', trim($stringValue, ' ')), ' '); - } - - return null; - } - - private static function convertBooleanValue($value) - { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - return (int) $value; - } - - return ($value) ? Calculation::getTRUE() : Calculation::getFALSE(); + return TextData\Trim::spaces($stringValue); } /** * ASCIICODE. * + * @Deprecated 1.18.0 + * + * @see Use the code() method in the TextData\CharacterConvert class instead + * * @param string $characters Value * * @return int|string A string if arguments are invalid */ public static function ASCIICODE($characters) { - if (($characters === null) || ($characters === '')) { - return Functions::VALUE(); - } - $characters = Functions::flattenSingleValue($characters); - if (is_bool($characters)) { - $characters = self::convertBooleanValue($characters); - } - - $character = $characters; - if (mb_strlen($characters, 'UTF-8') > 1) { - $character = mb_substr($characters, 0, 1, 'UTF-8'); - } - - return self::unicodeToOrd($character); + return TextData\CharacterConvert::code($characters); } /** * CONCATENATE. * + * @Deprecated 1.18.0 + * + * @see Use the CONCATENATE() method in the TextData\Concatenate class instead + * * @return string */ public static function CONCATENATE(...$args) { - $returnValue = ''; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - foreach ($aArgs as $arg) { - if (is_bool($arg)) { - $arg = self::convertBooleanValue($arg); - } - $returnValue .= $arg; - } - - return $returnValue; + return TextData\Concatenate::CONCATENATE(...$args); } /** @@ -146,6 +93,10 @@ class TextData * This function converts a number to text using currency format, with the decimals rounded to the specified place. * The format used is $#,##0.00_);($#,##0.00).. * + * @Deprecated 1.18.0 + * + * @see Use the DOLLAR() method in the TextData\Format class instead + * * @param float $value The value to format * @param int $decimals The number of digits to display to the right of the decimal point. * If decimals is negative, number is rounded to the left of the decimal point. @@ -155,33 +106,16 @@ class TextData */ public static function DOLLAR($value = 0, $decimals = 2) { - $value = Functions::flattenSingleValue($value); - $decimals = $decimals === null ? 0 : Functions::flattenSingleValue($decimals); - - // Validate parameters - if (!is_numeric($value) || !is_numeric($decimals)) { - return Functions::VALUE(); - } - $decimals = floor($decimals); - - $mask = '$#,##0'; - if ($decimals > 0) { - $mask .= '.' . str_repeat('0', $decimals); - } else { - $round = 10 ** abs($decimals); - if ($value < 0) { - $round = 0 - $round; - } - $value = MathTrig::MROUND($value, $round); - } - $mask = "$mask;($mask)"; - - return NumberFormat::toFormattedString($value, $mask); + return TextData\Format::DOLLAR($value, $decimals); } /** * SEARCHSENSITIVE. * + * @Deprecated 1.18.0 + * + * @see Use the sensitive() method in the TextData\Search class instead + * * @param string $needle The string to look for * @param string $haystack The string in which to look * @param int $offset Offset within $haystack @@ -190,33 +124,16 @@ class TextData */ public static function SEARCHSENSITIVE($needle, $haystack, $offset = 1) { - $needle = Functions::flattenSingleValue($needle); - $haystack = Functions::flattenSingleValue($haystack); - $offset = Functions::flattenSingleValue($offset); - - if (!is_bool($needle)) { - if (is_bool($haystack)) { - $haystack = ($haystack) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - if (($offset > 0) && (StringHelper::countCharacters($haystack) > $offset)) { - if (StringHelper::countCharacters($needle) === 0) { - return $offset; - } - - $pos = mb_strpos($haystack, $needle, --$offset, 'UTF-8'); - if ($pos !== false) { - return ++$pos; - } - } - } - - return Functions::VALUE(); + return TextData\Search::sensitive($needle, $haystack, $offset); } /** * SEARCHINSENSITIVE. * + * @Deprecated 1.18.0 + * + * @see Use the insensitive() method in the TextData\Search class instead + * * @param string $needle The string to look for * @param string $haystack The string in which to look * @param int $offset Offset within $haystack @@ -225,33 +142,16 @@ class TextData */ public static function SEARCHINSENSITIVE($needle, $haystack, $offset = 1) { - $needle = Functions::flattenSingleValue($needle); - $haystack = Functions::flattenSingleValue($haystack); - $offset = Functions::flattenSingleValue($offset); - - if (!is_bool($needle)) { - if (is_bool($haystack)) { - $haystack = ($haystack) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - if (($offset > 0) && (StringHelper::countCharacters($haystack) > $offset)) { - if (StringHelper::countCharacters($needle) === 0) { - return $offset; - } - - $pos = mb_stripos($haystack, $needle, --$offset, 'UTF-8'); - if ($pos !== false) { - return ++$pos; - } - } - } - - return Functions::VALUE(); + return TextData\Search::insensitive($needle, $haystack, $offset); } /** * FIXEDFORMAT. * + * @Deprecated 1.18.0 + * + * @see Use the FIXEDFORMAT() method in the TextData\Format class instead + * * @param mixed $value Value to check * @param int $decimals * @param bool $no_commas @@ -260,35 +160,16 @@ class TextData */ public static function FIXEDFORMAT($value, $decimals = 2, $no_commas = false) { - $value = Functions::flattenSingleValue($value); - $decimals = Functions::flattenSingleValue($decimals); - $no_commas = Functions::flattenSingleValue($no_commas); - - // Validate parameters - if (!is_numeric($value) || !is_numeric($decimals)) { - return Functions::VALUE(); - } - $decimals = (int) floor($decimals); - - $valueResult = round($value, $decimals); - if ($decimals < 0) { - $decimals = 0; - } - if (!$no_commas) { - $valueResult = number_format( - $valueResult, - $decimals, - StringHelper::getDecimalSeparator(), - StringHelper::getThousandsSeparator() - ); - } - - return (string) $valueResult; + return TextData\Format::FIXEDFORMAT($value, $decimals, $no_commas); } /** * LEFT. * + * @Deprecated 1.18.0 + * + * @see Use the left() method in the TextData\Extract class instead + * * @param string $value Value * @param int $chars Number of characters * @@ -296,23 +177,16 @@ class TextData */ public static function LEFT($value = '', $chars = 1) { - $value = Functions::flattenSingleValue($value); - $chars = Functions::flattenSingleValue($chars); - - if ($chars < 0) { - return Functions::VALUE(); - } - - if (is_bool($value)) { - $value = ($value) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - return mb_substr($value, 0, $chars, 'UTF-8'); + return TextData\Extract::left($value, $chars); } /** * MID. * + * @Deprecated 1.18.0 + * + * @see Use the mid() method in the TextData\Extract class instead + * * @param string $value Value * @param int $start Start character * @param int $chars Number of characters @@ -321,28 +195,16 @@ class TextData */ public static function MID($value = '', $start = 1, $chars = null) { - $value = Functions::flattenSingleValue($value); - $start = Functions::flattenSingleValue($start); - $chars = Functions::flattenSingleValue($chars); - - if (($start < 1) || ($chars < 0)) { - return Functions::VALUE(); - } - - if (is_bool($value)) { - $value = ($value) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - if (empty($chars)) { - return ''; - } - - return mb_substr($value, --$start, $chars, 'UTF-8'); + return TextData\Extract::mid($value, $start, $chars); } /** * RIGHT. * + * @Deprecated 1.18.0 + * + * @see Use the right() method in the TextData\Extract class instead + * * @param string $value Value * @param int $chars Number of characters * @@ -350,36 +212,23 @@ class TextData */ public static function RIGHT($value = '', $chars = 1) { - $value = Functions::flattenSingleValue($value); - $chars = Functions::flattenSingleValue($chars); - - if ($chars < 0) { - return Functions::VALUE(); - } - - if (is_bool($value)) { - $value = ($value) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - return mb_substr($value, mb_strlen($value, 'UTF-8') - $chars, $chars, 'UTF-8'); + return TextData\Extract::right($value, $chars); } /** * STRINGLENGTH. * + * @Deprecated 1.18.0 + * + * @see Use the length() method in the TextData\Text class instead + * * @param string $value Value * * @return int */ public static function STRINGLENGTH($value = '') { - $value = Functions::flattenSingleValue($value); - - if (is_bool($value)) { - $value = ($value) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - return mb_strlen($value, 'UTF-8'); + return TextData\Text::length($value); } /** @@ -387,19 +236,17 @@ class TextData * * Converts a string value to upper case. * + * @Deprecated 1.18.0 + * + * @see Use the lower() method in the TextData\CaseConvert class instead + * * @param string $mixedCaseString * * @return string */ public static function LOWERCASE($mixedCaseString) { - $mixedCaseString = Functions::flattenSingleValue($mixedCaseString); - - if (is_bool($mixedCaseString)) { - $mixedCaseString = ($mixedCaseString) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - return StringHelper::strToLower($mixedCaseString); + return TextData\CaseConvert::lower($mixedCaseString); } /** @@ -407,19 +254,17 @@ class TextData * * Converts a string value to upper case. * + * @Deprecated 1.18.0 + * + * @see Use the upper() method in the TextData\CaseConvert class instead + * * @param string $mixedCaseString * * @return string */ public static function UPPERCASE($mixedCaseString) { - $mixedCaseString = Functions::flattenSingleValue($mixedCaseString); - - if (is_bool($mixedCaseString)) { - $mixedCaseString = ($mixedCaseString) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - return StringHelper::strToUpper($mixedCaseString); + return TextData\CaseConvert::upper($mixedCaseString); } /** @@ -427,24 +272,26 @@ class TextData * * Converts a string value to upper case. * + * @Deprecated 1.18.0 + * + * @see Use the proper() method in the TextData\CaseConvert class instead + * * @param string $mixedCaseString * * @return string */ public static function PROPERCASE($mixedCaseString) { - $mixedCaseString = Functions::flattenSingleValue($mixedCaseString); - - if (is_bool($mixedCaseString)) { - $mixedCaseString = ($mixedCaseString) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - return StringHelper::strToTitle($mixedCaseString); + return TextData\CaseConvert::proper($mixedCaseString); } /** * REPLACE. * + * @Deprecated 1.18.0 + * + * @see Use the replace() method in the TextData\Replace class instead + * * @param string $oldText String to modify * @param int $start Start character * @param int $chars Number of characters @@ -454,20 +301,16 @@ class TextData */ public static function REPLACE($oldText, $start, $chars, $newText) { - $oldText = Functions::flattenSingleValue($oldText); - $start = Functions::flattenSingleValue($start); - $chars = Functions::flattenSingleValue($chars); - $newText = Functions::flattenSingleValue($newText); - - $left = self::LEFT($oldText, $start - 1); - $right = self::RIGHT($oldText, self::STRINGLENGTH($oldText) - ($start + $chars) + 1); - - return $left . $newText . $right; + return TextData\Replace::replace($oldText, $start, $chars, $newText); } /** * SUBSTITUTE. * + * @Deprecated 1.18.0 + * + * @see Use the substitute() method in the TextData\Replace class instead + * * @param string $text Value * @param string $fromText From Value * @param string $toText To Value @@ -477,52 +320,32 @@ class TextData */ public static function SUBSTITUTE($text = '', $fromText = '', $toText = '', $instance = 0) { - $text = Functions::flattenSingleValue($text); - $fromText = Functions::flattenSingleValue($fromText); - $toText = Functions::flattenSingleValue($toText); - $instance = floor(Functions::flattenSingleValue($instance)); - - if ($instance == 0) { - return str_replace($fromText, $toText, $text); - } - - $pos = -1; - while ($instance > 0) { - $pos = mb_strpos($text, $fromText, $pos + 1, 'UTF-8'); - if ($pos === false) { - break; - } - --$instance; - } - - if ($pos !== false) { - return self::REPLACE($text, ++$pos, mb_strlen($fromText, 'UTF-8'), $toText); - } - - return $text; + return TextData\Replace::substitute($text, $fromText, $toText, $instance); } /** * RETURNSTRING. * + * @Deprecated 1.18.0 + * + * @see Use the test() method in the TextData\Text class instead + * * @param mixed $testValue Value to check * * @return null|string */ public static function RETURNSTRING($testValue = '') { - $testValue = Functions::flattenSingleValue($testValue); - - if (is_string($testValue)) { - return $testValue; - } - - return null; + return TextData\Text::test($testValue); } /** * TEXTFORMAT. * + * @Deprecated 1.18.0 + * + * @see Use the TEXTFORMAT() method in the TextData\Format class instead + * * @param mixed $value Value to check * @param string $format Format mask to use * @@ -530,65 +353,32 @@ class TextData */ public static function TEXTFORMAT($value, $format) { - $value = Functions::flattenSingleValue($value); - $format = Functions::flattenSingleValue($format); - - if ((is_string($value)) && (!is_numeric($value)) && Date::isDateTimeFormatCode($format)) { - $value = DateTime::DATEVALUE($value); - } - - return (string) NumberFormat::toFormattedString($value, $format); + return TextData\Format::TEXTFORMAT($value, $format); } /** * VALUE. * + * @Deprecated 1.18.0 + * + * @see Use the VALUE() method in the TextData\Format class instead + * * @param mixed $value Value to check * * @return DateTimeInterface|float|int|string A string if arguments are invalid */ public static function VALUE($value = '') { - $value = Functions::flattenSingleValue($value); - - if (!is_numeric($value)) { - $numberValue = str_replace( - StringHelper::getThousandsSeparator(), - '', - trim($value, " \t\n\r\0\x0B" . StringHelper::getCurrencyCode()) - ); - if (is_numeric($numberValue)) { - return (float) $numberValue; - } - - $dateSetting = Functions::getReturnDateType(); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - - if (strpos($value, ':') !== false) { - $timeValue = DateTime::TIMEVALUE($value); - if ($timeValue !== Functions::VALUE()) { - Functions::setReturnDateType($dateSetting); - - return $timeValue; - } - } - $dateValue = DateTime::DATEVALUE($value); - if ($dateValue !== Functions::VALUE()) { - Functions::setReturnDateType($dateSetting); - - return $dateValue; - } - Functions::setReturnDateType($dateSetting); - - return Functions::VALUE(); - } - - return (float) $value; + return TextData\Format::VALUE($value); } /** * NUMBERVALUE. * + * @Deprecated 1.18.0 + * + * @see Use the NUMBERVALUE() method in the TextData\Format class instead + * * @param mixed $value Value to check * @param string $decimalSeparator decimal separator, defaults to locale defined value * @param string $groupSeparator group/thosands separator, defaults to locale defined value @@ -597,39 +387,7 @@ class TextData */ public static function NUMBERVALUE($value = '', $decimalSeparator = null, $groupSeparator = null) { - $value = Functions::flattenSingleValue($value); - $decimalSeparator = Functions::flattenSingleValue($decimalSeparator); - $groupSeparator = Functions::flattenSingleValue($groupSeparator); - - if (!is_numeric($value)) { - $decimalSeparator = empty($decimalSeparator) ? StringHelper::getDecimalSeparator() : $decimalSeparator; - $groupSeparator = empty($groupSeparator) ? StringHelper::getThousandsSeparator() : $groupSeparator; - - $decimalPositions = preg_match_all('/' . preg_quote($decimalSeparator) . '/', $value, $matches, PREG_OFFSET_CAPTURE); - if ($decimalPositions > 1) { - return Functions::VALUE(); - } - $decimalOffset = array_pop($matches[0])[1]; - if (strpos($value, $groupSeparator, $decimalOffset) !== false) { - return Functions::VALUE(); - } - - $value = str_replace([$groupSeparator, $decimalSeparator], ['', '.'], $value); - - // Handle the special case of trailing % signs - $percentageString = rtrim($value, '%'); - if (!is_numeric($percentageString)) { - return Functions::VALUE(); - } - - $percentageAdjustment = strlen($value) - strlen($percentageString); - if ($percentageAdjustment) { - $value = (float) $percentageString; - $value /= 10 ** ($percentageAdjustment * 2); - } - } - - return (float) $value; + return TextData\Format::NUMBERVALUE($value, $decimalSeparator, $groupSeparator); } /** @@ -637,22 +395,27 @@ class TextData * EXACT is case-sensitive but ignores formatting differences. * Use EXACT to test text being entered into a document. * - * @param $value1 - * @param $value2 + * @Deprecated 1.18.0 + * + * @see Use the exact() method in the TextData\Text class instead + * + * @param mixed $value1 + * @param mixed $value2 * * @return bool */ public static function EXACT($value1, $value2) { - $value1 = Functions::flattenSingleValue($value1); - $value2 = Functions::flattenSingleValue($value2); - - return (string) $value2 === (string) $value1; + return TextData\Text::exact($value1, $value2); } /** * TEXTJOIN. * + * @Deprecated 1.18.0 + * + * @see Use the TEXTJOIN() method in the TextData\Concatenate class instead + * * @param mixed $delimiter * @param mixed $ignoreEmpty * @param mixed $args @@ -661,16 +424,25 @@ class TextData */ public static function TEXTJOIN($delimiter, $ignoreEmpty, ...$args) { - // Loop through arguments - $aArgs = Functions::flattenArray($args); - foreach ($aArgs as $key => &$arg) { - if ($ignoreEmpty && trim($arg) == '') { - unset($aArgs[$key]); - } elseif (is_bool($arg)) { - $arg = self::convertBooleanValue($arg); - } - } + return TextData\Concatenate::TEXTJOIN($delimiter, $ignoreEmpty, ...$args); + } - return implode($delimiter, $aArgs); + /** + * REPT. + * + * Returns the result of builtin function repeat after validating args. + * + * @Deprecated 1.18.0 + * + * @see Use the builtinREPT() method in the TextData\Concatenate class instead + * + * @param string $str Should be numeric + * @param mixed $number Should be int + * + * @return string + */ + public static function builtinREPT($str, $number) + { + return TextData\Concatenate::builtinREPT($str, $number); } } diff --git a/src/PhpSpreadsheet/Calculation/TextData/CaseConvert.php b/src/PhpSpreadsheet/Calculation/TextData/CaseConvert.php new file mode 100644 index 00000000..664cc2d8 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/TextData/CaseConvert.php @@ -0,0 +1,54 @@ + 255) { + return Functions::VALUE(); + } + $result = iconv('UCS-4LE', 'UTF-8', pack('V', $character)); + + return ($result === false) ? '' : $result; + } + + /** + * CODE. + * + * @param mixed $characters String character to convert to its ASCII value + * + * @return int|string A string if arguments are invalid + */ + public static function code($characters) + { + $characters = Helpers::extractString($characters); + if ($characters === '') { + return Functions::VALUE(); + } + + $character = $characters; + if (mb_strlen($characters, 'UTF-8') > 1) { + $character = mb_substr($characters, 0, 1, 'UTF-8'); + } + + return self::unicodeToOrd($character); + } + + private static function unicodeToOrd(string $character): int + { + $retVal = 0; + $iconv = iconv('UTF-8', 'UCS-4LE', $character); + if ($iconv !== false) { + $result = unpack('V', $iconv); + if (is_array($result) && isset($result[1])) { + $retVal = $result[1]; + } + } + + return $retVal; + } +} diff --git a/src/PhpSpreadsheet/Calculation/TextData/Concatenate.php b/src/PhpSpreadsheet/Calculation/TextData/Concatenate.php new file mode 100644 index 00000000..d53fc822 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/TextData/Concatenate.php @@ -0,0 +1,71 @@ + &$arg) { + if ($ignoreEmpty === true && is_string($arg) && trim($arg) === '') { + unset($aArgs[$key]); + } elseif (is_bool($arg)) { + $arg = Helpers::convertBooleanValue($arg); + } + } + + return implode($delimiter, $aArgs); + } + + /** + * REPT. + * + * Returns the result of builtin function round after validating args. + * + * @param mixed $stringValue The value to repeat + * @param mixed $repeatCount The number of times the string value should be repeated + */ + public static function builtinREPT($stringValue, $repeatCount): string + { + $repeatCount = Functions::flattenSingleValue($repeatCount); + $stringValue = Helpers::extractString($stringValue); + + if (!is_numeric($repeatCount) || $repeatCount < 0) { + return Functions::VALUE(); + } + + return str_repeat($stringValue, (int) $repeatCount); + } +} diff --git a/src/PhpSpreadsheet/Calculation/TextData/Extract.php b/src/PhpSpreadsheet/Calculation/TextData/Extract.php new file mode 100644 index 00000000..7f18e0c6 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/TextData/Extract.php @@ -0,0 +1,64 @@ +getMessage(); + } + + return mb_substr($value ?? '', 0, $chars, 'UTF-8'); + } + + /** + * MID. + * + * @param mixed $value String value from which to extract characters + * @param mixed $start Integer offset of the first character that we want to extract + * @param mixed $chars The number of characters to extract (as an integer) + */ + public static function mid($value, $start, $chars): string + { + try { + $value = Helpers::extractString($value); + $start = Helpers::extractInt($start, 1); + $chars = Helpers::extractInt($chars, 0); + } catch (CalcExp $e) { + return $e->getMessage(); + } + + return mb_substr($value ?? '', --$start, $chars, 'UTF-8'); + } + + /** + * RIGHT. + * + * @param mixed $value String value from which to extract characters + * @param mixed $chars The number of characters to extract (as an integer) + */ + public static function right($value, $chars = 1): string + { + try { + $value = Helpers::extractString($value); + $chars = Helpers::extractInt($chars, 0, 1); + } catch (CalcExp $e) { + return $e->getMessage(); + } + + return mb_substr($value ?? '', mb_strlen($value ?? '', 'UTF-8') - $chars, $chars, 'UTF-8'); + } +} diff --git a/src/PhpSpreadsheet/Calculation/TextData/Format.php b/src/PhpSpreadsheet/Calculation/TextData/Format.php new file mode 100644 index 00000000..3286de0c --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/TextData/Format.php @@ -0,0 +1,236 @@ +getMessage(); + } + + $mask = '$#,##0'; + if ($decimals > 0) { + $mask .= '.' . str_repeat('0', $decimals); + } else { + $round = 10 ** abs($decimals); + if ($value < 0) { + $round = 0 - $round; + } + $value = MathTrig\Round::multiple($value, $round); + } + $mask = "{$mask};-{$mask}"; + + return NumberFormat::toFormattedString($value, $mask); + } + + /** + * FIXED. + * + * @param mixed $value The value to format + * @param mixed $decimals Integer value for the number of decimal places that should be formatted + * @param mixed $noCommas Boolean value indicating whether the value should have thousands separators or not + */ + public static function FIXEDFORMAT($value, $decimals = 2, $noCommas = false): string + { + try { + $value = Helpers::extractFloat($value); + $decimals = Helpers::extractInt($decimals, -100, 0, true); + $noCommas = Functions::flattenSingleValue($noCommas); + } catch (CalcExp $e) { + return $e->getMessage(); + } + + $valueResult = round($value, $decimals); + if ($decimals < 0) { + $decimals = 0; + } + if ($noCommas === false) { + $valueResult = number_format( + $valueResult, + $decimals, + StringHelper::getDecimalSeparator(), + StringHelper::getThousandsSeparator() + ); + } + + return (string) $valueResult; + } + + /** + * TEXT. + * + * @param mixed $value The value to format + * @param mixed $format A string with the Format mask that should be used + */ + public static function TEXTFORMAT($value, $format): string + { + $value = Helpers::extractString($value); + $format = Helpers::extractString($format); + + if (!is_numeric($value) && Date::isDateTimeFormatCode($format)) { + $value = DateTimeExcel\DateValue::fromString($value); + } + + return (string) NumberFormat::toFormattedString($value, $format); + } + + /** + * @param mixed $value Value to check + * + * @return mixed + */ + private static function convertValue($value) + { + $value = ($value === null) ? 0 : Functions::flattenSingleValue($value); + if (is_bool($value)) { + if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { + $value = (int) $value; + } else { + throw new CalcExp(Functions::VALUE()); + } + } + + return $value; + } + + /** + * VALUE. + * + * @param mixed $value Value to check + * + * @return DateTimeInterface|float|int|string A string if arguments are invalid + */ + public static function VALUE($value = '') + { + try { + $value = self::convertValue($value); + } catch (CalcExp $e) { + return $e->getMessage(); + } + if (!is_numeric($value)) { + $numberValue = str_replace( + StringHelper::getThousandsSeparator(), + '', + trim($value, " \t\n\r\0\x0B" . StringHelper::getCurrencyCode()) + ); + if (is_numeric($numberValue)) { + return (float) $numberValue; + } + + $dateSetting = Functions::getReturnDateType(); + Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); + + if (strpos($value, ':') !== false) { + $timeValue = DateTimeExcel\TimeValue::fromString($value); + if ($timeValue !== Functions::VALUE()) { + Functions::setReturnDateType($dateSetting); + + return $timeValue; + } + } + $dateValue = DateTimeExcel\DateValue::fromString($value); + if ($dateValue !== Functions::VALUE()) { + Functions::setReturnDateType($dateSetting); + + return $dateValue; + } + Functions::setReturnDateType($dateSetting); + + return Functions::VALUE(); + } + + return (float) $value; + } + + /** + * @param mixed $decimalSeparator + */ + private static function getDecimalSeparator($decimalSeparator): string + { + $decimalSeparator = Functions::flattenSingleValue($decimalSeparator); + + return empty($decimalSeparator) ? StringHelper::getDecimalSeparator() : (string) $decimalSeparator; + } + + /** + * @param mixed $groupSeparator + */ + private static function getGroupSeparator($groupSeparator): string + { + $groupSeparator = Functions::flattenSingleValue($groupSeparator); + + return empty($groupSeparator) ? StringHelper::getThousandsSeparator() : (string) $groupSeparator; + } + + /** + * NUMBERVALUE. + * + * @param mixed $value The value to format + * @param mixed $decimalSeparator A string with the decimal separator to use, defaults to locale defined value + * @param mixed $groupSeparator A string with the group/thousands separator to use, defaults to locale defined value + * + * @return float|string + */ + public static function NUMBERVALUE($value = '', $decimalSeparator = null, $groupSeparator = null) + { + try { + $value = self::convertValue($value); + $decimalSeparator = self::getDecimalSeparator($decimalSeparator); + $groupSeparator = self::getGroupSeparator($groupSeparator); + } catch (CalcExp $e) { + return $e->getMessage(); + } + + if (!is_numeric($value)) { + $decimalPositions = preg_match_all('/' . preg_quote($decimalSeparator) . '/', $value, $matches, PREG_OFFSET_CAPTURE); + if ($decimalPositions > 1) { + return Functions::VALUE(); + } + $decimalOffset = array_pop($matches[0])[1]; + if (strpos($value, $groupSeparator, $decimalOffset) !== false) { + return Functions::VALUE(); + } + + $value = str_replace([$groupSeparator, $decimalSeparator], ['', '.'], $value); + + // Handle the special case of trailing % signs + $percentageString = rtrim($value, '%'); + if (!is_numeric($percentageString)) { + return Functions::VALUE(); + } + + $percentageAdjustment = strlen($value) - strlen($percentageString); + if ($percentageAdjustment) { + $value = (float) $percentageString; + $value /= 10 ** ($percentageAdjustment * 2); + } + } + + return is_array($value) ? Functions::VALUE() : (float) $value; + } +} diff --git a/src/PhpSpreadsheet/Calculation/TextData/Helpers.php b/src/PhpSpreadsheet/Calculation/TextData/Helpers.php new file mode 100644 index 00000000..423b6d3f --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/TextData/Helpers.php @@ -0,0 +1,90 @@ +getMessage(); + } + + return $left . $newText . $right; + } + + /** + * SUBSTITUTE. + * + * @param mixed $text The text string value to modify + * @param mixed $fromText The string value that we want to replace in $text + * @param mixed $toText The string value that we want to replace with in $text + * @param mixed $instance Integer instance Number for the occurrence of frmText to change + */ + public static function substitute($text = '', $fromText = '', $toText = '', $instance = null): string + { + try { + $text = Helpers::extractString($text); + $fromText = Helpers::extractString($fromText); + $toText = Helpers::extractString($toText); + $instance = Functions::flattenSingleValue($instance); + if ($instance === null) { + return str_replace($fromText, $toText, $text); + } + if (is_bool($instance)) { + if ($instance === false || Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_OPENOFFICE) { + return Functions::Value(); + } + $instance = 1; + } + $instance = Helpers::extractInt($instance, 1, 0, true); + } catch (CalcExp $e) { + return $e->getMessage(); + } + + $pos = -1; + while ($instance > 0) { + $pos = mb_strpos($text, $fromText, $pos + 1, 'UTF-8'); + if ($pos === false) { + break; + } + --$instance; + } + + if ($pos !== false) { + return self::REPLACE($text, ++$pos, mb_strlen($fromText, 'UTF-8'), $toText); + } + + return $text; + } +} diff --git a/src/PhpSpreadsheet/Calculation/TextData/Search.php b/src/PhpSpreadsheet/Calculation/TextData/Search.php new file mode 100644 index 00000000..c9eed2e5 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/TextData/Search.php @@ -0,0 +1,76 @@ +getMessage(); + } + + if (StringHelper::countCharacters($haystack) >= $offset) { + if (StringHelper::countCharacters($needle) === 0) { + return $offset; + } + + $pos = mb_strpos($haystack, $needle, --$offset, 'UTF-8'); + if ($pos !== false) { + return ++$pos; + } + } + + return Functions::VALUE(); + } + + /** + * SEARCH (case insensitive search). + * + * @param mixed $needle The string to look for + * @param mixed $haystack The string in which to look + * @param mixed $offset Integer offset within $haystack to start searching from + * + * @return int|string + */ + public static function insensitive($needle, $haystack, $offset = 1) + { + try { + $needle = Helpers::extractString($needle); + $haystack = Helpers::extractString($haystack); + $offset = Helpers::extractInt($offset, 1, 0, true); + } catch (CalcExp $e) { + return $e->getMessage(); + } + + if (StringHelper::countCharacters($haystack) >= $offset) { + if (StringHelper::countCharacters($needle) === 0) { + return $offset; + } + + $pos = mb_stripos($haystack, $needle, --$offset, 'UTF-8'); + if ($pos !== false) { + return ++$pos; + } + } + + return Functions::VALUE(); + } +} diff --git a/src/PhpSpreadsheet/Calculation/TextData/Text.php b/src/PhpSpreadsheet/Calculation/TextData/Text.php new file mode 100644 index 00000000..6f8253ea --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/TextData/Text.php @@ -0,0 +1,54 @@ + 2048) { - return Functions::VALUE(); // Invalid URL length - } - - if (!preg_match('/^http[s]?:\/\//', $url)) { - return Functions::VALUE(); // Invalid protocol - } - - // Get results from the the webservice - $client = Settings::getHttpClient(); - $requestFactory = Settings::getRequestFactory(); - $request = $requestFactory->createRequest('GET', $url); - - try { - $response = $client->sendRequest($request); - } catch (ClientExceptionInterface $e) { - return Functions::VALUE(); // cURL error - } - - if ($response->getStatusCode() != 200) { - return Functions::VALUE(); // cURL error - } - - $output = $response->getBody()->getContents(); - if (strlen($output) > 32767) { - return Functions::VALUE(); // Output not a string or too long - } - - return $output; + return Web\Service::webService($url); } } diff --git a/src/PhpSpreadsheet/Calculation/Web/Service.php b/src/PhpSpreadsheet/Calculation/Web/Service.php new file mode 100644 index 00000000..05e04bf9 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/Web/Service.php @@ -0,0 +1,75 @@ + 2048) { + return Functions::VALUE(); // Invalid URL length + } + + if (!preg_match('/^http[s]?:\/\//', $url)) { + return Functions::VALUE(); // Invalid protocol + } + + // Get results from the the webservice + $client = Settings::getHttpClient(); + $requestFactory = Settings::getRequestFactory(); + $request = $requestFactory->createRequest('GET', $url); + + try { + $response = $client->sendRequest($request); + } catch (ClientExceptionInterface $e) { + return Functions::VALUE(); // cURL error + } + + if ($response->getStatusCode() != 200) { + return Functions::VALUE(); // cURL error + } + + $output = $response->getBody()->getContents(); + if (strlen($output) > 32767) { + return Functions::VALUE(); // Output not a string or too long + } + + return $output; + } + + /** + * URLENCODE. + * + * Returns data from a web service on the Internet or Intranet. + * + * Excel Function: + * urlEncode(text) + * + * @param mixed $text + * + * @return string the url encoded output + */ + public static function urlEncode($text) + { + if (!is_string($text)) { + return Functions::VALUE(); + } + + return str_replace('+', '%20', urlencode($text)); + } +} diff --git a/src/PhpSpreadsheet/Calculation/functionlist.txt b/src/PhpSpreadsheet/Calculation/functionlist.txt index e71d18f4..270715cd 100644 --- a/src/PhpSpreadsheet/Calculation/functionlist.txt +++ b/src/PhpSpreadsheet/Calculation/functionlist.txt @@ -40,6 +40,8 @@ BITOR BITRSHIFT BITXOR CEILING +CEILING.MATH +CEILING.PRECISE CELL CHAR CHIDIST @@ -51,6 +53,7 @@ CODE COLUMN COLUMNS COMBIN +COMBINA COMPLEX CONCAT CONCATENATE @@ -247,6 +250,7 @@ MODE MONTH MROUND MULTINOMIAL +MUNIT N NA NEGBINOMDIST @@ -276,6 +280,7 @@ PEARSON PERCENTILE PERCENTRANK PERMUT +PERMUTATIONA PHONETIC PI PMT diff --git a/src/PhpSpreadsheet/Calculation/locale/Translations.xlsx b/src/PhpSpreadsheet/Calculation/locale/Translations.xlsx new file mode 100644 index 00000000..518176ab Binary files /dev/null and b/src/PhpSpreadsheet/Calculation/locale/Translations.xlsx differ diff --git a/src/PhpSpreadsheet/Calculation/locale/cs/config b/src/PhpSpreadsheet/Calculation/locale/cs/config index df513734..49f40fcb 100644 --- a/src/PhpSpreadsheet/Calculation/locale/cs/config +++ b/src/PhpSpreadsheet/Calculation/locale/cs/config @@ -1,23 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## +## Ceština (Czech) +## +############################################################ -ArgumentSeparator = ; - +ArgumentSeparator = ; ## -## (For future use) +## Error Codes ## -currencySymbol = Kč - - -## -## Excel Error Codes (For future use) -## -NULL = #NULL! -DIV0 = #DIV/0! -VALUE = #HODNOTA! -REF = #REF! -NAME = #NÁZEV? -NUM = #NUM! -NA = #N/A +NULL +DIV0 = #DĚLENÍ_NULOU! +VALUE = #HODNOTA! +REF = #ODKAZ! +NAME = #NÁZEV? +NUM = #ČÍSLO! +NA = #NENÍ_K_DISPOZICI diff --git a/src/PhpSpreadsheet/Calculation/locale/cs/functions b/src/PhpSpreadsheet/Calculation/locale/cs/functions index 733d406f..49c4945c 100644 --- a/src/PhpSpreadsheet/Calculation/locale/cs/functions +++ b/src/PhpSpreadsheet/Calculation/locale/cs/functions @@ -1,416 +1,520 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Ceština (Czech) ## +############################################################ ## -## Add-in and Automation functions Funkce doplňků a automatizace +## Funkce pro práci s datovými krychlemi (Cube Functions) ## -GETPIVOTDATA = ZÍSKATKONTDATA ## Vrátí data uložená v kontingenční tabulce. Pomocí funkce ZÍSKATKONTDATA můžete načíst souhrnná data z kontingenční tabulky, pokud jsou tato data v kontingenční sestavě zobrazena. - +CUBEKPIMEMBER = CUBEKPIMEMBER +CUBEMEMBER = CUBEMEMBER +CUBEMEMBERPROPERTY = CUBEMEMBERPROPERTY +CUBERANKEDMEMBER = CUBERANKEDMEMBER +CUBESET = CUBESET +CUBESETCOUNT = CUBESETCOUNT +CUBEVALUE = CUBEVALUE ## -## Cube functions Funkce pro práci s krychlemi +## Funkce databáze (Database Functions) ## -CUBEKPIMEMBER = CUBEKPIMEMBER ## Vrátí název, vlastnost a velikost klíčového ukazatele výkonu (KUV) a zobrazí v buňce název a vlastnost. Klíčový ukazatel výkonu je kvantifikovatelná veličina, například hrubý měsíční zisk nebo čtvrtletní obrat na zaměstnance, která se používá pro sledování výkonnosti organizace. -CUBEMEMBER = CUBEMEMBER ## Vrátí člen nebo n-tici v hierarchii krychle. Slouží k ověření, zda v krychli existuje člen nebo n-tice. -CUBEMEMBERPROPERTY = CUBEMEMBERPROPERTY ## Vrátí hodnotu vlastnosti člena v krychli. Slouží k ověření, zda v krychli existuje člen s daným názvem, a k vrácení konkrétní vlastnosti tohoto člena. -CUBERANKEDMEMBER = CUBERANKEDMEMBER ## Vrátí n-tý nebo pořadový člen sady. Použijte ji pro vrácení jednoho nebo více prvků sady, například obchodníka s nejvyšším obratem nebo deseti nejlepších studentů. -CUBESET = CUBESET ## Definuje vypočtenou sadu členů nebo n-tic odesláním výrazu sady do krychle na serveru, který vytvoří sadu a potom ji vrátí do aplikace Microsoft Office Excel. -CUBESETCOUNT = CUBESETCOUNT ## Vrátí počet položek v množině -CUBEVALUE = CUBEVALUE ## Vrátí úhrnnou hodnotu z krychle. - +DAVERAGE = DPRŮMĚR +DCOUNT = DPOČET +DCOUNTA = DPOČET2 +DGET = DZÍSKAT +DMAX = DMAX +DMIN = DMIN +DPRODUCT = DSOUČIN +DSTDEV = DSMODCH.VÝBĚR +DSTDEVP = DSMODCH +DSUM = DSUMA +DVAR = DVAR.VÝBĚR +DVARP = DVAR ## -## Database functions Funkce databáze +## Funkce data a času (Date & Time Functions) ## -DAVERAGE = DPRŮMĚR ## Vrátí průměr vybraných položek databáze. -DCOUNT = DPOČET ## Spočítá buňky databáze obsahující čísla. -DCOUNTA = DPOČET2 ## Spočítá buňky databáze, které nejsou prázdné. -DGET = DZÍSKAT ## Extrahuje z databáze jeden záznam splňující zadaná kritéria. -DMAX = DMAX ## Vrátí maximální hodnotu z vybraných položek databáze. -DMIN = DMIN ## Vrátí minimální hodnotu z vybraných položek databáze. -DPRODUCT = DSOUČIN ## Vynásobí hodnoty určitého pole záznamů v databázi, které splňují daná kritéria. -DSTDEV = DSMODCH.VÝBĚR ## Odhadne směrodatnou odchylku výběru vybraných položek databáze. -DSTDEVP = DSMODCH ## Vypočte směrodatnou odchylku základního souboru vybraných položek databáze. -DSUM = DSUMA ## Sečte čísla ve sloupcovém poli záznamů databáze, která splňují daná kritéria. -DVAR = DVAR.VÝBĚR ## Odhadne rozptyl výběru vybraných položek databáze. -DVARP = DVAR ## Vypočte rozptyl základního souboru vybraných položek databáze. - +DATE = DATUM +DATEVALUE = DATUMHODN +DAY = DEN +DAYS = DAYS +DAYS360 = ROK360 +EDATE = EDATE +EOMONTH = EOMONTH +HOUR = HODINA +ISOWEEKNUM = ISOWEEKNUM +MINUTE = MINUTA +MONTH = MĚSÍC +NETWORKDAYS = NETWORKDAYS +NETWORKDAYS.INTL = NETWORKDAYS.INTL +NOW = NYNÍ +SECOND = SEKUNDA +TIME = ČAS +TIMEVALUE = ČASHODN +TODAY = DNES +WEEKDAY = DENTÝDNE +WEEKNUM = WEEKNUM +WORKDAY = WORKDAY +WORKDAY.INTL = WORKDAY.INTL +YEAR = ROK +YEARFRAC = YEARFRAC ## -## Date and time functions Funkce data a času +## Inženýrské funkce (Engineering Functions) ## -DATE = DATUM ## Vrátí pořadové číslo určitého data. -DATEVALUE = DATUMHODN ## Převede datum ve formě textu na pořadové číslo. -DAY = DEN ## Převede pořadové číslo na den v měsíci. -DAYS360 = ROK360 ## Vrátí počet dní mezi dvěma daty na základě roku s 360 dny. -EDATE = EDATE ## Vrátí pořadové číslo data, které označuje určený počet měsíců před nebo po počátečním datu. -EOMONTH = EOMONTH ## Vrátí pořadové číslo posledního dne měsíce před nebo po zadaném počtu měsíců. -HOUR = HODINA ## Převede pořadové číslo na hodinu. -MINUTE = MINUTA ## Převede pořadové číslo na minutu. -MONTH = MĚSÍC ## Převede pořadové číslo na měsíc. -NETWORKDAYS = NETWORKDAYS ## Vrátí počet celých pracovních dní mezi dvěma daty. -NOW = NYNÍ ## Vrátí pořadové číslo aktuálního data a času. -SECOND = SEKUNDA ## Převede pořadové číslo na sekundu. -TIME = ČAS ## Vrátí pořadové číslo určitého času. -TIMEVALUE = ČASHODN ## Převede čas ve formě textu na pořadové číslo. -TODAY = DNES ## Vrátí pořadové číslo dnešního data. -WEEKDAY = DENTÝDNE ## Převede pořadové číslo na den v týdnu. -WEEKNUM = WEEKNUM ## Převede pořadové číslo na číslo představující číselnou pozici týdne v roce. -WORKDAY = WORKDAY ## Vrátí pořadové číslo data před nebo po zadaném počtu pracovních dní. -YEAR = ROK ## Převede pořadové číslo na rok. -YEARFRAC = YEARFRAC ## Vrátí část roku vyjádřenou zlomkem a představující počet celých dní mezi počátečním a koncovým datem. - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BIN2DEC +BIN2HEX = BIN2HEX +BIN2OCT = BIN2OCT +BITAND = BITAND +BITLSHIFT = BITLSHIFT +BITOR = BITOR +BITRSHIFT = BITRSHIFT +BITXOR = BITXOR +COMPLEX = COMPLEX +CONVERT = CONVERT +DEC2BIN = DEC2BIN +DEC2HEX = DEC2HEX +DEC2OCT = DEC2OCT +DELTA = DELTA +ERF = ERF +ERF.PRECISE = ERF.PRECISE +ERFC = ERFC +ERFC.PRECISE = ERFC.PRECISE +GESTEP = GESTEP +HEX2BIN = HEX2BIN +HEX2DEC = HEX2DEC +HEX2OCT = HEX2OCT +IMABS = IMABS +IMAGINARY = IMAGINARY +IMARGUMENT = IMARGUMENT +IMCONJUGATE = IMCONJUGATE +IMCOS = IMCOS +IMCOSH = IMCOSH +IMCOT = IMCOT +IMCSC = IMCSC +IMCSCH = IMCSCH +IMDIV = IMDIV +IMEXP = IMEXP +IMLN = IMLN +IMLOG10 = IMLOG10 +IMLOG2 = IMLOG2 +IMPOWER = IMPOWER +IMPRODUCT = IMPRODUCT +IMREAL = IMREAL +IMSEC = IMSEC +IMSECH = IMSECH +IMSIN = IMSIN +IMSINH = IMSINH +IMSQRT = IMSQRT +IMSUB = IMSUB +IMSUM = IMSUM +IMTAN = IMTAN +OCT2BIN = OCT2BIN +OCT2DEC = OCT2DEC +OCT2HEX = OCT2HEX ## -## Engineering functions Inženýrské funkce (Technické funkce) +## Finanční funkce (Financial Functions) ## -BESSELI = BESSELI ## Vrátí modifikovanou Besselovu funkci In(x). -BESSELJ = BESSELJ ## Vrátí modifikovanou Besselovu funkci Jn(x). -BESSELK = BESSELK ## Vrátí modifikovanou Besselovu funkci Kn(x). -BESSELY = BESSELY ## Vrátí Besselovu funkci Yn(x). -BIN2DEC = BIN2DEC ## Převede binární číslo na desítkové. -BIN2HEX = BIN2HEX ## Převede binární číslo na šestnáctkové. -BIN2OCT = BIN2OCT ## Převede binární číslo na osmičkové. -COMPLEX = COMPLEX ## Převede reálnou a imaginární část na komplexní číslo. -CONVERT = CONVERT ## Převede číslo do jiného jednotkového měrného systému. -DEC2BIN = DEC2BIN ## Převede desítkového čísla na dvojkové -DEC2HEX = DEC2HEX ## Převede desítkové číslo na šestnáctkové. -DEC2OCT = DEC2OCT ## Převede desítkové číslo na osmičkové. -DELTA = DELTA ## Testuje rovnost dvou hodnot. -ERF = ERF ## Vrátí chybovou funkci. -ERFC = ERFC ## Vrátí doplňkovou chybovou funkci. -GESTEP = GESTEP ## Testuje, zda je číslo větší než mezní hodnota. -HEX2BIN = HEX2BIN ## Převede šestnáctkové číslo na binární. -HEX2DEC = HEX2DEC ## Převede šestnáctkové číslo na desítkové. -HEX2OCT = HEX2OCT ## Převede šestnáctkové číslo na osmičkové. -IMABS = IMABS ## Vrátí absolutní hodnotu (modul) komplexního čísla. -IMAGINARY = IMAGINARY ## Vrátí imaginární část komplexního čísla. -IMARGUMENT = IMARGUMENT ## Vrátí argument théta, úhel vyjádřený v radiánech. -IMCONJUGATE = IMCONJUGATE ## Vrátí komplexně sdružené číslo ke komplexnímu číslu. -IMCOS = IMCOS ## Vrátí kosinus komplexního čísla. -IMDIV = IMDIV ## Vrátí podíl dvou komplexních čísel. -IMEXP = IMEXP ## Vrátí exponenciální tvar komplexního čísla. -IMLN = IMLN ## Vrátí přirozený logaritmus komplexního čísla. -IMLOG10 = IMLOG10 ## Vrátí dekadický logaritmus komplexního čísla. -IMLOG2 = IMLOG2 ## Vrátí logaritmus komplexního čísla při základu 2. -IMPOWER = IMPOWER ## Vrátí komplexní číslo umocněné na celé číslo. -IMPRODUCT = IMPRODUCT ## Vrátí součin komplexních čísel. -IMREAL = IMREAL ## Vrátí reálnou část komplexního čísla. -IMSIN = IMSIN ## Vrátí sinus komplexního čísla. -IMSQRT = IMSQRT ## Vrátí druhou odmocninu komplexního čísla. -IMSUB = IMSUB ## Vrátí rozdíl mezi dvěma komplexními čísly. -IMSUM = IMSUM ## Vrátí součet dvou komplexních čísel. -OCT2BIN = OCT2BIN ## Převede osmičkové číslo na binární. -OCT2DEC = OCT2DEC ## Převede osmičkové číslo na desítkové. -OCT2HEX = OCT2HEX ## Převede osmičkové číslo na šestnáctkové. - +ACCRINT = ACCRINT +ACCRINTM = ACCRINTM +AMORDEGRC = AMORDEGRC +AMORLINC = AMORLINC +COUPDAYBS = COUPDAYBS +COUPDAYS = COUPDAYS +COUPDAYSNC = COUPDAYSNC +COUPNCD = COUPNCD +COUPNUM = COUPNUM +COUPPCD = COUPPCD +CUMIPMT = CUMIPMT +CUMPRINC = CUMPRINC +DB = ODPIS.ZRYCH +DDB = ODPIS.ZRYCH2 +DISC = DISC +DOLLARDE = DOLLARDE +DOLLARFR = DOLLARFR +DURATION = DURATION +EFFECT = EFFECT +FV = BUDHODNOTA +FVSCHEDULE = FVSCHEDULE +INTRATE = INTRATE +IPMT = PLATBA.ÚROK +IRR = MÍRA.VÝNOSNOSTI +ISPMT = ISPMT +MDURATION = MDURATION +MIRR = MOD.MÍRA.VÝNOSNOSTI +NOMINAL = NOMINAL +NPER = POČET.OBDOBÍ +NPV = ČISTÁ.SOUČHODNOTA +ODDFPRICE = ODDFPRICE +ODDFYIELD = ODDFYIELD +ODDLPRICE = ODDLPRICE +ODDLYIELD = ODDLYIELD +PDURATION = PDURATION +PMT = PLATBA +PPMT = PLATBA.ZÁKLAD +PRICE = PRICE +PRICEDISC = PRICEDISC +PRICEMAT = PRICEMAT +PV = SOUČHODNOTA +RATE = ÚROKOVÁ.MÍRA +RECEIVED = RECEIVED +RRI = RRI +SLN = ODPIS.LIN +SYD = ODPIS.NELIN +TBILLEQ = TBILLEQ +TBILLPRICE = TBILLPRICE +TBILLYIELD = TBILLYIELD +VDB = ODPIS.ZA.INT +XIRR = XIRR +XNPV = XNPV +YIELD = YIELD +YIELDDISC = YIELDDISC +YIELDMAT = YIELDMAT ## -## Financial functions Finanční funkce +## Informační funkce (Information Functions) ## -ACCRINT = ACCRINT ## Vrátí nahromaděný úrok z cenného papíru, ze kterého je úrok placen v pravidelných termínech. -ACCRINTM = ACCRINTM ## Vrátí nahromaděný úrok z cenného papíru, ze kterého je úrok placen k datu splatnosti. -AMORDEGRC = AMORDEGRC ## Vrátí lineární amortizaci v každém účetním období pomocí koeficientu amortizace. -AMORLINC = AMORLINC ## Vrátí lineární amortizaci v každém účetním období. -COUPDAYBS = COUPDAYBS ## Vrátí počet dnů od začátku období placení kupónů do data splatnosti. -COUPDAYS = COUPDAYS ## Vrátí počet dnů v období placení kupónů, které obsahuje den zúčtování. -COUPDAYSNC = COUPDAYSNC ## Vrátí počet dnů od data zúčtování do následujícího data placení kupónu. -COUPNCD = COUPNCD ## Vrátí následující datum placení kupónu po datu zúčtování. -COUPNUM = COUPNUM ## Vrátí počet kupónů splatných mezi datem zúčtování a datem splatnosti. -COUPPCD = COUPPCD ## Vrátí předchozí datum placení kupónu před datem zúčtování. -CUMIPMT = CUMIPMT ## Vrátí kumulativní úrok splacený mezi dvěma obdobími. -CUMPRINC = CUMPRINC ## Vrátí kumulativní jistinu splacenou mezi dvěma obdobími půjčky. -DB = ODPIS.ZRYCH ## Vrátí odpis aktiva za určité období pomocí degresivní metody odpisu s pevným zůstatkem. -DDB = ODPIS.ZRYCH2 ## Vrátí odpis aktiva za určité období pomocí dvojité degresivní metody odpisu nebo jiné metody, kterou zadáte. -DISC = DISC ## Vrátí diskontní sazbu cenného papíru. -DOLLARDE = DOLLARDE ## Převede částku v korunách vyjádřenou zlomkem na částku v korunách vyjádřenou desetinným číslem. -DOLLARFR = DOLLARFR ## Převede částku v korunách vyjádřenou desetinným číslem na částku v korunách vyjádřenou zlomkem. -DURATION = DURATION ## Vrátí roční dobu cenného papíru s pravidelnými úrokovými sazbami. -EFFECT = EFFECT ## Vrátí efektivní roční úrokovou sazbu. -FV = BUDHODNOTA ## Vrátí budoucí hodnotu investice. -FVSCHEDULE = FVSCHEDULE ## Vrátí budoucí hodnotu počáteční jistiny po použití série sazeb složitého úroku. -INTRATE = INTRATE ## Vrátí úrokovou sazbu plně investovaného cenného papíru. -IPMT = PLATBA.ÚROK ## Vrátí výšku úroku investice za dané období. -IRR = MÍRA.VÝNOSNOSTI ## Vrátí vnitřní výnosové procento série peněžních toků. -ISPMT = ISPMT ## Vypočte výši úroku z investice zaplaceného během určitého období. -MDURATION = MDURATION ## Vrátí Macauleyho modifikovanou dobu cenného papíru o nominální hodnotě 100 Kč. -MIRR = MOD.MÍRA.VÝNOSNOSTI ## Vrátí vnitřní sazbu výnosu, přičemž kladné a záporné hodnoty peněžních prostředků jsou financovány podle různých sazeb. -NOMINAL = NOMINAL ## Vrátí nominální roční úrokovou sazbu. -NPER = POČET.OBDOBÍ ## Vrátí počet období pro investici. -NPV = ČISTÁ.SOUČHODNOTA ## Vrátí čistou současnou hodnotu investice vypočítanou na základě série pravidelných peněžních toků a diskontní sazby. -ODDFPRICE = ODDFPRICE ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč s odlišným prvním obdobím. -ODDFYIELD = ODDFYIELD ## Vrátí výnos cenného papíru s odlišným prvním obdobím. -ODDLPRICE = ODDLPRICE ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč s odlišným posledním obdobím. -ODDLYIELD = ODDLYIELD ## Vrátí výnos cenného papíru s odlišným posledním obdobím. -PMT = PLATBA ## Vrátí hodnotu pravidelné splátky anuity. -PPMT = PLATBA.ZÁKLAD ## Vrátí hodnotu splátky jistiny pro zadanou investici za dané období. -PRICE = PRICE ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč, ze kterého je úrok placen v pravidelných termínech. -PRICEDISC = PRICEDISC ## Vrátí cenu diskontního cenného papíru o nominální hodnotě 100 Kč. -PRICEMAT = PRICEMAT ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč, ze kterého je úrok placen k datu splatnosti. -PV = SOUČHODNOTA ## Vrátí současnou hodnotu investice. -RATE = ÚROKOVÁ.MÍRA ## Vrátí úrokovou sazbu vztaženou na období anuity. -RECEIVED = RECEIVED ## Vrátí částku obdrženou k datu splatnosti plně investovaného cenného papíru. -SLN = ODPIS.LIN ## Vrátí přímé odpisy aktiva pro jedno období. -SYD = ODPIS.NELIN ## Vrátí směrné číslo ročních odpisů aktiva pro zadané období. -TBILLEQ = TBILLEQ ## Vrátí výnos směnky státní pokladny ekvivalentní výnosu obligace. -TBILLPRICE = TBILLPRICE ## Vrátí cenu směnky státní pokladny o nominální hodnotě 100 Kč. -TBILLYIELD = TBILLYIELD ## Vrátí výnos směnky státní pokladny. -VDB = ODPIS.ZA.INT ## Vrátí odpis aktiva pro určité období nebo část období pomocí degresivní metody odpisu. -XIRR = XIRR ## Vrátí vnitřní výnosnost pro harmonogram peněžních toků, který nemusí být nutně periodický. -XNPV = XNPV ## Vrátí čistou současnou hodnotu pro harmonogram peněžních toků, který nemusí být nutně periodický. -YIELD = YIELD ## Vrátí výnos cenného papíru, ze kterého je úrok placen v pravidelných termínech. -YIELDDISC = YIELDDISC ## Vrátí roční výnos diskontního cenného papíru, například směnky státní pokladny. -YIELDMAT = YIELDMAT ## Vrátí roční výnos cenného papíru, ze kterého je úrok placen k datu splatnosti. - +CELL = POLÍČKO +ERROR.TYPE = CHYBA.TYP +INFO = O.PROSTŘEDÍ +ISBLANK = JE.PRÁZDNÉ +ISERR = JE.CHYBA +ISERROR = JE.CHYBHODN +ISEVEN = ISEVEN +ISFORMULA = ISFORMULA +ISLOGICAL = JE.LOGHODN +ISNA = JE.NEDEF +ISNONTEXT = JE.NETEXT +ISNUMBER = JE.ČISLO +ISODD = ISODD +ISREF = JE.ODKAZ +ISTEXT = JE.TEXT +N = N +NA = NEDEF +SHEET = SHEET +SHEETS = SHEETS +TYPE = TYP ## -## Information functions Informační funkce +## Logické funkce (Logical Functions) ## -CELL = POLÍČKO ## Vrátí informace o formátování, umístění nebo obsahu buňky. -ERROR.TYPE = CHYBA.TYP ## Vrátí číslo odpovídající typu chyby. -INFO = O.PROSTŘEDÍ ## Vrátí informace o aktuálním pracovním prostředí. -ISBLANK = JE.PRÁZDNÉ ## Vrátí hodnotu PRAVDA, pokud se argument hodnota odkazuje na prázdnou buňku. -ISERR = JE.CHYBA ## Vrátí hodnotu PRAVDA, pokud je argument hodnota libovolná chybová hodnota (kromě #N/A). -ISERROR = JE.CHYBHODN ## Vrátí hodnotu PRAVDA, pokud je argument hodnota libovolná chybová hodnota. -ISEVEN = ISEVEN ## Vrátí hodnotu PRAVDA, pokud je číslo sudé. -ISLOGICAL = JE.LOGHODN ## Vrátí hodnotu PRAVDA, pokud je argument hodnota logická hodnota. -ISNA = JE.NEDEF ## Vrátí hodnotu PRAVDA, pokud je argument hodnota chybová hodnota #N/A. -ISNONTEXT = JE.NETEXT ## Vrátí hodnotu PRAVDA, pokud argument hodnota není text. -ISNUMBER = JE.ČÍSLO ## Vrátí hodnotu PRAVDA, pokud je argument hodnota číslo. -ISODD = ISODD ## Vrátí hodnotu PRAVDA, pokud je číslo liché. -ISREF = JE.ODKAZ ## Vrátí hodnotu PRAVDA, pokud je argument hodnota odkaz. -ISTEXT = JE.TEXT ## Vrátí hodnotu PRAVDA, pokud je argument hodnota text. -N = N ## Vrátí hodnotu převedenou na číslo. -NA = NEDEF ## Vrátí chybovou hodnotu #N/A. -TYPE = TYP ## Vrátí číslo označující datový typ hodnoty. - +AND = A +FALSE = NEPRAVDA +IF = KDYŽ +IFERROR = IFERROR +IFNA = IFNA +IFS = IFS +NOT = NE +OR = NEBO +SWITCH = SWITCH +TRUE = PRAVDA +XOR = XOR ## -## Logical functions Logické funkce +## Vyhledávací funkce a funkce pro odkazy (Lookup & Reference Functions) ## -AND = A ## Vrátí hodnotu PRAVDA, mají-li všechny argumenty hodnotu PRAVDA. -FALSE = NEPRAVDA ## Vrátí logickou hodnotu NEPRAVDA. -IF = KDYŽ ## Určí, který logický test má proběhnout. -IFERROR = IFERROR ## Pokud je vzorec vyhodnocen jako chyba, vrátí zadanou hodnotu. V opačném případě vrátí výsledek vzorce. -NOT = NE ## Provede logickou negaci argumentu funkce. -OR = NEBO ## Vrátí hodnotu PRAVDA, je-li alespoň jeden argument roven hodnotě PRAVDA. -TRUE = PRAVDA ## Vrátí logickou hodnotu PRAVDA. - +ADDRESS = ODKAZ +AREAS = POČET.BLOKŮ +CHOOSE = ZVOLIT +COLUMN = SLOUPEC +COLUMNS = SLOUPCE +FORMULATEXT = FORMULATEXT +GETPIVOTDATA = ZÍSKATKONTDATA +HLOOKUP = VVYHLEDAT +HYPERLINK = HYPERTEXTOVÝ.ODKAZ +INDEX = INDEX +INDIRECT = NEPŘÍMÝ.ODKAZ +LOOKUP = VYHLEDAT +MATCH = POZVYHLEDAT +OFFSET = POSUN +ROW = ŘÁDEK +ROWS = ŘÁDKY +RTD = RTD +TRANSPOSE = TRANSPOZICE +VLOOKUP = SVYHLEDAT ## -## Lookup and reference functions Vyhledávací funkce +## Matematické a trigonometrické funkce (Math & Trig Functions) ## -ADDRESS = ODKAZ ## Vrátí textový odkaz na jednu buňku listu. -AREAS = POČET.BLOKŮ ## Vrátí počet oblastí v odkazu. -CHOOSE = ZVOLIT ## Zvolí hodnotu ze seznamu hodnot. -COLUMN = SLOUPEC ## Vrátí číslo sloupce odkazu. -COLUMNS = SLOUPCE ## Vrátí počet sloupců v odkazu. -HLOOKUP = VVYHLEDAT ## Prohledá horní řádek matice a vrátí hodnotu určené buňky. -HYPERLINK = HYPERTEXTOVÝ.ODKAZ ## Vytvoří zástupce nebo odkaz, který otevře dokument uložený na síťovém serveru, v síti intranet nebo Internet. -INDEX = INDEX ## Pomocí rejstříku zvolí hodnotu z odkazu nebo matice. -INDIRECT = NEPŘÍMÝ.ODKAZ ## Vrátí odkaz určený textovou hodnotou. -LOOKUP = VYHLEDAT ## Vyhledá hodnoty ve vektoru nebo matici. -MATCH = POZVYHLEDAT ## Vyhledá hodnoty v odkazu nebo matici. -OFFSET = POSUN ## Vrátí posun odkazu od zadaného odkazu. -ROW = ŘÁDEK ## Vrátí číslo řádku odkazu. -ROWS = ŘÁDKY ## Vrátí počet řádků v odkazu. -RTD = RTD ## Načte data reálného času z programu, který podporuje automatizaci modelu COM (Automatizace: Způsob práce s objekty určité aplikace z jiné aplikace nebo nástroje pro vývoj. Automatizace (dříve nazývaná automatizace OLE) je počítačovým standardem a je funkcí modelu COM (Component Object Model).). -TRANSPOSE = TRANSPOZICE ## Vrátí transponovanou matici. -VLOOKUP = SVYHLEDAT ## Prohledá první sloupec matice, přesune kurzor v řádku a vrátí hodnotu buňky. - +ABS = ABS +ACOS = ARCCOS +ACOSH = ARCCOSH +ACOT = ACOT +ACOTH = ACOTH +AGGREGATE = AGGREGATE +ARABIC = ARABIC +ASIN = ARCSIN +ASINH = ARCSINH +ATAN = ARCTG +ATAN2 = ARCTG2 +ATANH = ARCTGH +BASE = BASE +CEILING.MATH = CEILING.MATH +COMBIN = KOMBINACE +COMBINA = COMBINA +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = DECIMAL +DEGREES = DEGREES +EVEN = ZAOKROUHLIT.NA.SUDÉ +EXP = EXP +FACT = FAKTORIÁL +FACTDOUBLE = FACTDOUBLE +FLOOR.MATH = FLOOR.MATH +GCD = GCD +INT = CELÁ.ČÁST +LCM = LCM +LN = LN +LOG = LOGZ +LOG10 = LOG +MDETERM = DETERMINANT +MINVERSE = INVERZE +MMULT = SOUČIN.MATIC +MOD = MOD +MROUND = MROUND +MULTINOMIAL = MULTINOMIAL +MUNIT = MUNIT +ODD = ZAOKROUHLIT.NA.LICHÉ +PI = PI +POWER = POWER +PRODUCT = SOUČIN +QUOTIENT = QUOTIENT +RADIANS = RADIANS +RAND = NÁHČÍSLO +RANDBETWEEN = RANDBETWEEN +ROMAN = ROMAN +ROUND = ZAOKROUHLIT +ROUNDDOWN = ROUNDDOWN +ROUNDUP = ROUNDUP +SEC = SEC +SECH = SECH +SERIESSUM = SERIESSUM +SIGN = SIGN +SIN = SIN +SINH = SINH +SQRT = ODMOCNINA +SQRTPI = SQRTPI +SUBTOTAL = SUBTOTAL +SUM = SUMA +SUMIF = SUMIF +SUMIFS = SUMIFS +SUMPRODUCT = SOUČIN.SKALÁRNÍ +SUMSQ = SUMA.ČTVERCŮ +SUMX2MY2 = SUMX2MY2 +SUMX2PY2 = SUMX2PY2 +SUMXMY2 = SUMXMY2 +TAN = TG +TANH = TGH +TRUNC = USEKNOUT ## -## Math and trigonometry functions Matematické a trigonometrické funkce +## Statistické funkce (Statistical Functions) ## -ABS = ABS ## Vrátí absolutní hodnotu čísla. -ACOS = ARCCOS ## Vrátí arkuskosinus čísla. -ACOSH = ARCCOSH ## Vrátí hyperbolický arkuskosinus čísla. -ASIN = ARCSIN ## Vrátí arkussinus čísla. -ASINH = ARCSINH ## Vrátí hyperbolický arkussinus čísla. -ATAN = ARCTG ## Vrátí arkustangens čísla. -ATAN2 = ARCTG2 ## Vrátí arkustangens x-ové a y-ové souřadnice. -ATANH = ARCTGH ## Vrátí hyperbolický arkustangens čísla. -CEILING = ZAOKR.NAHORU ## Zaokrouhlí číslo na nejbližší celé číslo nebo na nejbližší násobek zadané hodnoty. -COMBIN = KOMBINACE ## Vrátí počet kombinací pro daný počet položek. -COS = COS ## Vrátí kosinus čísla. -COSH = COSH ## Vrátí hyperbolický kosinus čísla. -DEGREES = DEGREES ## Převede radiány na stupně. -EVEN = ZAOKROUHLIT.NA.SUDÉ ## Zaokrouhlí číslo nahoru na nejbližší celé sudé číslo. -EXP = EXP ## Vrátí základ přirozeného logaritmu e umocněný na zadané číslo. -FACT = FAKTORIÁL ## Vrátí faktoriál čísla. -FACTDOUBLE = FACTDOUBLE ## Vrátí dvojitý faktoriál čísla. -FLOOR = ZAOKR.DOLŮ ## Zaokrouhlí číslo dolů, směrem k nule. -GCD = GCD ## Vrátí největší společný dělitel. -INT = CELÁ.ČÁST ## Zaokrouhlí číslo dolů na nejbližší celé číslo. -LCM = LCM ## Vrátí nejmenší společný násobek. -LN = LN ## Vrátí přirozený logaritmus čísla. -LOG = LOGZ ## Vrátí logaritmus čísla při zadaném základu. -LOG10 = LOG ## Vrátí dekadický logaritmus čísla. -MDETERM = DETERMINANT ## Vrátí determinant matice. -MINVERSE = INVERZE ## Vrátí inverzní matici. -MMULT = SOUČIN.MATIC ## Vrátí součin dvou matic. -MOD = MOD ## Vrátí zbytek po dělení. -MROUND = MROUND ## Vrátí číslo zaokrouhlené na požadovaný násobek. -MULTINOMIAL = MULTINOMIAL ## Vrátí mnohočlen z množiny čísel. -ODD = ZAOKROUHLIT.NA.LICHÉ ## Zaokrouhlí číslo nahoru na nejbližší celé liché číslo. -PI = PI ## Vrátí hodnotu čísla pí. -POWER = POWER ## Umocní číslo na zadanou mocninu. -PRODUCT = SOUČIN ## Vynásobí argumenty funkce. -QUOTIENT = QUOTIENT ## Vrátí celou část dělení. -RADIANS = RADIANS ## Převede stupně na radiány. -RAND = NÁHČÍSLO ## Vrátí náhodné číslo mezi 0 a 1. -RANDBETWEEN = RANDBETWEEN ## Vrátí náhodné číslo mezi zadanými čísly. -ROMAN = ROMAN ## Převede arabskou číslici na římskou ve formátu textu. -ROUND = ZAOKROUHLIT ## Zaokrouhlí číslo na zadaný počet číslic. -ROUNDDOWN = ROUNDDOWN ## Zaokrouhlí číslo dolů, směrem k nule. -ROUNDUP = ROUNDUP ## Zaokrouhlí číslo nahoru, směrem od nuly. -SERIESSUM = SERIESSUM ## Vrátí součet mocninné řady určené podle vzorce. -SIGN = SIGN ## Vrátí znaménko čísla. -SIN = SIN ## Vrátí sinus daného úhlu. -SINH = SINH ## Vrátí hyperbolický sinus čísla. -SQRT = ODMOCNINA ## Vrátí kladnou druhou odmocninu. -SQRTPI = SQRTPI ## Vrátí druhou odmocninu výrazu (číslo * pí). -SUBTOTAL = SUBTOTAL ## Vrátí souhrn v seznamu nebo databázi. -SUM = SUMA ## Sečte argumenty funkce. -SUMIF = SUMIF ## Sečte buňky vybrané podle zadaných kritérií. -SUMIFS = SUMIFS ## Sečte buňky určené více zadanými podmínkami. -SUMPRODUCT = SOUČIN.SKALÁRNÍ ## Vrátí součet součinů odpovídajících prvků matic. -SUMSQ = SUMA.ČTVERCŮ ## Vrátí součet čtverců argumentů. -SUMX2MY2 = SUMX2MY2 ## Vrátí součet rozdílu čtverců odpovídajících hodnot ve dvou maticích. -SUMX2PY2 = SUMX2PY2 ## Vrátí součet součtu čtverců odpovídajících hodnot ve dvou maticích. -SUMXMY2 = SUMXMY2 ## Vrátí součet čtverců rozdílů odpovídajících hodnot ve dvou maticích. -TAN = TGTG ## Vrátí tangens čísla. -TANH = TGH ## Vrátí hyperbolický tangens čísla. -TRUNC = USEKNOUT ## Zkrátí číslo na celé číslo. - +AVEDEV = PRŮMODCHYLKA +AVERAGE = PRŮMĚR +AVERAGEA = AVERAGEA +AVERAGEIF = AVERAGEIF +AVERAGEIFS = AVERAGEIFS +BETA.DIST = BETA.DIST +BETA.INV = BETA.INV +BINOM.DIST = BINOM.DIST +BINOM.DIST.RANGE = BINOM.DIST.RANGE +BINOM.INV = BINOM.INV +CHISQ.DIST = CHISQ.DIST +CHISQ.DIST.RT = CHISQ.DIST.RT +CHISQ.INV = CHISQ.INV +CHISQ.INV.RT = CHISQ.INV.RT +CHISQ.TEST = CHISQ.TEST +CONFIDENCE.NORM = CONFIDENCE.NORM +CONFIDENCE.T = CONFIDENCE.T +CORREL = CORREL +COUNT = POČET +COUNTA = POČET2 +COUNTBLANK = COUNTBLANK +COUNTIF = COUNTIF +COUNTIFS = COUNTIFS +COVARIANCE.P = COVARIANCE.P +COVARIANCE.S = COVARIANCE.S +DEVSQ = DEVSQ +EXPON.DIST = EXPON.DIST +F.DIST = F.DIST +F.DIST.RT = F.DIST.RT +F.INV = F.INV +F.INV.RT = F.INV.RT +F.TEST = F.TEST +FISHER = FISHER +FISHERINV = FISHERINV +FORECAST.ETS = FORECAST.ETS +FORECAST.ETS.CONFINT = FORECAST.ETS.CONFINT +FORECAST.ETS.SEASONALITY = FORECAST.ETS.SEASONALITY +FORECAST.ETS.STAT = FORECAST.ETS.STAT +FORECAST.LINEAR = FORECAST.LINEAR +FREQUENCY = ČETNOSTI +GAMMA = GAMMA +GAMMA.DIST = GAMMA.DIST +GAMMA.INV = GAMMA.INV +GAMMALN = GAMMALN +GAMMALN.PRECISE = GAMMALN.PRECISE +GAUSS = GAUSS +GEOMEAN = GEOMEAN +GROWTH = LOGLINTREND +HARMEAN = HARMEAN +HYPGEOM.DIST = HYPGEOM.DIST +INTERCEPT = INTERCEPT +KURT = KURT +LARGE = LARGE +LINEST = LINREGRESE +LOGEST = LOGLINREGRESE +LOGNORM.DIST = LOGNORM.DIST +LOGNORM.INV = LOGNORM.INV +MAX = MAX +MAXA = MAXA +MAXIFS = MAXIFS +MEDIAN = MEDIAN +MIN = MIN +MINA = MINA +MINIFS = MINIFS +MODE.MULT = MODE.MULT +MODE.SNGL = MODE.SNGL +NEGBINOM.DIST = NEGBINOM.DIST +NORM.DIST = NORM.DIST +NORM.INV = NORM.INV +NORM.S.DIST = NORM.S.DIST +NORM.S.INV = NORM.S.INV +PEARSON = PEARSON +PERCENTILE.EXC = PERCENTIL.EXC +PERCENTILE.INC = PERCENTIL.INC +PERCENTRANK.EXC = PERCENTRANK.EXC +PERCENTRANK.INC = PERCENTRANK.INC +PERMUT = PERMUTACE +PERMUTATIONA = PERMUTATIONA +PHI = PHI +POISSON.DIST = POISSON.DIST +PROB = PROB +QUARTILE.EXC = QUARTIL.EXC +QUARTILE.INC = QUARTIL.INC +RANK.AVG = RANK.AVG +RANK.EQ = RANK.EQ +RSQ = RKQ +SKEW = SKEW +SKEW.P = SKEW.P +SLOPE = SLOPE +SMALL = SMALL +STANDARDIZE = STANDARDIZE +STDEV.P = SMODCH.P +STDEV.S = SMODCH.VÝBĚR.S +STDEVA = STDEVA +STDEVPA = STDEVPA +STEYX = STEYX +T.DIST = T.DIST +T.DIST.2T = T.DIST.2T +T.DIST.RT = T.DIST.RT +T.INV = T.INV +T.INV.2T = T.INV.2T +T.TEST = T.TEST +TREND = LINTREND +TRIMMEAN = TRIMMEAN +VAR.P = VAR.P +VAR.S = VAR.S +VARA = VARA +VARPA = VARPA +WEIBULL.DIST = WEIBULL.DIST +Z.TEST = Z.TEST ## -## Statistical functions Statistické funkce +## Textové funkce (Text Functions) ## -AVEDEV = PRŮMODCHYLKA ## Vrátí průměrnou hodnotu absolutních odchylek datových bodů od jejich střední hodnoty. -AVERAGE = PRŮMĚR ## Vrátí průměrnou hodnotu argumentů. -AVERAGEA = AVERAGEA ## Vrátí průměrnou hodnotu argumentů včetně čísel, textu a logických hodnot. -AVERAGEIF = AVERAGEIF ## Vrátí průměrnou hodnotu (aritmetický průměr) všech buněk v oblasti, které vyhovují příslušné podmínce. -AVERAGEIFS = AVERAGEIFS ## Vrátí průměrnou hodnotu (aritmetický průměr) všech buněk vyhovujících několika podmínkám. -BETADIST = BETADIST ## Vrátí hodnotu součtového rozdělení beta. -BETAINV = BETAINV ## Vrátí inverzní hodnotu součtového rozdělení pro zadané rozdělení beta. -BINOMDIST = BINOMDIST ## Vrátí hodnotu binomického rozdělení pravděpodobnosti jednotlivých veličin. -CHIDIST = CHIDIST ## Vrátí jednostrannou pravděpodobnost rozdělení chí-kvadrát. -CHIINV = CHIINV ## Vrátí hodnotu funkce inverzní k distribuční funkci jednostranné pravděpodobnosti rozdělení chí-kvadrát. -CHITEST = CHITEST ## Vrátí test nezávislosti. -CONFIDENCE = CONFIDENCE ## Vrátí interval spolehlivosti pro střední hodnotu základního souboru. -CORREL = CORREL ## Vrátí korelační koeficient mezi dvěma množinami dat. -COUNT = POČET ## Vrátí počet čísel v seznamu argumentů. -COUNTA = POČET2 ## Vrátí počet hodnot v seznamu argumentů. -COUNTBLANK = COUNTBLANK ## Spočítá počet prázdných buněk v oblasti. -COUNTIF = COUNTIF ## Spočítá buňky v oblasti, které odpovídají zadaným kritériím. -COUNTIFS = COUNTIFS ## Spočítá buňky v oblasti, které odpovídají více kritériím. -COVAR = COVAR ## Vrátí hodnotu kovariance, průměrnou hodnotu součinů párových odchylek -CRITBINOM = CRITBINOM ## Vrátí nejmenší hodnotu, pro kterou má součtové binomické rozdělení hodnotu větší nebo rovnu hodnotě kritéria. -DEVSQ = DEVSQ ## Vrátí součet čtverců odchylek. -EXPONDIST = EXPONDIST ## Vrátí hodnotu exponenciálního rozdělení. -FDIST = FDIST ## Vrátí hodnotu rozdělení pravděpodobnosti F. -FINV = FINV ## Vrátí hodnotu inverzní funkce k distribuční funkci rozdělení F. -FISHER = FISHER ## Vrátí hodnotu Fisherovy transformace. -FISHERINV = FISHERINV ## Vrátí hodnotu inverzní funkce k Fisherově transformaci. -FORECAST = FORECAST ## Vrátí hodnotu lineárního trendu. -FREQUENCY = ČETNOSTI ## Vrátí četnost rozdělení jako svislou matici. -FTEST = FTEST ## Vrátí výsledek F-testu. -GAMMADIST = GAMMADIST ## Vrátí hodnotu rozdělení gama. -GAMMAINV = GAMMAINV ## Vrátí hodnotu inverzní funkce k distribuční funkci součtového rozdělení gama. -GAMMALN = GAMMALN ## Vrátí přirozený logaritmus funkce gama, Γ(x). -GEOMEAN = GEOMEAN ## Vrátí geometrický průměr. -GROWTH = LOGLINTREND ## Vrátí hodnoty exponenciálního trendu. -HARMEAN = HARMEAN ## Vrátí harmonický průměr. -HYPGEOMDIST = HYPGEOMDIST ## Vrátí hodnotu hypergeometrického rozdělení. -INTERCEPT = INTERCEPT ## Vrátí úsek lineární regresní čáry. -KURT = KURT ## Vrátí hodnotu excesu množiny dat. -LARGE = LARGE ## Vrátí k-tou největší hodnotu množiny dat. -LINEST = LINREGRESE ## Vrátí parametry lineárního trendu. -LOGEST = LOGLINREGRESE ## Vrátí parametry exponenciálního trendu. -LOGINV = LOGINV ## Vrátí inverzní funkci k distribuční funkci logaritmicko-normálního rozdělení. -LOGNORMDIST = LOGNORMDIST ## Vrátí hodnotu součtového logaritmicko-normálního rozdělení. -MAX = MAX ## Vrátí maximální hodnotu seznamu argumentů. -MAXA = MAXA ## Vrátí maximální hodnotu seznamu argumentů včetně čísel, textu a logických hodnot. -MEDIAN = MEDIAN ## Vrátí střední hodnotu zadaných čísel. -MIN = MIN ## Vrátí minimální hodnotu seznamu argumentů. -MINA = MINA ## Vrátí nejmenší hodnotu v seznamu argumentů včetně čísel, textu a logických hodnot. -MODE = MODE ## Vrátí hodnotu, která se v množině dat vyskytuje nejčastěji. -NEGBINOMDIST = NEGBINOMDIST ## Vrátí hodnotu negativního binomického rozdělení. -NORMDIST = NORMDIST ## Vrátí hodnotu normálního součtového rozdělení. -NORMINV = NORMINV ## Vrátí inverzní funkci k funkci normálního součtového rozdělení. -NORMSDIST = NORMSDIST ## Vrátí hodnotu standardního normálního součtového rozdělení. -NORMSINV = NORMSINV ## Vrátí inverzní funkci k funkci standardního normálního součtového rozdělení. -PEARSON = PEARSON ## Vrátí Pearsonův výsledný momentový korelační koeficient. -PERCENTILE = PERCENTIL ## Vrátí hodnotu k-tého percentilu hodnot v oblasti. -PERCENTRANK = PERCENTRANK ## Vrátí pořadí hodnoty v množině dat vyjádřené procentuální částí množiny dat. -PERMUT = PERMUTACE ## Vrátí počet permutací pro zadaný počet objektů. -POISSON = POISSON ## Vrátí hodnotu distribuční funkce Poissonova rozdělení. -PROB = PROB ## Vrátí pravděpodobnost výskytu hodnot v oblasti mezi dvěma mezními hodnotami. -QUARTILE = QUARTIL ## Vrátí hodnotu kvartilu množiny dat. -RANK = RANK ## Vrátí pořadí čísla v seznamu čísel. -RSQ = RKQ ## Vrátí druhou mocninu Pearsonova výsledného momentového korelačního koeficientu. -SKEW = SKEW ## Vrátí zešikmení rozdělení. -SLOPE = SLOPE ## Vrátí směrnici lineární regresní čáry. -SMALL = SMALL ## Vrátí k-tou nejmenší hodnotu množiny dat. -STANDARDIZE = STANDARDIZE ## Vrátí normalizovanou hodnotu. -STDEV = SMODCH.VÝBĚR ## Vypočte směrodatnou odchylku výběru. -STDEVA = STDEVA ## Vypočte směrodatnou odchylku výběru včetně čísel, textu a logických hodnot. -STDEVP = SMODCH ## Vypočte směrodatnou odchylku základního souboru. -STDEVPA = STDEVPA ## Vypočte směrodatnou odchylku základního souboru včetně čísel, textu a logických hodnot. -STEYX = STEYX ## Vrátí standardní chybu předpovězené hodnoty y pro každou hodnotu x v regresi. -TDIST = TDIST ## Vrátí hodnotu Studentova t-rozdělení. -TINV = TINV ## Vrátí inverzní funkci k distribuční funkci Studentova t-rozdělení. -TREND = LINTREND ## Vrátí hodnoty lineárního trendu. -TRIMMEAN = TRIMMEAN ## Vrátí střední hodnotu vnitřní části množiny dat. -TTEST = TTEST ## Vrátí pravděpodobnost spojenou se Studentovým t-testem. -VAR = VAR.VÝBĚR ## Vypočte rozptyl výběru. -VARA = VARA ## Vypočte rozptyl výběru včetně čísel, textu a logických hodnot. -VARP = VAR ## Vypočte rozptyl základního souboru. -VARPA = VARPA ## Vypočte rozptyl základního souboru včetně čísel, textu a logických hodnot. -WEIBULL = WEIBULL ## Vrátí hodnotu Weibullova rozdělení. -ZTEST = ZTEST ## Vrátí jednostrannou P-hodnotu z-testu. - +BAHTTEXT = BAHTTEXT +CHAR = ZNAK +CLEAN = VYČISTIT +CODE = KÓD +CONCAT = CONCAT +DOLLAR = KČ +EXACT = STEJNÉ +FIND = NAJÍT +FIXED = ZAOKROUHLIT.NA.TEXT +LEFT = ZLEVA +LEN = DÉLKA +LOWER = MALÁ +MID = ČÁST +NUMBERVALUE = NUMBERVALUE +PHONETIC = ZVUKOVÉ +PROPER = VELKÁ2 +REPLACE = NAHRADIT +REPT = OPAKOVAT +RIGHT = ZPRAVA +SEARCH = HLEDAT +SUBSTITUTE = DOSADIT +T = T +TEXT = HODNOTA.NA.TEXT +TEXTJOIN = TEXTJOIN +TRIM = PROČISTIT +UNICHAR = UNICHAR +UNICODE = UNICODE +UPPER = VELKÁ +VALUE = HODNOTA ## -## Text functions Textové funkce +## Webové funkce (Web Functions) ## -ASC = ASC ## Změní znaky s plnou šířkou (dvoubajtové)v řetězci znaků na znaky s poloviční šířkou (jednobajtové). -BAHTTEXT = BAHTTEXT ## Převede číslo na text ve formátu, měny ß (baht). -CHAR = ZNAK ## Vrátí znak určený číslem kódu. -CLEAN = VYČISTIT ## Odebere z textu všechny netisknutelné znaky. -CODE = KÓD ## Vrátí číselný kód prvního znaku zadaného textového řetězce. -CONCATENATE = CONCATENATE ## Spojí několik textových položek do jedné. -DOLLAR = KČ ## Převede číslo na text ve formátu měny Kč (česká koruna). -EXACT = STEJNÉ ## Zkontroluje, zda jsou dvě textové hodnoty shodné. -FIND = NAJÍT ## Nalezne textovou hodnotu uvnitř jiné (rozlišuje malá a velká písmena). -FINDB = FINDB ## Nalezne textovou hodnotu uvnitř jiné (rozlišuje malá a velká písmena). -FIXED = ZAOKROUHLIT.NA.TEXT ## Zformátuje číslo jako text s pevným počtem desetinných míst. -JIS = JIS ## Změní znaky s poloviční šířkou (jednobajtové) v řetězci znaků na znaky s plnou šířkou (dvoubajtové). -LEFT = ZLEVA ## Vrátí první znaky textové hodnoty umístěné nejvíce vlevo. -LEFTB = LEFTB ## Vrátí první znaky textové hodnoty umístěné nejvíce vlevo. -LEN = DÉLKA ## Vrátí počet znaků textového řetězce. -LENB = LENB ## Vrátí počet znaků textového řetězce. -LOWER = MALÁ ## Převede text na malá písmena. -MID = ČÁST ## Vrátí určitý počet znaků textového řetězce počínaje zadaným místem. -MIDB = MIDB ## Vrátí určitý počet znaků textového řetězce počínaje zadaným místem. -PHONETIC = ZVUKOVÉ ## Extrahuje fonetické znaky (furigana) z textového řetězce. -PROPER = VELKÁ2 ## Převede první písmeno každého slova textové hodnoty na velké. -REPLACE = NAHRADIT ## Nahradí znaky uvnitř textu. -REPLACEB = NAHRADITB ## Nahradí znaky uvnitř textu. -REPT = OPAKOVAT ## Zopakuje text podle zadaného počtu opakování. -RIGHT = ZPRAVA ## Vrátí první znaky textové hodnoty umístěné nejvíce vpravo. -RIGHTB = RIGHTB ## Vrátí první znaky textové hodnoty umístěné nejvíce vpravo. -SEARCH = HLEDAT ## Nalezne textovou hodnotu uvnitř jiné (malá a velká písmena nejsou rozlišována). -SEARCHB = SEARCHB ## Nalezne textovou hodnotu uvnitř jiné (malá a velká písmena nejsou rozlišována). -SUBSTITUTE = DOSADIT ## V textovém řetězci nahradí starý text novým. -T = T ## Převede argumenty na text. -TEXT = HODNOTA.NA.TEXT ## Zformátuje číslo a převede ho na text. -TRIM = PROČISTIT ## Odstraní z textu mezery. -UPPER = VELKÁ ## Převede text na velká písmena. -VALUE = HODNOTA ## Převede textový argument na číslo. +ENCODEURL = ENCODEURL +FILTERXML = FILTERXML +WEBSERVICE = WEBSERVICE + +## +## Funkce pro kompatibilitu (Compatibility Functions) +## +BETADIST = BETADIST +BETAINV = BETAINV +BINOMDIST = BINOMDIST +CEILING = ZAOKR.NAHORU +CHIDIST = CHIDIST +CHIINV = CHIINV +CHITEST = CHITEST +CONCATENATE = CONCATENATE +CONFIDENCE = CONFIDENCE +COVAR = COVAR +CRITBINOM = CRITBINOM +EXPONDIST = EXPONDIST +FDIST = FDIST +FINV = FINV +FLOOR = ZAOKR.DOLŮ +FORECAST = FORECAST +FTEST = FTEST +GAMMADIST = GAMMADIST +GAMMAINV = GAMMAINV +HYPGEOMDIST = HYPGEOMDIST +LOGINV = LOGINV +LOGNORMDIST = LOGNORMDIST +MODE = MODE +NEGBINOMDIST = NEGBINOMDIST +NORMDIST = NORMDIST +NORMINV = NORMINV +NORMSDIST = NORMSDIST +NORMSINV = NORMSINV +PERCENTILE = PERCENTIL +PERCENTRANK = PERCENTRANK +POISSON = POISSON +QUARTILE = QUARTIL +RANK = RANK +STDEV = SMODCH.VÝBĚR +STDEVP = SMODCH +TDIST = TDIST +TINV = TINV +TTEST = TTEST +VAR = VAR.VÝBĚR +VARP = VAR +WEIBULL = WEIBULL +ZTEST = ZTEST diff --git a/src/PhpSpreadsheet/Calculation/locale/da/config b/src/PhpSpreadsheet/Calculation/locale/da/config index a7aa8fee..284b2490 100644 --- a/src/PhpSpreadsheet/Calculation/locale/da/config +++ b/src/PhpSpreadsheet/Calculation/locale/da/config @@ -1,25 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## +## Dansk (Danish) +## +############################################################ -ArgumentSeparator = ; - +ArgumentSeparator = ; ## -## (For future use) +## Error Codes ## -currencySymbol = kr - - - -## -## Excel Error Codes (For future use) - -## -NULL = #NUL! -DIV0 = #DIVISION/0! -VALUE = #VÆRDI! -REF = #REFERENCE! -NAME = #NAVN? -NUM = #NUM! -NA = #I/T +NULL = #NUL! +DIV0 +VALUE = #VÆRDI! +REF = #REFERENCE! +NAME = #NAVN? +NUM +NA = #I/T diff --git a/src/PhpSpreadsheet/Calculation/locale/da/functions b/src/PhpSpreadsheet/Calculation/locale/da/functions index d02aa2ec..6260760b 100644 --- a/src/PhpSpreadsheet/Calculation/locale/da/functions +++ b/src/PhpSpreadsheet/Calculation/locale/da/functions @@ -1,416 +1,537 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Dansk (Danish) ## +############################################################ ## -## Add-in and Automation functions Tilføjelsesprogram- og automatiseringsfunktioner +## Kubefunktioner (Cube Functions) ## -GETPIVOTDATA = HENTPIVOTDATA ## Returnerer data, der er lagret i en pivottabelrapport - +CUBEKPIMEMBER = KUBE.KPI.MEDLEM +CUBEMEMBER = KUBEMEDLEM +CUBEMEMBERPROPERTY = KUBEMEDLEM.EGENSKAB +CUBERANKEDMEMBER = KUBERANGERET.MEDLEM +CUBESET = KUBESÆT +CUBESETCOUNT = KUBESÆT.ANTAL +CUBEVALUE = KUBEVÆRDI ## -## Cube functions Kubefunktioner +## Databasefunktioner (Database Functions) ## -CUBEKPIMEMBER = KUBE.KPI.MEDLEM ## Returnerer navn, egenskab og mål for en KPI-indikator og viser navnet og egenskaben i cellen. En KPI-indikator er en målbar størrelse, f.eks. bruttooverskud pr. måned eller personaleudskiftning pr. kvartal, der bruges til at overvåge en organisations præstationer. -CUBEMEMBER = KUBE.MEDLEM ## Returnerer et medlem eller en tupel fra kubehierarkiet. Bruges til at validere, om et medlem eller en tupel findes i kuben. -CUBEMEMBERPROPERTY = KUBEMEDLEM.EGENSKAB ## Returnerer værdien af en egenskab for et medlem i kuben. Bruges til at validere, om et medlemsnavn findes i kuben, og returnere den angivne egenskab for medlemmet. -CUBERANKEDMEMBER = KUBEMEDLEM.RANG ## Returnerer det n'te eller rangordnede medlem i et sæt. Bruges til at returnere et eller flere elementer i et sæt, f.eks. topsælgere eller de 10 bedste elever. -CUBESET = KUBESÆT ## Definerer et beregnet sæt medlemmer eller tupler ved at sende et sætudtryk til kuben på serveren, som opretter sættet og returnerer det til Microsoft Office Excel. -CUBESETCOUNT = KUBESÆT.TÆL ## Returnerer antallet af elementer i et sæt. -CUBEVALUE = KUBEVÆRDI ## Returnerer en sammenlagt (aggregeret) værdi fra en kube. - +DAVERAGE = DMIDDEL +DCOUNT = DTÆL +DCOUNTA = DTÆLV +DGET = DHENT +DMAX = DMAKS +DMIN = DMIN +DPRODUCT = DPRODUKT +DSTDEV = DSTDAFV +DSTDEVP = DSTDAFVP +DSUM = DSUM +DVAR = DVARIANS +DVARP = DVARIANSP ## -## Database functions Databasefunktioner +## Dato- og klokkeslætfunktioner (Date & Time Functions) ## -DAVERAGE = DMIDDEL ## Returnerer gennemsnittet af markerede databaseposter -DCOUNT = DTÆL ## Tæller de celler, der indeholder tal, i en database -DCOUNTA = DTÆLV ## Tæller udfyldte celler i en database -DGET = DHENT ## Uddrager en enkelt post, der opfylder de angivne kriterier, fra en database -DMAX = DMAKS ## Returnerer den største værdi blandt markerede databaseposter -DMIN = DMIN ## Returnerer den mindste værdi blandt markerede databaseposter -DPRODUCT = DPRODUKT ## Ganger værdierne i et bestemt felt med poster, der opfylder kriterierne i en database -DSTDEV = DSTDAFV ## Beregner et skøn over standardafvigelsen baseret på en stikprøve af markerede databaseposter -DSTDEVP = DSTDAFVP ## Beregner standardafvigelsen baseret på hele populationen af markerede databaseposter -DSUM = DSUM ## Sammenlægger de tal i feltkolonnen i databasen, der opfylder kriterierne -DVAR = DVARIANS ## Beregner varians baseret på en stikprøve af markerede databaseposter -DVARP = DVARIANSP ## Beregner varians baseret på hele populationen af markerede databaseposter - +DATE = DATO +DATEDIF = DATO.FORSKEL +DATESTRING = DATOSTRENG +DATEVALUE = DATOVÆRDI +DAY = DAG +DAYS = DAGE +DAYS360 = DAGE360 +EDATE = EDATO +EOMONTH = SLUT.PÅ.MÅNED +HOUR = TIME +ISOWEEKNUM = ISOUGE.NR +MINUTE = MINUT +MONTH = MÅNED +NETWORKDAYS = ANTAL.ARBEJDSDAGE +NETWORKDAYS.INTL = ANTAL.ARBEJDSDAGE.INTL +NOW = NU +SECOND = SEKUND +THAIDAYOFWEEK = THAILANDSKUGEDAG +THAIMONTHOFYEAR = THAILANDSKMÅNED +THAIYEAR = THAILANDSKÅR +TIME = TID +TIMEVALUE = TIDSVÆRDI +TODAY = IDAG +WEEKDAY = UGEDAG +WEEKNUM = UGE.NR +WORKDAY = ARBEJDSDAG +WORKDAY.INTL = ARBEJDSDAG.INTL +YEAR = ÅR +YEARFRAC = ÅR.BRØK ## -## Date and time functions Dato- og klokkeslætsfunktioner +## Tekniske funktioner (Engineering Functions) ## -DATE = DATO ## Returnerer serienummeret for en bestemt dato -DATEVALUE = DATOVÆRDI ## Konverterer en dato i form af tekst til et serienummer -DAY = DAG ## Konverterer et serienummer til en dag i måneden -DAYS360 = DAGE360 ## Beregner antallet af dage mellem to datoer på grundlag af et år med 360 dage -EDATE = EDATO ## Returnerer serienummeret for den dato, der ligger det angivne antal måneder før eller efter startdatoen -EOMONTH = SLUT.PÅ.MÅNED ## Returnerer serienummeret på den sidste dag i måneden før eller efter et angivet antal måneder -HOUR = TIME ## Konverterer et serienummer til en time -MINUTE = MINUT ## Konverterer et serienummer til et minut -MONTH = MÅNED ## Konverterer et serienummer til en måned -NETWORKDAYS = ANTAL.ARBEJDSDAGE ## Returnerer antallet af hele arbejdsdage mellem to datoer -NOW = NU ## Returnerer serienummeret for den aktuelle dato eller det aktuelle klokkeslæt -SECOND = SEKUND ## Konverterer et serienummer til et sekund -TIME = KLOKKESLÆT ## Returnerer serienummeret for et bestemt klokkeslæt -TIMEVALUE = TIDSVÆRDI ## Konverterer et klokkeslæt i form af tekst til et serienummer -TODAY = IDAG ## Returnerer serienummeret for dags dato -WEEKDAY = UGEDAG ## Konverterer et serienummer til en ugedag -WEEKNUM = UGE.NR ## Konverterer et serienummer til et tal, der angiver ugenummeret i året -WORKDAY = ARBEJDSDAG ## Returnerer serienummeret for dagen før eller efter det angivne antal arbejdsdage -YEAR = ÅR ## Konverterer et serienummer til et år -YEARFRAC = ÅR.BRØK ## Returnerer årsbrøken, der repræsenterer antallet af hele dage mellem startdato og slutdato - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BIN.TIL.DEC +BIN2HEX = BIN.TIL.HEX +BIN2OCT = BIN.TIL.OKT +BITAND = BITOG +BITLSHIFT = BITLSKIFT +BITOR = BITELLER +BITRSHIFT = BITRSKIFT +BITXOR = BITXELLER +COMPLEX = KOMPLEKS +CONVERT = KONVERTER +DEC2BIN = DEC.TIL.BIN +DEC2HEX = DEC.TIL.HEX +DEC2OCT = DEC.TIL.OKT +DELTA = DELTA +ERF = FEJLFUNK +ERF.PRECISE = ERF.PRECISE +ERFC = FEJLFUNK.KOMP +ERFC.PRECISE = ERFC.PRECISE +GESTEP = GETRIN +HEX2BIN = HEX.TIL.BIN +HEX2DEC = HEX.TIL.DEC +HEX2OCT = HEX.TIL.OKT +IMABS = IMAGABS +IMAGINARY = IMAGINÆR +IMARGUMENT = IMAGARGUMENT +IMCONJUGATE = IMAGKONJUGERE +IMCOS = IMAGCOS +IMCOSH = IMAGCOSH +IMCOT = IMAGCOT +IMCSC = IMAGCSC +IMCSCH = IMAGCSCH +IMDIV = IMAGDIV +IMEXP = IMAGEKSP +IMLN = IMAGLN +IMLOG10 = IMAGLOG10 +IMLOG2 = IMAGLOG2 +IMPOWER = IMAGPOTENS +IMPRODUCT = IMAGPRODUKT +IMREAL = IMAGREELT +IMSEC = IMAGSEC +IMSECH = IMAGSECH +IMSIN = IMAGSIN +IMSINH = IMAGSINH +IMSQRT = IMAGKVROD +IMSUB = IMAGSUB +IMSUM = IMAGSUM +IMTAN = IMAGTAN +OCT2BIN = OKT.TIL.BIN +OCT2DEC = OKT.TIL.DEC +OCT2HEX = OKT.TIL.HEX ## -## Engineering functions Tekniske funktioner +## Finansielle funktioner (Financial Functions) ## -BESSELI = BESSELI ## Returnerer den modificerede Bessel-funktion In(x) -BESSELJ = BESSELJ ## Returnerer Bessel-funktionen Jn(x) -BESSELK = BESSELK ## Returnerer den modificerede Bessel-funktion Kn(x) -BESSELY = BESSELY ## Returnerer Bessel-funktionen Yn(x) -BIN2DEC = BIN.TIL.DEC ## Konverterer et binært tal til et decimaltal -BIN2HEX = BIN.TIL.HEX ## Konverterer et binært tal til et heksadecimalt tal -BIN2OCT = BIN.TIL.OKT ## Konverterer et binært tal til et oktaltal. -COMPLEX = KOMPLEKS ## Konverterer reelle og imaginære koefficienter til et komplekst tal -CONVERT = KONVERTER ## Konverterer et tal fra én måleenhed til en anden -DEC2BIN = DEC.TIL.BIN ## Konverterer et decimaltal til et binært tal -DEC2HEX = DEC.TIL.HEX ## Konverterer et decimaltal til et heksadecimalt tal -DEC2OCT = DEC.TIL.OKT ## Konverterer et decimaltal til et oktaltal -DELTA = DELTA ## Tester, om to værdier er ens -ERF = FEJLFUNK ## Returner fejlfunktionen -ERFC = FEJLFUNK.KOMP ## Returnerer den komplementære fejlfunktion -GESTEP = GETRIN ## Tester, om et tal er større end en grænseværdi -HEX2BIN = HEX.TIL.BIN ## Konverterer et heksadecimalt tal til et binært tal -HEX2DEC = HEX.TIL.DEC ## Konverterer et decimaltal til et heksadecimalt tal -HEX2OCT = HEX.TIL.OKT ## Konverterer et heksadecimalt tal til et oktaltal -IMABS = IMAGABS ## Returnerer den absolutte værdi (modulus) for et komplekst tal -IMAGINARY = IMAGINÆR ## Returnerer den imaginære koefficient for et komplekst tal -IMARGUMENT = IMAGARGUMENT ## Returnerer argumentet theta, en vinkel udtrykt i radianer -IMCONJUGATE = IMAGKONJUGERE ## Returnerer den komplekse konjugation af et komplekst tal -IMCOS = IMAGCOS ## Returnerer et komplekst tals cosinus -IMDIV = IMAGDIV ## Returnerer kvotienten for to komplekse tal -IMEXP = IMAGEKSP ## Returnerer et komplekst tals eksponentialfunktion -IMLN = IMAGLN ## Returnerer et komplekst tals naturlige logaritme -IMLOG10 = IMAGLOG10 ## Returnerer et komplekst tals sædvanlige logaritme (titalslogaritme) -IMLOG2 = IMAGLOG2 ## Returnerer et komplekst tals sædvanlige logaritme (totalslogaritme) -IMPOWER = IMAGPOTENS ## Returnerer et komplekst tal opløftet i en heltalspotens -IMPRODUCT = IMAGPRODUKT ## Returnerer produktet af komplekse tal -IMREAL = IMAGREELT ## Returnerer den reelle koefficient for et komplekst tal -IMSIN = IMAGSIN ## Returnerer et komplekst tals sinus -IMSQRT = IMAGKVROD ## Returnerer et komplekst tals kvadratrod -IMSUB = IMAGSUB ## Returnerer forskellen mellem to komplekse tal -IMSUM = IMAGSUM ## Returnerer summen af komplekse tal -OCT2BIN = OKT.TIL.BIN ## Konverterer et oktaltal til et binært tal -OCT2DEC = OKT.TIL.DEC ## Konverterer et oktaltal til et decimaltal -OCT2HEX = OKT.TIL.HEX ## Konverterer et oktaltal til et heksadecimalt tal - +ACCRINT = PÅLØBRENTE +ACCRINTM = PÅLØBRENTE.UDLØB +AMORDEGRC = AMORDEGRC +AMORLINC = AMORLINC +COUPDAYBS = KUPONDAGE.SA +COUPDAYS = KUPONDAGE.A +COUPDAYSNC = KUPONDAGE.ANK +COUPNCD = KUPONDAG.NÆSTE +COUPNUM = KUPONBETALINGER +COUPPCD = KUPONDAG.FORRIGE +CUMIPMT = AKKUM.RENTE +CUMPRINC = AKKUM.HOVEDSTOL +DB = DB +DDB = DSA +DISC = DISKONTO +DOLLARDE = KR.DECIMAL +DOLLARFR = KR.BRØK +DURATION = VARIGHED +EFFECT = EFFEKTIV.RENTE +FV = FV +FVSCHEDULE = FVTABEL +INTRATE = RENTEFOD +IPMT = R.YDELSE +IRR = IA +ISPMT = ISPMT +MDURATION = MVARIGHED +MIRR = MIA +NOMINAL = NOMINEL +NPER = NPER +NPV = NUTIDSVÆRDI +ODDFPRICE = ULIGE.KURS.PÅLYDENDE +ODDFYIELD = ULIGE.FØRSTE.AFKAST +ODDLPRICE = ULIGE.SIDSTE.KURS +ODDLYIELD = ULIGE.SIDSTE.AFKAST +PDURATION = PVARIGHED +PMT = YDELSE +PPMT = H.YDELSE +PRICE = KURS +PRICEDISC = KURS.DISKONTO +PRICEMAT = KURS.UDLØB +PV = NV +RATE = RENTE +RECEIVED = MODTAGET.VED.UDLØB +RRI = RRI +SLN = LA +SYD = ÅRSAFSKRIVNING +TBILLEQ = STATSOBLIGATION +TBILLPRICE = STATSOBLIGATION.KURS +TBILLYIELD = STATSOBLIGATION.AFKAST +VDB = VSA +XIRR = INTERN.RENTE +XNPV = NETTO.NUTIDSVÆRDI +YIELD = AFKAST +YIELDDISC = AFKAST.DISKONTO +YIELDMAT = AFKAST.UDLØBSDATO ## -## Financial functions Finansielle funktioner +## Informationsfunktioner (Information Functions) ## -ACCRINT = PÅLØBRENTE ## Returnerer den påløbne rente for et værdipapir med periodiske renteudbetalinger -ACCRINTM = PÅLØBRENTE.UDLØB ## Returnerer den påløbne rente for et værdipapir, hvor renteudbetalingen finder sted ved papirets udløb -AMORDEGRC = AMORDEGRC ## Returnerer afskrivningsbeløbet for hver regnskabsperiode ved hjælp af en afskrivningskoefficient -AMORLINC = AMORLINC ## Returnerer afskrivningsbeløbet for hver regnskabsperiode -COUPDAYBS = KUPONDAGE.SA ## Returnerer antallet af dage fra starten af kuponperioden til afregningsdatoen -COUPDAYS = KUPONDAGE.A ## Returnerer antallet af dage fra begyndelsen af kuponperioden til afregningsdatoen -COUPDAYSNC = KUPONDAGE.ANK ## Returnerer antallet af dage i den kuponperiode, der indeholder afregningsdatoen -COUPNCD = KUPONDAG.NÆSTE ## Returnerer den næste kupondato efter afregningsdatoen -COUPNUM = KUPONBETALINGER ## Returnerer antallet af kuponudbetalinger mellem afregnings- og udløbsdatoen -COUPPCD = KUPONDAG.FORRIGE ## Returnerer den forrige kupondato før afregningsdatoen -CUMIPMT = AKKUM.RENTE ## Returnerer den akkumulerede rente, der betales på et lån mellem to perioder -CUMPRINC = AKKUM.HOVEDSTOL ## Returnerer den akkumulerede nedbringelse af hovedstol mellem to perioder -DB = DB ## Returnerer afskrivningen på et aktiv i en angivet periode ved anvendelse af saldometoden -DDB = DSA ## Returnerer afskrivningsbeløbet for et aktiv over en bestemt periode ved anvendelse af dobbeltsaldometoden eller en anden afskrivningsmetode, som du angiver -DISC = DISKONTO ## Returnerer et værdipapirs diskonto -DOLLARDE = KR.DECIMAL ## Konverterer en kronepris udtrykt som brøk til en kronepris udtrykt som decimaltal -DOLLARFR = KR.BRØK ## Konverterer en kronepris udtrykt som decimaltal til en kronepris udtrykt som brøk -DURATION = VARIGHED ## Returnerer den årlige løbetid for et værdipapir med periodiske renteudbetalinger -EFFECT = EFFEKTIV.RENTE ## Returnerer den årlige effektive rente -FV = FV ## Returnerer fremtidsværdien af en investering -FVSCHEDULE = FVTABEL ## Returnerer den fremtidige værdi af en hovedstol, når der er tilskrevet rente og rentes rente efter forskellige rentesatser -INTRATE = RENTEFOD ## Returnerer renten på et fuldt ud investeret værdipapir -IPMT = R.YDELSE ## Returnerer renten fra en investering for en given periode -IRR = IA ## Returnerer den interne rente for en række pengestrømme -ISPMT = ISPMT ## Beregner den betalte rente i løbet af en bestemt investeringsperiode -MDURATION = MVARIGHED ## Returnerer Macauleys modificerede løbetid for et værdipapir med en formodet pari på kr. 100 -MIRR = MIA ## Returnerer den interne forrentning, hvor positive og negative pengestrømme finansieres til forskellig rente -NOMINAL = NOMINEL ## Returnerer den årlige nominelle rente -NPER = NPER ## Returnerer antallet af perioder for en investering -NPV = NUTIDSVÆRDI ## Returnerer nettonutidsværdien for en investering baseret på en række periodiske pengestrømme og en diskonteringssats -ODDFPRICE = ULIGE.KURS.PÅLYDENDE ## Returnerer kursen pr. kr. 100 nominel værdi for et værdipapir med en ulige (kort eller lang) første periode -ODDFYIELD = ULIGE.FØRSTE.AFKAST ## Returnerer afkastet for et værdipapir med ulige første periode -ODDLPRICE = ULIGE.SIDSTE.KURS ## Returnerer kursen pr. kr. 100 nominel værdi for et værdipapir med ulige sidste periode -ODDLYIELD = ULIGE.SIDSTE.AFKAST ## Returnerer afkastet for et værdipapir med ulige sidste periode -PMT = YDELSE ## Returnerer renten fra en investering for en given periode -PPMT = H.YDELSE ## Returnerer ydelsen på hovedstolen for en investering i en given periode -PRICE = KURS ## Returnerer kursen pr. kr 100 nominel værdi for et værdipapir med periodiske renteudbetalinger -PRICEDISC = KURS.DISKONTO ## Returnerer kursen pr. kr 100 nominel værdi for et diskonteret værdipapir -PRICEMAT = KURS.UDLØB ## Returnerer kursen pr. kr 100 nominel værdi for et værdipapir, hvor renten udbetales ved papirets udløb -PV = NV ## Returnerer den nuværende værdi af en investering -RATE = RENTE ## Returnerer renten i hver periode for en annuitet -RECEIVED = MODTAGET.VED.UDLØB ## Returnerer det beløb, der modtages ved udløbet af et fuldt ud investeret værdipapir -SLN = LA ## Returnerer den lineære afskrivning for et aktiv i en enkelt periode -SYD = ÅRSAFSKRIVNING ## Returnerer den årlige afskrivning på et aktiv i en bestemt periode -TBILLEQ = STATSOBLIGATION ## Returnerer det obligationsækvivalente afkast for en statsobligation -TBILLPRICE = STATSOBLIGATION.KURS ## Returnerer kursen pr. kr 100 nominel værdi for en statsobligation -TBILLYIELD = STATSOBLIGATION.AFKAST ## Returnerer en afkastet på en statsobligation -VDB = VSA ## Returnerer afskrivningen på et aktiv i en angivet periode, herunder delperioder, ved brug af dobbeltsaldometoden -XIRR = INTERN.RENTE ## Returnerer den interne rente for en plan over pengestrømme, der ikke behøver at være periodiske -XNPV = NETTO.NUTIDSVÆRDI ## Returnerer nutidsværdien for en plan over pengestrømme, der ikke behøver at være periodiske -YIELD = AFKAST ## Returnerer afkastet for et værdipapir med periodiske renteudbetalinger -YIELDDISC = AFKAST.DISKONTO ## Returnerer det årlige afkast for et diskonteret værdipapir, f.eks. en statsobligation -YIELDMAT = AFKAST.UDLØBSDATO ## Returnerer det årlige afkast for et værdipapir, hvor renten udbetales ved papirets udløb - +CELL = CELLE +ERROR.TYPE = FEJLTYPE +INFO = INFO +ISBLANK = ER.TOM +ISERR = ER.FJL +ISERROR = ER.FEJL +ISEVEN = ER.LIGE +ISFORMULA = ER.FORMEL +ISLOGICAL = ER.LOGISK +ISNA = ER.IKKE.TILGÆNGELIG +ISNONTEXT = ER.IKKE.TEKST +ISNUMBER = ER.TAL +ISODD = ER.ULIGE +ISREF = ER.REFERENCE +ISTEXT = ER.TEKST +N = TAL +NA = IKKE.TILGÆNGELIG +SHEET = ARK +SHEETS = ARK.FLERE +TYPE = VÆRDITYPE ## -## Information functions Informationsfunktioner +## Logiske funktioner (Logical Functions) ## -CELL = CELLE ## Returnerer oplysninger om formatering, placering eller indhold af en celle -ERROR.TYPE = FEJLTYPE ## Returnerer et tal, der svarer til en fejltype -INFO = INFO ## Returnerer oplysninger om det aktuelle operativmiljø -ISBLANK = ER.TOM ## Returnerer SAND, hvis værdien er tom -ISERR = ER.FJL ## Returnerer SAND, hvis værdien er en fejlværdi undtagen #I/T -ISERROR = ER.FEJL ## Returnerer SAND, hvis værdien er en fejlværdi -ISEVEN = ER.LIGE ## Returnerer SAND, hvis tallet er lige -ISLOGICAL = ER.LOGISK ## Returnerer SAND, hvis værdien er en logisk værdi -ISNA = ER.IKKE.TILGÆNGELIG ## Returnerer SAND, hvis værdien er fejlværdien #I/T -ISNONTEXT = ER.IKKE.TEKST ## Returnerer SAND, hvis værdien ikke er tekst -ISNUMBER = ER.TAL ## Returnerer SAND, hvis værdien er et tal -ISODD = ER.ULIGE ## Returnerer SAND, hvis tallet er ulige -ISREF = ER.REFERENCE ## Returnerer SAND, hvis værdien er en reference -ISTEXT = ER.TEKST ## Returnerer SAND, hvis værdien er tekst -N = TAL ## Returnerer en værdi konverteret til et tal -NA = IKKE.TILGÆNGELIG ## Returnerer fejlværdien #I/T -TYPE = VÆRDITYPE ## Returnerer et tal, der angiver datatypen for en værdi - +AND = OG +FALSE = FALSK +IF = HVIS +IFERROR = HVIS.FEJL +IFNA = HVISIT +IFS = HVISER +NOT = IKKE +OR = ELLER +SWITCH = SKIFT +TRUE = SAND +XOR = XELLER ## -## Logical functions Logiske funktioner +## Opslags- og referencefunktioner (Lookup & Reference Functions) ## -AND = OG ## Returnerer SAND, hvis alle argumenterne er sande -FALSE = FALSK ## Returnerer den logiske værdi FALSK -IF = HVIS ## Angiver en logisk test, der skal udføres -IFERROR = HVIS.FEJL ## Returnerer en værdi, du angiver, hvis en formel evauleres som en fejl. Returnerer i modsat fald resultatet af formlen -NOT = IKKE ## Vender argumentets logik om -OR = ELLER ## Returneret værdien SAND, hvis mindst ét argument er sandt -TRUE = SAND ## Returnerer den logiske værdi SAND - +ADDRESS = ADRESSE +AREAS = OMRÅDER +CHOOSE = VÆLG +COLUMN = KOLONNE +COLUMNS = KOLONNER +FORMULATEXT = FORMELTEKST +GETPIVOTDATA = GETPIVOTDATA +HLOOKUP = VOPSLAG +HYPERLINK = HYPERLINK +INDEX = INDEKS +INDIRECT = INDIREKTE +LOOKUP = SLÅ.OP +MATCH = SAMMENLIGN +OFFSET = FORSKYDNING +ROW = RÆKKE +ROWS = RÆKKER +RTD = RTD +TRANSPOSE = TRANSPONER +VLOOKUP = LOPSLAG ## -## Lookup and reference functions Opslags- og referencefunktioner +## Matematiske og trigonometriske funktioner (Math & Trig Functions) ## -ADDRESS = ADRESSE ## Returnerer en reference som tekst til en enkelt celle i et regneark -AREAS = OMRÅDER ## Returnerer antallet af områder i en reference -CHOOSE = VÆLG ## Vælger en værdi på en liste med værdier -COLUMN = KOLONNE ## Returnerer kolonnenummeret i en reference -COLUMNS = KOLONNER ## Returnerer antallet af kolonner i en reference -HLOOKUP = VOPSLAG ## Søger i den øverste række af en matrix og returnerer værdien af den angivne celle -HYPERLINK = HYPERLINK ## Opretter en genvej kaldet et hyperlink, der åbner et dokument, som er lagret på en netværksserver, på et intranet eller på internettet -INDEX = INDEKS ## Anvender et indeks til at vælge en værdi fra en reference eller en matrix -INDIRECT = INDIREKTE ## Returnerer en reference, der er angivet af en tekstværdi -LOOKUP = SLÅ.OP ## Søger værdier i en vektor eller en matrix -MATCH = SAMMENLIGN ## Søger værdier i en reference eller en matrix -OFFSET = FORSKYDNING ## Returnerer en reference forskudt i forhold til en given reference -ROW = RÆKKE ## Returnerer rækkenummeret for en reference -ROWS = RÆKKER ## Returnerer antallet af rækker i en reference -RTD = RTD ## Henter realtidsdata fra et program, der understøtter COM-automatisering (Automation: En metode til at arbejde med objekter fra et andet program eller udviklingsværktøj. Automation, som tidligere blev kaldt OLE Automation, er en industristandard og en funktion i COM (Component Object Model).) -TRANSPOSE = TRANSPONER ## Returnerer en transponeret matrix -VLOOKUP = LOPSLAG ## Søger i øverste række af en matrix og flytter på tværs af rækken for at returnere en celleværdi - +ABS = ABS +ACOS = ARCCOS +ACOSH = ARCCOSH +ACOT = ARCCOT +ACOTH = ARCCOTH +AGGREGATE = SAMLING +ARABIC = ARABISK +ASIN = ARCSIN +ASINH = ARCSINH +ATAN = ARCTAN +ATAN2 = ARCTAN2 +ATANH = ARCTANH +BASE = BASIS +CEILING.MATH = LOFT.MAT +CEILING.PRECISE = LOFT.PRECISE +COMBIN = KOMBIN +COMBINA = KOMBINA +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = DECIMAL +DEGREES = GRADER +ECMA.CEILING = ECMA.LOFT +EVEN = LIGE +EXP = EKSP +FACT = FAKULTET +FACTDOUBLE = DOBBELT.FAKULTET +FLOOR.MATH = AFRUND.BUND.MAT +FLOOR.PRECISE = AFRUND.GULV.PRECISE +GCD = STØRSTE.FÆLLES.DIVISOR +INT = HELTAL +ISO.CEILING = ISO.LOFT +LCM = MINDSTE.FÆLLES.MULTIPLUM +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = MDETERM +MINVERSE = MINVERT +MMULT = MPRODUKT +MOD = REST +MROUND = MAFRUND +MULTINOMIAL = MULTINOMIAL +MUNIT = MENHED +ODD = ULIGE +PI = PI +POWER = POTENS +PRODUCT = PRODUKT +QUOTIENT = KVOTIENT +RADIANS = RADIANER +RAND = SLUMP +RANDBETWEEN = SLUMPMELLEM +ROMAN = ROMERTAL +ROUND = AFRUND +ROUNDBAHTDOWN = RUNDBAHTNED +ROUNDBAHTUP = RUNDBAHTOP +ROUNDDOWN = RUND.NED +ROUNDUP = RUND.OP +SEC = SEC +SECH = SECH +SERIESSUM = SERIESUM +SIGN = FORTEGN +SIN = SIN +SINH = SINH +SQRT = KVROD +SQRTPI = KVRODPI +SUBTOTAL = SUBTOTAL +SUM = SUM +SUMIF = SUM.HVIS +SUMIFS = SUM.HVISER +SUMPRODUCT = SUMPRODUKT +SUMSQ = SUMKV +SUMX2MY2 = SUMX2MY2 +SUMX2PY2 = SUMX2PY2 +SUMXMY2 = SUMXMY2 +TAN = TAN +TANH = TANH +TRUNC = AFKORT ## -## Math and trigonometry functions Matematiske og trigonometriske funktioner +## Statistiske funktioner (Statistical Functions) ## -ABS = ABS ## Returnerer den absolutte værdi af et tal -ACOS = ARCCOS ## Returnerer et tals arcus cosinus -ACOSH = ARCCOSH ## Returnerer den inverse hyperbolske cosinus af tal -ASIN = ARCSIN ## Returnerer et tals arcus sinus -ASINH = ARCSINH ## Returnerer den inverse hyperbolske sinus for tal -ATAN = ARCTAN ## Returnerer et tals arcus tangens -ATAN2 = ARCTAN2 ## Returnerer de angivne x- og y-koordinaters arcus tangens -ATANH = ARCTANH ## Returnerer et tals inverse hyperbolske tangens -CEILING = AFRUND.LOFT ## Afrunder et tal til nærmeste heltal eller til nærmeste multiplum af betydning -COMBIN = KOMBIN ## Returnerer antallet af kombinationer for et givet antal objekter -COS = COS ## Returnerer et tals cosinus -COSH = COSH ## Returnerer den inverse hyperbolske cosinus af et tal -DEGREES = GRADER ## Konverterer radianer til grader -EVEN = LIGE ## Runder et tal op til nærmeste lige heltal -EXP = EKSP ## Returnerer e opløftet til en potens af et angivet tal -FACT = FAKULTET ## Returnerer et tals fakultet -FACTDOUBLE = DOBBELT.FAKULTET ## Returnerer et tals dobbelte fakultet -FLOOR = AFRUND.GULV ## Runder et tal ned mod nul -GCD = STØRSTE.FÆLLES.DIVISOR ## Returnerer den største fælles divisor -INT = HELTAL ## Nedrunder et tal til det nærmeste heltal -LCM = MINDSTE.FÆLLES.MULTIPLUM ## Returnerer det mindste fælles multiplum -LN = LN ## Returnerer et tals naturlige logaritme -LOG = LOG ## Returnerer logaritmen for et tal på grundlag af et angivet grundtal -LOG10 = LOG10 ## Returnerer titalslogaritmen af et tal -MDETERM = MDETERM ## Returnerer determinanten for en matrix -MINVERSE = MINVERT ## Returnerer den inverse matrix for en matrix -MMULT = MPRODUKT ## Returnerer matrixproduktet af to matrixer -MOD = REST ## Returnerer restværdien fra division -MROUND = MAFRUND ## Returnerer et tal afrundet til det ønskede multiplum -MULTINOMIAL = MULTINOMIAL ## Returnerer et multinomialt talsæt -ODD = ULIGE ## Runder et tal op til nærmeste ulige heltal -PI = PI ## Returnerer værdien af pi -POWER = POTENS ## Returnerer resultatet af et tal opløftet til en potens -PRODUCT = PRODUKT ## Multiplicerer argumenterne -QUOTIENT = KVOTIENT ## Returnerer heltalsdelen ved division -RADIANS = RADIANER ## Konverterer grader til radianer -RAND = SLUMP ## Returnerer et tilfældigt tal mellem 0 og 1 -RANDBETWEEN = SLUMP.MELLEM ## Returnerer et tilfældigt tal mellem de tal, der angives -ROMAN = ROMERTAL ## Konverterer et arabertal til romertal som tekst -ROUND = AFRUND ## Afrunder et tal til et angivet antal decimaler -ROUNDDOWN = RUND.NED ## Runder et tal ned mod nul -ROUNDUP = RUND.OP ## Runder et tal op, væk fra 0 (nul) -SERIESSUM = SERIESUM ## Returnerer summen af en potensserie baseret på en formel -SIGN = FORTEGN ## Returnerer et tals fortegn -SIN = SIN ## Returnerer en given vinkels sinusværdi -SINH = SINH ## Returnerer den hyperbolske sinus af et tal -SQRT = KVROD ## Returnerer en positiv kvadratrod -SQRTPI = KVRODPI ## Returnerer kvadratroden af (tal * pi;) -SUBTOTAL = SUBTOTAL ## Returnerer en subtotal på en liste eller i en database -SUM = SUM ## Lægger argumenterne sammen -SUMIF = SUM.HVIS ## Lægger de celler sammen, der er specificeret af et givet kriterium. -SUMIFS = SUM.HVISER ## Lægger de celler i et område sammen, der opfylder flere kriterier. -SUMPRODUCT = SUMPRODUKT ## Returnerer summen af produkter af ens matrixkomponenter -SUMSQ = SUMKV ## Returnerer summen af argumenternes kvadrater -SUMX2MY2 = SUMX2MY2 ## Returnerer summen af differensen mellem kvadrater af ens værdier i to matrixer -SUMX2PY2 = SUMX2PY2 ## Returnerer summen af summen af kvadrater af tilsvarende værdier i to matrixer -SUMXMY2 = SUMXMY2 ## Returnerer summen af kvadrater af differenser mellem ens værdier i to matrixer -TAN = TAN ## Returnerer et tals tangens -TANH = TANH ## Returnerer et tals hyperbolske tangens -TRUNC = AFKORT ## Afkorter et tal til et heltal - +AVEDEV = MAD +AVERAGE = MIDDEL +AVERAGEA = MIDDELV +AVERAGEIF = MIDDEL.HVIS +AVERAGEIFS = MIDDEL.HVISER +BETA.DIST = BETA.FORDELING +BETA.INV = BETA.INV +BINOM.DIST = BINOMIAL.FORDELING +BINOM.DIST.RANGE = BINOMIAL.DIST.INTERVAL +BINOM.INV = BINOMIAL.INV +CHISQ.DIST = CHI2.FORDELING +CHISQ.DIST.RT = CHI2.FORD.RT +CHISQ.INV = CHI2.INV +CHISQ.INV.RT = CHI2.INV.RT +CHISQ.TEST = CHI2.TEST +CONFIDENCE.NORM = KONFIDENS.NORM +CONFIDENCE.T = KONFIDENST +CORREL = KORRELATION +COUNT = TÆL +COUNTA = TÆLV +COUNTBLANK = ANTAL.BLANKE +COUNTIF = TÆL.HVIS +COUNTIFS = TÆL.HVISER +COVARIANCE.P = KOVARIANS.P +COVARIANCE.S = KOVARIANS.S +DEVSQ = SAK +EXPON.DIST = EKSP.FORDELING +F.DIST = F.FORDELING +F.DIST.RT = F.FORDELING.RT +F.INV = F.INV +F.INV.RT = F.INV.RT +F.TEST = F.TEST +FISHER = FISHER +FISHERINV = FISHERINV +FORECAST.ETS = PROGNOSE.ETS +FORECAST.ETS.CONFINT = PROGNOSE.ETS.CONFINT +FORECAST.ETS.SEASONALITY = PROGNOSE.ETS.SÆSONUDSVING +FORECAST.ETS.STAT = PROGNOSE.ETS.STAT +FORECAST.LINEAR = PROGNOSE.LINEÆR +FREQUENCY = FREKVENS +GAMMA = GAMMA +GAMMA.DIST = GAMMA.FORDELING +GAMMA.INV = GAMMA.INV +GAMMALN = GAMMALN +GAMMALN.PRECISE = GAMMALN.PRECISE +GAUSS = GAUSS +GEOMEAN = GEOMIDDELVÆRDI +GROWTH = FORØGELSE +HARMEAN = HARMIDDELVÆRDI +HYPGEOM.DIST = HYPGEO.FORDELING +INTERCEPT = SKÆRING +KURT = TOPSTEJL +LARGE = STØRSTE +LINEST = LINREGR +LOGEST = LOGREGR +LOGNORM.DIST = LOGNORM.FORDELING +LOGNORM.INV = LOGNORM.INV +MAX = MAKS +MAXA = MAKSV +MAXIFS = MAKSHVISER +MEDIAN = MEDIAN +MIN = MIN +MINA = MINV +MINIFS = MINHVISER +MODE.MULT = HYPPIGST.FLERE +MODE.SNGL = HYPPIGST.ENKELT +NEGBINOM.DIST = NEGBINOM.FORDELING +NORM.DIST = NORMAL.FORDELING +NORM.INV = NORM.INV +NORM.S.DIST = STANDARD.NORM.FORDELING +NORM.S.INV = STANDARD.NORM.INV +PEARSON = PEARSON +PERCENTILE.EXC = FRAKTIL.UDELAD +PERCENTILE.INC = FRAKTIL.MEDTAG +PERCENTRANK.EXC = PROCENTPLADS.UDELAD +PERCENTRANK.INC = PROCENTPLADS.MEDTAG +PERMUT = PERMUT +PERMUTATIONA = PERMUTATIONA +PHI = PHI +POISSON.DIST = POISSON.FORDELING +PROB = SANDSYNLIGHED +QUARTILE.EXC = KVARTIL.UDELAD +QUARTILE.INC = KVARTIL.MEDTAG +RANK.AVG = PLADS.GNSN +RANK.EQ = PLADS.LIGE +RSQ = FORKLARINGSGRAD +SKEW = SKÆVHED +SKEW.P = SKÆVHED.P +SLOPE = STIGNING +SMALL = MINDSTE +STANDARDIZE = STANDARDISER +STDEV.P = STDAFV.P +STDEV.S = STDAFV.S +STDEVA = STDAFVV +STDEVPA = STDAFVPV +STEYX = STFYX +T.DIST = T.FORDELING +T.DIST.2T = T.FORDELING.2T +T.DIST.RT = T.FORDELING.RT +T.INV = T.INV +T.INV.2T = T.INV.2T +T.TEST = T.TEST +TREND = TENDENS +TRIMMEAN = TRIMMIDDELVÆRDI +VAR.P = VARIANS.P +VAR.S = VARIANS.S +VARA = VARIANSV +VARPA = VARIANSPV +WEIBULL.DIST = WEIBULL.FORDELING +Z.TEST = Z.TEST ## -## Statistical functions Statistiske funktioner +## Tekstfunktioner (Text Functions) ## -AVEDEV = MAD ## Returnerer den gennemsnitlige numeriske afvigelse fra stikprøvens middelværdi -AVERAGE = MIDDEL ## Returnerer middelværdien af argumenterne -AVERAGEA = MIDDELV ## Returnerer middelværdien af argumenterne og medtager tal, tekst og logiske værdier -AVERAGEIF = MIDDEL.HVIS ## Returnerer gennemsnittet (den aritmetiske middelværdi) af alle de celler, der opfylder et givet kriterium, i et område -AVERAGEIFS = MIDDEL.HVISER ## Returnerer gennemsnittet (den aritmetiske middelværdi) af alle de celler, der opfylder flere kriterier. -BETADIST = BETAFORDELING ## Returnerer den kumulative betafordelingsfunktion -BETAINV = BETAINV ## Returnerer den inverse kumulative fordelingsfunktion for en angivet betafordeling -BINOMDIST = BINOMIALFORDELING ## Returnerer punktsandsynligheden for binomialfordelingen -CHIDIST = CHIFORDELING ## Returnerer fraktilsandsynligheden for en chi2-fordeling -CHIINV = CHIINV ## Returnerer den inverse fraktilsandsynlighed for en chi2-fordeling -CHITEST = CHITEST ## Foretager en test for uafhængighed -CONFIDENCE = KONFIDENSINTERVAL ## Returnerer et konfidensinterval for en population -CORREL = KORRELATION ## Returnerer korrelationskoefficienten mellem to datasæt -COUNT = TÆL ## Tæller antallet af tal på en liste med argumenter -COUNTA = TÆLV ## Tæller antallet af værdier på en liste med argumenter -COUNTBLANK = ANTAL.BLANKE ## Tæller antallet af tomme celler i et område -COUNTIF = TÆLHVIS ## Tæller antallet af celler, som opfylder de givne kriterier, i et område -COUNTIFS = TÆL.HVISER ## Tæller antallet af de celler, som opfylder flere kriterier, i et område -COVAR = KOVARIANS ## Beregner kovariansen mellem to stokastiske variabler -CRITBINOM = KRITBINOM ## Returnerer den mindste værdi for x, for hvilken det gælder, at fordelingsfunktionen er mindre end eller lig med kriterieværdien. -DEVSQ = SAK ## Returnerer summen af de kvadrerede afvigelser fra middelværdien -EXPONDIST = EKSPFORDELING ## Returnerer eksponentialfordelingen -FDIST = FFORDELING ## Returnerer fraktilsandsynligheden for F-fordelingen -FINV = FINV ## Returnerer den inverse fraktilsandsynlighed for F-fordelingen -FISHER = FISHER ## Returnerer Fisher-transformationen -FISHERINV = FISHERINV ## Returnerer den inverse Fisher-transformation -FORECAST = PROGNOSE ## Returnerer en prognoseværdi baseret på lineær tendens -FREQUENCY = FREKVENS ## Returnerer en frekvensfordeling i en søjlevektor -FTEST = FTEST ## Returnerer resultatet af en F-test til sammenligning af varians -GAMMADIST = GAMMAFORDELING ## Returnerer fordelingsfunktionen for gammafordelingen -GAMMAINV = GAMMAINV ## Returnerer den inverse fordelingsfunktion for gammafordelingen -GAMMALN = GAMMALN ## Returnerer den naturlige logaritme til gammafordelingen, G(x) -GEOMEAN = GEOMIDDELVÆRDI ## Returnerer det geometriske gennemsnit -GROWTH = FORØGELSE ## Returnerer værdier langs en eksponentiel tendens -HARMEAN = HARMIDDELVÆRDI ## Returnerer det harmoniske gennemsnit -HYPGEOMDIST = HYPGEOFORDELING ## Returnerer punktsandsynligheden i en hypergeometrisk fordeling -INTERCEPT = SKÆRING ## Returnerer afskæringsværdien på y-aksen i en lineær regression -KURT = TOPSTEJL ## Returnerer kurtosisværdien for en stokastisk variabel -LARGE = STOR ## Returnerer den k'te største værdi i et datasæt -LINEST = LINREGR ## Returnerer parameterestimaterne for en lineær tendens -LOGEST = LOGREGR ## Returnerer parameterestimaterne for en eksponentiel tendens -LOGINV = LOGINV ## Returnerer den inverse fordelingsfunktion for lognormalfordelingen -LOGNORMDIST = LOGNORMFORDELING ## Returnerer fordelingsfunktionen for lognormalfordelingen -MAX = MAKS ## Returnerer den maksimale værdi på en liste med argumenter. -MAXA = MAKSV ## Returnerer den maksimale værdi på en liste med argumenter og medtager tal, tekst og logiske værdier -MEDIAN = MEDIAN ## Returnerer medianen for de angivne tal -MIN = MIN ## Returnerer den mindste værdi på en liste med argumenter. -MINA = MINV ## Returnerer den mindste værdi på en liste med argumenter og medtager tal, tekst og logiske værdier -MODE = HYPPIGST ## Returnerer den hyppigste værdi i et datasæt -NEGBINOMDIST = NEGBINOMFORDELING ## Returnerer den negative binomialfordeling -NORMDIST = NORMFORDELING ## Returnerer fordelingsfunktionen for normalfordelingen -NORMINV = NORMINV ## Returnerer den inverse fordelingsfunktion for normalfordelingen -NORMSDIST = STANDARDNORMFORDELING ## Returnerer fordelingsfunktionen for standardnormalfordelingen -NORMSINV = STANDARDNORMINV ## Returnerer den inverse fordelingsfunktion for standardnormalfordelingen -PEARSON = PEARSON ## Returnerer Pearsons korrelationskoefficient -PERCENTILE = FRAKTIL ## Returnerer den k'te fraktil for datasættet -PERCENTRANK = PROCENTPLADS ## Returnerer den procentuelle rang for en given værdi i et datasæt -PERMUT = PERMUT ## Returnerer antallet af permutationer for et givet sæt objekter -POISSON = POISSON ## Returnerer fordelingsfunktionen for en Poisson-fordeling -PROB = SANDSYNLIGHED ## Returnerer intervalsandsynligheden -QUARTILE = KVARTIL ## Returnerer kvartilen i et givet datasæt -RANK = PLADS ## Returnerer rangen for et tal på en liste med tal -RSQ = FORKLARINGSGRAD ## Returnerer R2-værdien fra en simpel lineær regression -SKEW = SKÆVHED ## Returnerer skævheden for en stokastisk variabel -SLOPE = HÆLDNING ## Returnerer estimatet på hældningen fra en simpel lineær regression -SMALL = MINDSTE ## Returnerer den k'te mindste værdi i datasættet -STANDARDIZE = STANDARDISER ## Returnerer en standardiseret værdi -STDEV = STDAFV ## Estimerer standardafvigelsen på basis af en stikprøve -STDEVA = STDAFVV ## Beregner standardafvigelsen på basis af en prøve og medtager tal, tekst og logiske værdier -STDEVP = STDAFVP ## Beregner standardafvigelsen på basis af en hel population -STDEVPA = STDAFVPV ## Beregner standardafvigelsen på basis af en hel population og medtager tal, tekst og logiske værdier -STEYX = STFYX ## Returnerer standardafvigelsen for de estimerede y-værdier i den simple lineære regression -TDIST = TFORDELING ## Returnerer fordelingsfunktionen for Student's t-fordeling -TINV = TINV ## Returnerer den inverse fordelingsfunktion for Student's t-fordeling -TREND = TENDENS ## Returnerer værdi under antagelse af en lineær tendens -TRIMMEAN = TRIMMIDDELVÆRDI ## Returnerer den trimmede middelværdi for datasættet -TTEST = TTEST ## Returnerer den sandsynlighed, der er forbundet med Student's t-test -VAR = VARIANS ## Beregner variansen på basis af en prøve -VARA = VARIANSV ## Beregner variansen på basis af en prøve og medtager tal, tekst og logiske værdier -VARP = VARIANSP ## Beregner variansen på basis af hele populationen -VARPA = VARIANSPV ## Beregner variansen på basis af hele populationen og medtager tal, tekst og logiske værdier -WEIBULL = WEIBULL ## Returnerer fordelingsfunktionen for Weibull-fordelingen -ZTEST = ZTEST ## Returnerer sandsynlighedsværdien ved en en-sidet z-test - +BAHTTEXT = BAHTTEKST +CHAR = TEGN +CLEAN = RENS +CODE = KODE +CONCAT = CONCAT +DOLLAR = KR +EXACT = EKSAKT +FIND = FIND +FIXED = FAST +ISTHAIDIGIT = ERTHAILANDSKCIFFER +LEFT = VENSTRE +LEN = LÆNGDE +LOWER = SMÅ.BOGSTAVER +MID = MIDT +NUMBERSTRING = TALSTRENG +NUMBERVALUE = TALVÆRDI +PHONETIC = FONETISK +PROPER = STORT.FORBOGSTAV +REPLACE = ERSTAT +REPT = GENTAG +RIGHT = HØJRE +SEARCH = SØG +SUBSTITUTE = UDSKIFT +T = T +TEXT = TEKST +TEXTJOIN = TEKST.KOMBINER +THAIDIGIT = THAILANDSKCIFFER +THAINUMSOUND = THAILANDSKNUMLYD +THAINUMSTRING = THAILANDSKNUMSTRENG +THAISTRINGLENGTH = THAILANDSKSTRENGLÆNGDE +TRIM = FJERN.OVERFLØDIGE.BLANKE +UNICHAR = UNICHAR +UNICODE = UNICODE +UPPER = STORE.BOGSTAVER +VALUE = VÆRDI ## -## Text functions Tekstfunktioner +## Webfunktioner (Web Functions) ## -ASC = ASC ## Ændrer engelske tegn i fuld bredde (dobbelt-byte) eller katakana i en tegnstreng til tegn i halv bredde (enkelt-byte) -BAHTTEXT = BAHTTEKST ## Konverterer et tal til tekst ved hjælp af valutaformatet ß (baht) -CHAR = TEGN ## Returnerer det tegn, der svarer til kodenummeret -CLEAN = RENS ## Fjerner alle tegn, der ikke kan udskrives, fra tekst -CODE = KODE ## Returnerer en numerisk kode for det første tegn i en tekststreng -CONCATENATE = SAMMENKÆDNING ## Sammenkæder adskillige tekstelementer til ét tekstelement -DOLLAR = KR ## Konverterer et tal til tekst ved hjælp af valutaformatet kr. (kroner) -EXACT = EKSAKT ## Kontrollerer, om to tekstværdier er identiske -FIND = FIND ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes mellem store og små bogstaver) -FINDB = FINDB ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes mellem store og små bogstaver) -FIXED = FAST ## Formaterer et tal som tekst med et fast antal decimaler -JIS = JIS ## Ændrer engelske tegn i halv bredde (enkelt-byte) eller katakana i en tegnstreng til tegn i fuld bredde (dobbelt-byte) -LEFT = VENSTRE ## Returnerer tegnet længst til venstre i en tekstværdi -LEFTB = VENSTREB ## Returnerer tegnet længst til venstre i en tekstværdi -LEN = LÆNGDE ## Returnerer antallet af tegn i en tekststreng -LENB = LÆNGDEB ## Returnerer antallet af tegn i en tekststreng -LOWER = SMÅ.BOGSTAVER ## Konverterer tekst til små bogstaver -MID = MIDT ## Returnerer et bestemt antal tegn fra en tekststreng fra og med den angivne startposition -MIDB = MIDTB ## Returnerer et bestemt antal tegn fra en tekststreng fra og med den angivne startposition -PHONETIC = FONETISK ## Uddrager de fonetiske (furigana) tegn fra en tekststreng -PROPER = STORT.FORBOGSTAV ## Konverterer første bogstav i hvert ord i teksten til stort bogstav -REPLACE = ERSTAT ## Erstatter tegn i tekst -REPLACEB = ERSTATB ## Erstatter tegn i tekst -REPT = GENTAG ## Gentager tekst et givet antal gange -RIGHT = HØJRE ## Returnerer tegnet længste til højre i en tekstværdi -RIGHTB = HØJREB ## Returnerer tegnet længste til højre i en tekstværdi -SEARCH = SØG ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes ikke mellem store og små bogstaver) -SEARCHB = SØGB ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes ikke mellem store og små bogstaver) -SUBSTITUTE = UDSKIFT ## Udskifter gammel tekst med ny tekst i en tekststreng -T = T ## Konverterer argumenterne til tekst -TEXT = TEKST ## Formaterer et tal og konverterer det til tekst -TRIM = FJERN.OVERFLØDIGE.BLANKE ## Fjerner mellemrum fra tekst -UPPER = STORE.BOGSTAVER ## Konverterer tekst til store bogstaver -VALUE = VÆRDI ## Konverterer et tekstargument til et tal +ENCODEURL = KODNINGSURL +FILTERXML = FILTRERXML +WEBSERVICE = WEBTJENESTE + +## +## Kompatibilitetsfunktioner (Compatibility Functions) +## +BETADIST = BETAFORDELING +BETAINV = BETAINV +BINOMDIST = BINOMIALFORDELING +CEILING = AFRUND.LOFT +CHIDIST = CHIFORDELING +CHIINV = CHIINV +CHITEST = CHITEST +CONCATENATE = SAMMENKÆDNING +CONFIDENCE = KONFIDENSINTERVAL +COVAR = KOVARIANS +CRITBINOM = KRITBINOM +EXPONDIST = EKSPFORDELING +FDIST = FFORDELING +FINV = FINV +FLOOR = AFRUND.GULV +FORECAST = PROGNOSE +FTEST = FTEST +GAMMADIST = GAMMAFORDELING +GAMMAINV = GAMMAINV +HYPGEOMDIST = HYPGEOFORDELING +LOGINV = LOGINV +LOGNORMDIST = LOGNORMFORDELING +MODE = HYPPIGST +NEGBINOMDIST = NEGBINOMFORDELING +NORMDIST = NORMFORDELING +NORMINV = NORMINV +NORMSDIST = STANDARDNORMFORDELING +NORMSINV = STANDARDNORMINV +PERCENTILE = FRAKTIL +PERCENTRANK = PROCENTPLADS +POISSON = POISSON +QUARTILE = KVARTIL +RANK = PLADS +STDEV = STDAFV +STDEVP = STDAFVP +TDIST = TFORDELING +TINV = TINV +TTEST = TTEST +VAR = VARIANS +VARP = VARIANSP +WEIBULL = WEIBULL +ZTEST = ZTEST diff --git a/src/PhpSpreadsheet/Calculation/locale/de/config b/src/PhpSpreadsheet/Calculation/locale/de/config index 9751c4b6..4ca2b82b 100644 --- a/src/PhpSpreadsheet/Calculation/locale/de/config +++ b/src/PhpSpreadsheet/Calculation/locale/de/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## +## Deutsch (German) +## +############################################################ -ArgumentSeparator = ; - +ArgumentSeparator = ; ## -## (For future use) +## Error Codes ## -currencySymbol = € - - -## -## Excel Error Codes (For future use) - -## -NULL = #NULL! -DIV0 = #DIV/0! -VALUE = #WERT! -REF = #BEZUG! -NAME = #NAME? -NUM = #ZAHL! -NA = #NV +NULL +DIV0 +VALUE = #WERT! +REF = #BEZUG! +NAME +NUM = #ZAHL! +NA = #NV diff --git a/src/PhpSpreadsheet/Calculation/locale/de/functions b/src/PhpSpreadsheet/Calculation/locale/de/functions index 01df42f6..331232f7 100644 --- a/src/PhpSpreadsheet/Calculation/locale/de/functions +++ b/src/PhpSpreadsheet/Calculation/locale/de/functions @@ -1,416 +1,533 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Deutsch (German) ## +############################################################ ## -## Add-in and Automation functions Add-In- und Automatisierungsfunktionen +## Cubefunktionen (Cube Functions) ## -GETPIVOTDATA = PIVOTDATENZUORDNEN ## In einem PivotTable-Bericht gespeicherte Daten werden zurückgegeben. - +CUBEKPIMEMBER = CUBEKPIELEMENT +CUBEMEMBER = CUBEELEMENT +CUBEMEMBERPROPERTY = CUBEELEMENTEIGENSCHAFT +CUBERANKEDMEMBER = CUBERANGELEMENT +CUBESET = CUBEMENGE +CUBESETCOUNT = CUBEMENGENANZAHL +CUBEVALUE = CUBEWERT ## -## Cube functions Cubefunktionen +## Datenbankfunktionen (Database Functions) ## -CUBEKPIMEMBER = CUBEKPIELEMENT ## Gibt Name, Eigenschaft und Measure eines Key Performance Indicators (KPI) zurück und zeigt den Namen und die Eigenschaft in der Zelle an. Ein KPI ist ein quantifizierbares Maß, wie z. B. der monatliche Bruttogewinn oder die vierteljährliche Mitarbeiterfluktuation, mit dessen Hilfe das Leistungsverhalten eines Unternehmens überwacht werden kann. -CUBEMEMBER = CUBEELEMENT ## Gibt ein Element oder ein Tuple in einer Cubehierarchie zurück. Wird verwendet, um zu überprüfen, ob das Element oder Tuple im Cube vorhanden ist. -CUBEMEMBERPROPERTY = CUBEELEMENTEIGENSCHAFT ## Gibt den Wert einer Elementeigenschaft im Cube zurück. Wird verwendet, um zu überprüfen, ob ein Elementname im Cube vorhanden ist, und um die für dieses Element angegebene Eigenschaft zurückzugeben. -CUBERANKEDMEMBER = CUBERANGELEMENT ## Gibt das n-te oder n-rangige Element in einer Menge zurück. Wird verwendet, um mindestens ein Element in einer Menge zurückzugeben, wie z. B. bester Vertriebsmitarbeiter oder 10 beste Kursteilnehmer. -CUBESET = CUBEMENGE ## Definiert eine berechnete Menge Elemente oder Tuples durch Senden eines Mengenausdrucks an den Cube auf dem Server, der die Menge erstellt und an Microsoft Office Excel zurückgibt. -CUBESETCOUNT = CUBEMENGENANZAHL ## Gibt die Anzahl der Elemente in einer Menge zurück. -CUBEVALUE = CUBEWERT ## Gibt einen Aggregatwert aus einem Cube zurück. - +DAVERAGE = DBMITTELWERT +DCOUNT = DBANZAHL +DCOUNTA = DBANZAHL2 +DGET = DBAUSZUG +DMAX = DBMAX +DMIN = DBMIN +DPRODUCT = DBPRODUKT +DSTDEV = DBSTDABW +DSTDEVP = DBSTDABWN +DSUM = DBSUMME +DVAR = DBVARIANZ +DVARP = DBVARIANZEN ## -## Database functions Datenbankfunktionen +## Datums- und Uhrzeitfunktionen (Date & Time Functions) ## -DAVERAGE = DBMITTELWERT ## Gibt den Mittelwert der ausgewählten Datenbankeinträge zurück -DCOUNT = DBANZAHL ## Zählt die Zellen mit Zahlen in einer Datenbank -DCOUNTA = DBANZAHL2 ## Zählt nicht leere Zellen in einer Datenbank -DGET = DBAUSZUG ## Extrahiert aus einer Datenbank einen einzelnen Datensatz, der den angegebenen Kriterien entspricht -DMAX = DBMAX ## Gibt den größten Wert aus ausgewählten Datenbankeinträgen zurück -DMIN = DBMIN ## Gibt den kleinsten Wert aus ausgewählten Datenbankeinträgen zurück -DPRODUCT = DBPRODUKT ## Multipliziert die Werte in einem bestimmten Feld mit Datensätzen, die den Kriterien in einer Datenbank entsprechen -DSTDEV = DBSTDABW ## Schätzt die Standardabweichung auf der Grundlage einer Stichprobe aus ausgewählten Datenbankeinträgen -DSTDEVP = DBSTDABWN ## Berechnet die Standardabweichung auf der Grundlage der Grundgesamtheit ausgewählter Datenbankeinträge -DSUM = DBSUMME ## Addiert die Zahlen in der Feldspalte mit Datensätzen in der Datenbank, die den Kriterien entsprechen -DVAR = DBVARIANZ ## Schätzt die Varianz auf der Grundlage ausgewählter Datenbankeinträge -DVARP = DBVARIANZEN ## Berechnet die Varianz auf der Grundlage der Grundgesamtheit ausgewählter Datenbankeinträge - +DATE = DATUM +DATEVALUE = DATWERT +DAY = TAG +DAYS = TAGE +DAYS360 = TAGE360 +EDATE = EDATUM +EOMONTH = MONATSENDE +HOUR = STUNDE +ISOWEEKNUM = ISOKALENDERWOCHE +MINUTE = MINUTE +MONTH = MONAT +NETWORKDAYS = NETTOARBEITSTAGE +NETWORKDAYS.INTL = NETTOARBEITSTAGE.INTL +NOW = JETZT +SECOND = SEKUNDE +THAIDAYOFWEEK = THAIWOCHENTAG +THAIMONTHOFYEAR = THAIMONATDESJAHRES +THAIYEAR = THAIJAHR +TIME = ZEIT +TIMEVALUE = ZEITWERT +TODAY = HEUTE +WEEKDAY = WOCHENTAG +WEEKNUM = KALENDERWOCHE +WORKDAY = ARBEITSTAG +WORKDAY.INTL = ARBEITSTAG.INTL +YEAR = JAHR +YEARFRAC = BRTEILJAHRE ## -## Date and time functions Datums- und Zeitfunktionen +## Technische Funktionen (Engineering Functions) ## -DATE = DATUM ## Gibt die fortlaufende Zahl eines bestimmten Datums zurück -DATEVALUE = DATWERT ## Wandelt ein Datum in Form von Text in eine fortlaufende Zahl um -DAY = TAG ## Wandelt eine fortlaufende Zahl in den Tag des Monats um -DAYS360 = TAGE360 ## Berechnet die Anzahl der Tage zwischen zwei Datumsangaben ausgehend von einem Jahr, das 360 Tage hat -EDATE = EDATUM ## Gibt die fortlaufende Zahl des Datums zurück, bei dem es sich um die angegebene Anzahl von Monaten vor oder nach dem Anfangstermin handelt -EOMONTH = MONATSENDE ## Gibt die fortlaufende Zahl des letzten Tags des Monats vor oder nach einer festgelegten Anzahl von Monaten zurück -HOUR = STUNDE ## Wandelt eine fortlaufende Zahl in eine Stunde um -MINUTE = MINUTE ## Wandelt eine fortlaufende Zahl in eine Minute um -MONTH = MONAT ## Wandelt eine fortlaufende Zahl in einen Monat um -NETWORKDAYS = NETTOARBEITSTAGE ## Gibt die Anzahl von ganzen Arbeitstagen zwischen zwei Datumswerten zurück -NOW = JETZT ## Gibt die fortlaufende Zahl des aktuellen Datums und der aktuellen Uhrzeit zurück -SECOND = SEKUNDE ## Wandelt eine fortlaufende Zahl in eine Sekunde um -TIME = ZEIT ## Gibt die fortlaufende Zahl einer bestimmten Uhrzeit zurück -TIMEVALUE = ZEITWERT ## Wandelt eine Uhrzeit in Form von Text in eine fortlaufende Zahl um -TODAY = HEUTE ## Gibt die fortlaufende Zahl des heutigen Datums zurück -WEEKDAY = WOCHENTAG ## Wandelt eine fortlaufende Zahl in den Wochentag um -WEEKNUM = KALENDERWOCHE ## Wandelt eine fortlaufende Zahl in eine Zahl um, die angibt, in welche Woche eines Jahres das angegebene Datum fällt -WORKDAY = ARBEITSTAG ## Gibt die fortlaufende Zahl des Datums vor oder nach einer bestimmten Anzahl von Arbeitstagen zurück -YEAR = JAHR ## Wandelt eine fortlaufende Zahl in ein Jahr um -YEARFRAC = BRTEILJAHRE ## Gibt die Anzahl der ganzen Tage zwischen Ausgangsdatum und Enddatum in Bruchteilen von Jahren zurück - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BININDEZ +BIN2HEX = BININHEX +BIN2OCT = BININOKT +BITAND = BITUND +BITLSHIFT = BITLVERSCHIEB +BITOR = BITODER +BITRSHIFT = BITRVERSCHIEB +BITXOR = BITXODER +COMPLEX = KOMPLEXE +CONVERT = UMWANDELN +DEC2BIN = DEZINBIN +DEC2HEX = DEZINHEX +DEC2OCT = DEZINOKT +DELTA = DELTA +ERF = GAUSSFEHLER +ERF.PRECISE = GAUSSF.GENAU +ERFC = GAUSSFKOMPL +ERFC.PRECISE = GAUSSFKOMPL.GENAU +GESTEP = GGANZZAHL +HEX2BIN = HEXINBIN +HEX2DEC = HEXINDEZ +HEX2OCT = HEXINOKT +IMABS = IMABS +IMAGINARY = IMAGINÄRTEIL +IMARGUMENT = IMARGUMENT +IMCONJUGATE = IMKONJUGIERTE +IMCOS = IMCOS +IMCOSH = IMCOSHYP +IMCOT = IMCOT +IMCSC = IMCOSEC +IMCSCH = IMCOSECHYP +IMDIV = IMDIV +IMEXP = IMEXP +IMLN = IMLN +IMLOG10 = IMLOG10 +IMLOG2 = IMLOG2 +IMPOWER = IMAPOTENZ +IMPRODUCT = IMPRODUKT +IMREAL = IMREALTEIL +IMSEC = IMSEC +IMSECH = IMSECHYP +IMSIN = IMSIN +IMSINH = IMSINHYP +IMSQRT = IMWURZEL +IMSUB = IMSUB +IMSUM = IMSUMME +IMTAN = IMTAN +OCT2BIN = OKTINBIN +OCT2DEC = OKTINDEZ +OCT2HEX = OKTINHEX ## -## Engineering functions Konstruktionsfunktionen +## Finanzmathematische Funktionen (Financial Functions) ## -BESSELI = BESSELI ## Gibt die geänderte Besselfunktion In(x) zurück -BESSELJ = BESSELJ ## Gibt die Besselfunktion Jn(x) zurück -BESSELK = BESSELK ## Gibt die geänderte Besselfunktion Kn(x) zurück -BESSELY = BESSELY ## Gibt die Besselfunktion Yn(x) zurück -BIN2DEC = BININDEZ ## Wandelt eine binäre Zahl (Dualzahl) in eine dezimale Zahl um -BIN2HEX = BININHEX ## Wandelt eine binäre Zahl (Dualzahl) in eine hexadezimale Zahl um -BIN2OCT = BININOKT ## Wandelt eine binäre Zahl (Dualzahl) in eine oktale Zahl um -COMPLEX = KOMPLEXE ## Wandelt den Real- und Imaginärteil in eine komplexe Zahl um -CONVERT = UMWANDELN ## Wandelt eine Zahl von einem Maßsystem in ein anderes um -DEC2BIN = DEZINBIN ## Wandelt eine dezimale Zahl in eine binäre Zahl (Dualzahl) um -DEC2HEX = DEZINHEX ## Wandelt eine dezimale Zahl in eine hexadezimale Zahl um -DEC2OCT = DEZINOKT ## Wandelt eine dezimale Zahl in eine oktale Zahl um -DELTA = DELTA ## Überprüft, ob zwei Werte gleich sind -ERF = GAUSSFEHLER ## Gibt die Gauss'sche Fehlerfunktion zurück -ERFC = GAUSSFKOMPL ## Gibt das Komplement zur Gauss'schen Fehlerfunktion zurück -GESTEP = GGANZZAHL ## Überprüft, ob eine Zahl größer als ein gegebener Schwellenwert ist -HEX2BIN = HEXINBIN ## Wandelt eine hexadezimale Zahl in eine Binärzahl um -HEX2DEC = HEXINDEZ ## Wandelt eine hexadezimale Zahl in eine dezimale Zahl um -HEX2OCT = HEXINOKT ## Wandelt eine hexadezimale Zahl in eine Oktalzahl um -IMABS = IMABS ## Gibt den Absolutbetrag (Modulo) einer komplexen Zahl zurück -IMAGINARY = IMAGINÄRTEIL ## Gibt den Imaginärteil einer komplexen Zahl zurück -IMARGUMENT = IMARGUMENT ## Gibt das Argument Theta zurück, einen Winkel, der als Bogenmaß ausgedrückt wird -IMCONJUGATE = IMKONJUGIERTE ## Gibt die konjugierte komplexe Zahl zu einer komplexen Zahl zurück -IMCOS = IMCOS ## Gibt den Kosinus einer komplexen Zahl zurück -IMDIV = IMDIV ## Gibt den Quotienten zweier komplexer Zahlen zurück -IMEXP = IMEXP ## Gibt die algebraische Form einer in exponentieller Schreibweise vorliegenden komplexen Zahl zurück -IMLN = IMLN ## Gibt den natürlichen Logarithmus einer komplexen Zahl zurück -IMLOG10 = IMLOG10 ## Gibt den Logarithmus einer komplexen Zahl zur Basis 10 zurück -IMLOG2 = IMLOG2 ## Gibt den Logarithmus einer komplexen Zahl zur Basis 2 zurück -IMPOWER = IMAPOTENZ ## Potenziert eine komplexe Zahl mit einer ganzen Zahl -IMPRODUCT = IMPRODUKT ## Gibt das Produkt von komplexen Zahlen zurück -IMREAL = IMREALTEIL ## Gibt den Realteil einer komplexen Zahl zurück -IMSIN = IMSIN ## Gibt den Sinus einer komplexen Zahl zurück -IMSQRT = IMWURZEL ## Gibt die Quadratwurzel einer komplexen Zahl zurück -IMSUB = IMSUB ## Gibt die Differenz zwischen zwei komplexen Zahlen zurück -IMSUM = IMSUMME ## Gibt die Summe von komplexen Zahlen zurück -OCT2BIN = OKTINBIN ## Wandelt eine oktale Zahl in eine binäre Zahl (Dualzahl) um -OCT2DEC = OKTINDEZ ## Wandelt eine oktale Zahl in eine dezimale Zahl um -OCT2HEX = OKTINHEX ## Wandelt eine oktale Zahl in eine hexadezimale Zahl um - +ACCRINT = AUFGELZINS +ACCRINTM = AUFGELZINSF +AMORDEGRC = AMORDEGRK +AMORLINC = AMORLINEARK +COUPDAYBS = ZINSTERMTAGVA +COUPDAYS = ZINSTERMTAGE +COUPDAYSNC = ZINSTERMTAGNZ +COUPNCD = ZINSTERMNZ +COUPNUM = ZINSTERMZAHL +COUPPCD = ZINSTERMVZ +CUMIPMT = KUMZINSZ +CUMPRINC = KUMKAPITAL +DB = GDA2 +DDB = GDA +DISC = DISAGIO +DOLLARDE = NOTIERUNGDEZ +DOLLARFR = NOTIERUNGBRU +DURATION = DURATION +EFFECT = EFFEKTIV +FV = ZW +FVSCHEDULE = ZW2 +INTRATE = ZINSSATZ +IPMT = ZINSZ +IRR = IKV +ISPMT = ISPMT +MDURATION = MDURATION +MIRR = QIKV +NOMINAL = NOMINAL +NPER = ZZR +NPV = NBW +ODDFPRICE = UNREGER.KURS +ODDFYIELD = UNREGER.REND +ODDLPRICE = UNREGLE.KURS +ODDLYIELD = UNREGLE.REND +PDURATION = PDURATION +PMT = RMZ +PPMT = KAPZ +PRICE = KURS +PRICEDISC = KURSDISAGIO +PRICEMAT = KURSFÄLLIG +PV = BW +RATE = ZINS +RECEIVED = AUSZAHLUNG +RRI = ZSATZINVEST +SLN = LIA +SYD = DIA +TBILLEQ = TBILLÄQUIV +TBILLPRICE = TBILLKURS +TBILLYIELD = TBILLRENDITE +VDB = VDB +XIRR = XINTZINSFUSS +XNPV = XKAPITALWERT +YIELD = RENDITE +YIELDDISC = RENDITEDIS +YIELDMAT = RENDITEFÄLL ## -## Financial functions Finanzmathematische Funktionen +## Informationsfunktionen (Information Functions) ## -ACCRINT = AUFGELZINS ## Gibt die aufgelaufenen Zinsen (Stückzinsen) eines Wertpapiers mit periodischen Zinszahlungen zurück -ACCRINTM = AUFGELZINSF ## Gibt die aufgelaufenen Zinsen (Stückzinsen) eines Wertpapiers zurück, die bei Fälligkeit ausgezahlt werden -AMORDEGRC = AMORDEGRK ## Gibt die Abschreibung für die einzelnen Abschreibungszeiträume mithilfe eines Abschreibungskoeffizienten zurück -AMORLINC = AMORLINEARK ## Gibt die Abschreibung für die einzelnen Abschreibungszeiträume zurück -COUPDAYBS = ZINSTERMTAGVA ## Gibt die Anzahl der Tage vom Anfang des Zinstermins bis zum Abrechnungstermin zurück -COUPDAYS = ZINSTERMTAGE ## Gibt die Anzahl der Tage der Zinsperiode zurück, die den Abrechnungstermin einschließt -COUPDAYSNC = ZINSTERMTAGNZ ## Gibt die Anzahl der Tage vom Abrechnungstermin bis zum nächsten Zinstermin zurück -COUPNCD = ZINSTERMNZ ## Gibt das Datum des ersten Zinstermins nach dem Abrechnungstermin zurück -COUPNUM = ZINSTERMZAHL ## Gibt die Anzahl der Zinstermine zwischen Abrechnungs- und Fälligkeitsdatum zurück -COUPPCD = ZINSTERMVZ ## Gibt das Datum des letzten Zinstermins vor dem Abrechnungstermin zurück -CUMIPMT = KUMZINSZ ## Berechnet die kumulierten Zinsen, die zwischen zwei Perioden zu zahlen sind -CUMPRINC = KUMKAPITAL ## Berechnet die aufgelaufene Tilgung eines Darlehens, die zwischen zwei Perioden zu zahlen ist -DB = GDA2 ## Gibt die geometrisch-degressive Abschreibung eines Wirtschaftsguts für eine bestimmte Periode zurück -DDB = GDA ## Gibt die Abschreibung eines Anlageguts für einen angegebenen Zeitraum unter Verwendung der degressiven Doppelraten-Abschreibung oder eines anderen von Ihnen angegebenen Abschreibungsverfahrens zurück -DISC = DISAGIO ## Gibt den in Prozent ausgedrückten Abzinsungssatz eines Wertpapiers zurück -DOLLARDE = NOTIERUNGDEZ ## Wandelt eine Notierung, die als Dezimalbruch ausgedrückt wurde, in eine Dezimalzahl um -DOLLARFR = NOTIERUNGBRU ## Wandelt eine Notierung, die als Dezimalzahl ausgedrückt wurde, in einen Dezimalbruch um -DURATION = DURATION ## Gibt die jährliche Duration eines Wertpapiers mit periodischen Zinszahlungen zurück -EFFECT = EFFEKTIV ## Gibt die jährliche Effektivverzinsung zurück -FV = ZW ## Gibt den zukünftigen Wert (Endwert) einer Investition zurück -FVSCHEDULE = ZW2 ## Gibt den aufgezinsten Wert des Anfangskapitals für eine Reihe periodisch unterschiedlicher Zinssätze zurück -INTRATE = ZINSSATZ ## Gibt den Zinssatz eines voll investierten Wertpapiers zurück -IPMT = ZINSZ ## Gibt die Zinszahlung einer Investition für die angegebene Periode zurück -IRR = IKV ## Gibt den internen Zinsfuß einer Investition ohne Finanzierungskosten oder Reinvestitionsgewinne zurück -ISPMT = ISPMT ## Berechnet die während eines bestimmten Zeitraums für eine Investition gezahlten Zinsen -MDURATION = MDURATION ## Gibt die geänderte Dauer für ein Wertpapier mit einem angenommenen Nennwert von 100 € zurück -MIRR = QIKV ## Gibt den internen Zinsfuß zurück, wobei positive und negative Zahlungen zu unterschiedlichen Sätzen finanziert werden -NOMINAL = NOMINAL ## Gibt die jährliche Nominalverzinsung zurück -NPER = ZZR ## Gibt die Anzahl der Zahlungsperioden einer Investition zurück -NPV = NBW ## Gibt den Nettobarwert einer Investition auf Basis periodisch anfallender Zahlungen und eines Abzinsungsfaktors zurück -ODDFPRICE = UNREGER.KURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers mit einem unregelmäßigen ersten Zinstermin zurück -ODDFYIELD = UNREGER.REND ## Gibt die Rendite eines Wertpapiers mit einem unregelmäßigen ersten Zinstermin zurück -ODDLPRICE = UNREGLE.KURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers mit einem unregelmäßigen letzten Zinstermin zurück -ODDLYIELD = UNREGLE.REND ## Gibt die Rendite eines Wertpapiers mit einem unregelmäßigen letzten Zinstermin zurück -PMT = RMZ ## Gibt die periodische Zahlung für eine Annuität zurück -PPMT = KAPZ ## Gibt die Kapitalrückzahlung einer Investition für eine angegebene Periode zurück -PRICE = KURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers zurück, das periodisch Zinsen auszahlt -PRICEDISC = KURSDISAGIO ## Gibt den Kurs pro 100 € Nennwert eines unverzinslichen Wertpapiers zurück -PRICEMAT = KURSFÄLLIG ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers zurück, das Zinsen am Fälligkeitsdatum auszahlt -PV = BW ## Gibt den Barwert einer Investition zurück -RATE = ZINS ## Gibt den Zinssatz pro Zeitraum einer Annuität zurück -RECEIVED = AUSZAHLUNG ## Gibt den Auszahlungsbetrag eines voll investierten Wertpapiers am Fälligkeitstermin zurück -SLN = LIA ## Gibt die lineare Abschreibung eines Wirtschaftsguts pro Periode zurück -SYD = DIA ## Gibt die arithmetisch-degressive Abschreibung eines Wirtschaftsguts für eine bestimmte Periode zurück -TBILLEQ = TBILLÄQUIV ## Gibt die Rendite für ein Wertpapier zurück -TBILLPRICE = TBILLKURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers zurück -TBILLYIELD = TBILLRENDITE ## Gibt die Rendite für ein Wertpapier zurück -VDB = VDB ## Gibt die degressive Abschreibung eines Wirtschaftsguts für eine bestimmte Periode oder Teilperiode zurück -XIRR = XINTZINSFUSS ## Gibt den internen Zinsfuß einer Reihe nicht periodisch anfallender Zahlungen zurück -XNPV = XKAPITALWERT ## Gibt den Nettobarwert (Kapitalwert) einer Reihe nicht periodisch anfallender Zahlungen zurück -YIELD = RENDITE ## Gibt die Rendite eines Wertpapiers zurück, das periodisch Zinsen auszahlt -YIELDDISC = RENDITEDIS ## Gibt die jährliche Rendite eines unverzinslichen Wertpapiers zurück -YIELDMAT = RENDITEFÄLL ## Gibt die jährliche Rendite eines Wertpapiers zurück, das Zinsen am Fälligkeitsdatum auszahlt - +CELL = ZELLE +ERROR.TYPE = FEHLER.TYP +INFO = INFO +ISBLANK = ISTLEER +ISERR = ISTFEHL +ISERROR = ISTFEHLER +ISEVEN = ISTGERADE +ISFORMULA = ISTFORMEL +ISLOGICAL = ISTLOG +ISNA = ISTNV +ISNONTEXT = ISTKTEXT +ISNUMBER = ISTZAHL +ISODD = ISTUNGERADE +ISREF = ISTBEZUG +ISTEXT = ISTTEXT +N = N +NA = NV +SHEET = BLATT +SHEETS = BLÄTTER +TYPE = TYP ## -## Information functions Informationsfunktionen +## Logische Funktionen (Logical Functions) ## -CELL = ZELLE ## Gibt Informationen zu Formatierung, Position oder Inhalt einer Zelle zurück -ERROR.TYPE = FEHLER.TYP ## Gibt eine Zahl zurück, die einem Fehlertyp entspricht -INFO = INFO ## Gibt Informationen zur aktuellen Betriebssystemumgebung zurück -ISBLANK = ISTLEER ## Gibt WAHR zurück, wenn der Wert leer ist -ISERR = ISTFEHL ## Gibt WAHR zurück, wenn der Wert ein beliebiger Fehlerwert außer #N/V ist -ISERROR = ISTFEHLER ## Gibt WAHR zurück, wenn der Wert ein beliebiger Fehlerwert ist -ISEVEN = ISTGERADE ## Gibt WAHR zurück, wenn es sich um eine gerade Zahl handelt -ISLOGICAL = ISTLOG ## Gibt WAHR zurück, wenn der Wert ein Wahrheitswert ist -ISNA = ISTNV ## Gibt WAHR zurück, wenn der Wert der Fehlerwert #N/V ist -ISNONTEXT = ISTKTEXT ## Gibt WAHR zurück, wenn der Wert ein Element ist, das keinen Text enthält -ISNUMBER = ISTZAHL ## Gibt WAHR zurück, wenn der Wert eine Zahl ist -ISODD = ISTUNGERADE ## Gibt WAHR zurück, wenn es sich um eine ungerade Zahl handelt -ISREF = ISTBEZUG ## Gibt WAHR zurück, wenn der Wert ein Bezug ist -ISTEXT = ISTTEXT ## Gibt WAHR zurück, wenn der Wert ein Element ist, das Text enthält -N = N ## Gibt den in eine Zahl umgewandelten Wert zurück -NA = NV ## Gibt den Fehlerwert #NV zurück -TYPE = TYP ## Gibt eine Zahl zurück, die den Datentyp des angegebenen Werts anzeigt - +AND = UND +FALSE = FALSCH +IF = WENN +IFERROR = WENNFEHLER +IFNA = WENNNV +IFS = WENNS +NOT = NICHT +OR = ODER +SWITCH = ERSTERWERT +TRUE = WAHR +XOR = XODER ## -## Logical functions Logische Funktionen +## Nachschlage- und Verweisfunktionen (Lookup & Reference Functions) ## -AND = UND ## Gibt WAHR zurück, wenn alle zugehörigen Argumente WAHR sind -FALSE = FALSCH ## Gibt den Wahrheitswert FALSCH zurück -IF = WENN ## Gibt einen logischen Test zum Ausführen an -IFERROR = WENNFEHLER ## Gibt einen von Ihnen festgelegten Wert zurück, wenn die Auswertung der Formel zu einem Fehler führt; andernfalls wird das Ergebnis der Formel zurückgegeben -NOT = NICHT ## Kehrt den Wahrheitswert der zugehörigen Argumente um -OR = ODER ## Gibt WAHR zurück, wenn ein Argument WAHR ist -TRUE = WAHR ## Gibt den Wahrheitswert WAHR zurück - +ADDRESS = ADRESSE +AREAS = BEREICHE +CHOOSE = WAHL +COLUMN = SPALTE +COLUMNS = SPALTEN +FORMULATEXT = FORMELTEXT +GETPIVOTDATA = PIVOTDATENZUORDNEN +HLOOKUP = WVERWEIS +HYPERLINK = HYPERLINK +INDEX = INDEX +INDIRECT = INDIREKT +LOOKUP = VERWEIS +MATCH = VERGLEICH +OFFSET = BEREICH.VERSCHIEBEN +ROW = ZEILE +ROWS = ZEILEN +RTD = RTD +TRANSPOSE = MTRANS +VLOOKUP = SVERWEIS ## -## Lookup and reference functions Nachschlage- und Verweisfunktionen +## Mathematische und trigonometrische Funktionen (Math & Trig Functions) ## -ADDRESS = ADRESSE ## Gibt einen Bezug auf eine einzelne Zelle in einem Tabellenblatt als Text zurück -AREAS = BEREICHE ## Gibt die Anzahl der innerhalb eines Bezugs aufgeführten Bereiche zurück -CHOOSE = WAHL ## Wählt einen Wert aus eine Liste mit Werten aus -COLUMN = SPALTE ## Gibt die Spaltennummer eines Bezugs zurück -COLUMNS = SPALTEN ## Gibt die Anzahl der Spalten in einem Bezug zurück -HLOOKUP = HVERWEIS ## Sucht in der obersten Zeile einer Matrix und gibt den Wert der angegebenen Zelle zurück -HYPERLINK = HYPERLINK ## Erstellt eine Verknüpfung, über die ein auf einem Netzwerkserver, in einem Intranet oder im Internet gespeichertes Dokument geöffnet wird -INDEX = INDEX ## Verwendet einen Index, um einen Wert aus einem Bezug oder einer Matrix auszuwählen -INDIRECT = INDIREKT ## Gibt einen Bezug zurück, der von einem Textwert angegeben wird -LOOKUP = LOOKUP ## Sucht Werte in einem Vektor oder einer Matrix -MATCH = VERGLEICH ## Sucht Werte in einem Bezug oder einer Matrix -OFFSET = BEREICH.VERSCHIEBEN ## Gibt einen Bezugoffset aus einem gegebenen Bezug zurück -ROW = ZEILE ## Gibt die Zeilennummer eines Bezugs zurück -ROWS = ZEILEN ## Gibt die Anzahl der Zeilen in einem Bezug zurück -RTD = RTD ## Ruft Echtzeitdaten von einem Programm ab, das die COM-Automatisierung (Automatisierung: Ein Verfahren, bei dem aus einer Anwendung oder einem Entwicklungstool heraus mit den Objekten einer anderen Anwendung gearbeitet wird. Die früher als OLE-Automatisierung bezeichnete Automatisierung ist ein Industriestandard und eine Funktion von COM (Component Object Model).) unterstützt -TRANSPOSE = MTRANS ## Gibt die transponierte Matrix einer Matrix zurück -VLOOKUP = SVERWEIS ## Sucht in der ersten Spalte einer Matrix und arbeitet sich durch die Zeile, um den Wert einer Zelle zurückzugeben - +ABS = ABS +ACOS = ARCCOS +ACOSH = ARCCOSHYP +ACOT = ARCCOT +ACOTH = ARCCOTHYP +AGGREGATE = AGGREGAT +ARABIC = ARABISCH +ASIN = ARCSIN +ASINH = ARCSINHYP +ATAN = ARCTAN +ATAN2 = ARCTAN2 +ATANH = ARCTANHYP +BASE = BASIS +CEILING.MATH = OBERGRENZE.MATHEMATIK +CEILING.PRECISE = OBERGRENZE.GENAU +COMBIN = KOMBINATIONEN +COMBINA = KOMBINATIONEN2 +COS = COS +COSH = COSHYP +COT = COT +COTH = COTHYP +CSC = COSEC +CSCH = COSECHYP +DECIMAL = DEZIMAL +DEGREES = GRAD +ECMA.CEILING = ECMA.OBERGRENZE +EVEN = GERADE +EXP = EXP +FACT = FAKULTÄT +FACTDOUBLE = ZWEIFAKULTÄT +FLOOR.MATH = UNTERGRENZE.MATHEMATIK +FLOOR.PRECISE = UNTERGRENZE.GENAU +GCD = GGT +INT = GANZZAHL +ISO.CEILING = ISO.OBERGRENZE +LCM = KGV +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = MDET +MINVERSE = MINV +MMULT = MMULT +MOD = REST +MROUND = VRUNDEN +MULTINOMIAL = POLYNOMIAL +MUNIT = MEINHEIT +ODD = UNGERADE +PI = PI +POWER = POTENZ +PRODUCT = PRODUKT +QUOTIENT = QUOTIENT +RADIANS = BOGENMASS +RAND = ZUFALLSZAHL +RANDBETWEEN = ZUFALLSBEREICH +ROMAN = RÖMISCH +ROUND = RUNDEN +ROUNDBAHTDOWN = RUNDBAHTNED +ROUNDBAHTUP = BAHTAUFRUNDEN +ROUNDDOWN = ABRUNDEN +ROUNDUP = AUFRUNDEN +SEC = SEC +SECH = SECHYP +SERIESSUM = POTENZREIHE +SIGN = VORZEICHEN +SIN = SIN +SINH = SINHYP +SQRT = WURZEL +SQRTPI = WURZELPI +SUBTOTAL = TEILERGEBNIS +SUM = SUMME +SUMIF = SUMMEWENN +SUMIFS = SUMMEWENNS +SUMPRODUCT = SUMMENPRODUKT +SUMSQ = QUADRATESUMME +SUMX2MY2 = SUMMEX2MY2 +SUMX2PY2 = SUMMEX2PY2 +SUMXMY2 = SUMMEXMY2 +TAN = TAN +TANH = TANHYP +TRUNC = KÜRZEN ## -## Math and trigonometry functions Mathematische und trigonometrische Funktionen +## Statistische Funktionen (Statistical Functions) ## -ABS = ABS ## Gibt den Absolutwert einer Zahl zurück -ACOS = ARCCOS ## Gibt den Arkuskosinus einer Zahl zurück -ACOSH = ARCCOSHYP ## Gibt den umgekehrten hyperbolischen Kosinus einer Zahl zurück -ASIN = ARCSIN ## Gibt den Arkussinus einer Zahl zurück -ASINH = ARCSINHYP ## Gibt den umgekehrten hyperbolischen Sinus einer Zahl zurück -ATAN = ARCTAN ## Gibt den Arkustangens einer Zahl zurück -ATAN2 = ARCTAN2 ## Gibt den Arkustangens einer x- und einer y-Koordinate zurück -ATANH = ARCTANHYP ## Gibt den umgekehrten hyperbolischen Tangens einer Zahl zurück -CEILING = OBERGRENZE ## Rundet eine Zahl auf die nächste ganze Zahl oder das nächste Vielfache von Schritt -COMBIN = KOMBINATIONEN ## Gibt die Anzahl der Kombinationen für eine bestimmte Anzahl von Objekten zurück -COS = COS ## Gibt den Kosinus einer Zahl zurück -COSH = COSHYP ## Gibt den hyperbolischen Kosinus einer Zahl zurück -DEGREES = GRAD ## Wandelt Bogenmaß (Radiant) in Grad um -EVEN = GERADE ## Rundet eine Zahl auf die nächste gerade ganze Zahl auf -EXP = EXP ## Potenziert die Basis e mit der als Argument angegebenen Zahl -FACT = FAKULTÄT ## Gibt die Fakultät einer Zahl zurück -FACTDOUBLE = ZWEIFAKULTÄT ## Gibt die Fakultät zu Zahl mit Schrittlänge 2 zurück -FLOOR = UNTERGRENZE ## Rundet die Zahl auf Anzahl_Stellen ab -GCD = GGT ## Gibt den größten gemeinsamen Teiler zurück -INT = GANZZAHL ## Rundet eine Zahl auf die nächstkleinere ganze Zahl ab -LCM = KGV ## Gibt das kleinste gemeinsame Vielfache zurück -LN = LN ## Gibt den natürlichen Logarithmus einer Zahl zurück -LOG = LOG ## Gibt den Logarithmus einer Zahl zu der angegebenen Basis zurück -LOG10 = LOG10 ## Gibt den Logarithmus einer Zahl zur Basis 10 zurück -MDETERM = MDET ## Gibt die Determinante einer Matrix zurück -MINVERSE = MINV ## Gibt die inverse Matrix einer Matrix zurück -MMULT = MMULT ## Gibt das Produkt zweier Matrizen zurück -MOD = REST ## Gibt den Rest einer Division zurück -MROUND = VRUNDEN ## Gibt eine auf das gewünschte Vielfache gerundete Zahl zurück -MULTINOMIAL = POLYNOMIAL ## Gibt den Polynomialkoeffizienten einer Gruppe von Zahlen zurück -ODD = UNGERADE ## Rundet eine Zahl auf die nächste ungerade ganze Zahl auf -PI = PI ## Gibt den Wert Pi zurück -POWER = POTENZ ## Gibt als Ergebnis eine potenzierte Zahl zurück -PRODUCT = PRODUKT ## Multipliziert die zugehörigen Argumente -QUOTIENT = QUOTIENT ## Gibt den ganzzahligen Anteil einer Division zurück -RADIANS = BOGENMASS ## Wandelt Grad in Bogenmaß (Radiant) um -RAND = ZUFALLSZAHL ## Gibt eine Zufallszahl zwischen 0 und 1 zurück -RANDBETWEEN = ZUFALLSBEREICH ## Gibt eine Zufallszahl aus dem festgelegten Bereich zurück -ROMAN = RÖMISCH ## Wandelt eine arabische Zahl in eine römische Zahl als Text um -ROUND = RUNDEN ## Rundet eine Zahl auf eine bestimmte Anzahl von Dezimalstellen -ROUNDDOWN = ABRUNDEN ## Rundet die Zahl auf Anzahl_Stellen ab -ROUNDUP = AUFRUNDEN ## Rundet die Zahl auf Anzahl_Stellen auf -SERIESSUM = POTENZREIHE ## Gibt die Summe von Potenzen (zur Berechnung von Potenzreihen und dichotomen Wahrscheinlichkeiten) zurück -SIGN = VORZEICHEN ## Gibt das Vorzeichen einer Zahl zurück -SIN = SIN ## Gibt den Sinus einer Zahl zurück -SINH = SINHYP ## Gibt den hyperbolischen Sinus einer Zahl zurück -SQRT = WURZEL ## Gibt die Quadratwurzel einer Zahl zurück -SQRTPI = WURZELPI ## Gibt die Wurzel aus der mit Pi (pi) multiplizierten Zahl zurück -SUBTOTAL = TEILERGEBNIS ## Gibt ein Teilergebnis in einer Liste oder Datenbank zurück -SUM = SUMME ## Addiert die zugehörigen Argumente -SUMIF = SUMMEWENN ## Addiert Zahlen, die mit den Suchkriterien übereinstimmen -SUMIFS = SUMMEWENNS ## Die Zellen, die mehrere Kriterien erfüllen, werden in einem Bereich hinzugefügt -SUMPRODUCT = SUMMENPRODUKT ## Gibt die Summe der Produkte zusammengehöriger Matrixkomponenten zurück -SUMSQ = QUADRATESUMME ## Gibt die Summe der quadrierten Argumente zurück -SUMX2MY2 = SUMMEX2MY2 ## Gibt die Summe der Differenzen der Quadrate für zusammengehörige Komponenten zweier Matrizen zurück -SUMX2PY2 = SUMMEX2PY2 ## Gibt die Summe der Quadrate für zusammengehörige Komponenten zweier Matrizen zurück -SUMXMY2 = SUMMEXMY2 ## Gibt die Summe der quadrierten Differenzen für zusammengehörige Komponenten zweier Matrizen zurück -TAN = TAN ## Gibt den Tangens einer Zahl zurück -TANH = TANHYP ## Gibt den hyperbolischen Tangens einer Zahl zurück -TRUNC = KÜRZEN ## Schneidet die Kommastellen einer Zahl ab und gibt als Ergebnis eine ganze Zahl zurück - +AVEDEV = MITTELABW +AVERAGE = MITTELWERT +AVERAGEA = MITTELWERTA +AVERAGEIF = MITTELWERTWENN +AVERAGEIFS = MITTELWERTWENNS +BETA.DIST = BETA.VERT +BETA.INV = BETA.INV +BINOM.DIST = BINOM.VERT +BINOM.DIST.RANGE = BINOM.VERT.BEREICH +BINOM.INV = BINOM.INV +CHISQ.DIST = CHIQU.VERT +CHISQ.DIST.RT = CHIQU.VERT.RE +CHISQ.INV = CHIQU.INV +CHISQ.INV.RT = CHIQU.INV.RE +CHISQ.TEST = CHIQU.TEST +CONFIDENCE.NORM = KONFIDENZ.NORM +CONFIDENCE.T = KONFIDENZ.T +CORREL = KORREL +COUNT = ANZAHL +COUNTA = ANZAHL2 +COUNTBLANK = ANZAHLLEEREZELLEN +COUNTIF = ZÄHLENWENN +COUNTIFS = ZÄHLENWENNS +COVARIANCE.P = KOVARIANZ.P +COVARIANCE.S = KOVARIANZ.S +DEVSQ = SUMQUADABW +EXPON.DIST = EXPON.VERT +F.DIST = F.VERT +F.DIST.RT = F.VERT.RE +F.INV = F.INV +F.INV.RT = F.INV.RE +F.TEST = F.TEST +FISHER = FISHER +FISHERINV = FISHERINV +FORECAST.ETS = PROGNOSE.ETS +FORECAST.ETS.CONFINT = PROGNOSE.ETS.KONFINT +FORECAST.ETS.SEASONALITY = PROGNOSE.ETS.SAISONALITÄT +FORECAST.ETS.STAT = PROGNOSE.ETS.STAT +FORECAST.LINEAR = PROGNOSE.LINEAR +FREQUENCY = HÄUFIGKEIT +GAMMA = GAMMA +GAMMA.DIST = GAMMA.VERT +GAMMA.INV = GAMMA.INV +GAMMALN = GAMMALN +GAMMALN.PRECISE = GAMMALN.GENAU +GAUSS = GAUSS +GEOMEAN = GEOMITTEL +GROWTH = VARIATION +HARMEAN = HARMITTEL +HYPGEOM.DIST = HYPGEOM.VERT +INTERCEPT = ACHSENABSCHNITT +KURT = KURT +LARGE = KGRÖSSTE +LINEST = RGP +LOGEST = RKP +LOGNORM.DIST = LOGNORM.VERT +LOGNORM.INV = LOGNORM.INV +MAX = MAX +MAXA = MAXA +MAXIFS = MAXWENNS +MEDIAN = MEDIAN +MIN = MIN +MINA = MINA +MINIFS = MINWENNS +MODE.MULT = MODUS.VIELF +MODE.SNGL = MODUS.EINF +NEGBINOM.DIST = NEGBINOM.VERT +NORM.DIST = NORM.VERT +NORM.INV = NORM.INV +NORM.S.DIST = NORM.S.VERT +NORM.S.INV = NORM.S.INV +PEARSON = PEARSON +PERCENTILE.EXC = QUANTIL.EXKL +PERCENTILE.INC = QUANTIL.INKL +PERCENTRANK.EXC = QUANTILSRANG.EXKL +PERCENTRANK.INC = QUANTILSRANG.INKL +PERMUT = VARIATIONEN +PERMUTATIONA = VARIATIONEN2 +PHI = PHI +POISSON.DIST = POISSON.VERT +PROB = WAHRSCHBEREICH +QUARTILE.EXC = QUARTILE.EXKL +QUARTILE.INC = QUARTILE.INKL +RANK.AVG = RANG.MITTELW +RANK.EQ = RANG.GLEICH +RSQ = BESTIMMTHEITSMASS +SKEW = SCHIEFE +SKEW.P = SCHIEFE.P +SLOPE = STEIGUNG +SMALL = KKLEINSTE +STANDARDIZE = STANDARDISIERUNG +STDEV.P = STABW.N +STDEV.S = STABW.S +STDEVA = STABWA +STDEVPA = STABWNA +STEYX = STFEHLERYX +T.DIST = T.VERT +T.DIST.2T = T.VERT.2S +T.DIST.RT = T.VERT.RE +T.INV = T.INV +T.INV.2T = T.INV.2S +T.TEST = T.TEST +TREND = TREND +TRIMMEAN = GESTUTZTMITTEL +VAR.P = VAR.P +VAR.S = VAR.S +VARA = VARIANZA +VARPA = VARIANZENA +WEIBULL.DIST = WEIBULL.VERT +Z.TEST = G.TEST ## -## Statistical functions Statistische Funktionen +## Textfunktionen (Text Functions) ## -AVEDEV = MITTELABW ## Gibt die durchschnittliche absolute Abweichung einer Reihe von Merkmalsausprägungen und ihrem Mittelwert zurück -AVERAGE = MITTELWERT ## Gibt den Mittelwert der zugehörigen Argumente zurück -AVERAGEA = MITTELWERTA ## Gibt den Mittelwert der zugehörigen Argumente, die Zahlen, Text und Wahrheitswerte enthalten, zurück -AVERAGEIF = MITTELWERTWENN ## Der Durchschnittswert (arithmetisches Mittel) für alle Zellen in einem Bereich, die einem angegebenen Kriterium entsprechen, wird zurückgegeben -AVERAGEIFS = MITTELWERTWENNS ## Gibt den Durchschnittswert (arithmetisches Mittel) aller Zellen zurück, die mehreren Kriterien entsprechen -BETADIST = BETAVERT ## Gibt die Werte der kumulierten Betaverteilungsfunktion zurück -BETAINV = BETAINV ## Gibt das Quantil der angegebenen Betaverteilung zurück -BINOMDIST = BINOMVERT ## Gibt Wahrscheinlichkeiten einer binomialverteilten Zufallsvariablen zurück -CHIDIST = CHIVERT ## Gibt Werte der Verteilungsfunktion (1-Alpha) einer Chi-Quadrat-verteilten Zufallsgröße zurück -CHIINV = CHIINV ## Gibt Quantile der Verteilungsfunktion (1-Alpha) der Chi-Quadrat-Verteilung zurück -CHITEST = CHITEST ## Gibt die Teststatistik eines Unabhängigkeitstests zurück -CONFIDENCE = KONFIDENZ ## Ermöglicht die Berechnung des 1-Alpha Konfidenzintervalls für den Erwartungswert einer Zufallsvariablen -CORREL = KORREL ## Gibt den Korrelationskoeffizienten zweier Reihen von Merkmalsausprägungen zurück -COUNT = ANZAHL ## Gibt die Anzahl der Zahlen in der Liste mit Argumenten an -COUNTA = ANZAHL2 ## Gibt die Anzahl der Werte in der Liste mit Argumenten an -COUNTBLANK = ANZAHLLEEREZELLEN ## Gibt die Anzahl der leeren Zellen in einem Bereich an -COUNTIF = ZÄHLENWENN ## Gibt die Anzahl der Zellen in einem Bereich an, deren Inhalte mit den Suchkriterien übereinstimmen -COUNTIFS = ZÄHLENWENNS ## Gibt die Anzahl der Zellen in einem Bereich an, deren Inhalte mit mehreren Suchkriterien übereinstimmen -COVAR = KOVAR ## Gibt die Kovarianz zurück, den Mittelwert der für alle Datenpunktpaare gebildeten Produkte der Abweichungen -CRITBINOM = KRITBINOM ## Gibt den kleinsten Wert zurück, für den die kumulierten Wahrscheinlichkeiten der Binomialverteilung kleiner oder gleich einer Grenzwahrscheinlichkeit sind -DEVSQ = SUMQUADABW ## Gibt die Summe der quadrierten Abweichungen der Datenpunkte von ihrem Stichprobenmittelwert zurück -EXPONDIST = EXPONVERT ## Gibt Wahrscheinlichkeiten einer exponential verteilten Zufallsvariablen zurück -FDIST = FVERT ## Gibt Werte der Verteilungsfunktion (1-Alpha) einer F-verteilten Zufallsvariablen zurück -FINV = FINV ## Gibt Quantile der F-Verteilung zurück -FISHER = FISHER ## Gibt die Fisher-Transformation zurück -FISHERINV = FISHERINV ## Gibt die Umkehrung der Fisher-Transformation zurück -FORECAST = PROGNOSE ## Gibt einen Wert zurück, der sich aus einem linearen Trend ergibt -FREQUENCY = HÄUFIGKEIT ## Gibt eine Häufigkeitsverteilung als vertikale Matrix zurück -FTEST = FTEST ## Gibt die Teststatistik eines F-Tests zurück -GAMMADIST = GAMMAVERT ## Gibt Wahrscheinlichkeiten einer gammaverteilten Zufallsvariablen zurück -GAMMAINV = GAMMAINV ## Gibt Quantile der Gammaverteilung zurück -GAMMALN = GAMMALN ## Gibt den natürlichen Logarithmus der Gammafunktion zurück, Γ(x) -GEOMEAN = GEOMITTEL ## Gibt das geometrische Mittel zurück -GROWTH = VARIATION ## Gibt Werte zurück, die sich aus einem exponentiellen Trend ergeben -HARMEAN = HARMITTEL ## Gibt das harmonische Mittel zurück -HYPGEOMDIST = HYPGEOMVERT ## Gibt Wahrscheinlichkeiten einer hypergeometrisch-verteilten Zufallsvariablen zurück -INTERCEPT = ACHSENABSCHNITT ## Gibt den Schnittpunkt der Regressionsgeraden zurück -KURT = KURT ## Gibt die Kurtosis (Exzess) einer Datengruppe zurück -LARGE = KGRÖSSTE ## Gibt den k-größten Wert einer Datengruppe zurück -LINEST = RGP ## Gibt die Parameter eines linearen Trends zurück -LOGEST = RKP ## Gibt die Parameter eines exponentiellen Trends zurück -LOGINV = LOGINV ## Gibt Quantile der Lognormalverteilung zurück -LOGNORMDIST = LOGNORMVERT ## Gibt Werte der Verteilungsfunktion einer lognormalverteilten Zufallsvariablen zurück -MAX = MAX ## Gibt den Maximalwert einer Liste mit Argumenten zurück -MAXA = MAXA ## Gibt den Maximalwert einer Liste mit Argumenten zurück, die Zahlen, Text und Wahrheitswerte enthalten -MEDIAN = MEDIAN ## Gibt den Median der angegebenen Zahlen zurück -MIN = MIN ## Gibt den Minimalwert einer Liste mit Argumenten zurück -MINA = MINA ## Gibt den kleinsten Wert einer Liste mit Argumenten zurück, die Zahlen, Text und Wahrheitswerte enthalten -MODE = MODALWERT ## Gibt den am häufigsten vorkommenden Wert in einer Datengruppe zurück -NEGBINOMDIST = NEGBINOMVERT ## Gibt Wahrscheinlichkeiten einer negativen, binominal verteilten Zufallsvariablen zurück -NORMDIST = NORMVERT ## Gibt Wahrscheinlichkeiten einer normal verteilten Zufallsvariablen zurück -NORMINV = NORMINV ## Gibt Quantile der Normalverteilung zurück -NORMSDIST = STANDNORMVERT ## Gibt Werte der Verteilungsfunktion einer standardnormalverteilten Zufallsvariablen zurück -NORMSINV = STANDNORMINV ## Gibt Quantile der Standardnormalverteilung zurück -PEARSON = PEARSON ## Gibt den Pearsonschen Korrelationskoeffizienten zurück -PERCENTILE = QUANTIL ## Gibt das Alpha-Quantil einer Gruppe von Daten zurück -PERCENTRANK = QUANTILSRANG ## Gibt den prozentualen Rang (Alpha) eines Werts in einer Datengruppe zurück -PERMUT = VARIATIONEN ## Gibt die Anzahl der Möglichkeiten zurück, um k Elemente aus einer Menge von n Elementen ohne Zurücklegen zu ziehen -POISSON = POISSON ## Gibt Wahrscheinlichkeiten einer poissonverteilten Zufallsvariablen zurück -PROB = WAHRSCHBEREICH ## Gibt die Wahrscheinlichkeit für ein von zwei Werten eingeschlossenes Intervall zurück -QUARTILE = QUARTILE ## Gibt die Quartile der Datengruppe zurück -RANK = RANG ## Gibt den Rang zurück, den eine Zahl innerhalb einer Liste von Zahlen einnimmt -RSQ = BESTIMMTHEITSMASS ## Gibt das Quadrat des Pearsonschen Korrelationskoeffizienten zurück -SKEW = SCHIEFE ## Gibt die Schiefe einer Verteilung zurück -SLOPE = STEIGUNG ## Gibt die Steigung der Regressionsgeraden zurück -SMALL = KKLEINSTE ## Gibt den k-kleinsten Wert einer Datengruppe zurück -STANDARDIZE = STANDARDISIERUNG ## Gibt den standardisierten Wert zurück -STDEV = STABW ## Schätzt die Standardabweichung ausgehend von einer Stichprobe -STDEVA = STABWA ## Schätzt die Standardabweichung ausgehend von einer Stichprobe, die Zahlen, Text und Wahrheitswerte enthält -STDEVP = STABWN ## Berechnet die Standardabweichung ausgehend von der Grundgesamtheit -STDEVPA = STABWNA ## Berechnet die Standardabweichung ausgehend von der Grundgesamtheit, die Zahlen, Text und Wahrheitswerte enthält -STEYX = STFEHLERYX ## Gibt den Standardfehler der geschätzten y-Werte für alle x-Werte der Regression zurück -TDIST = TVERT ## Gibt Werte der Verteilungsfunktion (1-Alpha) einer (Student) t-verteilten Zufallsvariablen zurück -TINV = TINV ## Gibt Quantile der t-Verteilung zurück -TREND = TREND ## Gibt Werte zurück, die sich aus einem linearen Trend ergeben -TRIMMEAN = GESTUTZTMITTEL ## Gibt den Mittelwert einer Datengruppe zurück, ohne die Randwerte zu berücksichtigen -TTEST = TTEST ## Gibt die Teststatistik eines Student'schen t-Tests zurück -VAR = VARIANZ ## Schätzt die Varianz ausgehend von einer Stichprobe -VARA = VARIANZA ## Schätzt die Varianz ausgehend von einer Stichprobe, die Zahlen, Text und Wahrheitswerte enthält -VARP = VARIANZEN ## Berechnet die Varianz ausgehend von der Grundgesamtheit -VARPA = VARIANZENA ## Berechnet die Varianz ausgehend von der Grundgesamtheit, die Zahlen, Text und Wahrheitswerte enthält -WEIBULL = WEIBULL ## Gibt Wahrscheinlichkeiten einer weibullverteilten Zufallsvariablen zurück -ZTEST = GTEST ## Gibt den einseitigen Wahrscheinlichkeitswert für einen Gausstest (Normalverteilung) zurück - +BAHTTEXT = BAHTTEXT +CHAR = ZEICHEN +CLEAN = SÄUBERN +CODE = CODE +CONCAT = TEXTKETTE +DOLLAR = DM +EXACT = IDENTISCH +FIND = FINDEN +FIXED = FEST +ISTHAIDIGIT = ISTTHAIZAHLENWORT +LEFT = LINKS +LEN = LÄNGE +LOWER = KLEIN +MID = TEIL +NUMBERVALUE = ZAHLENWERT +PROPER = GROSS2 +REPLACE = ERSETZEN +REPT = WIEDERHOLEN +RIGHT = RECHTS +SEARCH = SUCHEN +SUBSTITUTE = WECHSELN +T = T +TEXT = TEXT +TEXTJOIN = TEXTVERKETTEN +THAIDIGIT = THAIZAHLENWORT +THAINUMSOUND = THAIZAHLSOUND +THAINUMSTRING = THAILANDSKNUMSTRENG +THAISTRINGLENGTH = THAIZEICHENFOLGENLÄNGE +TRIM = GLÄTTEN +UNICHAR = UNIZEICHEN +UNICODE = UNICODE +UPPER = GROSS +VALUE = WERT ## -## Text functions Textfunktionen +## Webfunktionen (Web Functions) ## -ASC = ASC ## Konvertiert DB-Text in einer Zeichenfolge (lateinische Buchstaben oder Katakana) in SB-Text -BAHTTEXT = BAHTTEXT ## Wandelt eine Zahl in Text im Währungsformat ß (Baht) um -CHAR = ZEICHEN ## Gibt das der Codezahl entsprechende Zeichen zurück -CLEAN = SÄUBERN ## Löscht alle nicht druckbaren Zeichen aus einem Text -CODE = CODE ## Gibt die Codezahl des ersten Zeichens in einem Text zurück -CONCATENATE = VERKETTEN ## Verknüpft mehrere Textelemente zu einem Textelement -DOLLAR = DM ## Wandelt eine Zahl in Text im Währungsformat € (Euro) um -EXACT = IDENTISCH ## Prüft, ob zwei Textwerte identisch sind -FIND = FINDEN ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird unterschieden) -FINDB = FINDENB ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird unterschieden) -FIXED = FEST ## Formatiert eine Zahl als Text mit einer festen Anzahl von Dezimalstellen -JIS = JIS ## Konvertiert SB-Text in einer Zeichenfolge (lateinische Buchstaben oder Katakana) in DB-Text -LEFT = LINKS ## Gibt die Zeichen ganz links in einem Textwert zurück -LEFTB = LINKSB ## Gibt die Zeichen ganz links in einem Textwert zurück -LEN = LÄNGE ## Gibt die Anzahl der Zeichen in einer Zeichenfolge zurück -LENB = LÄNGEB ## Gibt die Anzahl der Zeichen in einer Zeichenfolge zurück -LOWER = KLEIN ## Wandelt Text in Kleinbuchstaben um -MID = TEIL ## Gibt eine bestimmte Anzahl Zeichen aus einer Zeichenfolge ab der von Ihnen angegebenen Stelle zurück -MIDB = TEILB ## Gibt eine bestimmte Anzahl Zeichen aus einer Zeichenfolge ab der von Ihnen angegebenen Stelle zurück -PHONETIC = PHONETIC ## Extrahiert die phonetischen (Furigana-)Zeichen aus einer Textzeichenfolge -PROPER = GROSS2 ## Wandelt den ersten Buchstaben aller Wörter eines Textwerts in Großbuchstaben um -REPLACE = ERSETZEN ## Ersetzt Zeichen in Text -REPLACEB = ERSETZENB ## Ersetzt Zeichen in Text -REPT = WIEDERHOLEN ## Wiederholt einen Text so oft wie angegeben -RIGHT = RECHTS ## Gibt die Zeichen ganz rechts in einem Textwert zurück -RIGHTB = RECHTSB ## Gibt die Zeichen ganz rechts in einem Textwert zurück -SEARCH = SUCHEN ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird nicht unterschieden) -SEARCHB = SUCHENB ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird nicht unterschieden) -SUBSTITUTE = WECHSELN ## Ersetzt in einer Zeichenfolge neuen Text gegen alten -T = T ## Wandelt die zugehörigen Argumente in Text um -TEXT = TEXT ## Formatiert eine Zahl und wandelt sie in Text um -TRIM = GLÄTTEN ## Entfernt Leerzeichen aus Text -UPPER = GROSS ## Wandelt Text in Großbuchstaben um -VALUE = WERT ## Wandelt ein Textargument in eine Zahl um +ENCODEURL = URLCODIEREN +FILTERXML = XMLFILTERN +WEBSERVICE = WEBDIENST + +## +## Kompatibilitätsfunktionen (Compatibility Functions) +## +BETADIST = BETAVERT +BETAINV = BETAINV +BINOMDIST = BINOMVERT +CEILING = OBERGRENZE +CHIDIST = CHIVERT +CHIINV = CHIINV +CHITEST = CHITEST +CONCATENATE = VERKETTEN +CONFIDENCE = KONFIDENZ +COVAR = KOVAR +CRITBINOM = KRITBINOM +EXPONDIST = EXPONVERT +FDIST = FVERT +FINV = FINV +FLOOR = UNTERGRENZE +FORECAST = SCHÄTZER +FTEST = FTEST +GAMMADIST = GAMMAVERT +GAMMAINV = GAMMAINV +HYPGEOMDIST = HYPGEOMVERT +LOGINV = LOGINV +LOGNORMDIST = LOGNORMVERT +MODE = MODALWERT +NEGBINOMDIST = NEGBINOMVERT +NORMDIST = NORMVERT +NORMINV = NORMINV +NORMSDIST = STANDNORMVERT +NORMSINV = STANDNORMINV +PERCENTILE = QUANTIL +PERCENTRANK = QUANTILSRANG +POISSON = POISSON +QUARTILE = QUARTILE +RANK = RANG +STDEV = STABW +STDEVP = STABWN +TDIST = TVERT +TINV = TINV +TTEST = TTEST +VAR = VARIANZ +VARP = VARIANZEN +WEIBULL = WEIBULL +ZTEST = GTEST diff --git a/src/PhpSpreadsheet/Calculation/locale/es/config b/src/PhpSpreadsheet/Calculation/locale/es/config index 5b9b9488..fe044efa 100644 --- a/src/PhpSpreadsheet/Calculation/locale/es/config +++ b/src/PhpSpreadsheet/Calculation/locale/es/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## +## Español (Spanish) +## +############################################################ -ArgumentSeparator = ; - +ArgumentSeparator = ; ## -## (For future use) +## Error Codes ## -currencySymbol = $ ## I'm surprised that the Excel Documentation suggests $ rather than € - - -## -## Excel Error Codes (For future use) - -## -NULL = #¡NULO! -DIV0 = #¡DIV/0! -VALUE = #¡VALOR! -REF = #¡REF! -NAME = #¿NOMBRE? -NUM = #¡NÚM! -NA = #N/A +NULL = #¡NULO! +DIV0 = #¡DIV/0! +VALUE = #¡VALOR! +REF = #¡REF! +NAME = #¿NOMBRE? +NUM = #¡NUM! +NA diff --git a/src/PhpSpreadsheet/Calculation/locale/es/functions b/src/PhpSpreadsheet/Calculation/locale/es/functions index ac1ac86a..1f9f2891 100644 --- a/src/PhpSpreadsheet/Calculation/locale/es/functions +++ b/src/PhpSpreadsheet/Calculation/locale/es/functions @@ -1,416 +1,537 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Español (Spanish) ## +############################################################ ## -## Add-in and Automation functions Funciones de complementos y automatización +## Funciones de cubo (Cube Functions) ## -GETPIVOTDATA = IMPORTARDATOSDINAMICOS ## Devuelve los datos almacenados en un informe de tabla dinámica. - +CUBEKPIMEMBER = MIEMBROKPICUBO +CUBEMEMBER = MIEMBROCUBO +CUBEMEMBERPROPERTY = PROPIEDADMIEMBROCUBO +CUBERANKEDMEMBER = MIEMBRORANGOCUBO +CUBESET = CONJUNTOCUBO +CUBESETCOUNT = RECUENTOCONJUNTOCUBO +CUBEVALUE = VALORCUBO ## -## Cube functions Funciones de cubo +## Funciones de base de datos (Database Functions) ## -CUBEKPIMEMBER = MIEMBROKPICUBO ## Devuelve un nombre, propiedad y medida de indicador de rendimiento clave (KPI) y muestra el nombre y la propiedad en la celda. Un KPI es una medida cuantificable, como los beneficios brutos mensuales o la facturación trimestral por empleado, que se usa para supervisar el rendimiento de una organización. -CUBEMEMBER = MIEMBROCUBO ## Devuelve un miembro o tupla en una jerarquía de cubo. Se usa para validar la existencia del miembro o la tupla en el cubo. -CUBEMEMBERPROPERTY = PROPIEDADMIEMBROCUBO ## Devuelve el valor de una propiedad de miembro del cubo Se usa para validar la existencia de un nombre de miembro en el cubo y para devolver la propiedad especificada para este miembro. -CUBERANKEDMEMBER = MIEMBRORANGOCUBO ## Devuelve el miembro n, o clasificado, de un conjunto. Se usa para devolver uno o más elementos de un conjunto, por ejemplo, el representante con mejores ventas o los diez mejores alumnos. -CUBESET = CONJUNTOCUBO ## Define un conjunto calculado de miembros o tuplas mediante el envío de una expresión de conjunto al cubo en el servidor, lo que crea el conjunto y, después, devuelve dicho conjunto a Microsoft Office Excel. -CUBESETCOUNT = RECUENTOCONJUNTOCUBO ## Devuelve el número de elementos de un conjunto. -CUBEVALUE = VALORCUBO ## Devuelve un valor agregado de un cubo. - +DAVERAGE = BDPROMEDIO +DCOUNT = BDCONTAR +DCOUNTA = BDCONTARA +DGET = BDEXTRAER +DMAX = BDMAX +DMIN = BDMIN +DPRODUCT = BDPRODUCTO +DSTDEV = BDDESVEST +DSTDEVP = BDDESVESTP +DSUM = BDSUMA +DVAR = BDVAR +DVARP = BDVARP ## -## Database functions Funciones de base de datos +## Funciones de fecha y hora (Date & Time Functions) ## -DAVERAGE = BDPROMEDIO ## Devuelve el promedio de las entradas seleccionadas en la base de datos. -DCOUNT = BDCONTAR ## Cuenta el número de celdas que contienen números en una base de datos. -DCOUNTA = BDCONTARA ## Cuenta el número de celdas no vacías en una base de datos. -DGET = BDEXTRAER ## Extrae de una base de datos un único registro que cumple los criterios especificados. -DMAX = BDMAX ## Devuelve el valor máximo de las entradas seleccionadas de la base de datos. -DMIN = BDMIN ## Devuelve el valor mínimo de las entradas seleccionadas de la base de datos. -DPRODUCT = BDPRODUCTO ## Multiplica los valores de un campo concreto de registros de una base de datos que cumplen los criterios especificados. -DSTDEV = BDDESVEST ## Calcula la desviación estándar a partir de una muestra de entradas seleccionadas en la base de datos. -DSTDEVP = BDDESVESTP ## Calcula la desviación estándar en función de la población total de las entradas seleccionadas de la base de datos. -DSUM = BDSUMA ## Suma los números de la columna de campo de los registros de la base de datos que cumplen los criterios. -DVAR = BDVAR ## Calcula la varianza a partir de una muestra de entradas seleccionadas de la base de datos. -DVARP = BDVARP ## Calcula la varianza a partir de la población total de entradas seleccionadas de la base de datos. - +DATE = FECHA +DATEDIF = SIFECHA +DATESTRING = CADENA.FECHA +DATEVALUE = FECHANUMERO +DAY = DIA +DAYS = DIAS +DAYS360 = DIAS360 +EDATE = FECHA.MES +EOMONTH = FIN.MES +HOUR = HORA +ISOWEEKNUM = ISO.NUM.DE.SEMANA +MINUTE = MINUTO +MONTH = MES +NETWORKDAYS = DIAS.LAB +NETWORKDAYS.INTL = DIAS.LAB.INTL +NOW = AHORA +SECOND = SEGUNDO +THAIDAYOFWEEK = DIASEMTAI +THAIMONTHOFYEAR = MESAÑOTAI +THAIYEAR = AÑOTAI +TIME = NSHORA +TIMEVALUE = HORANUMERO +TODAY = HOY +WEEKDAY = DIASEM +WEEKNUM = NUM.DE.SEMANA +WORKDAY = DIA.LAB +WORKDAY.INTL = DIA.LAB.INTL +YEAR = AÑO +YEARFRAC = FRAC.AÑO ## -## Date and time functions Funciones de fecha y hora +## Funciones de ingeniería (Engineering Functions) ## -DATE = FECHA ## Devuelve el número de serie correspondiente a una fecha determinada. -DATEVALUE = FECHANUMERO ## Convierte una fecha con formato de texto en un valor de número de serie. -DAY = DIA ## Convierte un número de serie en un valor de día del mes. -DAYS360 = DIAS360 ## Calcula el número de días entre dos fechas a partir de un año de 360 días. -EDATE = FECHA.MES ## Devuelve el número de serie de la fecha equivalente al número indicado de meses anteriores o posteriores a la fecha inicial. -EOMONTH = FIN.MES ## Devuelve el número de serie correspondiente al último día del mes anterior o posterior a un número de meses especificado. -HOUR = HORA ## Convierte un número de serie en un valor de hora. -MINUTE = MINUTO ## Convierte un número de serie en un valor de minuto. -MONTH = MES ## Convierte un número de serie en un valor de mes. -NETWORKDAYS = DIAS.LAB ## Devuelve el número de todos los días laborables existentes entre dos fechas. -NOW = AHORA ## Devuelve el número de serie correspondiente a la fecha y hora actuales. -SECOND = SEGUNDO ## Convierte un número de serie en un valor de segundo. -TIME = HORA ## Devuelve el número de serie correspondiente a una hora determinada. -TIMEVALUE = HORANUMERO ## Convierte una hora con formato de texto en un valor de número de serie. -TODAY = HOY ## Devuelve el número de serie correspondiente al día actual. -WEEKDAY = DIASEM ## Convierte un número de serie en un valor de día de la semana. -WEEKNUM = NUM.DE.SEMANA ## Convierte un número de serie en un número que representa el lugar numérico correspondiente a una semana de un año. -WORKDAY = DIA.LAB ## Devuelve el número de serie de la fecha que tiene lugar antes o después de un número determinado de días laborables. -YEAR = AÑO ## Convierte un número de serie en un valor de año. -YEARFRAC = FRAC.AÑO ## Devuelve la fracción de año que representa el número total de días existentes entre el valor de fecha_inicial y el de fecha_final. - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BIN.A.DEC +BIN2HEX = BIN.A.HEX +BIN2OCT = BIN.A.OCT +BITAND = BIT.Y +BITLSHIFT = BIT.DESPLIZQDA +BITOR = BIT.O +BITRSHIFT = BIT.DESPLDCHA +BITXOR = BIT.XO +COMPLEX = COMPLEJO +CONVERT = CONVERTIR +DEC2BIN = DEC.A.BIN +DEC2HEX = DEC.A.HEX +DEC2OCT = DEC.A.OCT +DELTA = DELTA +ERF = FUN.ERROR +ERF.PRECISE = FUN.ERROR.EXACTO +ERFC = FUN.ERROR.COMPL +ERFC.PRECISE = FUN.ERROR.COMPL.EXACTO +GESTEP = MAYOR.O.IGUAL +HEX2BIN = HEX.A.BIN +HEX2DEC = HEX.A.DEC +HEX2OCT = HEX.A.OCT +IMABS = IM.ABS +IMAGINARY = IMAGINARIO +IMARGUMENT = IM.ANGULO +IMCONJUGATE = IM.CONJUGADA +IMCOS = IM.COS +IMCOSH = IM.COSH +IMCOT = IM.COT +IMCSC = IM.CSC +IMCSCH = IM.CSCH +IMDIV = IM.DIV +IMEXP = IM.EXP +IMLN = IM.LN +IMLOG10 = IM.LOG10 +IMLOG2 = IM.LOG2 +IMPOWER = IM.POT +IMPRODUCT = IM.PRODUCT +IMREAL = IM.REAL +IMSEC = IM.SEC +IMSECH = IM.SECH +IMSIN = IM.SENO +IMSINH = IM.SENOH +IMSQRT = IM.RAIZ2 +IMSUB = IM.SUSTR +IMSUM = IM.SUM +IMTAN = IM.TAN +OCT2BIN = OCT.A.BIN +OCT2DEC = OCT.A.DEC +OCT2HEX = OCT.A.HEX ## -## Engineering functions Funciones de ingeniería +## Funciones financieras (Financial Functions) ## -BESSELI = BESSELI ## Devuelve la función Bessel In(x) modificada. -BESSELJ = BESSELJ ## Devuelve la función Bessel Jn(x). -BESSELK = BESSELK ## Devuelve la función Bessel Kn(x) modificada. -BESSELY = BESSELY ## Devuelve la función Bessel Yn(x). -BIN2DEC = BIN.A.DEC ## Convierte un número binario en decimal. -BIN2HEX = BIN.A.HEX ## Convierte un número binario en hexadecimal. -BIN2OCT = BIN.A.OCT ## Convierte un número binario en octal. -COMPLEX = COMPLEJO ## Convierte coeficientes reales e imaginarios en un número complejo. -CONVERT = CONVERTIR ## Convierte un número de un sistema de medida a otro. -DEC2BIN = DEC.A.BIN ## Convierte un número decimal en binario. -DEC2HEX = DEC.A.HEX ## Convierte un número decimal en hexadecimal. -DEC2OCT = DEC.A.OCT ## Convierte un número decimal en octal. -DELTA = DELTA ## Comprueba si dos valores son iguales. -ERF = FUN.ERROR ## Devuelve la función de error. -ERFC = FUN.ERROR.COMPL ## Devuelve la función de error complementario. -GESTEP = MAYOR.O.IGUAL ## Comprueba si un número es mayor que un valor de umbral. -HEX2BIN = HEX.A.BIN ## Convierte un número hexadecimal en binario. -HEX2DEC = HEX.A.DEC ## Convierte un número hexadecimal en decimal. -HEX2OCT = HEX.A.OCT ## Convierte un número hexadecimal en octal. -IMABS = IM.ABS ## Devuelve el valor absoluto (módulo) de un número complejo. -IMAGINARY = IMAGINARIO ## Devuelve el coeficiente imaginario de un número complejo. -IMARGUMENT = IM.ANGULO ## Devuelve el argumento theta, un ángulo expresado en radianes. -IMCONJUGATE = IM.CONJUGADA ## Devuelve la conjugada compleja de un número complejo. -IMCOS = IM.COS ## Devuelve el coseno de un número complejo. -IMDIV = IM.DIV ## Devuelve el cociente de dos números complejos. -IMEXP = IM.EXP ## Devuelve el valor exponencial de un número complejo. -IMLN = IM.LN ## Devuelve el logaritmo natural (neperiano) de un número complejo. -IMLOG10 = IM.LOG10 ## Devuelve el logaritmo en base 10 de un número complejo. -IMLOG2 = IM.LOG2 ## Devuelve el logaritmo en base 2 de un número complejo. -IMPOWER = IM.POT ## Devuelve un número complejo elevado a una potencia entera. -IMPRODUCT = IM.PRODUCT ## Devuelve el producto de números complejos. -IMREAL = IM.REAL ## Devuelve el coeficiente real de un número complejo. -IMSIN = IM.SENO ## Devuelve el seno de un número complejo. -IMSQRT = IM.RAIZ2 ## Devuelve la raíz cuadrada de un número complejo. -IMSUB = IM.SUSTR ## Devuelve la diferencia entre dos números complejos. -IMSUM = IM.SUM ## Devuelve la suma de números complejos. -OCT2BIN = OCT.A.BIN ## Convierte un número octal en binario. -OCT2DEC = OCT.A.DEC ## Convierte un número octal en decimal. -OCT2HEX = OCT.A.HEX ## Convierte un número octal en hexadecimal. - +ACCRINT = INT.ACUM +ACCRINTM = INT.ACUM.V +AMORDEGRC = AMORTIZ.PROGRE +AMORLINC = AMORTIZ.LIN +COUPDAYBS = CUPON.DIAS.L1 +COUPDAYS = CUPON.DIAS +COUPDAYSNC = CUPON.DIAS.L2 +COUPNCD = CUPON.FECHA.L2 +COUPNUM = CUPON.NUM +COUPPCD = CUPON.FECHA.L1 +CUMIPMT = PAGO.INT.ENTRE +CUMPRINC = PAGO.PRINC.ENTRE +DB = DB +DDB = DDB +DISC = TASA.DESC +DOLLARDE = MONEDA.DEC +DOLLARFR = MONEDA.FRAC +DURATION = DURACION +EFFECT = INT.EFECTIVO +FV = VF +FVSCHEDULE = VF.PLAN +INTRATE = TASA.INT +IPMT = PAGOINT +IRR = TIR +ISPMT = INT.PAGO.DIR +MDURATION = DURACION.MODIF +MIRR = TIRM +NOMINAL = TASA.NOMINAL +NPER = NPER +NPV = VNA +ODDFPRICE = PRECIO.PER.IRREGULAR.1 +ODDFYIELD = RENDTO.PER.IRREGULAR.1 +ODDLPRICE = PRECIO.PER.IRREGULAR.2 +ODDLYIELD = RENDTO.PER.IRREGULAR.2 +PDURATION = P.DURACION +PMT = PAGO +PPMT = PAGOPRIN +PRICE = PRECIO +PRICEDISC = PRECIO.DESCUENTO +PRICEMAT = PRECIO.VENCIMIENTO +PV = VA +RATE = TASA +RECEIVED = CANTIDAD.RECIBIDA +RRI = RRI +SLN = SLN +SYD = SYD +TBILLEQ = LETRA.DE.TEST.EQV.A.BONO +TBILLPRICE = LETRA.DE.TES.PRECIO +TBILLYIELD = LETRA.DE.TES.RENDTO +VDB = DVS +XIRR = TIR.NO.PER +XNPV = VNA.NO.PER +YIELD = RENDTO +YIELDDISC = RENDTO.DESC +YIELDMAT = RENDTO.VENCTO ## -## Financial functions Funciones financieras +## Funciones de información (Information Functions) ## -ACCRINT = INT.ACUM ## Devuelve el interés acumulado de un valor bursátil con pagos de interés periódicos. -ACCRINTM = INT.ACUM.V ## Devuelve el interés acumulado de un valor bursátil con pagos de interés al vencimiento. -AMORDEGRC = AMORTIZ.PROGRE ## Devuelve la amortización de cada período contable mediante el uso de un coeficiente de amortización. -AMORLINC = AMORTIZ.LIN ## Devuelve la amortización de cada uno de los períodos contables. -COUPDAYBS = CUPON.DIAS.L1 ## Devuelve el número de días desde el principio del período de un cupón hasta la fecha de liquidación. -COUPDAYS = CUPON.DIAS ## Devuelve el número de días del período (entre dos cupones) donde se encuentra la fecha de liquidación. -COUPDAYSNC = CUPON.DIAS.L2 ## Devuelve el número de días desde la fecha de liquidación hasta la fecha del próximo cupón. -COUPNCD = CUPON.FECHA.L2 ## Devuelve la fecha del próximo cupón después de la fecha de liquidación. -COUPNUM = CUPON.NUM ## Devuelve el número de pagos de cupón entre la fecha de liquidación y la fecha de vencimiento. -COUPPCD = CUPON.FECHA.L1 ## Devuelve la fecha de cupón anterior a la fecha de liquidación. -CUMIPMT = PAGO.INT.ENTRE ## Devuelve el interés acumulado pagado entre dos períodos. -CUMPRINC = PAGO.PRINC.ENTRE ## Devuelve el capital acumulado pagado de un préstamo entre dos períodos. -DB = DB ## Devuelve la amortización de un bien durante un período específico a través del método de amortización de saldo fijo. -DDB = DDB ## Devuelve la amortización de un bien durante un período específico a través del método de amortización por doble disminución de saldo u otro método que se especifique. -DISC = TASA.DESC ## Devuelve la tasa de descuento de un valor bursátil. -DOLLARDE = MONEDA.DEC ## Convierte una cotización de un valor bursátil expresada en forma fraccionaria en una cotización de un valor bursátil expresada en forma decimal. -DOLLARFR = MONEDA.FRAC ## Convierte una cotización de un valor bursátil expresada en forma decimal en una cotización de un valor bursátil expresada en forma fraccionaria. -DURATION = DURACION ## Devuelve la duración anual de un valor bursátil con pagos de interés periódico. -EFFECT = INT.EFECTIVO ## Devuelve la tasa de interés anual efectiva. -FV = VF ## Devuelve el valor futuro de una inversión. -FVSCHEDULE = VF.PLAN ## Devuelve el valor futuro de un capital inicial después de aplicar una serie de tasas de interés compuesto. -INTRATE = TASA.INT ## Devuelve la tasa de interés para la inversión total de un valor bursátil. -IPMT = PAGOINT ## Devuelve el pago de intereses de una inversión durante un período determinado. -IRR = TIR ## Devuelve la tasa interna de retorno para una serie de flujos de efectivo periódicos. -ISPMT = INT.PAGO.DIR ## Calcula el interés pagado durante un período específico de una inversión. -MDURATION = DURACION.MODIF ## Devuelve la duración de Macauley modificada de un valor bursátil con un valor nominal supuesto de 100 $. -MIRR = TIRM ## Devuelve la tasa interna de retorno donde se financian flujos de efectivo positivos y negativos a tasas diferentes. -NOMINAL = TASA.NOMINAL ## Devuelve la tasa nominal de interés anual. -NPER = NPER ## Devuelve el número de períodos de una inversión. -NPV = VNA ## Devuelve el valor neto actual de una inversión en función de una serie de flujos periódicos de efectivo y una tasa de descuento. -ODDFPRICE = PRECIO.PER.IRREGULAR.1 ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil con un primer período impar. -ODDFYIELD = RENDTO.PER.IRREGULAR.1 ## Devuelve el rendimiento de un valor bursátil con un primer período impar. -ODDLPRICE = PRECIO.PER.IRREGULAR.2 ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil con un último período impar. -ODDLYIELD = RENDTO.PER.IRREGULAR.2 ## Devuelve el rendimiento de un valor bursátil con un último período impar. -PMT = PAGO ## Devuelve el pago periódico de una anualidad. -PPMT = PAGOPRIN ## Devuelve el pago de capital de una inversión durante un período determinado. -PRICE = PRECIO ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil que paga una tasa de interés periódico. -PRICEDISC = PRECIO.DESCUENTO ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil con descuento. -PRICEMAT = PRECIO.VENCIMIENTO ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil que paga interés a su vencimiento. -PV = VALACT ## Devuelve el valor actual de una inversión. -RATE = TASA ## Devuelve la tasa de interés por período de una anualidad. -RECEIVED = CANTIDAD.RECIBIDA ## Devuelve la cantidad recibida al vencimiento de un valor bursátil completamente invertido. -SLN = SLN ## Devuelve la amortización por método directo de un bien en un período dado. -SYD = SYD ## Devuelve la amortización por suma de dígitos de los años de un bien durante un período especificado. -TBILLEQ = LETRA.DE.TES.EQV.A.BONO ## Devuelve el rendimiento de un bono equivalente a una letra del Tesoro (de EE.UU.) -TBILLPRICE = LETRA.DE.TES.PRECIO ## Devuelve el precio por un valor nominal de 100 $ de una letra del Tesoro (de EE.UU.) -TBILLYIELD = LETRA.DE.TES.RENDTO ## Devuelve el rendimiento de una letra del Tesoro (de EE.UU.) -VDB = DVS ## Devuelve la amortización de un bien durante un período específico o parcial a través del método de cálculo del saldo en disminución. -XIRR = TIR.NO.PER ## Devuelve la tasa interna de retorno para un flujo de efectivo que no es necesariamente periódico. -XNPV = VNA.NO.PER ## Devuelve el valor neto actual para un flujo de efectivo que no es necesariamente periódico. -YIELD = RENDTO ## Devuelve el rendimiento de un valor bursátil que paga intereses periódicos. -YIELDDISC = RENDTO.DESC ## Devuelve el rendimiento anual de un valor bursátil con descuento; por ejemplo, una letra del Tesoro (de EE.UU.) -YIELDMAT = RENDTO.VENCTO ## Devuelve el rendimiento anual de un valor bursátil que paga intereses al vencimiento. - +CELL = CELDA +ERROR.TYPE = TIPO.DE.ERROR +INFO = INFO +ISBLANK = ESBLANCO +ISERR = ESERR +ISERROR = ESERROR +ISEVEN = ES.PAR +ISFORMULA = ESFORMULA +ISLOGICAL = ESLOGICO +ISNA = ESNOD +ISNONTEXT = ESNOTEXTO +ISNUMBER = ESNUMERO +ISODD = ES.IMPAR +ISREF = ESREF +ISTEXT = ESTEXTO +N = N +NA = NOD +SHEET = HOJA +SHEETS = HOJAS +TYPE = TIPO ## -## Information functions Funciones de información +## Funciones lógicas (Logical Functions) ## -CELL = CELDA ## Devuelve información acerca del formato, la ubicación o el contenido de una celda. -ERROR.TYPE = TIPO.DE.ERROR ## Devuelve un número que corresponde a un tipo de error. -INFO = INFO ## Devuelve información acerca del entorno operativo en uso. -ISBLANK = ESBLANCO ## Devuelve VERDADERO si el valor está en blanco. -ISERR = ESERR ## Devuelve VERDADERO si el valor es cualquier valor de error excepto #N/A. -ISERROR = ESERROR ## Devuelve VERDADERO si el valor es cualquier valor de error. -ISEVEN = ES.PAR ## Devuelve VERDADERO si el número es par. -ISLOGICAL = ESLOGICO ## Devuelve VERDADERO si el valor es un valor lógico. -ISNA = ESNOD ## Devuelve VERDADERO si el valor es el valor de error #N/A. -ISNONTEXT = ESNOTEXTO ## Devuelve VERDADERO si el valor no es texto. -ISNUMBER = ESNUMERO ## Devuelve VERDADERO si el valor es un número. -ISODD = ES.IMPAR ## Devuelve VERDADERO si el número es impar. -ISREF = ESREF ## Devuelve VERDADERO si el valor es una referencia. -ISTEXT = ESTEXTO ## Devuelve VERDADERO si el valor es texto. -N = N ## Devuelve un valor convertido en un número. -NA = ND ## Devuelve el valor de error #N/A. -TYPE = TIPO ## Devuelve un número que indica el tipo de datos de un valor. - +AND = Y +FALSE = FALSO +IF = SI +IFERROR = SI.ERROR +IFNA = SI.ND +IFS = SI.CONJUNTO +NOT = NO +OR = O +SWITCH = CAMBIAR +TRUE = VERDADERO +XOR = XO ## -## Logical functions Funciones lógicas +## Funciones de búsqueda y referencia (Lookup & Reference Functions) ## -AND = Y ## Devuelve VERDADERO si todos sus argumentos son VERDADERO. -FALSE = FALSO ## Devuelve el valor lógico FALSO. -IF = SI ## Especifica una prueba lógica que realizar. -IFERROR = SI.ERROR ## Devuelve un valor que se especifica si una fórmula lo evalúa como un error; de lo contrario, devuelve el resultado de la fórmula. -NOT = NO ## Invierte el valor lógico del argumento. -OR = O ## Devuelve VERDADERO si cualquier argumento es VERDADERO. -TRUE = VERDADERO ## Devuelve el valor lógico VERDADERO. - +ADDRESS = DIRECCION +AREAS = AREAS +CHOOSE = ELEGIR +COLUMN = COLUMNA +COLUMNS = COLUMNAS +FORMULATEXT = FORMULATEXTO +GETPIVOTDATA = IMPORTARDATOSDINAMICOS +HLOOKUP = BUSCARH +HYPERLINK = HIPERVINCULO +INDEX = INDICE +INDIRECT = INDIRECTO +LOOKUP = BUSCAR +MATCH = COINCIDIR +OFFSET = DESREF +ROW = FILA +ROWS = FILAS +RTD = RDTR +TRANSPOSE = TRANSPONER +VLOOKUP = BUSCARV ## -## Lookup and reference functions Funciones de búsqueda y referencia +## Funciones matemáticas y trigonométricas (Math & Trig Functions) ## -ADDRESS = DIRECCION ## Devuelve una referencia como texto a una sola celda de una hoja de cálculo. -AREAS = AREAS ## Devuelve el número de áreas de una referencia. -CHOOSE = ELEGIR ## Elige un valor de una lista de valores. -COLUMN = COLUMNA ## Devuelve el número de columna de una referencia. -COLUMNS = COLUMNAS ## Devuelve el número de columnas de una referencia. -HLOOKUP = BUSCARH ## Busca en la fila superior de una matriz y devuelve el valor de la celda indicada. -HYPERLINK = HIPERVINCULO ## Crea un acceso directo o un salto que abre un documento almacenado en un servidor de red, en una intranet o en Internet. -INDEX = INDICE ## Usa un índice para elegir un valor de una referencia o matriz. -INDIRECT = INDIRECTO ## Devuelve una referencia indicada por un valor de texto. -LOOKUP = BUSCAR ## Busca valores de un vector o una matriz. -MATCH = COINCIDIR ## Busca valores de una referencia o matriz. -OFFSET = DESREF ## Devuelve un desplazamiento de referencia respecto a una referencia dada. -ROW = FILA ## Devuelve el número de fila de una referencia. -ROWS = FILAS ## Devuelve el número de filas de una referencia. -RTD = RDTR ## Recupera datos en tiempo real desde un programa compatible con la automatización COM (automatización: modo de trabajar con los objetos de una aplicación desde otra aplicación o herramienta de entorno. La automatización, antes denominada automatización OLE, es un estándar de la industria y una función del Modelo de objetos componentes (COM).). -TRANSPOSE = TRANSPONER ## Devuelve la transposición de una matriz. -VLOOKUP = BUSCARV ## Busca en la primera columna de una matriz y se mueve en horizontal por la fila para devolver el valor de una celda. - +ABS = ABS +ACOS = ACOS +ACOSH = ACOSH +ACOT = ACOT +ACOTH = ACOTH +AGGREGATE = AGREGAR +ARABIC = NUMERO.ARABE +ASIN = ASENO +ASINH = ASENOH +ATAN = ATAN +ATAN2 = ATAN2 +ATANH = ATANH +BASE = BASE +CEILING.MATH = MULTIPLO.SUPERIOR.MAT +CEILING.PRECISE = MULTIPLO.SUPERIOR.EXACTO +COMBIN = COMBINAT +COMBINA = COMBINA +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = CONV.DECIMAL +DEGREES = GRADOS +ECMA.CEILING = MULTIPLO.SUPERIOR.ECMA +EVEN = REDONDEA.PAR +EXP = EXP +FACT = FACT +FACTDOUBLE = FACT.DOBLE +FLOOR.MATH = MULTIPLO.INFERIOR.MAT +FLOOR.PRECISE = MULTIPLO.INFERIOR.EXACTO +GCD = M.C.D +INT = ENTERO +ISO.CEILING = MULTIPLO.SUPERIOR.ISO +LCM = M.C.M +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = MDETERM +MINVERSE = MINVERSA +MMULT = MMULT +MOD = RESIDUO +MROUND = REDOND.MULT +MULTINOMIAL = MULTINOMIAL +MUNIT = M.UNIDAD +ODD = REDONDEA.IMPAR +PI = PI +POWER = POTENCIA +PRODUCT = PRODUCTO +QUOTIENT = COCIENTE +RADIANS = RADIANES +RAND = ALEATORIO +RANDBETWEEN = ALEATORIO.ENTRE +ROMAN = NUMERO.ROMANO +ROUND = REDONDEAR +ROUNDBAHTDOWN = REDONDEAR.BAHT.MAS +ROUNDBAHTUP = REDONDEAR.BAHT.MENOS +ROUNDDOWN = REDONDEAR.MENOS +ROUNDUP = REDONDEAR.MAS +SEC = SEC +SECH = SECH +SERIESSUM = SUMA.SERIES +SIGN = SIGNO +SIN = SENO +SINH = SENOH +SQRT = RAIZ +SQRTPI = RAIZ2PI +SUBTOTAL = SUBTOTALES +SUM = SUMA +SUMIF = SUMAR.SI +SUMIFS = SUMAR.SI.CONJUNTO +SUMPRODUCT = SUMAPRODUCTO +SUMSQ = SUMA.CUADRADOS +SUMX2MY2 = SUMAX2MENOSY2 +SUMX2PY2 = SUMAX2MASY2 +SUMXMY2 = SUMAXMENOSY2 +TAN = TAN +TANH = TANH +TRUNC = TRUNCAR ## -## Math and trigonometry functions Funciones matemáticas y trigonométricas +## Funciones estadísticas (Statistical Functions) ## -ABS = ABS ## Devuelve el valor absoluto de un número. -ACOS = ACOS ## Devuelve el arcocoseno de un número. -ACOSH = ACOSH ## Devuelve el coseno hiperbólico inverso de un número. -ASIN = ASENO ## Devuelve el arcoseno de un número. -ASINH = ASENOH ## Devuelve el seno hiperbólico inverso de un número. -ATAN = ATAN ## Devuelve la arcotangente de un número. -ATAN2 = ATAN2 ## Devuelve la arcotangente de las coordenadas "x" e "y". -ATANH = ATANH ## Devuelve la tangente hiperbólica inversa de un número. -CEILING = MULTIPLO.SUPERIOR ## Redondea un número al entero más próximo o al múltiplo significativo más cercano. -COMBIN = COMBINAT ## Devuelve el número de combinaciones para un número determinado de objetos. -COS = COS ## Devuelve el coseno de un número. -COSH = COSH ## Devuelve el coseno hiperbólico de un número. -DEGREES = GRADOS ## Convierte radianes en grados. -EVEN = REDONDEA.PAR ## Redondea un número hasta el entero par más próximo. -EXP = EXP ## Devuelve e elevado a la potencia de un número dado. -FACT = FACT ## Devuelve el factorial de un número. -FACTDOUBLE = FACT.DOBLE ## Devuelve el factorial doble de un número. -FLOOR = MULTIPLO.INFERIOR ## Redondea un número hacia abajo, en dirección hacia cero. -GCD = M.C.D ## Devuelve el máximo común divisor. -INT = ENTERO ## Redondea un número hacia abajo hasta el entero más próximo. -LCM = M.C.M ## Devuelve el mínimo común múltiplo. -LN = LN ## Devuelve el logaritmo natural (neperiano) de un número. -LOG = LOG ## Devuelve el logaritmo de un número en una base especificada. -LOG10 = LOG10 ## Devuelve el logaritmo en base 10 de un número. -MDETERM = MDETERM ## Devuelve la determinante matricial de una matriz. -MINVERSE = MINVERSA ## Devuelve la matriz inversa de una matriz. -MMULT = MMULT ## Devuelve el producto de matriz de dos matrices. -MOD = RESIDUO ## Devuelve el resto de la división. -MROUND = REDOND.MULT ## Devuelve un número redondeado al múltiplo deseado. -MULTINOMIAL = MULTINOMIAL ## Devuelve el polinomio de un conjunto de números. -ODD = REDONDEA.IMPAR ## Redondea un número hacia arriba hasta el entero impar más próximo. -PI = PI ## Devuelve el valor de pi. -POWER = POTENCIA ## Devuelve el resultado de elevar un número a una potencia. -PRODUCT = PRODUCTO ## Multiplica sus argumentos. -QUOTIENT = COCIENTE ## Devuelve la parte entera de una división. -RADIANS = RADIANES ## Convierte grados en radianes. -RAND = ALEATORIO ## Devuelve un número aleatorio entre 0 y 1. -RANDBETWEEN = ALEATORIO.ENTRE ## Devuelve un número aleatorio entre los números que especifique. -ROMAN = NUMERO.ROMANO ## Convierte un número arábigo en número romano, con formato de texto. -ROUND = REDONDEAR ## Redondea un número al número de decimales especificado. -ROUNDDOWN = REDONDEAR.MENOS ## Redondea un número hacia abajo, en dirección hacia cero. -ROUNDUP = REDONDEAR.MAS ## Redondea un número hacia arriba, en dirección contraria a cero. -SERIESSUM = SUMA.SERIES ## Devuelve la suma de una serie de potencias en función de la fórmula. -SIGN = SIGNO ## Devuelve el signo de un número. -SIN = SENO ## Devuelve el seno de un ángulo determinado. -SINH = SENOH ## Devuelve el seno hiperbólico de un número. -SQRT = RAIZ ## Devuelve la raíz cuadrada positiva de un número. -SQRTPI = RAIZ2PI ## Devuelve la raíz cuadrada de un número multiplicado por PI (número * pi). -SUBTOTAL = SUBTOTALES ## Devuelve un subtotal en una lista o base de datos. -SUM = SUMA ## Suma sus argumentos. -SUMIF = SUMAR.SI ## Suma las celdas especificadas que cumplen unos criterios determinados. -SUMIFS = SUMAR.SI.CONJUNTO ## Suma las celdas de un rango que cumplen varios criterios. -SUMPRODUCT = SUMAPRODUCTO ## Devuelve la suma de los productos de los correspondientes componentes de matriz. -SUMSQ = SUMA.CUADRADOS ## Devuelve la suma de los cuadrados de los argumentos. -SUMX2MY2 = SUMAX2MENOSY2 ## Devuelve la suma de la diferencia de los cuadrados de los valores correspondientes de dos matrices. -SUMX2PY2 = SUMAX2MASY2 ## Devuelve la suma de la suma de los cuadrados de los valores correspondientes de dos matrices. -SUMXMY2 = SUMAXMENOSY2 ## Devuelve la suma de los cuadrados de las diferencias de los valores correspondientes de dos matrices. -TAN = TAN ## Devuelve la tangente de un número. -TANH = TANH ## Devuelve la tangente hiperbólica de un número. -TRUNC = TRUNCAR ## Trunca un número a un entero. - +AVEDEV = DESVPROM +AVERAGE = PROMEDIO +AVERAGEA = PROMEDIOA +AVERAGEIF = PROMEDIO.SI +AVERAGEIFS = PROMEDIO.SI.CONJUNTO +BETA.DIST = DISTR.BETA.N +BETA.INV = INV.BETA.N +BINOM.DIST = DISTR.BINOM.N +BINOM.DIST.RANGE = DISTR.BINOM.SERIE +BINOM.INV = INV.BINOM +CHISQ.DIST = DISTR.CHICUAD +CHISQ.DIST.RT = DISTR.CHICUAD.CD +CHISQ.INV = INV.CHICUAD +CHISQ.INV.RT = INV.CHICUAD.CD +CHISQ.TEST = PRUEBA.CHICUAD +CONFIDENCE.NORM = INTERVALO.CONFIANZA.NORM +CONFIDENCE.T = INTERVALO.CONFIANZA.T +CORREL = COEF.DE.CORREL +COUNT = CONTAR +COUNTA = CONTARA +COUNTBLANK = CONTAR.BLANCO +COUNTIF = CONTAR.SI +COUNTIFS = CONTAR.SI.CONJUNTO +COVARIANCE.P = COVARIANCE.P +COVARIANCE.S = COVARIANZA.M +DEVSQ = DESVIA2 +EXPON.DIST = DISTR.EXP.N +F.DIST = DISTR.F.N +F.DIST.RT = DISTR.F.CD +F.INV = INV.F +F.INV.RT = INV.F.CD +F.TEST = PRUEBA.F.N +FISHER = FISHER +FISHERINV = PRUEBA.FISHER.INV +FORECAST.ETS = PRONOSTICO.ETS +FORECAST.ETS.CONFINT = PRONOSTICO.ETS.CONFINT +FORECAST.ETS.SEASONALITY = PRONOSTICO.ETS.ESTACIONALIDAD +FORECAST.ETS.STAT = PRONOSTICO.ETS.STAT +FORECAST.LINEAR = PRONOSTICO.LINEAL +FREQUENCY = FRECUENCIA +GAMMA = GAMMA +GAMMA.DIST = DISTR.GAMMA.N +GAMMA.INV = INV.GAMMA +GAMMALN = GAMMA.LN +GAMMALN.PRECISE = GAMMA.LN.EXACTO +GAUSS = GAUSS +GEOMEAN = MEDIA.GEOM +GROWTH = CRECIMIENTO +HARMEAN = MEDIA.ARMO +HYPGEOM.DIST = DISTR.HIPERGEOM.N +INTERCEPT = INTERSECCION.EJE +KURT = CURTOSIS +LARGE = K.ESIMO.MAYOR +LINEST = ESTIMACION.LINEAL +LOGEST = ESTIMACION.LOGARITMICA +LOGNORM.DIST = DISTR.LOGNORM +LOGNORM.INV = INV.LOGNORM +MAX = MAX +MAXA = MAXA +MAXIFS = MAX.SI.CONJUNTO +MEDIAN = MEDIANA +MIN = MIN +MINA = MINA +MINIFS = MIN.SI.CONJUNTO +MODE.MULT = MODA.VARIOS +MODE.SNGL = MODA.UNO +NEGBINOM.DIST = NEGBINOM.DIST +NORM.DIST = DISTR.NORM.N +NORM.INV = INV.NORM +NORM.S.DIST = DISTR.NORM.ESTAND.N +NORM.S.INV = INV.NORM.ESTAND +PEARSON = PEARSON +PERCENTILE.EXC = PERCENTIL.EXC +PERCENTILE.INC = PERCENTIL.INC +PERCENTRANK.EXC = RANGO.PERCENTIL.EXC +PERCENTRANK.INC = RANGO.PERCENTIL.INC +PERMUT = PERMUTACIONES +PERMUTATIONA = PERMUTACIONES.A +PHI = FI +POISSON.DIST = POISSON.DIST +PROB = PROBABILIDAD +QUARTILE.EXC = CUARTIL.EXC +QUARTILE.INC = CUARTIL.INC +RANK.AVG = JERARQUIA.MEDIA +RANK.EQ = JERARQUIA.EQV +RSQ = COEFICIENTE.R2 +SKEW = COEFICIENTE.ASIMETRIA +SKEW.P = COEFICIENTE.ASIMETRIA.P +SLOPE = PENDIENTE +SMALL = K.ESIMO.MENOR +STANDARDIZE = NORMALIZACION +STDEV.P = DESVEST.P +STDEV.S = DESVEST.M +STDEVA = DESVESTA +STDEVPA = DESVESTPA +STEYX = ERROR.TIPICO.XY +T.DIST = DISTR.T.N +T.DIST.2T = DISTR.T.2C +T.DIST.RT = DISTR.T.CD +T.INV = INV.T +T.INV.2T = INV.T.2C +T.TEST = PRUEBA.T.N +TREND = TENDENCIA +TRIMMEAN = MEDIA.ACOTADA +VAR.P = VAR.P +VAR.S = VAR.S +VARA = VARA +VARPA = VARPA +WEIBULL.DIST = DISTR.WEIBULL +Z.TEST = PRUEBA.Z.N ## -## Statistical functions Funciones estadísticas +## Funciones de texto (Text Functions) ## -AVEDEV = DESVPROM ## Devuelve el promedio de las desviaciones absolutas de la media de los puntos de datos. -AVERAGE = PROMEDIO ## Devuelve el promedio de sus argumentos. -AVERAGEA = PROMEDIOA ## Devuelve el promedio de sus argumentos, incluidos números, texto y valores lógicos. -AVERAGEIF = PROMEDIO.SI ## Devuelve el promedio (media aritmética) de todas las celdas de un rango que cumplen unos criterios determinados. -AVERAGEIFS = PROMEDIO.SI.CONJUNTO ## Devuelve el promedio (media aritmética) de todas las celdas que cumplen múltiples criterios. -BETADIST = DISTR.BETA ## Devuelve la función de distribución beta acumulativa. -BETAINV = DISTR.BETA.INV ## Devuelve la función inversa de la función de distribución acumulativa de una distribución beta especificada. -BINOMDIST = DISTR.BINOM ## Devuelve la probabilidad de una variable aleatoria discreta siguiendo una distribución binomial. -CHIDIST = DISTR.CHI ## Devuelve la probabilidad de una variable aleatoria continua siguiendo una distribución chi cuadrado de una sola cola. -CHIINV = PRUEBA.CHI.INV ## Devuelve la función inversa de la probabilidad de una variable aleatoria continua siguiendo una distribución chi cuadrado de una sola cola. -CHITEST = PRUEBA.CHI ## Devuelve la prueba de independencia. -CONFIDENCE = INTERVALO.CONFIANZA ## Devuelve el intervalo de confianza de la media de una población. -CORREL = COEF.DE.CORREL ## Devuelve el coeficiente de correlación entre dos conjuntos de datos. -COUNT = CONTAR ## Cuenta cuántos números hay en la lista de argumentos. -COUNTA = CONTARA ## Cuenta cuántos valores hay en la lista de argumentos. -COUNTBLANK = CONTAR.BLANCO ## Cuenta el número de celdas en blanco de un rango. -COUNTIF = CONTAR.SI ## Cuenta el número de celdas, dentro del rango, que cumplen el criterio especificado. -COUNTIFS = CONTAR.SI.CONJUNTO ## Cuenta el número de celdas, dentro del rango, que cumplen varios criterios. -COVAR = COVAR ## Devuelve la covarianza, que es el promedio de los productos de las desviaciones para cada pareja de puntos de datos. -CRITBINOM = BINOM.CRIT ## Devuelve el menor valor cuya distribución binomial acumulativa es menor o igual a un valor de criterio. -DEVSQ = DESVIA2 ## Devuelve la suma de los cuadrados de las desviaciones. -EXPONDIST = DISTR.EXP ## Devuelve la distribución exponencial. -FDIST = DISTR.F ## Devuelve la distribución de probabilidad F. -FINV = DISTR.F.INV ## Devuelve la función inversa de la distribución de probabilidad F. -FISHER = FISHER ## Devuelve la transformación Fisher. -FISHERINV = PRUEBA.FISHER.INV ## Devuelve la función inversa de la transformación Fisher. -FORECAST = PRONOSTICO ## Devuelve un valor en una tendencia lineal. -FREQUENCY = FRECUENCIA ## Devuelve una distribución de frecuencia como una matriz vertical. -FTEST = PRUEBA.F ## Devuelve el resultado de una prueba F. -GAMMADIST = DISTR.GAMMA ## Devuelve la distribución gamma. -GAMMAINV = DISTR.GAMMA.INV ## Devuelve la función inversa de la distribución gamma acumulativa. -GAMMALN = GAMMA.LN ## Devuelve el logaritmo natural de la función gamma, G(x). -GEOMEAN = MEDIA.GEOM ## Devuelve la media geométrica. -GROWTH = CRECIMIENTO ## Devuelve valores en una tendencia exponencial. -HARMEAN = MEDIA.ARMO ## Devuelve la media armónica. -HYPGEOMDIST = DISTR.HIPERGEOM ## Devuelve la distribución hipergeométrica. -INTERCEPT = INTERSECCION.EJE ## Devuelve la intersección de la línea de regresión lineal. -KURT = CURTOSIS ## Devuelve la curtosis de un conjunto de datos. -LARGE = K.ESIMO.MAYOR ## Devuelve el k-ésimo mayor valor de un conjunto de datos. -LINEST = ESTIMACION.LINEAL ## Devuelve los parámetros de una tendencia lineal. -LOGEST = ESTIMACION.LOGARITMICA ## Devuelve los parámetros de una tendencia exponencial. -LOGINV = DISTR.LOG.INV ## Devuelve la función inversa de la distribución logarítmico-normal. -LOGNORMDIST = DISTR.LOG.NORM ## Devuelve la distribución logarítmico-normal acumulativa. -MAX = MAX ## Devuelve el valor máximo de una lista de argumentos. -MAXA = MAXA ## Devuelve el valor máximo de una lista de argumentos, incluidos números, texto y valores lógicos. -MEDIAN = MEDIANA ## Devuelve la mediana de los números dados. -MIN = MIN ## Devuelve el valor mínimo de una lista de argumentos. -MINA = MINA ## Devuelve el valor mínimo de una lista de argumentos, incluidos números, texto y valores lógicos. -MODE = MODA ## Devuelve el valor más común de un conjunto de datos. -NEGBINOMDIST = NEGBINOMDIST ## Devuelve la distribución binomial negativa. -NORMDIST = DISTR.NORM ## Devuelve la distribución normal acumulativa. -NORMINV = DISTR.NORM.INV ## Devuelve la función inversa de la distribución normal acumulativa. -NORMSDIST = DISTR.NORM.ESTAND ## Devuelve la distribución normal estándar acumulativa. -NORMSINV = DISTR.NORM.ESTAND.INV ## Devuelve la función inversa de la distribución normal estándar acumulativa. -PEARSON = PEARSON ## Devuelve el coeficiente de momento de correlación de producto Pearson. -PERCENTILE = PERCENTIL ## Devuelve el k-ésimo percentil de los valores de un rango. -PERCENTRANK = RANGO.PERCENTIL ## Devuelve el rango porcentual de un valor de un conjunto de datos. -PERMUT = PERMUTACIONES ## Devuelve el número de permutaciones de un número determinado de objetos. -POISSON = POISSON ## Devuelve la distribución de Poisson. -PROB = PROBABILIDAD ## Devuelve la probabilidad de que los valores de un rango se encuentren entre dos límites. -QUARTILE = CUARTIL ## Devuelve el cuartil de un conjunto de datos. -RANK = JERARQUIA ## Devuelve la jerarquía de un número en una lista de números. -RSQ = COEFICIENTE.R2 ## Devuelve el cuadrado del coeficiente de momento de correlación de producto Pearson. -SKEW = COEFICIENTE.ASIMETRIA ## Devuelve la asimetría de una distribución. -SLOPE = PENDIENTE ## Devuelve la pendiente de la línea de regresión lineal. -SMALL = K.ESIMO.MENOR ## Devuelve el k-ésimo menor valor de un conjunto de datos. -STANDARDIZE = NORMALIZACION ## Devuelve un valor normalizado. -STDEV = DESVEST ## Calcula la desviación estándar a partir de una muestra. -STDEVA = DESVESTA ## Calcula la desviación estándar a partir de una muestra, incluidos números, texto y valores lógicos. -STDEVP = DESVESTP ## Calcula la desviación estándar en función de toda la población. -STDEVPA = DESVESTPA ## Calcula la desviación estándar en función de toda la población, incluidos números, texto y valores lógicos. -STEYX = ERROR.TIPICO.XY ## Devuelve el error estándar del valor de "y" previsto para cada "x" de la regresión. -TDIST = DISTR.T ## Devuelve la distribución de t de Student. -TINV = DISTR.T.INV ## Devuelve la función inversa de la distribución de t de Student. -TREND = TENDENCIA ## Devuelve valores en una tendencia lineal. -TRIMMEAN = MEDIA.ACOTADA ## Devuelve la media del interior de un conjunto de datos. -TTEST = PRUEBA.T ## Devuelve la probabilidad asociada a una prueba t de Student. -VAR = VAR ## Calcula la varianza en función de una muestra. -VARA = VARA ## Calcula la varianza en función de una muestra, incluidos números, texto y valores lógicos. -VARP = VARP ## Calcula la varianza en función de toda la población. -VARPA = VARPA ## Calcula la varianza en función de toda la población, incluidos números, texto y valores lógicos. -WEIBULL = DIST.WEIBULL ## Devuelve la distribución de Weibull. -ZTEST = PRUEBA.Z ## Devuelve el valor de una probabilidad de una cola de una prueba z. - +BAHTTEXT = TEXTOBAHT +CHAR = CARACTER +CLEAN = LIMPIAR +CODE = CODIGO +CONCAT = CONCAT +DOLLAR = MONEDA +EXACT = IGUAL +FIND = ENCONTRAR +FIXED = DECIMAL +ISTHAIDIGIT = ESDIGITOTAI +LEFT = IZQUIERDA +LEN = LARGO +LOWER = MINUSC +MID = EXTRAE +NUMBERSTRING = CADENA.NUMERO +NUMBERVALUE = VALOR.NUMERO +PHONETIC = FONETICO +PROPER = NOMPROPIO +REPLACE = REEMPLAZAR +REPT = REPETIR +RIGHT = DERECHA +SEARCH = HALLAR +SUBSTITUTE = SUSTITUIR +T = T +TEXT = TEXTO +TEXTJOIN = UNIRCADENAS +THAIDIGIT = DIGITOTAI +THAINUMSOUND = SONNUMTAI +THAINUMSTRING = CADENANUMTAI +THAISTRINGLENGTH = LONGCADENATAI +TRIM = ESPACIOS +UNICHAR = UNICAR +UNICODE = UNICODE +UPPER = MAYUSC +VALUE = VALOR ## -## Text functions Funciones de texto +## Funciones web (Web Functions) ## -ASC = ASC ## Convierte las letras inglesas o katakana de ancho completo (de dos bytes) dentro de una cadena de caracteres en caracteres de ancho medio (de un byte). -BAHTTEXT = TEXTOBAHT ## Convierte un número en texto, con el formato de moneda ß (Baht). -CHAR = CARACTER ## Devuelve el carácter especificado por el número de código. -CLEAN = LIMPIAR ## Quita del texto todos los caracteres no imprimibles. -CODE = CODIGO ## Devuelve un código numérico del primer carácter de una cadena de texto. -CONCATENATE = CONCATENAR ## Concatena varios elementos de texto en uno solo. -DOLLAR = MONEDA ## Convierte un número en texto, con el formato de moneda $ (dólar). -EXACT = IGUAL ## Comprueba si dos valores de texto son idénticos. -FIND = ENCONTRAR ## Busca un valor de texto dentro de otro (distingue mayúsculas de minúsculas). -FINDB = ENCONTRARB ## Busca un valor de texto dentro de otro (distingue mayúsculas de minúsculas). -FIXED = DECIMAL ## Da formato a un número como texto con un número fijo de decimales. -JIS = JIS ## Convierte las letras inglesas o katakana de ancho medio (de un byte) dentro de una cadena de caracteres en caracteres de ancho completo (de dos bytes). -LEFT = IZQUIERDA ## Devuelve los caracteres del lado izquierdo de un valor de texto. -LEFTB = IZQUIERDAB ## Devuelve los caracteres del lado izquierdo de un valor de texto. -LEN = LARGO ## Devuelve el número de caracteres de una cadena de texto. -LENB = LARGOB ## Devuelve el número de caracteres de una cadena de texto. -LOWER = MINUSC ## Pone el texto en minúsculas. -MID = EXTRAE ## Devuelve un número específico de caracteres de una cadena de texto que comienza en la posición que se especifique. -MIDB = EXTRAEB ## Devuelve un número específico de caracteres de una cadena de texto que comienza en la posición que se especifique. -PHONETIC = FONETICO ## Extrae los caracteres fonéticos (furigana) de una cadena de texto. -PROPER = NOMPROPIO ## Pone en mayúscula la primera letra de cada palabra de un valor de texto. -REPLACE = REEMPLAZAR ## Reemplaza caracteres de texto. -REPLACEB = REEMPLAZARB ## Reemplaza caracteres de texto. -REPT = REPETIR ## Repite el texto un número determinado de veces. -RIGHT = DERECHA ## Devuelve los caracteres del lado derecho de un valor de texto. -RIGHTB = DERECHAB ## Devuelve los caracteres del lado derecho de un valor de texto. -SEARCH = HALLAR ## Busca un valor de texto dentro de otro (no distingue mayúsculas de minúsculas). -SEARCHB = HALLARB ## Busca un valor de texto dentro de otro (no distingue mayúsculas de minúsculas). -SUBSTITUTE = SUSTITUIR ## Sustituye texto nuevo por texto antiguo en una cadena de texto. -T = T ## Convierte sus argumentos a texto. -TEXT = TEXTO ## Da formato a un número y lo convierte en texto. -TRIM = ESPACIOS ## Quita los espacios del texto. -UPPER = MAYUSC ## Pone el texto en mayúsculas. -VALUE = VALOR ## Convierte un argumento de texto en un número. +ENCODEURL = URLCODIF +FILTERXML = XMLFILTRO +WEBSERVICE = SERVICIOWEB + +## +## Funciones de compatibilidad (Compatibility Functions) +## +BETADIST = DISTR.BETA +BETAINV = DISTR.BETA.INV +BINOMDIST = DISTR.BINOM +CEILING = MULTIPLO.SUPERIOR +CHIDIST = DISTR.CHI +CHIINV = PRUEBA.CHI.INV +CHITEST = PRUEBA.CHI +CONCATENATE = CONCATENAR +CONFIDENCE = INTERVALO.CONFIANZA +COVAR = COVAR +CRITBINOM = BINOM.CRIT +EXPONDIST = DISTR.EXP +FDIST = DISTR.F +FINV = DISTR.F.INV +FLOOR = MULTIPLO.INFERIOR +FORECAST = PRONOSTICO +FTEST = PRUEBA.F +GAMMADIST = DISTR.GAMMA +GAMMAINV = DISTR.GAMMA.INV +HYPGEOMDIST = DISTR.HIPERGEOM +LOGINV = DISTR.LOG.INV +LOGNORMDIST = DISTR.LOG.NORM +MODE = MODA +NEGBINOMDIST = NEGBINOMDIST +NORMDIST = DISTR.NORM +NORMINV = DISTR.NORM.INV +NORMSDIST = DISTR.NORM.ESTAND +NORMSINV = DISTR.NORM.ESTAND.INV +PERCENTILE = PERCENTIL +PERCENTRANK = RANGO.PERCENTIL +POISSON = POISSON +QUARTILE = CUARTIL +RANK = JERARQUIA +STDEV = DESVEST +STDEVP = DESVESTP +TDIST = DISTR.T +TINV = DISTR.T.INV +TTEST = PRUEBA.T +VAR = VAR +VARP = VARP +WEIBULL = DIST.WEIBULL +ZTEST = PRUEBA.Z diff --git a/src/PhpSpreadsheet/Calculation/locale/fi/config b/src/PhpSpreadsheet/Calculation/locale/fi/config index 22aaf58b..5388f939 100644 --- a/src/PhpSpreadsheet/Calculation/locale/fi/config +++ b/src/PhpSpreadsheet/Calculation/locale/fi/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## +## Suomi (Finnish) +## +############################################################ -ArgumentSeparator = ; - +ArgumentSeparator = ; ## -## (For future use) +## Error Codes ## -currencySymbol = $ # Symbol not known, should it be a € (Euro)? - - -## -## Excel Error Codes (For future use) - -## -NULL = #TYHJÄ! -DIV0 = #JAKO/0! -VALUE = #ARVO! -REF = #VIITTAUS! -NAME = #NIMI? -NUM = #LUKU! -NA = #PUUTTUU +NULL = #TYHJÄ! +DIV0 = #JAKO/0! +VALUE = #ARVO! +REF = #VIITTAUS! +NAME = #NIMI? +NUM = #LUKU! +NA = #PUUTTUU! diff --git a/src/PhpSpreadsheet/Calculation/locale/fi/functions b/src/PhpSpreadsheet/Calculation/locale/fi/functions index 289e0eac..33068d93 100644 --- a/src/PhpSpreadsheet/Calculation/locale/fi/functions +++ b/src/PhpSpreadsheet/Calculation/locale/fi/functions @@ -1,416 +1,537 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Suomi (Finnish) ## +############################################################ ## -## Add-in and Automation functions Apuohjelma- ja automaatiofunktiot +## Kuutiofunktiot (Cube Functions) ## -GETPIVOTDATA = NOUDA.PIVOT.TIEDOT ## Palauttaa pivot-taulukkoraporttiin tallennettuja tietoja. - +CUBEKPIMEMBER = KUUTIOKPIJÄSEN +CUBEMEMBER = KUUTIONJÄSEN +CUBEMEMBERPROPERTY = KUUTIONJÄSENENOMINAISUUS +CUBERANKEDMEMBER = KUUTIONLUOKITELTUJÄSEN +CUBESET = KUUTIOJOUKKO +CUBESETCOUNT = KUUTIOJOUKKOJENMÄÄRÄ +CUBEVALUE = KUUTIONARVO ## -## Cube functions Kuutiofunktiot +## Tietokantafunktiot (Database Functions) ## -CUBEKPIMEMBER = KUUTIOKPIJÄSEN ## Palauttaa suorituskykyilmaisimen (KPI) nimen, ominaisuuden sekä mitan ja näyttää nimen sekä ominaisuuden solussa. KPI on mitattavissa oleva suure, kuten kuukauden bruttotuotto tai vuosineljänneksen työntekijäkohtainen liikevaihto, joiden avulla tarkkaillaan organisaation suorituskykyä. -CUBEMEMBER = KUUTIONJÄSEN ## Palauttaa kuutiohierarkian jäsenen tai monikon. Tällä funktiolla voit tarkistaa, että jäsen tai monikko on olemassa kuutiossa. -CUBEMEMBERPROPERTY = KUUTIONJÄSENENOMINAISUUS ## Palauttaa kuution jäsenominaisuuden arvon. Tällä funktiolla voit tarkistaa, että nimi on olemassa kuutiossa, ja palauttaa tämän jäsenen määritetyn ominaisuuden. -CUBERANKEDMEMBER = KUUTIONLUOKITELTUJÄSEN ## Palauttaa joukon n:nnen jäsenen. Tällä funktiolla voit palauttaa joukosta elementtejä, kuten parhaan myyjän tai 10 parasta opiskelijaa. -CUBESET = KUUTIOJOUKKO ## Määrittää lasketun jäsen- tai monikkojoukon lähettämällä joukon lausekkeita palvelimessa olevalle kuutiolle. Palvelin luo joukon ja palauttaa sen Microsoft Office Excelille. -CUBESETCOUNT = KUUTIOJOUKKOJENMÄÄRÄ ## Palauttaa joukon kohteiden määrän. -CUBEVALUE = KUUTIONARVO ## Palauttaa koostetun arvon kuutiosta. - +DAVERAGE = TKESKIARVO +DCOUNT = TLASKE +DCOUNTA = TLASKEA +DGET = TNOUDA +DMAX = TMAKS +DMIN = TMIN +DPRODUCT = TTULO +DSTDEV = TKESKIHAJONTA +DSTDEVP = TKESKIHAJONTAP +DSUM = TSUMMA +DVAR = TVARIANSSI +DVARP = TVARIANSSIP ## -## Database functions Tietokantafunktiot +## Päivämäärä- ja aikafunktiot (Date & Time Functions) ## -DAVERAGE = TKESKIARVO ## Palauttaa valittujen tietokantamerkintöjen keskiarvon. -DCOUNT = TLASKE ## Laskee tietokannan lukuja sisältävien solujen määrän. -DCOUNTA = TLASKEA ## Laskee tietokannan tietoja sisältävien solujen määrän. -DGET = TNOUDA ## Hakee määritettyjä ehtoja vastaavan tietueen tietokannasta. -DMAX = TMAKS ## Palauttaa suurimman arvon tietokannasta valittujen arvojen joukosta. -DMIN = TMIN ## Palauttaa pienimmän arvon tietokannasta valittujen arvojen joukosta. -DPRODUCT = TTULO ## Kertoo määritetyn ehdon täyttävien tietokannan tietueiden tietyssä kentässä olevat arvot. -DSTDEV = TKESKIHAJONTA ## Laskee keskihajonnan tietokannasta valituista arvoista muodostuvan otoksen perusteella. -DSTDEVP = TKESKIHAJONTAP ## Laskee keskihajonnan tietokannasta valittujen arvojen koko populaation perusteella. -DSUM = TSUMMA ## Lisää luvut määritetyn ehdon täyttävien tietokannan tietueiden kenttäsarakkeeseen. -DVAR = TVARIANSSI ## Laskee varianssin tietokannasta valittujen arvojen otoksen perusteella. -DVARP = TVARIANSSIP ## Laskee varianssin tietokannasta valittujen arvojen koko populaation perusteella. - +DATE = PÄIVÄYS +DATEDIF = PVMERO +DATESTRING = PVMMERKKIJONO +DATEVALUE = PÄIVÄYSARVO +DAY = PÄIVÄ +DAYS = PÄIVÄT +DAYS360 = PÄIVÄT360 +EDATE = PÄIVÄ.KUUKAUSI +EOMONTH = KUUKAUSI.LOPPU +HOUR = TUNNIT +ISOWEEKNUM = VIIKKO.ISO.NRO +MINUTE = MINUUTIT +MONTH = KUUKAUSI +NETWORKDAYS = TYÖPÄIVÄT +NETWORKDAYS.INTL = TYÖPÄIVÄT.KANSVÄL +NOW = NYT +SECOND = SEKUNNIT +THAIDAYOFWEEK = THAI.VIIKONPÄIVÄ +THAIMONTHOFYEAR = THAI.KUUKAUSI +THAIYEAR = THAI.VUOSI +TIME = AIKA +TIMEVALUE = AIKA_ARVO +TODAY = TÄMÄ.PÄIVÄ +WEEKDAY = VIIKONPÄIVÄ +WEEKNUM = VIIKKO.NRO +WORKDAY = TYÖPÄIVÄ +WORKDAY.INTL = TYÖPÄIVÄ.KANSVÄL +YEAR = VUOSI +YEARFRAC = VUOSI.OSA ## -## Date and time functions Päivämäärä- ja aikafunktiot +## Tekniset funktiot (Engineering Functions) ## -DATE = PÄIVÄYS ## Palauttaa annetun päivämäärän järjestysluvun. -DATEVALUE = PÄIVÄYSARVO ## Muuntaa tekstimuodossa olevan päivämäärän järjestysluvuksi. -DAY = PÄIVÄ ## Muuntaa järjestysluvun kuukauden päiväksi. -DAYS360 = PÄIVÄT360 ## Laskee kahden päivämäärän välisten päivien määrän käyttäen perustana 360-päiväistä vuotta. -EDATE = PÄIVÄ.KUUKAUSI ## Palauttaa järjestyslukuna päivämäärän, joka poikkeaa aloituspäivän päivämäärästä annetun kuukausimäärän verran joko eteen- tai taaksepäin. -EOMONTH = KUUKAUSI.LOPPU ## Palauttaa järjestyslukuna sen kuukauden viimeisen päivämäärän, joka poikkeaa annetun kuukausimäärän verran eteen- tai taaksepäin. -HOUR = TUNNIT ## Muuntaa järjestysluvun tunneiksi. -MINUTE = MINUUTIT ## Muuntaa järjestysluvun minuuteiksi. -MONTH = KUUKAUSI ## Muuntaa järjestysluvun kuukausiksi. -NETWORKDAYS = TYÖPÄIVÄT ## Palauttaa kahden päivämäärän välissä olevien täysien työpäivien määrän. -NOW = NYT ## Palauttaa kuluvan päivämäärän ja ajan järjestysnumeron. -SECOND = SEKUNNIT ## Muuntaa järjestysluvun sekunneiksi. -TIME = AIKA ## Palauttaa annetun kellonajan järjestysluvun. -TIMEVALUE = AIKA_ARVO ## Muuntaa tekstimuodossa olevan kellonajan järjestysluvuksi. -TODAY = TÄMÄ.PÄIVÄ ## Palauttaa kuluvan päivän päivämäärän järjestysluvun. -WEEKDAY = VIIKONPÄIVÄ ## Muuntaa järjestysluvun viikonpäiväksi. -WEEKNUM = VIIKKO.NRO ## Muuntaa järjestysluvun luvuksi, joka ilmaisee viikon järjestysluvun vuoden alusta laskettuna. -WORKDAY = TYÖPÄIVÄ ## Palauttaa järjestysluvun päivämäärälle, joka sijaitsee annettujen työpäivien verran eteen tai taaksepäin. -YEAR = VUOSI ## Muuntaa järjestysluvun vuosiksi. -YEARFRAC = VUOSI.OSA ## Palauttaa määritettyjen päivämäärien (aloituspäivä ja lopetuspäivä) välisen osan vuodesta. - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BINDES +BIN2HEX = BINHEKSA +BIN2OCT = BINOKT +BITAND = BITTI.JA +BITLSHIFT = BITTI.SIIRTO.V +BITOR = BITTI.TAI +BITRSHIFT = BITTI.SIIRTO.O +BITXOR = BITTI.EHDOTON.TAI +COMPLEX = KOMPLEKSI +CONVERT = MUUNNA +DEC2BIN = DESBIN +DEC2HEX = DESHEKSA +DEC2OCT = DESOKT +DELTA = SAMA.ARVO +ERF = VIRHEFUNKTIO +ERF.PRECISE = VIRHEFUNKTIO.TARKKA +ERFC = VIRHEFUNKTIO.KOMPLEMENTTI +ERFC.PRECISE = VIRHEFUNKTIO.KOMPLEMENTTI.TARKKA +GESTEP = RAJA +HEX2BIN = HEKSABIN +HEX2DEC = HEKSADES +HEX2OCT = HEKSAOKT +IMABS = KOMPLEKSI.ABS +IMAGINARY = KOMPLEKSI.IMAG +IMARGUMENT = KOMPLEKSI.ARG +IMCONJUGATE = KOMPLEKSI.KONJ +IMCOS = KOMPLEKSI.COS +IMCOSH = IMCOSH +IMCOT = KOMPLEKSI.COT +IMCSC = KOMPLEKSI.KOSEK +IMCSCH = KOMPLEKSI.KOSEKH +IMDIV = KOMPLEKSI.OSAM +IMEXP = KOMPLEKSI.EKSP +IMLN = KOMPLEKSI.LN +IMLOG10 = KOMPLEKSI.LOG10 +IMLOG2 = KOMPLEKSI.LOG2 +IMPOWER = KOMPLEKSI.POT +IMPRODUCT = KOMPLEKSI.TULO +IMREAL = KOMPLEKSI.REAALI +IMSEC = KOMPLEKSI.SEK +IMSECH = KOMPLEKSI.SEKH +IMSIN = KOMPLEKSI.SIN +IMSINH = KOMPLEKSI.SINH +IMSQRT = KOMPLEKSI.NELIÖJ +IMSUB = KOMPLEKSI.EROTUS +IMSUM = KOMPLEKSI.SUM +IMTAN = KOMPLEKSI.TAN +OCT2BIN = OKTBIN +OCT2DEC = OKTDES +OCT2HEX = OKTHEKSA ## -## Engineering functions Tekniset funktiot +## Rahoitusfunktiot (Financial Functions) ## -BESSELI = BESSELI ## Palauttaa muunnetun Bessel-funktion In(x). -BESSELJ = BESSELJ ## Palauttaa Bessel-funktion Jn(x). -BESSELK = BESSELK ## Palauttaa muunnetun Bessel-funktion Kn(x). -BESSELY = BESSELY ## Palauttaa Bessel-funktion Yn(x). -BIN2DEC = BINDES ## Muuntaa binaariluvun desimaaliluvuksi. -BIN2HEX = BINHEKSA ## Muuntaa binaariluvun heksadesimaaliluvuksi. -BIN2OCT = BINOKT ## Muuntaa binaariluvun oktaaliluvuksi. -COMPLEX = KOMPLEKSI ## Muuntaa reaali- ja imaginaariosien kertoimet kompleksiluvuksi. -CONVERT = MUUNNA ## Muuntaa luvun toisen mittajärjestelmän mukaiseksi. -DEC2BIN = DESBIN ## Muuntaa desimaaliluvun binaariluvuksi. -DEC2HEX = DESHEKSA ## Muuntaa kymmenjärjestelmän luvun heksadesimaaliluvuksi. -DEC2OCT = DESOKT ## Muuntaa kymmenjärjestelmän luvun oktaaliluvuksi. -DELTA = SAMA.ARVO ## Tarkistaa, ovatko kaksi arvoa yhtä suuria. -ERF = VIRHEFUNKTIO ## Palauttaa virhefunktion. -ERFC = VIRHEFUNKTIO.KOMPLEMENTTI ## Palauttaa komplementtivirhefunktion. -GESTEP = RAJA ## Testaa, onko luku suurempi kuin kynnysarvo. -HEX2BIN = HEKSABIN ## Muuntaa heksadesimaaliluvun binaariluvuksi. -HEX2DEC = HEKSADES ## Muuntaa heksadesimaaliluvun desimaaliluvuksi. -HEX2OCT = HEKSAOKT ## Muuntaa heksadesimaaliluvun oktaaliluvuksi. -IMABS = KOMPLEKSI.ITSEISARVO ## Palauttaa kompleksiluvun itseisarvon (moduluksen). -IMAGINARY = KOMPLEKSI.IMAG ## Palauttaa kompleksiluvun imaginaariosan kertoimen. -IMARGUMENT = KOMPLEKSI.ARG ## Palauttaa theeta-argumentin, joka on radiaaneina annettu kulma. -IMCONJUGATE = KOMPLEKSI.KONJ ## Palauttaa kompleksiluvun konjugaattiluvun. -IMCOS = KOMPLEKSI.COS ## Palauttaa kompleksiluvun kosinin. -IMDIV = KOMPLEKSI.OSAM ## Palauttaa kahden kompleksiluvun osamäärän. -IMEXP = KOMPLEKSI.EKSP ## Palauttaa kompleksiluvun eksponentin. -IMLN = KOMPLEKSI.LN ## Palauttaa kompleksiluvun luonnollisen logaritmin. -IMLOG10 = KOMPLEKSI.LOG10 ## Palauttaa kompleksiluvun kymmenkantaisen logaritmin. -IMLOG2 = KOMPLEKSI.LOG2 ## Palauttaa kompleksiluvun kaksikantaisen logaritmin. -IMPOWER = KOMPLEKSI.POT ## Palauttaa kokonaislukupotenssiin korotetun kompleksiluvun. -IMPRODUCT = KOMPLEKSI.TULO ## Palauttaa kompleksilukujen tulon. -IMREAL = KOMPLEKSI.REAALI ## Palauttaa kompleksiluvun reaaliosan kertoimen. -IMSIN = KOMPLEKSI.SIN ## Palauttaa kompleksiluvun sinin. -IMSQRT = KOMPLEKSI.NELIÖJ ## Palauttaa kompleksiluvun neliöjuuren. -IMSUB = KOMPLEKSI.EROTUS ## Palauttaa kahden kompleksiluvun erotuksen. -IMSUM = KOMPLEKSI.SUM ## Palauttaa kompleksilukujen summan. -OCT2BIN = OKTBIN ## Muuntaa oktaaliluvun binaariluvuksi. -OCT2DEC = OKTDES ## Muuntaa oktaaliluvun desimaaliluvuksi. -OCT2HEX = OKTHEKSA ## Muuntaa oktaaliluvun heksadesimaaliluvuksi. - +ACCRINT = KERTYNYT.KORKO +ACCRINTM = KERTYNYT.KORKO.LOPUSSA +AMORDEGRC = AMORDEGRC +AMORLINC = AMORLINC +COUPDAYBS = KORKOPÄIVÄT.ALUSTA +COUPDAYS = KORKOPÄIVÄT +COUPDAYSNC = KORKOPÄIVÄT.SEURAAVA +COUPNCD = KORKOPÄIVÄ.SEURAAVA +COUPNUM = KORKOPÄIVÄ.JAKSOT +COUPPCD = KORKOPÄIVÄ.EDELLINEN +CUMIPMT = MAKSETTU.KORKO +CUMPRINC = MAKSETTU.LYHENNYS +DB = DB +DDB = DDB +DISC = DISKONTTOKORKO +DOLLARDE = VALUUTTA.DES +DOLLARFR = VALUUTTA.MURTO +DURATION = KESTO +EFFECT = KORKO.EFEKT +FV = TULEVA.ARVO +FVSCHEDULE = TULEVA.ARVO.ERIKORKO +INTRATE = KORKO.ARVOPAPERI +IPMT = IPMT +IRR = SISÄINEN.KORKO +ISPMT = ISPMT +MDURATION = KESTO.MUUNN +MIRR = MSISÄINEN +NOMINAL = KORKO.VUOSI +NPER = NJAKSO +NPV = NNA +ODDFPRICE = PARITON.ENS.NIMELLISARVO +ODDFYIELD = PARITON.ENS.TUOTTO +ODDLPRICE = PARITON.VIIM.NIMELLISARVO +ODDLYIELD = PARITON.VIIM.TUOTTO +PDURATION = KESTO.JAKSO +PMT = MAKSU +PPMT = PPMT +PRICE = HINTA +PRICEDISC = HINTA.DISK +PRICEMAT = HINTA.LUNASTUS +PV = NA +RATE = KORKO +RECEIVED = SAATU.HINTA +RRI = TOT.ROI +SLN = STP +SYD = VUOSIPOISTO +TBILLEQ = OBLIG.TUOTTOPROS +TBILLPRICE = OBLIG.HINTA +TBILLYIELD = OBLIG.TUOTTO +VDB = VDB +XIRR = SISÄINEN.KORKO.JAKSOTON +XNPV = NNA.JAKSOTON +YIELD = TUOTTO +YIELDDISC = TUOTTO.DISK +YIELDMAT = TUOTTO.ERÄP ## -## Financial functions Rahoitusfunktiot +## Tietofunktiot (Information Functions) ## -ACCRINT = KERTYNYT.KORKO ## Laskee arvopaperille kertyneen koron, kun korko kertyy säännöllisin väliajoin. -ACCRINTM = KERTYNYT.KORKO.LOPUSSA ## Laskee arvopaperille kertyneen koron, kun korko maksetaan eräpäivänä. -AMORDEGRC = AMORDEGRC ## Laskee kunkin laskentakauden poiston poistokerrointa käyttämällä. -AMORLINC = AMORLINC ## Palauttaa kunkin laskentakauden poiston. -COUPDAYBS = KORKOPÄIVÄT.ALUSTA ## Palauttaa koronmaksukauden aloituspäivän ja tilityspäivän välisen ajanjakson päivien määrän. -COUPDAYS = KORKOPÄIVÄT ## Palauttaa päivien määrän koronmaksukaudelta, johon tilityspäivä kuuluu. -COUPDAYSNC = KORKOPÄIVÄT.SEURAAVA ## Palauttaa tilityspäivän ja seuraavan koronmaksupäivän välisen ajanjakson päivien määrän. -COUPNCD = KORKOMAKSU.SEURAAVA ## Palauttaa tilityspäivän jälkeisen seuraavan koronmaksupäivän. -COUPNUM = KORKOPÄIVÄJAKSOT ## Palauttaa arvopaperin ostopäivän ja erääntymispäivän välisten koronmaksupäivien määrän. -COUPPCD = KORKOPÄIVÄ.EDELLINEN ## Palauttaa tilityspäivää edeltävän koronmaksupäivän. -CUMIPMT = MAKSETTU.KORKO ## Palauttaa kahden jakson välisenä aikana kertyneen koron. -CUMPRINC = MAKSETTU.LYHENNYS ## Palauttaa lainalle kahden jakson välisenä aikana kertyneen lyhennyksen. -DB = DB ## Palauttaa kauden kirjanpidollisen poiston amerikkalaisen DB-menetelmän (Fixed-declining balance) mukaan. -DDB = DDB ## Palauttaa kauden kirjanpidollisen poiston amerikkalaisen DDB-menetelmän (Double-Declining Balance) tai jonkin muun määrittämäsi menetelmän mukaan. -DISC = DISKONTTOKORKO ## Palauttaa arvopaperin diskonttokoron. -DOLLARDE = VALUUTTA.DES ## Muuntaa murtolukuna ilmoitetun valuuttamäärän desimaaliluvuksi. -DOLLARFR = VALUUTTA.MURTO ## Muuntaa desimaalilukuna ilmaistun valuuttamäärän murtoluvuksi. -DURATION = KESTO ## Palauttaa keston arvopaperille, jonka koronmaksu tapahtuu säännöllisesti. -EFFECT = KORKO.EFEKT ## Palauttaa todellisen vuosikoron. -FV = TULEVA.ARVO ## Palauttaa sijoituksen tulevan arvon. -FVSCHEDULE = TULEVA.ARVO.ERIKORKO ## Palauttaa pääoman tulevan arvon, kun pääomalle on kertynyt korkoa vaihtelevasti. -INTRATE = KORKO.ARVOPAPERI ## Palauttaa arvopaperin korkokannan täysin sijoitetulle arvopaperille. -IPMT = IPMT ## Laskee sijoitukselle tai lainalle tiettynä ajanjaksona kertyvän koron. -IRR = SISÄINEN.KORKO ## Laskee sisäisen korkokannan kassavirrasta muodostuvalle sarjalle. -ISPMT = ONMAKSU ## Laskee sijoituksen maksetun koron tietyllä jaksolla. -MDURATION = KESTO.MUUNN ## Palauttaa muunnetun Macauley-keston arvopaperille, jonka oletettu nimellisarvo on 100 euroa. -MIRR = MSISÄINEN ## Palauttaa sisäisen korkokannan, kun positiivisten ja negatiivisten kassavirtojen rahoituskorko on erilainen. -NOMINAL = KORKO.VUOSI ## Palauttaa vuosittaisen nimelliskoron. -NPER = NJAKSO ## Palauttaa sijoituksen jaksojen määrän. -NPV = NNA ## Palauttaa sijoituksen nykyarvon toistuvista kassavirroista muodostuvan sarjan ja diskonttokoron perusteella. -ODDFPRICE = PARITON.ENS.NIMELLISARVO ## Palauttaa arvopaperin hinnan tilanteessa, jossa ensimmäinen jakso on pariton. -ODDFYIELD = PARITON.ENS.TUOTTO ## Palauttaa arvopaperin tuoton tilanteessa, jossa ensimmäinen jakso on pariton. -ODDLPRICE = PARITON.VIIM.NIMELLISARVO ## Palauttaa arvopaperin hinnan tilanteessa, jossa viimeinen jakso on pariton. -ODDLYIELD = PARITON.VIIM.TUOTTO ## Palauttaa arvopaperin tuoton tilanteessa, jossa viimeinen jakso on pariton. -PMT = MAKSU ## Palauttaa annuiteetin kausittaisen maksuerän. -PPMT = PPMT ## Laskee sijoitukselle tai lainalle tiettynä ajanjaksona maksettavan lyhennyksen. -PRICE = HINTA ## Palauttaa hinnan 100 euron nimellisarvoa kohden arvopaperille, jonka korko maksetaan säännöllisin väliajoin. -PRICEDISC = HINTA.DISK ## Palauttaa diskontatun arvopaperin hinnan 100 euron nimellisarvoa kohden. -PRICEMAT = HINTA.LUNASTUS ## Palauttaa hinnan 100 euron nimellisarvoa kohden arvopaperille, jonka korko maksetaan erääntymispäivänä. -PV = NA ## Palauttaa sijoituksen nykyarvon. -RATE = KORKO ## Palauttaa annuiteetin kausittaisen korkokannan. -RECEIVED = SAATU.HINTA ## Palauttaa arvopaperin tuoton erääntymispäivänä kokonaan maksetulle sijoitukselle. -SLN = STP ## Palauttaa sijoituksen tasapoiston yhdeltä jaksolta. -SYD = VUOSIPOISTO ## Palauttaa sijoituksen vuosipoiston annettuna kautena amerikkalaisen SYD-menetelmän (Sum-of-Year's Digits) avulla. -TBILLEQ = OBLIG.TUOTTOPROS ## Palauttaa valtion obligaation tuoton vastaavana joukkovelkakirjan tuottona. -TBILLPRICE = OBLIG.HINTA ## Palauttaa obligaation hinnan 100 euron nimellisarvoa kohden. -TBILLYIELD = OBLIG.TUOTTO ## Palauttaa obligaation tuoton. -VDB = VDB ## Palauttaa annetun kauden tai kauden osan kirjanpidollisen poiston amerikkalaisen DB-menetelmän (Fixed-declining balance) mukaan. -XIRR = SISÄINEN.KORKO.JAKSOTON ## Palauttaa sisäisen korkokannan kassavirtojen sarjoille, jotka eivät välttämättä ole säännöllisiä. -XNPV = NNA.JAKSOTON ## Palauttaa nettonykyarvon kassavirtasarjalle, joka ei välttämättä ole kausittainen. -YIELD = TUOTTO ## Palauttaa tuoton arvopaperille, jonka korko maksetaan säännöllisin väliajoin. -YIELDDISC = TUOTTO.DISK ## Palauttaa diskontatun arvopaperin, kuten obligaation, vuosittaisen tuoton. -YIELDMAT = TUOTTO.ERÄP ## Palauttaa erääntymispäivänään korkoa tuottavan arvopaperin vuosittaisen tuoton. - +CELL = SOLU +ERROR.TYPE = VIRHEEN.LAJI +INFO = KUVAUS +ISBLANK = ONTYHJÄ +ISERR = ONVIRH +ISERROR = ONVIRHE +ISEVEN = ONPARILLINEN +ISFORMULA = ONKAAVA +ISLOGICAL = ONTOTUUS +ISNA = ONPUUTTUU +ISNONTEXT = ONEI_TEKSTI +ISNUMBER = ONLUKU +ISODD = ONPARITON +ISREF = ONVIITT +ISTEXT = ONTEKSTI +N = N +NA = PUUTTUU +SHEET = TAULUKKO +SHEETS = TAULUKOT +TYPE = TYYPPI ## -## Information functions Erikoisfunktiot +## Loogiset funktiot (Logical Functions) ## -CELL = SOLU ## Palauttaa tietoja solun muotoilusta, sijainnista ja sisällöstä. -ERROR.TYPE = VIRHEEN.LAJI ## Palauttaa virhetyyppiä vastaavan luvun. -INFO = KUVAUS ## Palauttaa tietoja nykyisestä käyttöympäristöstä. -ISBLANK = ONTYHJÄ ## Palauttaa arvon TOSI, jos arvo on tyhjä. -ISERR = ONVIRH ## Palauttaa arvon TOSI, jos arvo on mikä tahansa virhearvo paitsi arvo #PUUTTUU!. -ISERROR = ONVIRHE ## Palauttaa arvon TOSI, jos arvo on mikä tahansa virhearvo. -ISEVEN = ONPARILLINEN ## Palauttaa arvon TOSI, jos arvo on parillinen. -ISLOGICAL = ONTOTUUS ## Palauttaa arvon TOSI, jos arvo on mikä tahansa looginen arvo. -ISNA = ONPUUTTUU ## Palauttaa arvon TOSI, jos virhearvo on #PUUTTUU!. -ISNONTEXT = ONEI_TEKSTI ## Palauttaa arvon TOSI, jos arvo ei ole teksti. -ISNUMBER = ONLUKU ## Palauttaa arvon TOSI, jos arvo on luku. -ISODD = ONPARITON ## Palauttaa arvon TOSI, jos arvo on pariton. -ISREF = ONVIITT ## Palauttaa arvon TOSI, jos arvo on viittaus. -ISTEXT = ONTEKSTI ## Palauttaa arvon TOSI, jos arvo on teksti. -N = N ## Palauttaa arvon luvuksi muunnettuna. -NA = PUUTTUU ## Palauttaa virhearvon #PUUTTUU!. -TYPE = TYYPPI ## Palauttaa luvun, joka ilmaisee arvon tietotyypin. - +AND = JA +FALSE = EPÄTOSI +IF = JOS +IFERROR = JOSVIRHE +IFNA = JOSPUUTTUU +IFS = JOSS +NOT = EI +OR = TAI +SWITCH = MUUTA +TRUE = TOSI +XOR = EHDOTON.TAI ## -## Logical functions Loogiset funktiot +## Haku- ja viitefunktiot (Lookup & Reference Functions) ## -AND = JA ## Palauttaa arvon TOSI, jos kaikkien argumenttien arvo on TOSI. -FALSE = EPÄTOSI ## Palauttaa totuusarvon EPÄTOSI. -IF = JOS ## Määrittää suoritettavan loogisen testin. -IFERROR = JOSVIRHE ## Palauttaa määrittämäsi arvon, jos kaavan tulos on virhe; muussa tapauksessa palauttaa kaavan tuloksen. -NOT = EI ## Kääntää argumentin loogisen arvon. -OR = TAI ## Palauttaa arvon TOSI, jos minkä tahansa argumentin arvo on TOSI. -TRUE = TOSI ## Palauttaa totuusarvon TOSI. - +ADDRESS = OSOITE +AREAS = ALUEET +CHOOSE = VALITSE.INDEKSI +COLUMN = SARAKE +COLUMNS = SARAKKEET +FORMULATEXT = KAAVA.TEKSTI +GETPIVOTDATA = NOUDA.PIVOT.TIEDOT +HLOOKUP = VHAKU +HYPERLINK = HYPERLINKKI +INDEX = INDEKSI +INDIRECT = EPÄSUORA +LOOKUP = HAKU +MATCH = VASTINE +OFFSET = SIIRTYMÄ +ROW = RIVI +ROWS = RIVIT +RTD = RTD +TRANSPOSE = TRANSPONOI +VLOOKUP = PHAKU ## -## Lookup and reference functions Haku- ja viitefunktiot +## Matemaattiset ja trigonometriset funktiot (Math & Trig Functions) ## -ADDRESS = OSOITE ## Palauttaa laskentataulukon soluun osoittavan viittauksen tekstinä. -AREAS = ALUEET ## Palauttaa viittauksessa olevien alueiden määrän. -CHOOSE = VALITSE.INDEKSI ## Valitsee arvon arvoluettelosta. -COLUMN = SARAKE ## Palauttaa viittauksen sarakenumeron. -COLUMNS = SARAKKEET ## Palauttaa viittauksessa olevien sarakkeiden määrän. -HLOOKUP = VHAKU ## Suorittaa haun matriisin ylimmältä riviltä ja palauttaa määritetyn solun arvon. -HYPERLINK = HYPERLINKKI ## Luo pikakuvakkeen tai tekstin, joka avaa verkkopalvelimeen, intranetiin tai Internetiin tallennetun tiedoston. -INDEX = INDEKSI ## Valitsee arvon viittauksesta tai matriisista indeksin mukaan. -INDIRECT = EPÄSUORA ## Palauttaa tekstiarvona ilmaistun viittauksen. -LOOKUP = HAKU ## Etsii arvoja vektorista tai matriisista. -MATCH = VASTINE ## Etsii arvoja viittauksesta tai matriisista. -OFFSET = SIIRTYMÄ ## Palauttaa annetun viittauksen siirtymän. -ROW = RIVI ## Palauttaa viittauksen rivinumeron. -ROWS = RIVIT ## Palauttaa viittauksessa olevien rivien määrän. -RTD = RTD ## Noutaa COM-automaatiota (automaatio: Tapa käsitellä sovelluksen objekteja toisesta sovelluksesta tai kehitystyökalusta. Automaatio, jota aiemmin kutsuttiin OLE-automaatioksi, on teollisuusstandardi ja COM-mallin (Component Object Model) ominaisuus.) tukevasta ohjelmasta reaaliaikaisia tietoja. -TRANSPOSE = TRANSPONOI ## Palauttaa matriisin käänteismatriisin. -VLOOKUP = PHAKU ## Suorittaa haun matriisin ensimmäisestä sarakkeesta ja palauttaa rivillä olevan solun arvon. - +ABS = ITSEISARVO +ACOS = ACOS +ACOSH = ACOSH +ACOT = ACOT +ACOTH = ACOTH +AGGREGATE = KOOSTE +ARABIC = ARABIA +ASIN = ASIN +ASINH = ASINH +ATAN = ATAN +ATAN2 = ATAN2 +ATANH = ATANH +BASE = PERUS +CEILING.MATH = PYÖRISTÄ.KERR.YLÖS.MATEMAATTINEN +CEILING.PRECISE = PYÖRISTÄ.KERR.YLÖS.TARKKA +COMBIN = KOMBINAATIO +COMBINA = KOMBINAATIOA +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = KOSEK +CSCH = KOSEKH +DECIMAL = DESIMAALI +DEGREES = ASTEET +ECMA.CEILING = ECMA.PYÖRISTÄ.KERR.YLÖS +EVEN = PARILLINEN +EXP = EKSPONENTTI +FACT = KERTOMA +FACTDOUBLE = KERTOMA.OSA +FLOOR.MATH = PYÖRISTÄ.KERR.ALAS.MATEMAATTINEN +FLOOR.PRECISE = PYÖRISTÄ.KERR.ALAS.TARKKA +GCD = SUURIN.YHT.TEKIJÄ +INT = KOKONAISLUKU +ISO.CEILING = ISO.PYÖRISTÄ.KERR.YLÖS +LCM = PIENIN.YHT.JAETTAVA +LN = LUONNLOG +LOG = LOG +LOG10 = LOG10 +MDETERM = MDETERM +MINVERSE = MKÄÄNTEINEN +MMULT = MKERRO +MOD = JAKOJ +MROUND = PYÖRISTÄ.KERR +MULTINOMIAL = MULTINOMI +MUNIT = YKSIKKÖM +ODD = PARITON +PI = PII +POWER = POTENSSI +PRODUCT = TULO +QUOTIENT = OSAMÄÄRÄ +RADIANS = RADIAANIT +RAND = SATUNNAISLUKU +RANDBETWEEN = SATUNNAISLUKU.VÄLILTÄ +ROMAN = ROMAN +ROUND = PYÖRISTÄ +ROUNDBAHTDOWN = PYÖRISTÄ.BAHT.ALAS +ROUNDBAHTUP = PYÖRISTÄ.BAHT.YLÖS +ROUNDDOWN = PYÖRISTÄ.DES.ALAS +ROUNDUP = PYÖRISTÄ.DES.YLÖS +SEC = SEK +SECH = SEKH +SERIESSUM = SARJA.SUMMA +SIGN = ETUMERKKI +SIN = SIN +SINH = SINH +SQRT = NELIÖJUURI +SQRTPI = NELIÖJUURI.PII +SUBTOTAL = VÄLISUMMA +SUM = SUMMA +SUMIF = SUMMA.JOS +SUMIFS = SUMMA.JOS.JOUKKO +SUMPRODUCT = TULOJEN.SUMMA +SUMSQ = NELIÖSUMMA +SUMX2MY2 = NELIÖSUMMIEN.EROTUS +SUMX2PY2 = NELIÖSUMMIEN.SUMMA +SUMXMY2 = EROTUSTEN.NELIÖSUMMA +TAN = TAN +TANH = TANH +TRUNC = KATKAISE ## -## Math and trigonometry functions Matemaattiset ja trigonometriset funktiot +## Tilastolliset funktiot (Statistical Functions) ## -ABS = ITSEISARVO ## Palauttaa luvun itseisarvon. -ACOS = ACOS ## Palauttaa luvun arkuskosinin. -ACOSH = ACOSH ## Palauttaa luvun käänteisen hyperbolisen kosinin. -ASIN = ASIN ## Palauttaa luvun arkussinin. -ASINH = ASINH ## Palauttaa luvun käänteisen hyperbolisen sinin. -ATAN = ATAN ## Palauttaa luvun arkustangentin. -ATAN2 = ATAN2 ## Palauttaa arkustangentin x- ja y-koordinaatin perusteella. -ATANH = ATANH ## Palauttaa luvun käänteisen hyperbolisen tangentin. -CEILING = PYÖRISTÄ.KERR.YLÖS ## Pyöristää luvun lähimpään kokonaislukuun tai tarkkuusargumentin lähimpään kerrannaiseen. -COMBIN = KOMBINAATIO ## Palauttaa mahdollisten kombinaatioiden määrän annetulle objektien määrälle. -COS = COS ## Palauttaa luvun kosinin. -COSH = COSH ## Palauttaa luvun hyperbolisen kosinin. -DEGREES = ASTEET ## Muuntaa radiaanit asteiksi. -EVEN = PARILLINEN ## Pyöristää luvun ylöspäin lähimpään parilliseen kokonaislukuun. -EXP = EKSPONENTTI ## Palauttaa e:n korotettuna annetun luvun osoittamaan potenssiin. -FACT = KERTOMA ## Palauttaa luvun kertoman. -FACTDOUBLE = KERTOMA.OSA ## Palauttaa luvun osakertoman. -FLOOR = PYÖRISTÄ.KERR.ALAS ## Pyöristää luvun alaspäin (nollaa kohti). -GCD = SUURIN.YHT.TEKIJÄ ## Palauttaa suurimman yhteisen tekijän. -INT = KOKONAISLUKU ## Pyöristää luvun alaspäin lähimpään kokonaislukuun. -LCM = PIENIN.YHT.JAETTAVA ## Palauttaa pienimmän yhteisen tekijän. -LN = LUONNLOG ## Palauttaa luvun luonnollisen logaritmin. -LOG = LOG ## Laskee luvun logaritmin käyttämällä annettua kantalukua. -LOG10 = LOG10 ## Palauttaa luvun kymmenkantaisen logaritmin. -MDETERM = MDETERM ## Palauttaa matriisin matriisideterminantin. -MINVERSE = MKÄÄNTEINEN ## Palauttaa matriisin käänteismatriisin. -MMULT = MKERRO ## Palauttaa kahden matriisin tulon. -MOD = JAKOJ ## Palauttaa jakolaskun jäännöksen. -MROUND = PYÖRISTÄ.KERR ## Palauttaa luvun pyöristettynä annetun luvun kerrannaiseen. -MULTINOMIAL = MULTINOMI ## Palauttaa lukujoukon multinomin. -ODD = PARITON ## Pyöristää luvun ylöspäin lähimpään parittomaan kokonaislukuun. -PI = PII ## Palauttaa piin arvon. -POWER = POTENSSI ## Palauttaa luvun korotettuna haluttuun potenssiin. -PRODUCT = TULO ## Kertoo annetut argumentit. -QUOTIENT = OSAMÄÄRÄ ## Palauttaa osamäärän kokonaislukuosan. -RADIANS = RADIAANIT ## Muuntaa asteet radiaaneiksi. -RAND = SATUNNAISLUKU ## Palauttaa satunnaisluvun väliltä 0–1. -RANDBETWEEN = SATUNNAISLUKU.VÄLILTÄ ## Palauttaa satunnaisluvun määritettyjen lukujen väliltä. -ROMAN = ROMAN ## Muuntaa arabialaisen numeron tekstimuotoiseksi roomalaiseksi numeroksi. -ROUND = PYÖRISTÄ ## Pyöristää luvun annettuun määrään desimaaleja. -ROUNDDOWN = PYÖRISTÄ.DES.ALAS ## Pyöristää luvun alaspäin (nollaa kohti). -ROUNDUP = PYÖRISTÄ.DES.YLÖS ## Pyöristää luvun ylöspäin (poispäin nollasta). -SERIESSUM = SARJA.SUMMA ## Palauttaa kaavaan perustuvan potenssisarjan arvon. -SIGN = ETUMERKKI ## Palauttaa luvun etumerkin. -SIN = SIN ## Palauttaa annetun kulman sinin. -SINH = SINH ## Palauttaa luvun hyperbolisen sinin. -SQRT = NELIÖJUURI ## Palauttaa positiivisen neliöjuuren. -SQRTPI = NELIÖJUURI.PII ## Palauttaa tulon (luku * pii) neliöjuuren. -SUBTOTAL = VÄLISUMMA ## Palauttaa luettelon tai tietokannan välisumman. -SUM = SUMMA ## Laskee yhteen annetut argumentit. -SUMIF = SUMMA.JOS ## Laskee ehdot täyttävien solujen summan. -SUMIFS = SUMMA.JOS.JOUKKO ## Laskee yhteen solualueen useita ehtoja vastaavat solut. -SUMPRODUCT = TULOJEN.SUMMA ## Palauttaa matriisin toisiaan vastaavien osien tulojen summan. -SUMSQ = NELIÖSUMMA ## Palauttaa argumenttien neliöiden summan. -SUMX2MY2 = NELIÖSUMMIEN.EROTUS ## Palauttaa kahden matriisin toisiaan vastaavien arvojen laskettujen neliösummien erotuksen. -SUMX2PY2 = NELIÖSUMMIEN.SUMMA ## Palauttaa kahden matriisin toisiaan vastaavien arvojen neliösummien summan. -SUMXMY2 = EROTUSTEN.NELIÖSUMMA ## Palauttaa kahden matriisin toisiaan vastaavien arvojen erotusten neliösumman. -TAN = TAN ## Palauttaa luvun tangentin. -TANH = TANH ## Palauttaa luvun hyperbolisen tangentin. -TRUNC = KATKAISE ## Katkaisee luvun kokonaisluvuksi. - +AVEDEV = KESKIPOIKKEAMA +AVERAGE = KESKIARVO +AVERAGEA = KESKIARVOA +AVERAGEIF = KESKIARVO.JOS +AVERAGEIFS = KESKIARVO.JOS.JOUKKO +BETA.DIST = BEETA.JAKAUMA +BETA.INV = BEETA.KÄÄNT +BINOM.DIST = BINOMI.JAKAUMA +BINOM.DIST.RANGE = BINOMI.JAKAUMA.ALUE +BINOM.INV = BINOMIJAKAUMA.KÄÄNT +CHISQ.DIST = CHINELIÖ.JAKAUMA +CHISQ.DIST.RT = CHINELIÖ.JAKAUMA.OH +CHISQ.INV = CHINELIÖ.KÄÄNT +CHISQ.INV.RT = CHINELIÖ.KÄÄNT.OH +CHISQ.TEST = CHINELIÖ.TESTI +CONFIDENCE.NORM = LUOTTAMUSVÄLI.NORM +CONFIDENCE.T = LUOTTAMUSVÄLI.T +CORREL = KORRELAATIO +COUNT = LASKE +COUNTA = LASKE.A +COUNTBLANK = LASKE.TYHJÄT +COUNTIF = LASKE.JOS +COUNTIFS = LASKE.JOS.JOUKKO +COVARIANCE.P = KOVARIANSSI.P +COVARIANCE.S = KOVARIANSSI.S +DEVSQ = OIKAISTU.NELIÖSUMMA +EXPON.DIST = EKSPONENTIAALI.JAKAUMA +F.DIST = F.JAKAUMA +F.DIST.RT = F.JAKAUMA.OH +F.INV = F.KÄÄNT +F.INV.RT = F.KÄÄNT.OH +F.TEST = F.TESTI +FISHER = FISHER +FISHERINV = FISHER.KÄÄNT +FORECAST.ETS = ENNUSTE.ETS +FORECAST.ETS.CONFINT = ENNUSTE.ETS.CONFINT +FORECAST.ETS.SEASONALITY = ENNUSTE.ETS.KAUSIVAIHTELU +FORECAST.ETS.STAT = ENNUSTE.ETS.STAT +FORECAST.LINEAR = ENNUSTE.LINEAARINEN +FREQUENCY = TAAJUUS +GAMMA = GAMMA +GAMMA.DIST = GAMMA.JAKAUMA +GAMMA.INV = GAMMA.JAKAUMA.KÄÄNT +GAMMALN = GAMMALN +GAMMALN.PRECISE = GAMMALN.TARKKA +GAUSS = GAUSS +GEOMEAN = KESKIARVO.GEOM +GROWTH = KASVU +HARMEAN = KESKIARVO.HARM +HYPGEOM.DIST = HYPERGEOM_JAKAUMA +INTERCEPT = LEIKKAUSPISTE +KURT = KURT +LARGE = SUURI +LINEST = LINREGR +LOGEST = LOGREGR +LOGNORM.DIST = LOGNORM_JAKAUMA +LOGNORM.INV = LOGNORM.KÄÄNT +MAX = MAKS +MAXA = MAKSA +MAXIFS = MAKS.JOS +MEDIAN = MEDIAANI +MIN = MIN +MINA = MINA +MINIFS = MIN.JOS +MODE.MULT = MOODI.USEA +MODE.SNGL = MOODI.YKSI +NEGBINOM.DIST = BINOMI.JAKAUMA.NEG +NORM.DIST = NORMAALI.JAKAUMA +NORM.INV = NORMAALI.JAKAUMA.KÄÄNT +NORM.S.DIST = NORM_JAKAUMA.NORMIT +NORM.S.INV = NORM_JAKAUMA.KÄÄNT +PEARSON = PEARSON +PERCENTILE.EXC = PROSENTTIPISTE.ULK +PERCENTILE.INC = PROSENTTIPISTE.SIS +PERCENTRANK.EXC = PROSENTTIJÄRJESTYS.ULK +PERCENTRANK.INC = PROSENTTIJÄRJESTYS.SIS +PERMUT = PERMUTAATIO +PERMUTATIONA = PERMUTAATIOA +PHI = FII +POISSON.DIST = POISSON.JAKAUMA +PROB = TODENNÄKÖISYYS +QUARTILE.EXC = NELJÄNNES.ULK +QUARTILE.INC = NELJÄNNES.SIS +RANK.AVG = ARVON.MUKAAN.KESKIARVO +RANK.EQ = ARVON.MUKAAN.TASAN +RSQ = PEARSON.NELIÖ +SKEW = JAKAUMAN.VINOUS +SKEW.P = JAKAUMAN.VINOUS.POP +SLOPE = KULMAKERROIN +SMALL = PIENI +STANDARDIZE = NORMITA +STDEV.P = KESKIHAJONTA.P +STDEV.S = KESKIHAJONTA.S +STDEVA = KESKIHAJONTAA +STDEVPA = KESKIHAJONTAPA +STEYX = KESKIVIRHE +T.DIST = T.JAKAUMA +T.DIST.2T = T.JAKAUMA.2S +T.DIST.RT = T.JAKAUMA.OH +T.INV = T.KÄÄNT +T.INV.2T = T.KÄÄNT.2S +T.TEST = T.TESTI +TREND = SUUNTAUS +TRIMMEAN = KESKIARVO.TASATTU +VAR.P = VAR.P +VAR.S = VAR.S +VARA = VARA +VARPA = VARPA +WEIBULL.DIST = WEIBULL.JAKAUMA +Z.TEST = Z.TESTI ## -## Statistical functions Tilastolliset funktiot +## Tekstifunktiot (Text Functions) ## -AVEDEV = KESKIPOIKKEAMA ## Palauttaa hajontojen itseisarvojen keskiarvon. -AVERAGE = KESKIARVO ## Palauttaa argumenttien keskiarvon. -AVERAGEA = KESKIARVOA ## Palauttaa argumenttien, mukaan lukien lukujen, tekstin ja loogisten arvojen, keskiarvon. -AVERAGEIF = KESKIARVO.JOS ## Palauttaa alueen niiden solujen keskiarvon (aritmeettisen keskiarvon), jotka täyttävät annetut ehdot. -AVERAGEIFS = KESKIARVO.JOS.JOUKKO ## Palauttaa niiden solujen keskiarvon (aritmeettisen keskiarvon), jotka vastaavat useita ehtoja. -BETADIST = BEETAJAKAUMA ## Palauttaa kumulatiivisen beetajakaumafunktion arvon. -BETAINV = BEETAJAKAUMA.KÄÄNT ## Palauttaa määritetyn beetajakauman käänteisen kumulatiivisen jakaumafunktion arvon. -BINOMDIST = BINOMIJAKAUMA ## Palauttaa yksittäisen termin binomijakaumatodennäköisyyden. -CHIDIST = CHIJAKAUMA ## Palauttaa yksisuuntaisen chi-neliön jakauman todennäköisyyden. -CHIINV = CHIJAKAUMA.KÄÄNT ## Palauttaa yksisuuntaisen chi-neliön jakauman todennäköisyyden käänteisarvon. -CHITEST = CHITESTI ## Palauttaa riippumattomuustestin tuloksen. -CONFIDENCE = LUOTTAMUSVÄLI ## Palauttaa luottamusvälin populaation keskiarvolle. -CORREL = KORRELAATIO ## Palauttaa kahden arvojoukon korrelaatiokertoimen. -COUNT = LASKE ## Laskee argumenttiluettelossa olevien lukujen määrän. -COUNTA = LASKE.A ## Laskee argumenttiluettelossa olevien arvojen määrän. -COUNTBLANK = LASKE.TYHJÄT ## Laskee alueella olevien tyhjien solujen määrän. -COUNTIF = LASKE.JOS ## Laskee alueella olevien sellaisten solujen määrän, joiden sisältö vastaa annettuja ehtoja. -COUNTIFS = LASKE.JOS.JOUKKO ## Laskee alueella olevien sellaisten solujen määrän, joiden sisältö vastaa useita ehtoja. -COVAR = KOVARIANSSI ## Palauttaa kovarianssin, joka on keskiarvo havaintoaineiston kunkin pisteparin poikkeamien tuloista. -CRITBINOM = BINOMIJAKAUMA.KRIT ## Palauttaa pienimmän arvon, jossa binomijakauman kertymäfunktion arvo on pienempi tai yhtä suuri kuin vertailuarvo. -DEVSQ = OIKAISTU.NELIÖSUMMA ## Palauttaa keskipoikkeamien neliösumman. -EXPONDIST = EKSPONENTIAALIJAKAUMA ## Palauttaa eksponentiaalijakauman. -FDIST = FJAKAUMA ## Palauttaa F-todennäköisyysjakauman. -FINV = FJAKAUMA.KÄÄNT ## Palauttaa F-todennäköisyysjakauman käänteisfunktion. -FISHER = FISHER ## Palauttaa Fisher-muunnoksen. -FISHERINV = FISHER.KÄÄNT ## Palauttaa käänteisen Fisher-muunnoksen. -FORECAST = ENNUSTE ## Palauttaa lineaarisen trendin arvon. -FREQUENCY = TAAJUUS ## Palauttaa frekvenssijakautuman pystysuuntaisena matriisina. -FTEST = FTESTI ## Palauttaa F-testin tuloksen. -GAMMADIST = GAMMAJAKAUMA ## Palauttaa gammajakauman. -GAMMAINV = GAMMAJAKAUMA.KÄÄNT ## Palauttaa käänteisen gammajakauman kertymäfunktion. -GAMMALN = GAMMALN ## Palauttaa gammafunktion luonnollisen logaritmin G(x). -GEOMEAN = KESKIARVO.GEOM ## Palauttaa geometrisen keskiarvon. -GROWTH = KASVU ## Palauttaa eksponentiaalisen trendin arvon. -HARMEAN = KESKIARVO.HARM ## Palauttaa harmonisen keskiarvon. -HYPGEOMDIST = HYPERGEOM.JAKAUMA ## Palauttaa hypergeometrisen jakauman. -INTERCEPT = LEIKKAUSPISTE ## Palauttaa lineaarisen regressiosuoran leikkauspisteen. -KURT = KURT ## Palauttaa tietoalueen vinous-arvon eli huipukkuuden. -LARGE = SUURI ## Palauttaa tietojoukon k:nneksi suurimman arvon. -LINEST = LINREGR ## Palauttaa lineaarisen trendin parametrit. -LOGEST = LOGREGR ## Palauttaa eksponentiaalisen trendin parametrit. -LOGINV = LOGNORM.JAKAUMA.KÄÄNT ## Palauttaa lognormeeratun jakauman käänteisfunktion. -LOGNORMDIST = LOGNORM.JAKAUMA ## Palauttaa lognormaalisen jakauman kertymäfunktion. -MAX = MAKS ## Palauttaa suurimman arvon argumenttiluettelosta. -MAXA = MAKSA ## Palauttaa argumenttien, mukaan lukien lukujen, tekstin ja loogisten arvojen, suurimman arvon. -MEDIAN = MEDIAANI ## Palauttaa annettujen lukujen mediaanin. -MIN = MIN ## Palauttaa pienimmän arvon argumenttiluettelosta. -MINA = MINA ## Palauttaa argumenttien, mukaan lukien lukujen, tekstin ja loogisten arvojen, pienimmän arvon. -MODE = MOODI ## Palauttaa tietojoukossa useimmin esiintyvän arvon. -NEGBINOMDIST = BINOMIJAKAUMA.NEG ## Palauttaa negatiivisen binomijakauman. -NORMDIST = NORM.JAKAUMA ## Palauttaa normaalijakauman kertymäfunktion. -NORMINV = NORM.JAKAUMA.KÄÄNT ## Palauttaa käänteisen normaalijakauman kertymäfunktion. -NORMSDIST = NORM.JAKAUMA.NORMIT ## Palauttaa normitetun normaalijakauman kertymäfunktion. -NORMSINV = NORM.JAKAUMA.NORMIT.KÄÄNT ## Palauttaa normitetun normaalijakauman kertymäfunktion käänteisarvon. -PEARSON = PEARSON ## Palauttaa Pearsonin tulomomenttikorrelaatiokertoimen. -PERCENTILE = PROSENTTIPISTE ## Palauttaa alueen arvojen k:nnen prosenttipisteen. -PERCENTRANK = PROSENTTIJÄRJESTYS ## Palauttaa tietojoukon arvon prosentuaalisen järjestysluvun. -PERMUT = PERMUTAATIO ## Palauttaa mahdollisten permutaatioiden määrän annetulle objektien määrälle. -POISSON = POISSON ## Palauttaa Poissonin todennäköisyysjakauman. -PROB = TODENNÄKÖISYYS ## Palauttaa todennäköisyyden sille, että arvot ovat tietyltä väliltä. -QUARTILE = NELJÄNNES ## Palauttaa tietoalueen neljänneksen. -RANK = ARVON.MUKAAN ## Palauttaa luvun paikan lukuarvoluettelossa. -RSQ = PEARSON.NELIÖ ## Palauttaa Pearsonin tulomomenttikorrelaatiokertoimen neliön. -SKEW = JAKAUMAN.VINOUS ## Palauttaa jakauman vinouden. -SLOPE = KULMAKERROIN ## Palauttaa lineaarisen regressiosuoran kulmakertoimen. -SMALL = PIENI ## Palauttaa tietojoukon k:nneksi pienimmän arvon. -STANDARDIZE = NORMITA ## Palauttaa normitetun arvon. -STDEV = KESKIHAJONTA ## Laskee populaation keskihajonnan otoksen perusteella. -STDEVA = KESKIHAJONTAA ## Laskee populaation keskihajonnan otoksen perusteella, mukaan lukien luvut, tekstin ja loogiset arvot. -STDEVP = KESKIHAJONTAP ## Laskee normaalijakautuman koko populaation perusteella. -STDEVPA = KESKIHAJONTAPA ## Laskee populaation keskihajonnan koko populaation perusteella, mukaan lukien luvut, tekstin ja totuusarvot. -STEYX = KESKIVIRHE ## Palauttaa regression kutakin x-arvoa vastaavan ennustetun y-arvon keskivirheen. -TDIST = TJAKAUMA ## Palauttaa t-jakautuman. -TINV = TJAKAUMA.KÄÄNT ## Palauttaa käänteisen t-jakauman. -TREND = SUUNTAUS ## Palauttaa lineaarisen trendin arvoja. -TRIMMEAN = KESKIARVO.TASATTU ## Palauttaa tietojoukon tasatun keskiarvon. -TTEST = TTESTI ## Palauttaa t-testiin liittyvän todennäköisyyden. -VAR = VAR ## Arvioi populaation varianssia otoksen perusteella. -VARA = VARA ## Laskee populaation varianssin otoksen perusteella, mukaan lukien luvut, tekstin ja loogiset arvot. -VARP = VARP ## Laskee varianssin koko populaation perusteella. -VARPA = VARPA ## Laskee populaation varianssin koko populaation perusteella, mukaan lukien luvut, tekstin ja totuusarvot. -WEIBULL = WEIBULL ## Palauttaa Weibullin jakauman. -ZTEST = ZTESTI ## Palauttaa z-testin yksisuuntaisen todennäköisyysarvon. - +BAHTTEXT = BAHTTEKSTI +CHAR = MERKKI +CLEAN = SIIVOA +CODE = KOODI +CONCAT = YHDISTÄ +DOLLAR = VALUUTTA +EXACT = VERTAA +FIND = ETSI +FIXED = KIINTEÄ +ISTHAIDIGIT = ON.THAI.NUMERO +LEFT = VASEN +LEN = PITUUS +LOWER = PIENET +MID = POIMI.TEKSTI +NUMBERSTRING = NROMERKKIJONO +NUMBERVALUE = NROARVO +PHONETIC = FONEETTINEN +PROPER = ERISNIMI +REPLACE = KORVAA +REPT = TOISTA +RIGHT = OIKEA +SEARCH = KÄY.LÄPI +SUBSTITUTE = VAIHDA +T = T +TEXT = TEKSTI +TEXTJOIN = TEKSTI.YHDISTÄ +THAIDIGIT = THAI.NUMERO +THAINUMSOUND = THAI.LUKU.ÄÄNI +THAINUMSTRING = THAI.LUKU.MERKKIJONO +THAISTRINGLENGTH = THAI.MERKKIJONON.PITUUS +TRIM = POISTA.VÄLIT +UNICHAR = UNICODEMERKKI +UNICODE = UNICODE +UPPER = ISOT +VALUE = ARVO ## -## Text functions Tekstifunktiot +## Verkkofunktiot (Web Functions) ## -ASC = ASC ## Muuntaa merkkijonossa olevat englanninkieliset DBCS- tai katakana-merkit SBCS-merkeiksi. -BAHTTEXT = BAHTTEKSTI ## Muuntaa luvun tekstiksi ß (baht) -valuuttamuotoa käyttämällä. -CHAR = MERKKI ## Palauttaa koodin lukua vastaavan merkin. -CLEAN = SIIVOA ## Poistaa tekstistä kaikki tulostumattomat merkit. -CODE = KOODI ## Palauttaa tekstimerkkijonon ensimmäisen merkin numerokoodin. -CONCATENATE = KETJUTA ## Yhdistää useat merkkijonot yhdeksi merkkijonoksi. -DOLLAR = VALUUTTA ## Muuntaa luvun tekstiksi $ (dollari) -valuuttamuotoa käyttämällä. -EXACT = VERTAA ## Tarkistaa, ovatko kaksi tekstiarvoa samanlaiset. -FIND = ETSI ## Etsii tekstiarvon toisen tekstin sisältä (tunnistaa isot ja pienet kirjaimet). -FINDB = ETSIB ## Etsii tekstiarvon toisen tekstin sisältä (tunnistaa isot ja pienet kirjaimet). -FIXED = KIINTEÄ ## Muotoilee luvun tekstiksi, jossa on kiinteä määrä desimaaleja. -JIS = JIS ## Muuntaa merkkijonossa olevat englanninkieliset SBCS- tai katakana-merkit DBCS-merkeiksi. -LEFT = VASEN ## Palauttaa tekstiarvon vasemmanpuoliset merkit. -LEFTB = VASENB ## Palauttaa tekstiarvon vasemmanpuoliset merkit. -LEN = PITUUS ## Palauttaa tekstimerkkijonon merkkien määrän. -LENB = PITUUSB ## Palauttaa tekstimerkkijonon merkkien määrän. -LOWER = PIENET ## Muuntaa tekstin pieniksi kirjaimiksi. -MID = POIMI.TEKSTI ## Palauttaa määritetyn määrän merkkejä merkkijonosta alkaen annetusta kohdasta. -MIDB = POIMI.TEKSTIB ## Palauttaa määritetyn määrän merkkejä merkkijonosta alkaen annetusta kohdasta. -PHONETIC = FONEETTINEN ## Hakee foneettiset (furigana) merkit merkkijonosta. -PROPER = ERISNIMI ## Muuttaa merkkijonon kunkin sanan ensimmäisen kirjaimen isoksi. -REPLACE = KORVAA ## Korvaa tekstissä olevat merkit. -REPLACEB = KORVAAB ## Korvaa tekstissä olevat merkit. -REPT = TOISTA ## Toistaa tekstin annetun määrän kertoja. -RIGHT = OIKEA ## Palauttaa tekstiarvon oikeanpuoliset merkit. -RIGHTB = OIKEAB ## Palauttaa tekstiarvon oikeanpuoliset merkit. -SEARCH = KÄY.LÄPI ## Etsii tekstiarvon toisen tekstin sisältä (isot ja pienet kirjaimet tulkitaan samoiksi merkeiksi). -SEARCHB = KÄY.LÄPIB ## Etsii tekstiarvon toisen tekstin sisältä (isot ja pienet kirjaimet tulkitaan samoiksi merkeiksi). -SUBSTITUTE = VAIHDA ## Korvaa merkkijonossa olevan tekstin toisella. -T = T ## Muuntaa argumentit tekstiksi. -TEXT = TEKSTI ## Muotoilee luvun ja muuntaa sen tekstiksi. -TRIM = POISTA.VÄLIT ## Poistaa välilyönnit tekstistä. -UPPER = ISOT ## Muuntaa tekstin isoiksi kirjaimiksi. -VALUE = ARVO ## Muuntaa tekstiargumentin luvuksi. +ENCODEURL = URLKOODAUS +FILTERXML = SUODATA.XML +WEBSERVICE = VERKKOPALVELU + +## +## Yhteensopivuusfunktiot (Compatibility Functions) +## +BETADIST = BEETAJAKAUMA +BETAINV = BEETAJAKAUMA.KÄÄNT +BINOMDIST = BINOMIJAKAUMA +CEILING = PYÖRISTÄ.KERR.YLÖS +CHIDIST = CHIJAKAUMA +CHIINV = CHIJAKAUMA.KÄÄNT +CHITEST = CHITESTI +CONCATENATE = KETJUTA +CONFIDENCE = LUOTTAMUSVÄLI +COVAR = KOVARIANSSI +CRITBINOM = BINOMIJAKAUMA.KRIT +EXPONDIST = EKSPONENTIAALIJAKAUMA +FDIST = FJAKAUMA +FINV = FJAKAUMA.KÄÄNT +FLOOR = PYÖRISTÄ.KERR.ALAS +FORECAST = ENNUSTE +FTEST = FTESTI +GAMMADIST = GAMMAJAKAUMA +GAMMAINV = GAMMAJAKAUMA.KÄÄNT +HYPGEOMDIST = HYPERGEOM.JAKAUMA +LOGINV = LOGNORM.JAKAUMA.KÄÄNT +LOGNORMDIST = LOGNORM.JAKAUMA +MODE = MOODI +NEGBINOMDIST = BINOMIJAKAUMA.NEG +NORMDIST = NORM.JAKAUMA +NORMINV = NORM.JAKAUMA.KÄÄNT +NORMSDIST = NORM.JAKAUMA.NORMIT +NORMSINV = NORM.JAKAUMA.NORMIT.KÄÄNT +PERCENTILE = PROSENTTIPISTE +PERCENTRANK = PROSENTTIJÄRJESTYS +POISSON = POISSON +QUARTILE = NELJÄNNES +RANK = ARVON.MUKAAN +STDEV = KESKIHAJONTA +STDEVP = KESKIHAJONTAP +TDIST = TJAKAUMA +TINV = TJAKAUMA.KÄÄNT +TTEST = TTESTI +VAR = VAR +VARP = VARP +WEIBULL = WEIBULL +ZTEST = ZTESTI diff --git a/src/PhpSpreadsheet/Calculation/locale/fr/config b/src/PhpSpreadsheet/Calculation/locale/fr/config index 81895986..bdac4121 100644 --- a/src/PhpSpreadsheet/Calculation/locale/fr/config +++ b/src/PhpSpreadsheet/Calculation/locale/fr/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## +## Français (French) +## +############################################################ -ArgumentSeparator = ; - +ArgumentSeparator = ; ## -## (For future use) +## Error Codes ## -currencySymbol = € - - -## -## Excel Error Codes (For future use) - -## -NULL = #NUL! -DIV0 = #DIV/0! -VALUE = #VALEUR! -REF = #REF! -NAME = #NOM? -NUM = #NOMBRE! -NA = #N/A +NULL = #NUL! +DIV0 +VALUE = #VALEUR! +REF +NAME = #NOM? +NUM = #NOMBRE! +NA diff --git a/src/PhpSpreadsheet/Calculation/locale/fr/functions b/src/PhpSpreadsheet/Calculation/locale/fr/functions index 7f40d5fd..78b603e9 100644 --- a/src/PhpSpreadsheet/Calculation/locale/fr/functions +++ b/src/PhpSpreadsheet/Calculation/locale/fr/functions @@ -1,416 +1,524 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Français (French) ## +############################################################ ## -## Add-in and Automation functions Fonctions de complément et d’automatisation +## Fonctions Cube (Cube Functions) ## -GETPIVOTDATA = LIREDONNEESTABCROISDYNAMIQUE ## Renvoie les données stockées dans un rapport de tableau croisé dynamique. - +CUBEKPIMEMBER = MEMBREKPICUBE +CUBEMEMBER = MEMBRECUBE +CUBEMEMBERPROPERTY = PROPRIETEMEMBRECUBE +CUBERANKEDMEMBER = RANGMEMBRECUBE +CUBESET = JEUCUBE +CUBESETCOUNT = NBJEUCUBE +CUBEVALUE = VALEURCUBE ## -## Cube functions Fonctions Cube +## Fonctions de base de données (Database Functions) ## -CUBEKPIMEMBER = MEMBREKPICUBE ## Renvoie un nom, une propriété et une mesure d’indicateur de performance clé et affiche le nom et la propriété dans la cellule. Un indicateur de performance clé est une mesure quantifiable, telle que la marge bénéficiaire brute mensuelle ou la rotation trimestrielle du personnel, utilisée pour évaluer les performances d’une entreprise. -CUBEMEMBER = MEMBRECUBE ## Renvoie un membre ou un uplet dans une hiérarchie de cubes. Utilisez cette fonction pour valider l’existence du membre ou de l’uplet dans le cube. -CUBEMEMBERPROPERTY = PROPRIETEMEMBRECUBE ## Renvoie la valeur d’une propriété de membre du cube. Utilisez cette fonction pour valider l’existence d’un nom de membre dans le cube et pour renvoyer la propriété spécifiée pour ce membre. -CUBERANKEDMEMBER = RANGMEMBRECUBE ## Renvoie le nième membre ou le membre placé à un certain rang dans un ensemble. Utilisez cette fonction pour renvoyer un ou plusieurs éléments d’un ensemble, tels que les meilleurs vendeurs ou les 10 meilleurs étudiants. -CUBESET = JEUCUBE ## Définit un ensemble calculé de membres ou d’uplets en envoyant une expression définie au cube sur le serveur qui crée l’ensemble et le renvoie à Microsoft Office Excel. -CUBESETCOUNT = NBJEUCUBE ## Renvoie le nombre d’éléments dans un jeu. -CUBEVALUE = VALEURCUBE ## Renvoie une valeur d’agrégation issue d’un cube. - +DAVERAGE = BDMOYENNE +DCOUNT = BDNB +DCOUNTA = BDNBVAL +DGET = BDLIRE +DMAX = BDMAX +DMIN = BDMIN +DPRODUCT = BDPRODUIT +DSTDEV = BDECARTYPE +DSTDEVP = BDECARTYPEP +DSUM = BDSOMME +DVAR = BDVAR +DVARP = BDVARP ## -## Database functions Fonctions de base de données +## Fonctions de date et d’heure (Date & Time Functions) ## -DAVERAGE = BDMOYENNE ## Renvoie la moyenne des entrées de base de données sélectionnées. -DCOUNT = BCOMPTE ## Compte le nombre de cellules d’une base de données qui contiennent des nombres. -DCOUNTA = BDNBVAL ## Compte les cellules non vides d’une base de données. -DGET = BDLIRE ## Extrait d’une base de données un enregistrement unique répondant aux critères spécifiés. -DMAX = BDMAX ## Renvoie la valeur maximale des entrées de base de données sélectionnées. -DMIN = BDMIN ## Renvoie la valeur minimale des entrées de base de données sélectionnées. -DPRODUCT = BDPRODUIT ## Multiplie les valeurs d’un champ particulier des enregistrements d’une base de données, qui répondent aux critères spécifiés. -DSTDEV = BDECARTYPE ## Calcule l’écart type pour un échantillon d’entrées de base de données sélectionnées. -DSTDEVP = BDECARTYPEP ## Calcule l’écart type pour l’ensemble d’une population d’entrées de base de données sélectionnées. -DSUM = BDSOMME ## Ajoute les nombres dans la colonne de champ des enregistrements de la base de données, qui répondent aux critères. -DVAR = BDVAR ## Calcule la variance pour un échantillon d’entrées de base de données sélectionnées. -DVARP = BDVARP ## Calcule la variance pour l’ensemble d’une population d’entrées de base de données sélectionnées. - +DATE = DATE +DATEVALUE = DATEVAL +DAY = JOUR +DAYS = JOURS +DAYS360 = JOURS360 +EDATE = MOIS.DECALER +EOMONTH = FIN.MOIS +HOUR = HEURE +ISOWEEKNUM = NO.SEMAINE.ISO +MINUTE = MINUTE +MONTH = MOIS +NETWORKDAYS = NB.JOURS.OUVRES +NETWORKDAYS.INTL = NB.JOURS.OUVRES.INTL +NOW = MAINTENANT +SECOND = SECONDE +TIME = TEMPS +TIMEVALUE = TEMPSVAL +TODAY = AUJOURDHUI +WEEKDAY = JOURSEM +WEEKNUM = NO.SEMAINE +WORKDAY = SERIE.JOUR.OUVRE +WORKDAY.INTL = SERIE.JOUR.OUVRE.INTL +YEAR = ANNEE +YEARFRAC = FRACTION.ANNEE ## -## Date and time functions Fonctions de date et d’heure +## Fonctions d’ingénierie (Engineering Functions) ## -DATE = DATE ## Renvoie le numéro de série d’une date précise. -DATEVALUE = DATEVAL ## Convertit une date représentée sous forme de texte en numéro de série. -DAY = JOUR ## Convertit un numéro de série en jour du mois. -DAYS360 = JOURS360 ## Calcule le nombre de jours qui séparent deux dates sur la base d’une année de 360 jours. -EDATE = MOIS.DECALER ## Renvoie le numéro séquentiel de la date qui représente une date spécifiée (l’argument date_départ), corrigée en plus ou en moins du nombre de mois indiqué. -EOMONTH = FIN.MOIS ## Renvoie le numéro séquentiel de la date du dernier jour du mois précédant ou suivant la date_départ du nombre de mois indiqué. -HOUR = HEURE ## Convertit un numéro de série en heure. -MINUTE = MINUTE ## Convertit un numéro de série en minute. -MONTH = MOIS ## Convertit un numéro de série en mois. -NETWORKDAYS = NB.JOURS.OUVRES ## Renvoie le nombre de jours ouvrés entiers compris entre deux dates. -NOW = MAINTENANT ## Renvoie le numéro de série de la date et de l’heure du jour. -SECOND = SECONDE ## Convertit un numéro de série en seconde. -TIME = TEMPS ## Renvoie le numéro de série d’une heure précise. -TIMEVALUE = TEMPSVAL ## Convertit une date représentée sous forme de texte en numéro de série. -TODAY = AUJOURDHUI ## Renvoie le numéro de série de la date du jour. -WEEKDAY = JOURSEM ## Convertit un numéro de série en jour de la semaine. -WEEKNUM = NO.SEMAINE ## Convertit un numéro de série en un numéro représentant l’ordre de la semaine dans l’année. -WORKDAY = SERIE.JOUR.OUVRE ## Renvoie le numéro de série de la date avant ou après le nombre de jours ouvrés spécifiés. -YEAR = ANNEE ## Convertit un numéro de série en année. -YEARFRAC = FRACTION.ANNEE ## Renvoie la fraction de l’année représentant le nombre de jours entre la date de début et la date de fin. - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BINDEC +BIN2HEX = BINHEX +BIN2OCT = BINOCT +BITAND = BITET +BITLSHIFT = BITDECALG +BITOR = BITOU +BITRSHIFT = BITDECALD +BITXOR = BITOUEXCLUSIF +COMPLEX = COMPLEXE +CONVERT = CONVERT +DEC2BIN = DECBIN +DEC2HEX = DECHEX +DEC2OCT = DECOCT +DELTA = DELTA +ERF = ERF +ERF.PRECISE = ERF.PRECIS +ERFC = ERFC +ERFC.PRECISE = ERFC.PRECIS +GESTEP = SUP.SEUIL +HEX2BIN = HEXBIN +HEX2DEC = HEXDEC +HEX2OCT = HEXOCT +IMABS = COMPLEXE.MODULE +IMAGINARY = COMPLEXE.IMAGINAIRE +IMARGUMENT = COMPLEXE.ARGUMENT +IMCONJUGATE = COMPLEXE.CONJUGUE +IMCOS = COMPLEXE.COS +IMCOSH = COMPLEXE.COSH +IMCOT = COMPLEXE.COT +IMCSC = COMPLEXE.CSC +IMCSCH = COMPLEXE.CSCH +IMDIV = COMPLEXE.DIV +IMEXP = COMPLEXE.EXP +IMLN = COMPLEXE.LN +IMLOG10 = COMPLEXE.LOG10 +IMLOG2 = COMPLEXE.LOG2 +IMPOWER = COMPLEXE.PUISSANCE +IMPRODUCT = COMPLEXE.PRODUIT +IMREAL = COMPLEXE.REEL +IMSEC = COMPLEXE.SEC +IMSECH = COMPLEXE.SECH +IMSIN = COMPLEXE.SIN +IMSINH = COMPLEXE.SINH +IMSQRT = COMPLEXE.RACINE +IMSUB = COMPLEXE.DIFFERENCE +IMSUM = COMPLEXE.SOMME +IMTAN = COMPLEXE.TAN +OCT2BIN = OCTBIN +OCT2DEC = OCTDEC +OCT2HEX = OCTHEX ## -## Engineering functions Fonctions d’ingénierie +## Fonctions financières (Financial Functions) ## -BESSELI = BESSELI ## Renvoie la fonction Bessel modifiée In(x). -BESSELJ = BESSELJ ## Renvoie la fonction Bessel Jn(x). -BESSELK = BESSELK ## Renvoie la fonction Bessel modifiée Kn(x). -BESSELY = BESSELY ## Renvoie la fonction Bessel Yn(x). -BIN2DEC = BINDEC ## Convertit un nombre binaire en nombre décimal. -BIN2HEX = BINHEX ## Convertit un nombre binaire en nombre hexadécimal. -BIN2OCT = BINOCT ## Convertit un nombre binaire en nombre octal. -COMPLEX = COMPLEXE ## Convertit des coefficients réel et imaginaire en un nombre complexe. -CONVERT = CONVERT ## Convertit un nombre d’une unité de mesure à une autre. -DEC2BIN = DECBIN ## Convertit un nombre décimal en nombre binaire. -DEC2HEX = DECHEX ## Convertit un nombre décimal en nombre hexadécimal. -DEC2OCT = DECOCT ## Convertit un nombre décimal en nombre octal. -DELTA = DELTA ## Teste l’égalité de deux nombres. -ERF = ERF ## Renvoie la valeur de la fonction d’erreur. -ERFC = ERFC ## Renvoie la valeur de la fonction d’erreur complémentaire. -GESTEP = SUP.SEUIL ## Teste si un nombre est supérieur à une valeur de seuil. -HEX2BIN = HEXBIN ## Convertit un nombre hexadécimal en nombre binaire. -HEX2DEC = HEXDEC ## Convertit un nombre hexadécimal en nombre décimal. -HEX2OCT = HEXOCT ## Convertit un nombre hexadécimal en nombre octal. -IMABS = COMPLEXE.MODULE ## Renvoie la valeur absolue (module) d’un nombre complexe. -IMAGINARY = COMPLEXE.IMAGINAIRE ## Renvoie le coefficient imaginaire d’un nombre complexe. -IMARGUMENT = COMPLEXE.ARGUMENT ## Renvoie l’argument thêta, un angle exprimé en radians. -IMCONJUGATE = COMPLEXE.CONJUGUE ## Renvoie le nombre complexe conjugué d’un nombre complexe. -IMCOS = IMCOS ## Renvoie le cosinus d’un nombre complexe. -IMDIV = COMPLEXE.DIV ## Renvoie le quotient de deux nombres complexes. -IMEXP = COMPLEXE.EXP ## Renvoie la fonction exponentielle d’un nombre complexe. -IMLN = COMPLEXE.LN ## Renvoie le logarithme népérien d’un nombre complexe. -IMLOG10 = COMPLEXE.LOG10 ## Calcule le logarithme en base 10 d’un nombre complexe. -IMLOG2 = COMPLEXE.LOG2 ## Calcule le logarithme en base 2 d’un nombre complexe. -IMPOWER = COMPLEXE.PUISSANCE ## Renvoie un nombre complexe élevé à une puissance entière. -IMPRODUCT = COMPLEXE.PRODUIT ## Renvoie le produit de plusieurs nombres complexes. -IMREAL = COMPLEXE.REEL ## Renvoie le coefficient réel d’un nombre complexe. -IMSIN = COMPLEXE.SIN ## Renvoie le sinus d’un nombre complexe. -IMSQRT = COMPLEXE.RACINE ## Renvoie la racine carrée d’un nombre complexe. -IMSUB = COMPLEXE.DIFFERENCE ## Renvoie la différence entre deux nombres complexes. -IMSUM = COMPLEXE.SOMME ## Renvoie la somme de plusieurs nombres complexes. -OCT2BIN = OCTBIN ## Convertit un nombre octal en nombre binaire. -OCT2DEC = OCTDEC ## Convertit un nombre octal en nombre décimal. -OCT2HEX = OCTHEX ## Convertit un nombre octal en nombre hexadécimal. - +ACCRINT = INTERET.ACC +ACCRINTM = INTERET.ACC.MAT +AMORDEGRC = AMORDEGRC +AMORLINC = AMORLINC +COUPDAYBS = NB.JOURS.COUPON.PREC +COUPDAYS = NB.JOURS.COUPONS +COUPDAYSNC = NB.JOURS.COUPON.SUIV +COUPNCD = DATE.COUPON.SUIV +COUPNUM = NB.COUPONS +COUPPCD = DATE.COUPON.PREC +CUMIPMT = CUMUL.INTER +CUMPRINC = CUMUL.PRINCPER +DB = DB +DDB = DDB +DISC = TAUX.ESCOMPTE +DOLLARDE = PRIX.DEC +DOLLARFR = PRIX.FRAC +DURATION = DUREE +EFFECT = TAUX.EFFECTIF +FV = VC +FVSCHEDULE = VC.PAIEMENTS +INTRATE = TAUX.INTERET +IPMT = INTPER +IRR = TRI +ISPMT = ISPMT +MDURATION = DUREE.MODIFIEE +MIRR = TRIM +NOMINAL = TAUX.NOMINAL +NPER = NPM +NPV = VAN +ODDFPRICE = PRIX.PCOUPON.IRREG +ODDFYIELD = REND.PCOUPON.IRREG +ODDLPRICE = PRIX.DCOUPON.IRREG +ODDLYIELD = REND.DCOUPON.IRREG +PDURATION = PDUREE +PMT = VPM +PPMT = PRINCPER +PRICE = PRIX.TITRE +PRICEDISC = VALEUR.ENCAISSEMENT +PRICEMAT = PRIX.TITRE.ECHEANCE +PV = VA +RATE = TAUX +RECEIVED = VALEUR.NOMINALE +RRI = TAUX.INT.EQUIV +SLN = AMORLIN +SYD = SYD +TBILLEQ = TAUX.ESCOMPTE.R +TBILLPRICE = PRIX.BON.TRESOR +TBILLYIELD = RENDEMENT.BON.TRESOR +VDB = VDB +XIRR = TRI.PAIEMENTS +XNPV = VAN.PAIEMENTS +YIELD = RENDEMENT.TITRE +YIELDDISC = RENDEMENT.SIMPLE +YIELDMAT = RENDEMENT.TITRE.ECHEANCE ## -## Financial functions Fonctions financières +## Fonctions d’information (Information Functions) ## -ACCRINT = INTERET.ACC ## Renvoie l’intérêt couru non échu d’un titre dont l’intérêt est perçu périodiquement. -ACCRINTM = INTERET.ACC.MAT ## Renvoie l’intérêt couru non échu d’un titre dont l’intérêt est perçu à l’échéance. -AMORDEGRC = AMORDEGRC ## Renvoie l’amortissement correspondant à chaque période comptable en utilisant un coefficient d’amortissement. -AMORLINC = AMORLINC ## Renvoie l’amortissement d’un bien à la fin d’une période fiscale donnée. -COUPDAYBS = NB.JOURS.COUPON.PREC ## Renvoie le nombre de jours entre le début de la période de coupon et la date de liquidation. -COUPDAYS = NB.JOURS.COUPONS ## Renvoie le nombre de jours pour la période du coupon contenant la date de liquidation. -COUPDAYSNC = NB.JOURS.COUPON.SUIV ## Renvoie le nombre de jours entre la date de liquidation et la date du coupon suivant la date de liquidation. -COUPNCD = DATE.COUPON.SUIV ## Renvoie la première date de coupon ultérieure à la date de règlement. -COUPNUM = NB.COUPONS ## Renvoie le nombre de coupons dus entre la date de règlement et la date d’échéance. -COUPPCD = DATE.COUPON.PREC ## Renvoie la date de coupon précédant la date de règlement. -CUMIPMT = CUMUL.INTER ## Renvoie l’intérêt cumulé payé sur un emprunt entre deux périodes. -CUMPRINC = CUMUL.PRINCPER ## Renvoie le montant cumulé des remboursements du capital d’un emprunt effectués entre deux périodes. -DB = DB ## Renvoie l’amortissement d’un bien pour une période spécifiée en utilisant la méthode de l’amortissement dégressif à taux fixe. -DDB = DDB ## Renvoie l’amortissement d’un bien pour toute période spécifiée, en utilisant la méthode de l’amortissement dégressif à taux double ou selon un coefficient à spécifier. -DISC = TAUX.ESCOMPTE ## Calcule le taux d’escompte d’une transaction. -DOLLARDE = PRIX.DEC ## Convertit un prix en euros, exprimé sous forme de fraction, en un prix en euros exprimé sous forme de nombre décimal. -DOLLARFR = PRIX.FRAC ## Convertit un prix en euros, exprimé sous forme de nombre décimal, en un prix en euros exprimé sous forme de fraction. -DURATION = DUREE ## Renvoie la durée, en années, d’un titre dont l’intérêt est perçu périodiquement. -EFFECT = TAUX.EFFECTIF ## Renvoie le taux d’intérêt annuel effectif. -FV = VC ## Renvoie la valeur future d’un investissement. -FVSCHEDULE = VC.PAIEMENTS ## Calcule la valeur future d’un investissement en appliquant une série de taux d’intérêt composites. -INTRATE = TAUX.INTERET ## Affiche le taux d’intérêt d’un titre totalement investi. -IPMT = INTPER ## Calcule le montant des intérêts d’un investissement pour une période donnée. -IRR = TRI ## Calcule le taux de rentabilité interne d’un investissement pour une succession de trésoreries. -ISPMT = ISPMT ## Calcule le montant des intérêts d’un investissement pour une période donnée. -MDURATION = DUREE.MODIFIEE ## Renvoie la durée de Macauley modifiée pour un titre ayant une valeur nominale hypothétique de 100_euros. -MIRR = TRIM ## Calcule le taux de rentabilité interne lorsque les paiements positifs et négatifs sont financés à des taux différents. -NOMINAL = TAUX.NOMINAL ## Calcule le taux d’intérêt nominal annuel. -NPER = NPM ## Renvoie le nombre de versements nécessaires pour rembourser un emprunt. -NPV = VAN ## Calcule la valeur actuelle nette d’un investissement basé sur une série de décaissements et un taux d’escompte. -ODDFPRICE = PRIX.PCOUPON.IRREG ## Renvoie le prix par tranche de valeur nominale de 100 euros d’un titre dont la première période de coupon est irrégulière. -ODDFYIELD = REND.PCOUPON.IRREG ## Renvoie le taux de rendement d’un titre dont la première période de coupon est irrégulière. -ODDLPRICE = PRIX.DCOUPON.IRREG ## Renvoie le prix par tranche de valeur nominale de 100 euros d’un titre dont la première période de coupon est irrégulière. -ODDLYIELD = REND.DCOUPON.IRREG ## Renvoie le taux de rendement d’un titre dont la dernière période de coupon est irrégulière. -PMT = VPM ## Calcule le paiement périodique d’un investissement donné. -PPMT = PRINCPER ## Calcule, pour une période donnée, la part de remboursement du principal d’un investissement. -PRICE = PRIX.TITRE ## Renvoie le prix d’un titre rapportant des intérêts périodiques, pour une valeur nominale de 100 euros. -PRICEDISC = VALEUR.ENCAISSEMENT ## Renvoie la valeur d’encaissement d’un escompte commercial, pour une valeur nominale de 100 euros. -PRICEMAT = PRIX.TITRE.ECHEANCE ## Renvoie le prix d’un titre dont la valeur nominale est 100 euros et qui rapporte des intérêts à l’échéance. -PV = PV ## Calcule la valeur actuelle d’un investissement. -RATE = TAUX ## Calcule le taux d’intérêt par période pour une annuité. -RECEIVED = VALEUR.NOMINALE ## Renvoie la valeur nominale à échéance d’un effet de commerce. -SLN = AMORLIN ## Calcule l’amortissement linéaire d’un bien pour une période donnée. -SYD = SYD ## Calcule l’amortissement d’un bien pour une période donnée sur la base de la méthode américaine Sum-of-Years Digits (amortissement dégressif à taux décroissant appliqué à une valeur constante). -TBILLEQ = TAUX.ESCOMPTE.R ## Renvoie le taux d’escompte rationnel d’un bon du Trésor. -TBILLPRICE = PRIX.BON.TRESOR ## Renvoie le prix d’un bon du Trésor d’une valeur nominale de 100 euros. -TBILLYIELD = RENDEMENT.BON.TRESOR ## Calcule le taux de rendement d’un bon du Trésor. -VDB = VDB ## Renvoie l’amortissement d’un bien pour une période spécifiée ou partielle en utilisant une méthode de l’amortissement dégressif à taux fixe. -XIRR = TRI.PAIEMENTS ## Calcule le taux de rentabilité interne d’un ensemble de paiements non périodiques. -XNPV = VAN.PAIEMENTS ## Renvoie la valeur actuelle nette d’un ensemble de paiements non périodiques. -YIELD = RENDEMENT.TITRE ## Calcule le rendement d’un titre rapportant des intérêts périodiquement. -YIELDDISC = RENDEMENT.SIMPLE ## Calcule le taux de rendement d’un emprunt à intérêt simple (par exemple, un bon du Trésor). -YIELDMAT = RENDEMENT.TITRE.ECHEANCE ## Renvoie le rendement annuel d’un titre qui rapporte des intérêts à l’échéance. - +CELL = CELLULE +ERROR.TYPE = TYPE.ERREUR +INFO = INFORMATIONS +ISBLANK = ESTVIDE +ISERR = ESTERR +ISERROR = ESTERREUR +ISEVEN = EST.PAIR +ISFORMULA = ESTFORMULE +ISLOGICAL = ESTLOGIQUE +ISNA = ESTNA +ISNONTEXT = ESTNONTEXTE +ISNUMBER = ESTNUM +ISODD = EST.IMPAIR +ISREF = ESTREF +ISTEXT = ESTTEXTE +N = N +NA = NA +SHEET = FEUILLE +SHEETS = FEUILLES +TYPE = TYPE ## -## Information functions Fonctions d’information +## Fonctions logiques (Logical Functions) ## -CELL = CELLULE ## Renvoie des informations sur la mise en forme, l’emplacement et le contenu d’une cellule. -ERROR.TYPE = TYPE.ERREUR ## Renvoie un nombre correspondant à un type d’erreur. -INFO = INFORMATIONS ## Renvoie des informations sur l’environnement d’exploitation actuel. -ISBLANK = ESTVIDE ## Renvoie VRAI si l’argument valeur est vide. -ISERR = ESTERR ## Renvoie VRAI si l’argument valeur fait référence à une valeur d’erreur, sauf #N/A. -ISERROR = ESTERREUR ## Renvoie VRAI si l’argument valeur fait référence à une valeur d’erreur. -ISEVEN = EST.PAIR ## Renvoie VRAI si le chiffre est pair. -ISLOGICAL = ESTLOGIQUE ## Renvoie VRAI si l’argument valeur fait référence à une valeur logique. -ISNA = ESTNA ## Renvoie VRAI si l’argument valeur fait référence à la valeur d’erreur #N/A. -ISNONTEXT = ESTNONTEXTE ## Renvoie VRAI si l’argument valeur ne se présente pas sous forme de texte. -ISNUMBER = ESTNUM ## Renvoie VRAI si l’argument valeur représente un nombre. -ISODD = EST.IMPAIR ## Renvoie VRAI si le chiffre est impair. -ISREF = ESTREF ## Renvoie VRAI si l’argument valeur est une référence. -ISTEXT = ESTTEXTE ## Renvoie VRAI si l’argument valeur se présente sous forme de texte. -N = N ## Renvoie une valeur convertie en nombre. -NA = NA ## Renvoie la valeur d’erreur #N/A. -TYPE = TYPE ## Renvoie un nombre indiquant le type de données d’une valeur. - +AND = ET +FALSE = FAUX +IF = SI +IFERROR = SIERREUR +IFNA = SI.NON.DISP +IFS = SI.CONDITIONS +NOT = NON +OR = OU +SWITCH = SI.MULTIPLE +TRUE = VRAI +XOR = OUX ## -## Logical functions Fonctions logiques +## Fonctions de recherche et de référence (Lookup & Reference Functions) ## -AND = ET ## Renvoie VRAI si tous ses arguments sont VRAI. -FALSE = FAUX ## Renvoie la valeur logique FAUX. -IF = SI ## Spécifie un test logique à effectuer. -IFERROR = SIERREUR ## Renvoie une valeur que vous spécifiez si une formule génère une erreur ; sinon, elle renvoie le résultat de la formule. -NOT = NON ## Inverse la logique de cet argument. -OR = OU ## Renvoie VRAI si un des arguments est VRAI. -TRUE = VRAI ## Renvoie la valeur logique VRAI. - +ADDRESS = ADRESSE +AREAS = ZONES +CHOOSE = CHOISIR +COLUMN = COLONNE +COLUMNS = COLONNES +FORMULATEXT = FORMULETEXTE +GETPIVOTDATA = LIREDONNEESTABCROISDYNAMIQUE +HLOOKUP = RECHERCHEH +HYPERLINK = LIEN_HYPERTEXTE +INDEX = INDEX +INDIRECT = INDIRECT +LOOKUP = RECHERCHE +MATCH = EQUIV +OFFSET = DECALER +ROW = LIGNE +ROWS = LIGNES +RTD = RTD +TRANSPOSE = TRANSPOSE +VLOOKUP = RECHERCHEV ## -## Lookup and reference functions Fonctions de recherche et de référence +## Fonctions mathématiques et trigonométriques (Math & Trig Functions) ## -ADDRESS = ADRESSE ## Renvoie une référence sous forme de texte à une seule cellule d’une feuille de calcul. -AREAS = ZONES ## Renvoie le nombre de zones dans une référence. -CHOOSE = CHOISIR ## Choisit une valeur dans une liste. -COLUMN = COLONNE ## Renvoie le numéro de colonne d’une référence. -COLUMNS = COLONNES ## Renvoie le nombre de colonnes dans une référence. -HLOOKUP = RECHERCHEH ## Effectue une recherche dans la première ligne d’une matrice et renvoie la valeur de la cellule indiquée. -HYPERLINK = LIEN_HYPERTEXTE ## Crée un raccourci ou un renvoi qui ouvre un document stocké sur un serveur réseau, sur un réseau Intranet ou sur Internet. -INDEX = INDEX ## Utilise un index pour choisir une valeur provenant d’une référence ou d’une matrice. -INDIRECT = INDIRECT ## Renvoie une référence indiquée par une valeur de texte. -LOOKUP = RECHERCHE ## Recherche des valeurs dans un vecteur ou une matrice. -MATCH = EQUIV ## Recherche des valeurs dans une référence ou une matrice. -OFFSET = DECALER ## Renvoie une référence décalée par rapport à une référence donnée. -ROW = LIGNE ## Renvoie le numéro de ligne d’une référence. -ROWS = LIGNES ## Renvoie le nombre de lignes dans une référence. -RTD = RTD ## Extrait les données en temps réel à partir d’un programme prenant en charge l’automation COM (Automation : utilisation des objets d'une application à partir d'une autre application ou d'un autre outil de développement. Autrefois appelée OLE Automation, Automation est une norme industrielle et une fonctionnalité du modèle d'objet COM (Component Object Model).). -TRANSPOSE = TRANSPOSE ## Renvoie la transposition d’une matrice. -VLOOKUP = RECHERCHEV ## Effectue une recherche dans la première colonne d’une matrice et se déplace sur la ligne pour renvoyer la valeur d’une cellule. - +ABS = ABS +ACOS = ACOS +ACOSH = ACOSH +ACOT = ACOT +ACOTH = ACOTH +AGGREGATE = AGREGAT +ARABIC = CHIFFRE.ARABE +ASIN = ASIN +ASINH = ASINH +ATAN = ATAN +ATAN2 = ATAN2 +ATANH = ATANH +BASE = BASE +CEILING.MATH = PLAFOND.MATH +CEILING.PRECISE = PLAFOND.PRECIS +COMBIN = COMBIN +COMBINA = COMBINA +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = DECIMAL +DEGREES = DEGRES +ECMA.CEILING = ECMA.PLAFOND +EVEN = PAIR +EXP = EXP +FACT = FACT +FACTDOUBLE = FACTDOUBLE +FLOOR.MATH = PLANCHER.MATH +FLOOR.PRECISE = PLANCHER.PRECIS +GCD = PGCD +INT = ENT +ISO.CEILING = ISO.PLAFOND +LCM = PPCM +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = DETERMAT +MINVERSE = INVERSEMAT +MMULT = PRODUITMAT +MOD = MOD +MROUND = ARRONDI.AU.MULTIPLE +MULTINOMIAL = MULTINOMIALE +MUNIT = MATRICE.UNITAIRE +ODD = IMPAIR +PI = PI +POWER = PUISSANCE +PRODUCT = PRODUIT +QUOTIENT = QUOTIENT +RADIANS = RADIANS +RAND = ALEA +RANDBETWEEN = ALEA.ENTRE.BORNES +ROMAN = ROMAIN +ROUND = ARRONDI +ROUNDDOWN = ARRONDI.INF +ROUNDUP = ARRONDI.SUP +SEC = SEC +SECH = SECH +SERIESSUM = SOMME.SERIES +SIGN = SIGNE +SIN = SIN +SINH = SINH +SQRT = RACINE +SQRTPI = RACINE.PI +SUBTOTAL = SOUS.TOTAL +SUM = SOMME +SUMIF = SOMME.SI +SUMIFS = SOMME.SI.ENS +SUMPRODUCT = SOMMEPROD +SUMSQ = SOMME.CARRES +SUMX2MY2 = SOMME.X2MY2 +SUMX2PY2 = SOMME.X2PY2 +SUMXMY2 = SOMME.XMY2 +TAN = TAN +TANH = TANH +TRUNC = TRONQUE ## -## Math and trigonometry functions Fonctions mathématiques et trigonométriques +## Fonctions statistiques (Statistical Functions) ## -ABS = ABS ## Renvoie la valeur absolue d’un nombre. -ACOS = ACOS ## Renvoie l’arccosinus d’un nombre. -ACOSH = ACOSH ## Renvoie le cosinus hyperbolique inverse d’un nombre. -ASIN = ASIN ## Renvoie l’arcsinus d’un nombre. -ASINH = ASINH ## Renvoie le sinus hyperbolique inverse d’un nombre. -ATAN = ATAN ## Renvoie l’arctangente d’un nombre. -ATAN2 = ATAN2 ## Renvoie l’arctangente des coordonnées x et y. -ATANH = ATANH ## Renvoie la tangente hyperbolique inverse d’un nombre. -CEILING = PLAFOND ## Arrondit un nombre au nombre entier le plus proche ou au multiple le plus proche de l’argument précision en s’éloignant de zéro. -COMBIN = COMBIN ## Renvoie le nombre de combinaisons que l’on peut former avec un nombre donné d’objets. -COS = COS ## Renvoie le cosinus d’un nombre. -COSH = COSH ## Renvoie le cosinus hyperbolique d’un nombre. -DEGREES = DEGRES ## Convertit des radians en degrés. -EVEN = PAIR ## Arrondit un nombre au nombre entier pair le plus proche en s’éloignant de zéro. -EXP = EXP ## Renvoie e élevé à la puissance d’un nombre donné. -FACT = FACT ## Renvoie la factorielle d’un nombre. -FACTDOUBLE = FACTDOUBLE ## Renvoie la factorielle double d’un nombre. -FLOOR = PLANCHER ## Arrondit un nombre en tendant vers 0 (zéro). -GCD = PGCD ## Renvoie le plus grand commun diviseur. -INT = ENT ## Arrondit un nombre à l’entier immédiatement inférieur. -LCM = PPCM ## Renvoie le plus petit commun multiple. -LN = LN ## Renvoie le logarithme népérien d’un nombre. -LOG = LOG ## Renvoie le logarithme d’un nombre dans la base spécifiée. -LOG10 = LOG10 ## Calcule le logarithme en base 10 d’un nombre. -MDETERM = DETERMAT ## Renvoie le déterminant d’une matrice. -MINVERSE = INVERSEMAT ## Renvoie la matrice inverse d’une matrice. -MMULT = PRODUITMAT ## Renvoie le produit de deux matrices. -MOD = MOD ## Renvoie le reste d’une division. -MROUND = ARRONDI.AU.MULTIPLE ## Donne l’arrondi d’un nombre au multiple spécifié. -MULTINOMIAL = MULTINOMIALE ## Calcule la multinomiale d’un ensemble de nombres. -ODD = IMPAIR ## Renvoie le nombre, arrondi à la valeur du nombre entier impair le plus proche en s’éloignant de zéro. -PI = PI ## Renvoie la valeur de pi. -POWER = PUISSANCE ## Renvoie la valeur du nombre élevé à une puissance. -PRODUCT = PRODUIT ## Multiplie ses arguments. -QUOTIENT = QUOTIENT ## Renvoie la partie entière du résultat d’une division. -RADIANS = RADIANS ## Convertit des degrés en radians. -RAND = ALEA ## Renvoie un nombre aléatoire compris entre 0 et 1. -RANDBETWEEN = ALEA.ENTRE.BORNES ## Renvoie un nombre aléatoire entre les nombres que vous spécifiez. -ROMAN = ROMAIN ## Convertit des chiffres arabes en chiffres romains, sous forme de texte. -ROUND = ARRONDI ## Arrondit un nombre au nombre de chiffres indiqué. -ROUNDDOWN = ARRONDI.INF ## Arrondit un nombre en tendant vers 0 (zéro). -ROUNDUP = ARRONDI.SUP ## Arrondit un nombre à l’entier supérieur, en s’éloignant de zéro. -SERIESSUM = SOMME.SERIES ## Renvoie la somme d’une série géométrique en s’appuyant sur la formule suivante : -SIGN = SIGNE ## Renvoie le signe d’un nombre. -SIN = SIN ## Renvoie le sinus d’un angle donné. -SINH = SINH ## Renvoie le sinus hyperbolique d’un nombre. -SQRT = RACINE ## Renvoie la racine carrée d’un nombre. -SQRTPI = RACINE.PI ## Renvoie la racine carrée de (nombre * pi). -SUBTOTAL = SOUS.TOTAL ## Renvoie un sous-total dans une liste ou une base de données. -SUM = SOMME ## Calcule la somme de ses arguments. -SUMIF = SOMME.SI ## Additionne les cellules spécifiées si elles répondent à un critère donné. -SUMIFS = SOMME.SI.ENS ## Ajoute les cellules d’une plage qui répondent à plusieurs critères. -SUMPRODUCT = SOMMEPROD ## Multiplie les valeurs correspondantes des matrices spécifiées et calcule la somme de ces produits. -SUMSQ = SOMME.CARRES ## Renvoie la somme des carrés des arguments. -SUMX2MY2 = SOMME.X2MY2 ## Renvoie la somme de la différence des carrés des valeurs correspondantes de deux matrices. -SUMX2PY2 = SOMME.X2PY2 ## Renvoie la somme de la somme des carrés des valeurs correspondantes de deux matrices. -SUMXMY2 = SOMME.XMY2 ## Renvoie la somme des carrés des différences entre les valeurs correspondantes de deux matrices. -TAN = TAN ## Renvoie la tangente d’un nombre. -TANH = TANH ## Renvoie la tangente hyperbolique d’un nombre. -TRUNC = TRONQUE ## Renvoie la partie entière d’un nombre. - +AVEDEV = ECART.MOYEN +AVERAGE = MOYENNE +AVERAGEA = AVERAGEA +AVERAGEIF = MOYENNE.SI +AVERAGEIFS = MOYENNE.SI.ENS +BETA.DIST = LOI.BETA.N +BETA.INV = BETA.INVERSE.N +BINOM.DIST = LOI.BINOMIALE.N +BINOM.DIST.RANGE = LOI.BINOMIALE.SERIE +BINOM.INV = LOI.BINOMIALE.INVERSE +CHISQ.DIST = LOI.KHIDEUX.N +CHISQ.DIST.RT = LOI.KHIDEUX.DROITE +CHISQ.INV = LOI.KHIDEUX.INVERSE +CHISQ.INV.RT = LOI.KHIDEUX.INVERSE.DROITE +CHISQ.TEST = CHISQ.TEST +CONFIDENCE.NORM = INTERVALLE.CONFIANCE.NORMAL +CONFIDENCE.T = INTERVALLE.CONFIANCE.STUDENT +CORREL = COEFFICIENT.CORRELATION +COUNT = NB +COUNTA = NBVAL +COUNTBLANK = NB.VIDE +COUNTIF = NB.SI +COUNTIFS = NB.SI.ENS +COVARIANCE.P = COVARIANCE.PEARSON +COVARIANCE.S = COVARIANCE.STANDARD +DEVSQ = SOMME.CARRES.ECARTS +EXPON.DIST = LOI.EXPONENTIELLE.N +F.DIST = LOI.F.N +F.DIST.RT = LOI.F.DROITE +F.INV = INVERSE.LOI.F.N +F.INV.RT = INVERSE.LOI.F.DROITE +F.TEST = F.TEST +FISHER = FISHER +FISHERINV = FISHER.INVERSE +FORECAST.ETS = PREVISION.ETS +FORECAST.ETS.CONFINT = PREVISION.ETS.CONFINT +FORECAST.ETS.SEASONALITY = PREVISION.ETS.CARACTERESAISONNIER +FORECAST.ETS.STAT = PREVISION.ETS.STAT +FORECAST.LINEAR = PREVISION.LINEAIRE +FREQUENCY = FREQUENCE +GAMMA = GAMMA +GAMMA.DIST = LOI.GAMMA.N +GAMMA.INV = LOI.GAMMA.INVERSE.N +GAMMALN = LNGAMMA +GAMMALN.PRECISE = LNGAMMA.PRECIS +GAUSS = GAUSS +GEOMEAN = MOYENNE.GEOMETRIQUE +GROWTH = CROISSANCE +HARMEAN = MOYENNE.HARMONIQUE +HYPGEOM.DIST = LOI.HYPERGEOMETRIQUE.N +INTERCEPT = ORDONNEE.ORIGINE +KURT = KURTOSIS +LARGE = GRANDE.VALEUR +LINEST = DROITEREG +LOGEST = LOGREG +LOGNORM.DIST = LOI.LOGNORMALE.N +LOGNORM.INV = LOI.LOGNORMALE.INVERSE.N +MAX = MAX +MAXA = MAXA +MAXIFS = MAX.SI +MEDIAN = MEDIANE +MIN = MIN +MINA = MINA +MINIFS = MIN.SI +MODE.MULT = MODE.MULTIPLE +MODE.SNGL = MODE.SIMPLE +NEGBINOM.DIST = LOI.BINOMIALE.NEG.N +NORM.DIST = LOI.NORMALE.N +NORM.INV = LOI.NORMALE.INVERSE.N +NORM.S.DIST = LOI.NORMALE.STANDARD.N +NORM.S.INV = LOI.NORMALE.STANDARD.INVERSE.N +PEARSON = PEARSON +PERCENTILE.EXC = CENTILE.EXCLURE +PERCENTILE.INC = CENTILE.INCLURE +PERCENTRANK.EXC = RANG.POURCENTAGE.EXCLURE +PERCENTRANK.INC = RANG.POURCENTAGE.INCLURE +PERMUT = PERMUTATION +PERMUTATIONA = PERMUTATIONA +PHI = PHI +POISSON.DIST = LOI.POISSON.N +PROB = PROBABILITE +QUARTILE.EXC = QUARTILE.EXCLURE +QUARTILE.INC = QUARTILE.INCLURE +RANK.AVG = MOYENNE.RANG +RANK.EQ = EQUATION.RANG +RSQ = COEFFICIENT.DETERMINATION +SKEW = COEFFICIENT.ASYMETRIE +SKEW.P = COEFFICIENT.ASYMETRIE.P +SLOPE = PENTE +SMALL = PETITE.VALEUR +STANDARDIZE = CENTREE.REDUITE +STDEV.P = ECARTYPE.PEARSON +STDEV.S = ECARTYPE.STANDARD +STDEVA = STDEVA +STDEVPA = STDEVPA +STEYX = ERREUR.TYPE.XY +T.DIST = LOI.STUDENT.N +T.DIST.2T = LOI.STUDENT.BILATERALE +T.DIST.RT = LOI.STUDENT.DROITE +T.INV = LOI.STUDENT.INVERSE.N +T.INV.2T = LOI.STUDENT.INVERSE.BILATERALE +T.TEST = T.TEST +TREND = TENDANCE +TRIMMEAN = MOYENNE.REDUITE +VAR.P = VAR.P.N +VAR.S = VAR.S +VARA = VARA +VARPA = VARPA +WEIBULL.DIST = LOI.WEIBULL.N +Z.TEST = Z.TEST ## -## Statistical functions Fonctions statistiques +## Fonctions de texte (Text Functions) ## -AVEDEV = ECART.MOYEN ## Renvoie la moyenne des écarts absolus observés dans la moyenne des points de données. -AVERAGE = MOYENNE ## Renvoie la moyenne de ses arguments. -AVERAGEA = AVERAGEA ## Renvoie la moyenne de ses arguments, nombres, texte et valeurs logiques inclus. -AVERAGEIF = MOYENNE.SI ## Renvoie la moyenne (arithmétique) de toutes les cellules d’une plage qui répondent à des critères donnés. -AVERAGEIFS = MOYENNE.SI.ENS ## Renvoie la moyenne (arithmétique) de toutes les cellules qui répondent à plusieurs critères. -BETADIST = LOI.BETA ## Renvoie la fonction de distribution cumulée. -BETAINV = BETA.INVERSE ## Renvoie l’inverse de la fonction de distribution cumulée pour une distribution bêta spécifiée. -BINOMDIST = LOI.BINOMIALE ## Renvoie la probabilité d’une variable aléatoire discrète suivant la loi binomiale. -CHIDIST = LOI.KHIDEUX ## Renvoie la probabilité unilatérale de la distribution khi-deux. -CHIINV = KHIDEUX.INVERSE ## Renvoie l’inverse de la probabilité unilatérale de la distribution khi-deux. -CHITEST = TEST.KHIDEUX ## Renvoie le test d’indépendance. -CONFIDENCE = INTERVALLE.CONFIANCE ## Renvoie l’intervalle de confiance pour une moyenne de population. -CORREL = COEFFICIENT.CORRELATION ## Renvoie le coefficient de corrélation entre deux séries de données. -COUNT = NB ## Détermine les nombres compris dans la liste des arguments. -COUNTA = NBVAL ## Détermine le nombre de valeurs comprises dans la liste des arguments. -COUNTBLANK = NB.VIDE ## Compte le nombre de cellules vides dans une plage. -COUNTIF = NB.SI ## Compte le nombre de cellules qui répondent à un critère donné dans une plage. -COUNTIFS = NB.SI.ENS ## Compte le nombre de cellules à l’intérieur d’une plage qui répondent à plusieurs critères. -COVAR = COVARIANCE ## Renvoie la covariance, moyenne des produits des écarts pour chaque série d’observations. -CRITBINOM = CRITERE.LOI.BINOMIALE ## Renvoie la plus petite valeur pour laquelle la distribution binomiale cumulée est inférieure ou égale à une valeur de critère. -DEVSQ = SOMME.CARRES.ECARTS ## Renvoie la somme des carrés des écarts. -EXPONDIST = LOI.EXPONENTIELLE ## Renvoie la distribution exponentielle. -FDIST = LOI.F ## Renvoie la distribution de probabilité F. -FINV = INVERSE.LOI.F ## Renvoie l’inverse de la distribution de probabilité F. -FISHER = FISHER ## Renvoie la transformation de Fisher. -FISHERINV = FISHER.INVERSE ## Renvoie l’inverse de la transformation de Fisher. -FORECAST = PREVISION ## Calcule une valeur par rapport à une tendance linéaire. -FREQUENCY = FREQUENCE ## Calcule la fréquence d’apparition des valeurs dans une plage de valeurs, puis renvoie des nombres sous forme de matrice verticale. -FTEST = TEST.F ## Renvoie le résultat d’un test F. -GAMMADIST = LOI.GAMMA ## Renvoie la probabilité d’une variable aléatoire suivant une loi Gamma. -GAMMAINV = LOI.GAMMA.INVERSE ## Renvoie, pour une probabilité donnée, la valeur d’une variable aléatoire suivant une loi Gamma. -GAMMALN = LNGAMMA ## Renvoie le logarithme népérien de la fonction Gamma, G(x) -GEOMEAN = MOYENNE.GEOMETRIQUE ## Renvoie la moyenne géométrique. -GROWTH = CROISSANCE ## Calcule des valeurs par rapport à une tendance exponentielle. -HARMEAN = MOYENNE.HARMONIQUE ## Renvoie la moyenne harmonique. -HYPGEOMDIST = LOI.HYPERGEOMETRIQUE ## Renvoie la probabilité d’une variable aléatoire discrète suivant une loi hypergéométrique. -INTERCEPT = ORDONNEE.ORIGINE ## Renvoie l’ordonnée à l’origine d’une droite de régression linéaire. -KURT = KURTOSIS ## Renvoie le kurtosis d’une série de données. -LARGE = GRANDE.VALEUR ## Renvoie la k-ième plus grande valeur d’une série de données. -LINEST = DROITEREG ## Renvoie les paramètres d’une tendance linéaire. -LOGEST = LOGREG ## Renvoie les paramètres d’une tendance exponentielle. -LOGINV = LOI.LOGNORMALE.INVERSE ## Renvoie l’inverse de la probabilité pour une variable aléatoire suivant la loi lognormale. -LOGNORMDIST = LOI.LOGNORMALE ## Renvoie la probabilité d’une variable aléatoire continue suivant une loi lognormale. -MAX = MAX ## Renvoie la valeur maximale contenue dans une liste d’arguments. -MAXA = MAXA ## Renvoie la valeur maximale d’une liste d’arguments, nombres, texte et valeurs logiques inclus. -MEDIAN = MEDIANE ## Renvoie la valeur médiane des nombres donnés. -MIN = MIN ## Renvoie la valeur minimale contenue dans une liste d’arguments. -MINA = MINA ## Renvoie la plus petite valeur d’une liste d’arguments, nombres, texte et valeurs logiques inclus. -MODE = MODE ## Renvoie la valeur la plus courante d’une série de données. -NEGBINOMDIST = LOI.BINOMIALE.NEG ## Renvoie la probabilité d’une variable aléatoire discrète suivant une loi binomiale négative. -NORMDIST = LOI.NORMALE ## Renvoie la probabilité d’une variable aléatoire continue suivant une loi normale. -NORMINV = LOI.NORMALE.INVERSE ## Renvoie, pour une probabilité donnée, la valeur d’une variable aléatoire suivant une loi normale standard. -NORMSDIST = LOI.NORMALE.STANDARD ## Renvoie la probabilité d’une variable aléatoire continue suivant une loi normale standard. -NORMSINV = LOI.NORMALE.STANDARD.INVERSE ## Renvoie l’inverse de la distribution cumulée normale standard. -PEARSON = PEARSON ## Renvoie le coefficient de corrélation d’échantillonnage de Pearson. -PERCENTILE = CENTILE ## Renvoie le k-ième centile des valeurs d’une plage. -PERCENTRANK = RANG.POURCENTAGE ## Renvoie le rang en pourcentage d’une valeur d’une série de données. -PERMUT = PERMUTATION ## Renvoie le nombre de permutations pour un nombre donné d’objets. -POISSON = LOI.POISSON ## Renvoie la probabilité d’une variable aléatoire suivant une loi de Poisson. -PROB = PROBABILITE ## Renvoie la probabilité que des valeurs d’une plage soient comprises entre deux limites. -QUARTILE = QUARTILE ## Renvoie le quartile d’une série de données. -RANK = RANG ## Renvoie le rang d’un nombre contenu dans une liste. -RSQ = COEFFICIENT.DETERMINATION ## Renvoie la valeur du coefficient de détermination R^2 d’une régression linéaire. -SKEW = COEFFICIENT.ASYMETRIE ## Renvoie l’asymétrie d’une distribution. -SLOPE = PENTE ## Renvoie la pente d’une droite de régression linéaire. -SMALL = PETITE.VALEUR ## Renvoie la k-ième plus petite valeur d’une série de données. -STANDARDIZE = CENTREE.REDUITE ## Renvoie une valeur centrée réduite. -STDEV = ECARTYPE ## Évalue l’écart type d’une population en se basant sur un échantillon de cette population. -STDEVA = STDEVA ## Évalue l’écart type d’une population en se basant sur un échantillon de cette population, nombres, texte et valeurs logiques inclus. -STDEVP = ECARTYPEP ## Calcule l’écart type d’une population à partir de la population entière. -STDEVPA = STDEVPA ## Calcule l’écart type d’une population à partir de l’ensemble de la population, nombres, texte et valeurs logiques inclus. -STEYX = ERREUR.TYPE.XY ## Renvoie l’erreur type de la valeur y prévue pour chaque x de la régression. -TDIST = LOI.STUDENT ## Renvoie la probabilité d’une variable aléatoire suivant une loi T de Student. -TINV = LOI.STUDENT.INVERSE ## Renvoie, pour une probabilité donnée, la valeur d’une variable aléatoire suivant une loi T de Student. -TREND = TENDANCE ## Renvoie des valeurs par rapport à une tendance linéaire. -TRIMMEAN = MOYENNE.REDUITE ## Renvoie la moyenne de l’intérieur d’une série de données. -TTEST = TEST.STUDENT ## Renvoie la probabilité associée à un test T de Student. -VAR = VAR ## Calcule la variance sur la base d’un échantillon. -VARA = VARA ## Estime la variance d’une population en se basant sur un échantillon de cette population, nombres, texte et valeurs logiques incluses. -VARP = VAR.P ## Calcule la variance sur la base de l’ensemble de la population. -VARPA = VARPA ## Calcule la variance d’une population en se basant sur la population entière, nombres, texte et valeurs logiques inclus. -WEIBULL = LOI.WEIBULL ## Renvoie la probabilité d’une variable aléatoire suivant une loi de Weibull. -ZTEST = TEST.Z ## Renvoie la valeur de probabilité unilatérale d’un test z. - +BAHTTEXT = BAHTTEXT +CHAR = CAR +CLEAN = EPURAGE +CODE = CODE +CONCAT = CONCAT +DOLLAR = DEVISE +EXACT = EXACT +FIND = TROUVE +FIXED = CTXT +LEFT = GAUCHE +LEN = NBCAR +LOWER = MINUSCULE +MID = STXT +NUMBERVALUE = VALEURNOMBRE +PHONETIC = PHONETIQUE +PROPER = NOMPROPRE +REPLACE = REMPLACER +REPT = REPT +RIGHT = DROITE +SEARCH = CHERCHE +SUBSTITUTE = SUBSTITUE +T = T +TEXT = TEXTE +TEXTJOIN = JOINDRE.TEXTE +TRIM = SUPPRESPACE +UNICHAR = UNICAR +UNICODE = UNICODE +UPPER = MAJUSCULE +VALUE = CNUM ## -## Text functions Fonctions de texte +## Fonctions web (Web Functions) ## -ASC = ASC ## Change les caractères anglais ou katakana à pleine chasse (codés sur deux octets) à l’intérieur d’une chaîne de caractères en caractères à demi-chasse (codés sur un octet). -BAHTTEXT = BAHTTEXT ## Convertit un nombre en texte en utilisant le format monétaire ß (baht). -CHAR = CAR ## Renvoie le caractère spécifié par le code numérique. -CLEAN = EPURAGE ## Supprime tous les caractères de contrôle du texte. -CODE = CODE ## Renvoie le numéro de code du premier caractère du texte. -CONCATENATE = CONCATENER ## Assemble plusieurs éléments textuels de façon à n’en former qu’un seul. -DOLLAR = EURO ## Convertit un nombre en texte en utilisant le format monétaire € (euro). -EXACT = EXACT ## Vérifie si deux valeurs de texte sont identiques. -FIND = TROUVE ## Trouve un valeur textuelle dans une autre, en respectant la casse. -FINDB = TROUVERB ## Trouve un valeur textuelle dans une autre, en respectant la casse. -FIXED = CTXT ## Convertit un nombre au format texte avec un nombre de décimales spécifié. -JIS = JIS ## Change les caractères anglais ou katakana à demi-chasse (codés sur un octet) à l’intérieur d’une chaîne de caractères en caractères à à pleine chasse (codés sur deux octets). -LEFT = GAUCHE ## Renvoie des caractères situés à l’extrême gauche d’une chaîne de caractères. -LEFTB = GAUCHEB ## Renvoie des caractères situés à l’extrême gauche d’une chaîne de caractères. -LEN = NBCAR ## Renvoie le nombre de caractères contenus dans une chaîne de texte. -LENB = LENB ## Renvoie le nombre de caractères contenus dans une chaîne de texte. -LOWER = MINUSCULE ## Convertit le texte en minuscules. -MID = STXT ## Renvoie un nombre déterminé de caractères d’une chaîne de texte à partir de la position que vous indiquez. -MIDB = STXTB ## Renvoie un nombre déterminé de caractères d’une chaîne de texte à partir de la position que vous indiquez. -PHONETIC = PHONETIQUE ## Extrait les caractères phonétiques (furigana) d’une chaîne de texte. -PROPER = NOMPROPRE ## Met en majuscules la première lettre de chaque mot dans une chaîne textuelle. -REPLACE = REMPLACER ## Remplace des caractères dans un texte. -REPLACEB = REMPLACERB ## Remplace des caractères dans un texte. -REPT = REPT ## Répète un texte un certain nombre de fois. -RIGHT = DROITE ## Renvoie des caractères situés à l’extrême droite d’une chaîne de caractères. -RIGHTB = DROITEB ## Renvoie des caractères situés à l’extrême droite d’une chaîne de caractères. -SEARCH = CHERCHE ## Trouve un texte dans un autre texte (sans respecter la casse). -SEARCHB = CHERCHERB ## Trouve un texte dans un autre texte (sans respecter la casse). -SUBSTITUTE = SUBSTITUE ## Remplace l’ancien texte d’une chaîne de caractères par un nouveau. -T = T ## Convertit ses arguments en texte. -TEXT = TEXTE ## Convertit un nombre au format texte. -TRIM = SUPPRESPACE ## Supprime les espaces du texte. -UPPER = MAJUSCULE ## Convertit le texte en majuscules. -VALUE = CNUM ## Convertit un argument textuel en nombre +ENCODEURL = URLENCODAGE +FILTERXML = FILTRE.XML +WEBSERVICE = SERVICEWEB + +## +## Fonctions de compatibilité (Compatibility Functions) +## +BETADIST = LOI.BETA +BETAINV = BETA.INVERSE +BINOMDIST = LOI.BINOMIALE +CEILING = PLAFOND +CHIDIST = LOI.KHIDEUX +CHIINV = KHIDEUX.INVERSE +CHITEST = TEST.KHIDEUX +CONCATENATE = CONCATENER +CONFIDENCE = INTERVALLE.CONFIANCE +COVAR = COVARIANCE +CRITBINOM = CRITERE.LOI.BINOMIALE +EXPONDIST = LOI.EXPONENTIELLE +FDIST = LOI.F +FINV = INVERSE.LOI.F +FLOOR = PLANCHER +FORECAST = PREVISION +FTEST = TEST.F +GAMMADIST = LOI.GAMMA +GAMMAINV = LOI.GAMMA.INVERSE +HYPGEOMDIST = LOI.HYPERGEOMETRIQUE +LOGINV = LOI.LOGNORMALE.INVERSE +LOGNORMDIST = LOI.LOGNORMALE +MODE = MODE +NEGBINOMDIST = LOI.BINOMIALE.NEG +NORMDIST = LOI.NORMALE +NORMINV = LOI.NORMALE.INVERSE +NORMSDIST = LOI.NORMALE.STANDARD +NORMSINV = LOI.NORMALE.STANDARD.INVERSE +PERCENTILE = CENTILE +PERCENTRANK = RANG.POURCENTAGE +POISSON = LOI.POISSON +QUARTILE = QUARTILE +RANK = RANG +STDEV = ECARTYPE +STDEVP = ECARTYPEP +TDIST = LOI.STUDENT +TINV = LOI.STUDENT.INVERSE +TTEST = TEST.STUDENT +VAR = VAR +VARP = VAR.P +WEIBULL = LOI.WEIBULL +ZTEST = TEST.Z diff --git a/src/PhpSpreadsheet/Calculation/locale/hu/config b/src/PhpSpreadsheet/Calculation/locale/hu/config index db61436c..dc585d71 100644 --- a/src/PhpSpreadsheet/Calculation/locale/hu/config +++ b/src/PhpSpreadsheet/Calculation/locale/hu/config @@ -1,23 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## +## Magyar (Hungarian) +## +############################################################ -ArgumentSeparator = ; - +ArgumentSeparator = ; ## -## (For future use) +## Error Codes ## -currencySymbol = Ft - - -## -## Excel Error Codes (For future use) -## -NULL = #NULLA! -DIV0 = #ZÉRÓOSZTÓ! -VALUE = #ÉRTÉK! -REF = #HIV! -NAME = #NÉV? -NUM = #SZÁM! -NA = #HIÁNYZIK +NULL = #NULLA! +DIV0 = #ZÉRÓOSZTÓ! +VALUE = #ÉRTÉK! +REF = #HIV! +NAME = #NÉV? +NUM = #SZÁM! +NA = #HIÁNYZIK diff --git a/src/PhpSpreadsheet/Calculation/locale/hu/functions b/src/PhpSpreadsheet/Calculation/locale/hu/functions index 3adffeb1..46b30127 100644 --- a/src/PhpSpreadsheet/Calculation/locale/hu/functions +++ b/src/PhpSpreadsheet/Calculation/locale/hu/functions @@ -1,416 +1,537 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Magyar (Hungarian) ## +############################################################ ## -## Add-in and Automation functions Bővítmények és automatizálási függvények +## Kockafüggvények (Cube Functions) ## -GETPIVOTDATA = KIMUTATÁSADATOT.VESZ ## A kimutatásokban tárolt adatok visszaadására használható. - +CUBEKPIMEMBER = KOCKA.FŐTELJMUT +CUBEMEMBER = KOCKA.TAG +CUBEMEMBERPROPERTY = KOCKA.TAG.TUL +CUBERANKEDMEMBER = KOCKA.HALM.ELEM +CUBESET = KOCKA.HALM +CUBESETCOUNT = KOCKA.HALM.DB +CUBEVALUE = KOCKA.ÉRTÉK ## -## Cube functions Kockafüggvények +## Adatbázis-kezelő függvények (Database Functions) ## -CUBEKPIMEMBER = KOCKA.FŐTELJMUT ## Egy fő teljesítménymutató (KPI) nevét, tulajdonságát és mértékegységét adja eredményül, a nevet és a tulajdonságot megjeleníti a cellában. A KPI-k számszerűsíthető mérési lehetőséget jelentenek – ilyen mutató például a havi bruttó nyereség vagy az egy alkalmazottra jutó negyedéves forgalom –, egy szervezet teljesítményének nyomonkövetésére használhatók. -CUBEMEMBER = KOCKA.TAG ## Kockahierachia tagját vagy rekordját adja eredményül. Ellenőrizhető vele, hogy szerepel-e a kockában az adott tag vagy rekord. -CUBEMEMBERPROPERTY = KOCKA.TAG.TUL ## A kocka egyik tagtulajdonságának értékét adja eredményül. Használatával ellenőrizhető, hogy szerepel-e egy tagnév a kockában, eredménye pedig az erre a tagra vonatkozó, megadott tulajdonság. -CUBERANKEDMEMBER = KOCKA.HALM.ELEM ## Egy halmaz rangsor szerinti n-edik tagját adja eredményül. Használatával egy halmaz egy vagy több elemét kaphatja meg, például a legnagyobb teljesítményű üzletkötőt vagy a 10 legjobb tanulót. -CUBESET = KOCKA.HALM ## Számított tagok vagy rekordok halmazát adja eredményül, ehhez egy beállított kifejezést elküld a kiszolgálón található kockának, majd ezt a halmazt adja vissza a Microsoft Office Excel alkalmazásnak. -CUBESETCOUNT = KOCKA.HALM.DB ## Egy halmaz elemszámát adja eredményül. -CUBEVALUE = KOCKA.ÉRTÉK ## Kockából összesített értéket ad eredményül. - +DAVERAGE = AB.ÁTLAG +DCOUNT = AB.DARAB +DCOUNTA = AB.DARAB2 +DGET = AB.MEZŐ +DMAX = AB.MAX +DMIN = AB.MIN +DPRODUCT = AB.SZORZAT +DSTDEV = AB.SZÓRÁS +DSTDEVP = AB.SZÓRÁS2 +DSUM = AB.SZUM +DVAR = AB.VAR +DVARP = AB.VAR2 ## -## Database functions Adatbázis-kezelő függvények +## Dátumfüggvények (Date & Time Functions) ## -DAVERAGE = AB.ÁTLAG ## A kijelölt adatbáziselemek átlagát számítja ki. -DCOUNT = AB.DARAB ## Megszámolja, hogy az adatbázisban hány cella tartalmaz számokat. -DCOUNTA = AB.DARAB2 ## Megszámolja az adatbázisban lévő nem üres cellákat. -DGET = AB.MEZŐ ## Egy adatbázisból egyetlen olyan rekordot ad vissza, amely megfelel a megadott feltételeknek. -DMAX = AB.MAX ## A kiválasztott adatbáziselemek közül a legnagyobb értéket adja eredményül. -DMIN = AB.MIN ## A kijelölt adatbáziselemek közül a legkisebb értéket adja eredményül. -DPRODUCT = AB.SZORZAT ## Az adatbázis megadott feltételeknek eleget tevő rekordjaira összeszorozza a megadott mezőben található számértékeket, és eredményül ezt a szorzatot adja. -DSTDEV = AB.SZÓRÁS ## A kijelölt adatbáziselemek egy mintája alapján megbecsüli a szórást. -DSTDEVP = AB.SZÓRÁS2 ## A kijelölt adatbáziselemek teljes sokasága alapján kiszámítja a szórást. -DSUM = AB.SZUM ## Összeadja a feltételnek megfelelő adatbázisrekordok mezőoszlopában a számokat. -DVAR = AB.VAR ## A kijelölt adatbáziselemek mintája alapján becslést ad a szórásnégyzetre. -DVARP = AB.VAR2 ## A kijelölt adatbáziselemek teljes sokasága alapján kiszámítja a szórásnégyzetet. - +DATE = DÁTUM +DATEDIF = DÁTUMTÓLIG +DATESTRING = DÁTUMSZÖVEG +DATEVALUE = DÁTUMÉRTÉK +DAY = NAP +DAYS = NAPOK +DAYS360 = NAP360 +EDATE = KALK.DÁTUM +EOMONTH = HÓNAP.UTOLSÓ.NAP +HOUR = ÓRA +ISOWEEKNUM = ISO.HÉT.SZÁMA +MINUTE = PERCEK +MONTH = HÓNAP +NETWORKDAYS = ÖSSZ.MUNKANAP +NETWORKDAYS.INTL = ÖSSZ.MUNKANAP.INTL +NOW = MOST +SECOND = MPERC +THAIDAYOFWEEK = THAIHÉTNAPJA +THAIMONTHOFYEAR = THAIHÓNAP +THAIYEAR = THAIÉV +TIME = IDŐ +TIMEVALUE = IDŐÉRTÉK +TODAY = MA +WEEKDAY = HÉT.NAPJA +WEEKNUM = HÉT.SZÁMA +WORKDAY = KALK.MUNKANAP +WORKDAY.INTL = KALK.MUNKANAP.INTL +YEAR = ÉV +YEARFRAC = TÖRTÉV ## -## Date and time functions Dátumfüggvények +## Mérnöki függvények (Engineering Functions) ## -DATE = DÁTUM ## Adott dátum dátumértékét adja eredményül. -DATEVALUE = DÁTUMÉRTÉK ## Szövegként megadott dátumot dátumértékké alakít át. -DAY = NAP ## Dátumértéket a hónap egy napjává (0-31) alakít. -DAYS360 = NAP360 ## Két dátum közé eső napok számát számítja ki a 360 napos év alapján. -EDATE = EDATE ## Adott dátumnál adott számú hónappal korábbi vagy későbbi dátum dátumértékét adja eredményül. -EOMONTH = EOMONTH ## Adott dátumnál adott számú hónappal korábbi vagy későbbi hónap utolsó napjának dátumértékét adja eredményül. -HOUR = ÓRA ## Időértéket órákká alakít. -MINUTE = PERC ## Időértéket percekké alakít. -MONTH = HÓNAP ## Időértéket hónapokká alakít. -NETWORKDAYS = NETWORKDAYS ## Két dátum között a teljes munkanapok számát adja meg. -NOW = MOST ## A napi dátum dátumértékét és a pontos idő időértékét adja eredményül. -SECOND = MPERC ## Időértéket másodpercekké alakít át. -TIME = IDŐ ## Adott időpont időértékét adja meg. -TIMEVALUE = IDŐÉRTÉK ## Szövegként megadott időpontot időértékké alakít át. -TODAY = MA ## A napi dátum dátumértékét adja eredményül. -WEEKDAY = HÉT.NAPJA ## Dátumértéket a hét napjává alakítja át. -WEEKNUM = WEEKNUM ## Visszatérési értéke egy szám, amely azt mutatja meg, hogy a megadott dátum az év hányadik hetére esik. -WORKDAY = WORKDAY ## Adott dátumnál adott munkanappal korábbi vagy későbbi dátum dátumértékét adja eredményül. -YEAR = ÉV ## Sorszámot évvé alakít át. -YEARFRAC = YEARFRAC ## Az adott dátumok közötti teljes napok számát törtévként adja meg. - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BIN.DEC +BIN2HEX = BIN.HEX +BIN2OCT = BIN.OKT +BITAND = BIT.ÉS +BITLSHIFT = BIT.BAL.ELTOL +BITOR = BIT.VAGY +BITRSHIFT = BIT.JOBB.ELTOL +BITXOR = BIT.XVAGY +COMPLEX = KOMPLEX +CONVERT = KONVERTÁLÁS +DEC2BIN = DEC.BIN +DEC2HEX = DEC.HEX +DEC2OCT = DEC.OKT +DELTA = DELTA +ERF = HIBAF +ERF.PRECISE = HIBAF.PONTOS +ERFC = HIBAF.KOMPLEMENTER +ERFC.PRECISE = HIBAFKOMPLEMENTER.PONTOS +GESTEP = KÜSZÖBNÉL.NAGYOBB +HEX2BIN = HEX.BIN +HEX2DEC = HEX.DEC +HEX2OCT = HEX.OKT +IMABS = KÉPZ.ABSZ +IMAGINARY = KÉPZETES +IMARGUMENT = KÉPZ.ARGUMENT +IMCONJUGATE = KÉPZ.KONJUGÁLT +IMCOS = KÉPZ.COS +IMCOSH = KÉPZ.COSH +IMCOT = KÉPZ.COT +IMCSC = KÉPZ.CSC +IMCSCH = KÉPZ.CSCH +IMDIV = KÉPZ.HÁNYAD +IMEXP = KÉPZ.EXP +IMLN = KÉPZ.LN +IMLOG10 = KÉPZ.LOG10 +IMLOG2 = KÉPZ.LOG2 +IMPOWER = KÉPZ.HATV +IMPRODUCT = KÉPZ.SZORZAT +IMREAL = KÉPZ.VALÓS +IMSEC = KÉPZ.SEC +IMSECH = KÉPZ.SECH +IMSIN = KÉPZ.SIN +IMSINH = KÉPZ.SINH +IMSQRT = KÉPZ.GYÖK +IMSUB = KÉPZ.KÜL +IMSUM = KÉPZ.ÖSSZEG +IMTAN = KÉPZ.TAN +OCT2BIN = OKT.BIN +OCT2DEC = OKT.DEC +OCT2HEX = OKT.HEX ## -## Engineering functions Mérnöki függvények +## Pénzügyi függvények (Financial Functions) ## -BESSELI = BESSELI ## Az In(x) módosított Bessel-függvény értékét adja eredményül. -BESSELJ = BESSELJ ## A Jn(x) Bessel-függvény értékét adja eredményül. -BESSELK = BESSELK ## A Kn(x) módosított Bessel-függvény értékét adja eredményül. -BESSELY = BESSELY ## Az Yn(x) módosított Bessel-függvény értékét adja eredményül. -BIN2DEC = BIN2DEC ## Bináris számot decimálissá alakít át. -BIN2HEX = BIN2HEX ## Bináris számot hexadecimálissá alakít át. -BIN2OCT = BIN2OCT ## Bináris számot oktálissá alakít át. -COMPLEX = COMPLEX ## Valós és képzetes részből komplex számot képez. -CONVERT = CONVERT ## Mértékegységeket vált át. -DEC2BIN = DEC2BIN ## Decimális számot binárissá alakít át. -DEC2HEX = DEC2HEX ## Decimális számot hexadecimálissá alakít át. -DEC2OCT = DEC2OCT ## Decimális számot oktálissá alakít át. -DELTA = DELTA ## Azt vizsgálja, hogy két érték egyenlő-e. -ERF = ERF ## A hibafüggvény értékét adja eredményül. -ERFC = ERFC ## A kiegészített hibafüggvény értékét adja eredményül. -GESTEP = GESTEP ## Azt vizsgálja, hogy egy szám nagyobb-e adott küszöbértéknél. -HEX2BIN = HEX2BIN ## Hexadecimális számot binárissá alakít át. -HEX2DEC = HEX2DEC ## Hexadecimális számot decimálissá alakít át. -HEX2OCT = HEX2OCT ## Hexadecimális számot oktálissá alakít át. -IMABS = IMABS ## Komplex szám abszolút értékét (modulusát) adja eredményül. -IMAGINARY = IMAGINARY ## Komplex szám képzetes részét adja eredményül. -IMARGUMENT = IMARGUMENT ## A komplex szám radiánban kifejezett théta argumentumát adja eredményül. -IMCONJUGATE = IMCONJUGATE ## Komplex szám komplex konjugáltját adja eredményül. -IMCOS = IMCOS ## Komplex szám koszinuszát adja eredményül. -IMDIV = IMDIV ## Két komplex szám hányadosát adja eredményül. -IMEXP = IMEXP ## Az e szám komplex kitevőjű hatványát adja eredményül. -IMLN = IMLN ## Komplex szám természetes logaritmusát adja eredményül. -IMLOG10 = IMLOG10 ## Komplex szám tízes alapú logaritmusát adja eredményül. -IMLOG2 = IMLOG2 ## Komplex szám kettes alapú logaritmusát adja eredményül. -IMPOWER = IMPOWER ## Komplex szám hatványát adja eredményül. -IMPRODUCT = IMPRODUCT ## Komplex számok szorzatát adja eredményül. -IMREAL = IMREAL ## Komplex szám valós részét adja eredményül. -IMSIN = IMSIN ## Komplex szám szinuszát adja eredményül. -IMSQRT = IMSQRT ## Komplex szám négyzetgyökét adja eredményül. -IMSUB = IMSUB ## Két komplex szám különbségét adja eredményül. -IMSUM = IMSUM ## Komplex számok összegét adja eredményül. -OCT2BIN = OCT2BIN ## Oktális számot binárissá alakít át. -OCT2DEC = OCT2DEC ## Oktális számot decimálissá alakít át. -OCT2HEX = OCT2HEX ## Oktális számot hexadecimálissá alakít át. - +ACCRINT = IDŐSZAKI.KAMAT +ACCRINTM = LEJÁRATI.KAMAT +AMORDEGRC = ÉRTÉKCSÖKK.TÉNYEZŐVEL +AMORLINC = ÉRTÉKCSÖKK +COUPDAYBS = SZELVÉNYIDŐ.KEZDETTŐL +COUPDAYS = SZELVÉNYIDŐ +COUPDAYSNC = SZELVÉNYIDŐ.KIFIZETÉSTŐL +COUPNCD = ELSŐ.SZELVÉNYDÁTUM +COUPNUM = SZELVÉNYSZÁM +COUPPCD = UTOLSÓ.SZELVÉNYDÁTUM +CUMIPMT = ÖSSZES.KAMAT +CUMPRINC = ÖSSZES.TŐKERÉSZ +DB = KCS2 +DDB = KCSA +DISC = LESZÁM +DOLLARDE = FORINT.DEC +DOLLARFR = FORINT.TÖRT +DURATION = KAMATÉRZ +EFFECT = TÉNYLEGES +FV = JBÉ +FVSCHEDULE = KJÉ +INTRATE = KAMATRÁTA +IPMT = RRÉSZLET +IRR = BMR +ISPMT = LRÉSZLETKAMAT +MDURATION = MKAMATÉRZ +MIRR = MEGTÉRÜLÉS +NOMINAL = NÉVLEGES +NPER = PER.SZÁM +NPV = NMÉ +ODDFPRICE = ELTÉRŐ.EÁR +ODDFYIELD = ELTÉRŐ.EHOZAM +ODDLPRICE = ELTÉRŐ.UÁR +ODDLYIELD = ELTÉRŐ.UHOZAM +PDURATION = KAMATÉRZ.PER +PMT = RÉSZLET +PPMT = PRÉSZLET +PRICE = ÁR +PRICEDISC = ÁR.LESZÁM +PRICEMAT = ÁR.LEJÁRAT +PV = MÉ +RATE = RÁTA +RECEIVED = KAPOTT +RRI = MR +SLN = LCSA +SYD = ÉSZÖ +TBILLEQ = KJEGY.EGYENÉRT +TBILLPRICE = KJEGY.ÁR +TBILLYIELD = KJEGY.HOZAM +VDB = ÉCSRI +XIRR = XBMR +XNPV = XNJÉ +YIELD = HOZAM +YIELDDISC = HOZAM.LESZÁM +YIELDMAT = HOZAM.LEJÁRAT ## -## Financial functions Pénzügyi függvények +## Információs függvények (Information Functions) ## -ACCRINT = ACCRINT ## Periodikusan kamatozó értékpapír felszaporodott kamatát adja eredményül. -ACCRINTM = ACCRINTM ## Lejáratkor kamatozó értékpapír felszaporodott kamatát adja eredményül. -AMORDEGRC = AMORDEGRC ## Állóeszköz lineáris értékcsökkenését adja meg az egyes könyvelési időszakokra vonatkozóan. -AMORLINC = AMORLINC ## Az egyes könyvelési időszakokban az értékcsökkenést adja meg. -COUPDAYBS = COUPDAYBS ## A szelvényidőszak kezdetétől a kifizetés időpontjáig eltelt napokat adja vissza. -COUPDAYS = COUPDAYS ## A kifizetés időpontját magában foglaló szelvényperiódus hosszát adja meg napokban. -COUPDAYSNC = COUPDAYSNC ## A kifizetés időpontja és a legközelebbi szelvénydátum közötti napok számát adja meg. -COUPNCD = COUPNCD ## A kifizetést követő legelső szelvénydátumot adja eredményül. -COUPNUM = COUPNUM ## A kifizetés és a lejárat időpontja között kifizetendő szelvények számát adja eredményül. -COUPPCD = COUPPCD ## A kifizetés előtti utolsó szelvénydátumot adja eredményül. -CUMIPMT = CUMIPMT ## Két fizetési időszak között kifizetett kamat halmozott értékét adja eredményül. -CUMPRINC = CUMPRINC ## Két fizetési időszak között kifizetett részletek halmozott (kamatot nem tartalmazó) értékét adja eredményül. -DB = KCS2 ## Eszköz adott időszak alatti értékcsökkenését számítja ki a lineáris leírási modell alkalmazásával. -DDB = KCSA ## Eszköz értékcsökkenését számítja ki adott időszakra vonatkozóan a progresszív vagy egyéb megadott leírási modell alkalmazásával. -DISC = DISC ## Értékpapír leszámítolási kamatlábát adja eredményül. -DOLLARDE = DOLLARDE ## Egy közönséges törtként megadott számot tizedes törtté alakít át. -DOLLARFR = DOLLARFR ## Tizedes törtként megadott számot közönséges törtté alakít át. -DURATION = DURATION ## Periodikus kamatfizetésű értékpapír éves kamatérzékenységét adja eredményül. -EFFECT = EFFECT ## Az éves tényleges kamatláb értékét adja eredményül. -FV = JBÉ ## Befektetés jövőbeli értékét számítja ki. -FVSCHEDULE = FVSCHEDULE ## A kezdőtőke adott kamatlábak szerint megnövelt jövőbeli értékét adja eredményül. -INTRATE = INTRATE ## A lejáratig teljesen lekötött értékpapír kamatrátáját adja eredményül. -IPMT = RRÉSZLET ## Hiteltörlesztésen belül a tőketörlesztés nagyságát számítja ki adott időszakra. -IRR = BMR ## A befektetés belső megtérülési rátáját számítja ki pénzáramláshoz. -ISPMT = LRÉSZLETKAMAT ## A befektetés adott időszakára fizetett kamatot számítja ki. -MDURATION = MDURATION ## Egy 100 Ft névértékű értékpapír Macauley-féle módosított kamatérzékenységét adja eredményül. -MIRR = MEGTÉRÜLÉS ## A befektetés belső megtérülési rátáját számítja ki a költségek és a bevételek különböző kamatlába mellett. -NOMINAL = NOMINAL ## Az éves névleges kamatláb értékét adja eredményül. -NPER = PER.SZÁM ## A törlesztési időszakok számát adja meg. -NPV = NMÉ ## Befektetéshez kapcsolódó pénzáramlás nettó jelenértékét számítja ki ismert pénzáramlás és kamatláb mellett. -ODDFPRICE = ODDFPRICE ## Egy 100 Ft névértékű, a futamidő elején töredék-időszakos értékpapír árát adja eredményül. -ODDFYIELD = ODDFYIELD ## A futamidő elején töredék-időszakos értékpapír hozamát adja eredményül. -ODDLPRICE = ODDLPRICE ## Egy 100 Ft névértékű, a futamidő végén töredék-időszakos értékpapír árát adja eredményül. -ODDLYIELD = ODDLYIELD ## A futamidő végén töredék-időszakos értékpapír hozamát adja eredményül. -PMT = RÉSZLET ## A törlesztési időszakra vonatkozó törlesztési összeget számítja ki. -PPMT = PRÉSZLET ## Hiteltörlesztésen belül a tőketörlesztés nagyságát számítja ki adott időszakra. -PRICE = PRICE ## Egy 100 Ft névértékű, periodikusan kamatozó értékpapír árát adja eredményül. -PRICEDISC = PRICEDISC ## Egy 100 Ft névértékű leszámítolt értékpapír árát adja eredményül. -PRICEMAT = PRICEMAT ## Egy 100 Ft névértékű, a lejáratkor kamatozó értékpapír árát adja eredményül. -PV = MÉ ## Befektetés jelenlegi értékét számítja ki. -RATE = RÁTA ## Egy törlesztési időszakban az egy időszakra eső kamatláb nagyságát számítja ki. -RECEIVED = RECEIVED ## A lejáratig teljesen lekötött értékpapír lejáratakor kapott összegét adja eredményül. -SLN = LCSA ## Tárgyi eszköz egy időszakra eső amortizációját adja meg bruttó érték szerinti lineáris leírási kulcsot alkalmazva. -SYD = SYD ## Tárgyi eszköz értékcsökkenését számítja ki adott időszakra az évek számjegyösszegével dolgozó módszer alapján. -TBILLEQ = TBILLEQ ## Kincstárjegy kötvény-egyenértékű hozamát adja eredményül. -TBILLPRICE = TBILLPRICE ## Egy 100 Ft névértékű kincstárjegy árát adja eredményül. -TBILLYIELD = TBILLYIELD ## Kincstárjegy hozamát adja eredményül. -VDB = ÉCSRI ## Tárgyi eszköz amortizációját számítja ki megadott vagy részidőszakra a csökkenő egyenleg módszerének alkalmazásával. -XIRR = XIRR ## Ütemezett készpénzforgalom (cash flow) belső megtérülési kamatrátáját adja eredményül. -XNPV = XNPV ## Ütemezett készpénzforgalom (cash flow) nettó jelenlegi értékét adja eredményül. -YIELD = YIELD ## Periodikusan kamatozó értékpapír hozamát adja eredményül. -YIELDDISC = YIELDDISC ## Leszámítolt értékpapír (például kincstárjegy) éves hozamát adja eredményül. -YIELDMAT = YIELDMAT ## Lejáratkor kamatozó értékpapír éves hozamát adja eredményül. - +CELL = CELLA +ERROR.TYPE = HIBA.TÍPUS +INFO = INFÓ +ISBLANK = ÜRES +ISERR = HIBA.E +ISERROR = HIBÁS +ISEVEN = PÁROSE +ISFORMULA = KÉPLET +ISLOGICAL = LOGIKAI +ISNA = NINCS +ISNONTEXT = NEM.SZÖVEG +ISNUMBER = SZÁM +ISODD = PÁRATLANE +ISREF = HIVATKOZÁS +ISTEXT = SZÖVEG.E +N = S +NA = HIÁNYZIK +SHEET = LAP +SHEETS = LAPOK +TYPE = TÍPUS ## -## Information functions Információs függvények +## Logikai függvények (Logical Functions) ## -CELL = CELLA ## Egy cella formátumára, elhelyezkedésére vagy tartalmára vonatkozó adatokat ad eredményül. -ERROR.TYPE = HIBA.TÍPUS ## Egy hibatípushoz tartozó számot ad eredményül. -INFO = INFÓ ## A rendszer- és munkakörnyezet pillanatnyi állapotáról ad felvilágosítást. -ISBLANK = ÜRES ## Eredménye IGAZ, ha az érték üres. -ISERR = HIBA ## Eredménye IGAZ, ha az érték valamelyik hibaérték a #HIÁNYZIK kivételével. -ISERROR = HIBÁS ## Eredménye IGAZ, ha az érték valamelyik hibaérték. -ISEVEN = ISEVEN ## Eredménye IGAZ, ha argumentuma páros szám. -ISLOGICAL = LOGIKAI ## Eredménye IGAZ, ha az érték logikai érték. -ISNA = NINCS ## Eredménye IGAZ, ha az érték a #HIÁNYZIK hibaérték. -ISNONTEXT = NEM.SZÖVEG ## Eredménye IGAZ, ha az érték nem szöveg. -ISNUMBER = SZÁM ## Eredménye IGAZ, ha az érték szám. -ISODD = ISODD ## Eredménye IGAZ, ha argumentuma páratlan szám. -ISREF = HIVATKOZÁS ## Eredménye IGAZ, ha az érték hivatkozás. -ISTEXT = SZÖVEG.E ## Eredménye IGAZ, ha az érték szöveg. -N = N ## Argumentumának értékét számmá alakítja. -NA = HIÁNYZIK ## Eredménye a #HIÁNYZIK hibaérték. -TYPE = TÍPUS ## Érték adattípusának azonosítószámát adja eredményül. - +AND = ÉS +FALSE = HAMIS +IF = HA +IFERROR = HAHIBA +IFNA = HAHIÁNYZIK +IFS = HAELSŐIGAZ +NOT = NEM +OR = VAGY +SWITCH = ÁTVÁLT +TRUE = IGAZ +XOR = XVAGY ## -## Logical functions Logikai függvények +## Keresési és hivatkozási függvények (Lookup & Reference Functions) ## -AND = ÉS ## Eredménye IGAZ, ha minden argumentuma IGAZ. -FALSE = HAMIS ## A HAMIS logikai értéket adja eredményül. -IF = HA ## Logikai vizsgálatot hajt végre. -IFERROR = HAHIBA ## A megadott értéket adja vissza, ha egy képlet hibához vezet; más esetben a képlet értékét adja eredményül. -NOT = NEM ## Argumentuma értékének ellentettjét adja eredményül. -OR = VAGY ## Eredménye IGAZ, ha bármely argumentuma IGAZ. -TRUE = IGAZ ## Az IGAZ logikai értéket adja eredményül. - +ADDRESS = CÍM +AREAS = TERÜLET +CHOOSE = VÁLASZT +COLUMN = OSZLOP +COLUMNS = OSZLOPOK +FORMULATEXT = KÉPLETSZÖVEG +GETPIVOTDATA = KIMUTATÁSADATOT.VESZ +HLOOKUP = VKERES +HYPERLINK = HIPERHIVATKOZÁS +INDEX = INDEX +INDIRECT = INDIREKT +LOOKUP = KERES +MATCH = HOL.VAN +OFFSET = ELTOLÁS +ROW = SOR +ROWS = SOROK +RTD = VIA +TRANSPOSE = TRANSZPONÁLÁS +VLOOKUP = FKERES ## -## Lookup and reference functions Keresési és hivatkozási függvények +## Matematikai és trigonometrikus függvények (Math & Trig Functions) ## -ADDRESS = CÍM ## A munkalap egy cellájára való hivatkozást adja szövegként eredményül. -AREAS = TERÜLET ## Hivatkozásban a területek számát adja eredményül. -CHOOSE = VÁLASZT ## Értékek listájából választ ki egy elemet. -COLUMN = OSZLOP ## Egy hivatkozás oszlopszámát adja eredményül. -COLUMNS = OSZLOPOK ## A hivatkozásban található oszlopok számát adja eredményül. -HLOOKUP = VKERES ## A megadott tömb felső sorában adott értékű elemet keres, és a megtalált elem oszlopából adott sorban elhelyezkedő értékkel tér vissza. -HYPERLINK = HIPERHIVATKOZÁS ## Hálózati kiszolgálón, intraneten vagy az interneten tárolt dokumentumot megnyitó parancsikont vagy hivatkozást hoz létre. -INDEX = INDEX ## Tömb- vagy hivatkozás indexszel megadott értékét adja vissza. -INDIRECT = INDIREKT ## Szöveg megadott hivatkozást ad eredményül. -LOOKUP = KERES ## Vektorban vagy tömbben keres meg értékeket. -MATCH = HOL.VAN ## Hivatkozásban vagy tömbben értékeket keres. -OFFSET = OFSZET ## Hivatkozás egy másik hivatkozástól számított távolságát adja meg. -ROW = SOR ## Egy hivatkozás sorának számát adja meg. -ROWS = SOROK ## Egy hivatkozás sorainak számát adja meg. -RTD = RTD ## Valós idejű adatokat keres vissza a COM automatizmust (automatizálás: Egy alkalmazás objektumaival való munka másik alkalmazásból vagy fejlesztőeszközből. A korábban OLE automatizmusnak nevezett automatizálás iparági szabvány, a Component Object Model (COM) szolgáltatása.) támogató programból. -TRANSPOSE = TRANSZPONÁLÁS ## Egy tömb transzponáltját adja eredményül. -VLOOKUP = FKERES ## A megadott tömb bal szélső oszlopában megkeres egy értéket, majd annak sora és a megadott oszlop metszéspontjában levő értéked adja eredményül. - +ABS = ABS +ACOS = ARCCOS +ACOSH = ACOSH +ACOT = ARCCOT +ACOTH = ARCCOTH +AGGREGATE = ÖSSZESÍT +ARABIC = ARAB +ASIN = ARCSIN +ASINH = ASINH +ATAN = ARCTAN +ATAN2 = ARCTAN2 +ATANH = ATANH +BASE = ALAP +CEILING.MATH = PLAFON.MAT +CEILING.PRECISE = PLAFON.PONTOS +COMBIN = KOMBINÁCIÓK +COMBINA = KOMBINÁCIÓK.ISM +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = TIZEDES +DEGREES = FOK +ECMA.CEILING = ECMA.PLAFON +EVEN = PÁROS +EXP = KITEVŐ +FACT = FAKT +FACTDOUBLE = FAKTDUPLA +FLOOR.MATH = PADLÓ.MAT +FLOOR.PRECISE = PADLÓ.PONTOS +GCD = LKO +INT = INT +ISO.CEILING = ISO.PLAFON +LCM = LKT +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = MDETERM +MINVERSE = INVERZ.MÁTRIX +MMULT = MSZORZAT +MOD = MARADÉK +MROUND = TÖBBSZ.KEREKÍT +MULTINOMIAL = SZORHÁNYFAKT +MUNIT = MMÁTRIX +ODD = PÁRATLAN +PI = PI +POWER = HATVÁNY +PRODUCT = SZORZAT +QUOTIENT = KVÓCIENS +RADIANS = RADIÁN +RAND = VÉL +RANDBETWEEN = VÉLETLEN.KÖZÖTT +ROMAN = RÓMAI +ROUND = KEREKÍTÉS +ROUNDBAHTDOWN = BAHTKEREK.LE +ROUNDBAHTUP = BAHTKEREK.FEL +ROUNDDOWN = KEREK.LE +ROUNDUP = KEREK.FEL +SEC = SEC +SECH = SECH +SERIESSUM = SORÖSSZEG +SIGN = ELŐJEL +SIN = SIN +SINH = SINH +SQRT = GYÖK +SQRTPI = GYÖKPI +SUBTOTAL = RÉSZÖSSZEG +SUM = SZUM +SUMIF = SZUMHA +SUMIFS = SZUMHATÖBB +SUMPRODUCT = SZORZATÖSSZEG +SUMSQ = NÉGYZETÖSSZEG +SUMX2MY2 = SZUMX2BŐLY2 +SUMX2PY2 = SZUMX2MEGY2 +SUMXMY2 = SZUMXBŐLY2 +TAN = TAN +TANH = TANH +TRUNC = CSONK ## -## Math and trigonometry functions Matematikai és trigonometrikus függvények +## Statisztikai függvények (Statistical Functions) ## -ABS = ABS ## Egy szám abszolút értékét adja eredményül. -ACOS = ARCCOS ## Egy szám arkusz koszinuszát számítja ki. -ACOSH = ACOSH ## Egy szám inverz koszinusz hiperbolikuszát számítja ki. -ASIN = ARCSIN ## Egy szám arkusz szinuszát számítja ki. -ASINH = ASINH ## Egy szám inverz szinusz hiperbolikuszát számítja ki. -ATAN = ARCTAN ## Egy szám arkusz tangensét számítja ki. -ATAN2 = ARCTAN2 ## X és y koordináták alapján számítja ki az arkusz tangens értéket. -ATANH = ATANH ## A szám inverz tangens hiperbolikuszát számítja ki. -CEILING = PLAFON ## Egy számot a legközelebbi egészre vagy a pontosságként megadott érték legközelebb eső többszörösére kerekít. -COMBIN = KOMBINÁCIÓK ## Adott számú objektum összes lehetséges kombinációinak számát számítja ki. -COS = COS ## Egy szám koszinuszát számítja ki. -COSH = COSH ## Egy szám koszinusz hiperbolikuszát számítja ki. -DEGREES = FOK ## Radiánt fokká alakít át. -EVEN = PÁROS ## Egy számot a legközelebbi páros egész számra kerekít. -EXP = KITEVŐ ## Az e adott kitevőjű hatványát adja eredményül. -FACT = FAKT ## Egy szám faktoriálisát számítja ki. -FACTDOUBLE = FACTDOUBLE ## Egy szám dupla faktoriálisát adja eredményül. -FLOOR = PADLÓ ## Egy számot lefelé, a nulla felé kerekít. -GCD = GCD ## A legnagyobb közös osztót adja eredményül. -INT = INT ## Egy számot lefelé kerekít a legközelebbi egészre. -LCM = LCM ## A legkisebb közös többszöröst adja eredményül. -LN = LN ## Egy szám természetes logaritmusát számítja ki. -LOG = LOG ## Egy szám adott alapú logaritmusát számítja ki. -LOG10 = LOG10 ## Egy szám 10-es alapú logaritmusát számítja ki. -MDETERM = MDETERM ## Egy tömb mátrix-determinánsát számítja ki. -MINVERSE = INVERZ.MÁTRIX ## Egy tömb mátrix inverzét adja eredményül. -MMULT = MSZORZAT ## Két tömb mátrix-szorzatát adja meg. -MOD = MARADÉK ## Egy szám osztási maradékát adja eredményül. -MROUND = MROUND ## A kívánt többszörösére kerekített értéket ad eredményül. -MULTINOMIAL = MULTINOMIAL ## Számhalmaz multinomiálisát adja eredményül. -ODD = PÁRATLAN ## Egy számot a legközelebbi páratlan számra kerekít. -PI = PI ## A pi matematikai állandót adja vissza. -POWER = HATVÁNY ## Egy szám adott kitevőjű hatványát számítja ki. -PRODUCT = SZORZAT ## Argumentumai szorzatát számítja ki. -QUOTIENT = QUOTIENT ## Egy hányados egész részét adja eredményül. -RADIANS = RADIÁN ## Fokot radiánná alakít át. -RAND = VÉL ## Egy 0 és 1 közötti véletlen számot ad eredményül. -RANDBETWEEN = RANDBETWEEN ## Megadott számok közé eső véletlen számot állít elő. -ROMAN = RÓMAI ## Egy számot római számokkal kifejezve szövegként ad eredményül. -ROUND = KEREKÍTÉS ## Egy számot adott számú számjegyre kerekít. -ROUNDDOWN = KEREKÍTÉS.LE ## Egy számot lefelé, a nulla felé kerekít. -ROUNDUP = KEREKÍTÉS.FEL ## Egy számot felfelé, a nullától távolabbra kerekít. -SERIESSUM = SERIESSUM ## Hatványsor összegét adja eredményül. -SIGN = ELŐJEL ## Egy szám előjelét adja meg. -SIN = SIN ## Egy szög szinuszát számítja ki. -SINH = SINH ## Egy szám szinusz hiperbolikuszát számítja ki. -SQRT = GYÖK ## Egy szám pozitív négyzetgyökét számítja ki. -SQRTPI = SQRTPI ## A (szám*pi) négyzetgyökét adja eredményül. -SUBTOTAL = RÉSZÖSSZEG ## Lista vagy adatbázis részösszegét adja eredményül. -SUM = SZUM ## Összeadja az argumentumlistájában lévő számokat. -SUMIF = SZUMHA ## A megadott feltételeknek eleget tevő cellákban található értékeket adja össze. -SUMIFS = SZUMHATÖBB ## Több megadott feltételnek eleget tévő tartománycellák összegét adja eredményül. -SUMPRODUCT = SZORZATÖSSZEG ## A megfelelő tömbelemek szorzatának összegét számítja ki. -SUMSQ = NÉGYZETÖSSZEG ## Argumentumai négyzetének összegét számítja ki. -SUMX2MY2 = SZUMX2BŐLY2 ## Két tömb megfelelő elemei négyzetének különbségét összegzi. -SUMX2PY2 = SZUMX2MEGY2 ## Két tömb megfelelő elemei négyzetének összegét összegzi. -SUMXMY2 = SZUMXBŐLY2 ## Két tömb megfelelő elemei különbségének négyzetösszegét számítja ki. -TAN = TAN ## Egy szám tangensét számítja ki. -TANH = TANH ## Egy szám tangens hiperbolikuszát számítja ki. -TRUNC = CSONK ## Egy számot egésszé csonkít. - +AVEDEV = ÁTL.ELTÉRÉS +AVERAGE = ÁTLAG +AVERAGEA = ÁTLAGA +AVERAGEIF = ÁTLAGHA +AVERAGEIFS = ÁTLAGHATÖBB +BETA.DIST = BÉTA.ELOSZL +BETA.INV = BÉTA.INVERZ +BINOM.DIST = BINOM.ELOSZL +BINOM.DIST.RANGE = BINOM.ELOSZL.TART +BINOM.INV = BINOM.INVERZ +CHISQ.DIST = KHINÉGYZET.ELOSZLÁS +CHISQ.DIST.RT = KHINÉGYZET.ELOSZLÁS.JOBB +CHISQ.INV = KHINÉGYZET.INVERZ +CHISQ.INV.RT = KHINÉGYZET.INVERZ.JOBB +CHISQ.TEST = KHINÉGYZET.PRÓBA +CONFIDENCE.NORM = MEGBÍZHATÓSÁG.NORM +CONFIDENCE.T = MEGBÍZHATÓSÁG.T +CORREL = KORREL +COUNT = DARAB +COUNTA = DARAB2 +COUNTBLANK = DARABÜRES +COUNTIF = DARABTELI +COUNTIFS = DARABHATÖBB +COVARIANCE.P = KOVARIANCIA.S +COVARIANCE.S = KOVARIANCIA.M +DEVSQ = SQ +EXPON.DIST = EXP.ELOSZL +F.DIST = F.ELOSZL +F.DIST.RT = F.ELOSZLÁS.JOBB +F.INV = F.INVERZ +F.INV.RT = F.INVERZ.JOBB +F.TEST = F.PRÓB +FISHER = FISHER +FISHERINV = INVERZ.FISHER +FORECAST.ETS = ELŐREJELZÉS.ESIM +FORECAST.ETS.CONFINT = ELŐREJELZÉS.ESIM.KONFINT +FORECAST.ETS.SEASONALITY = ELŐREJELZÉS.ESIM.SZEZONALITÁS +FORECAST.ETS.STAT = ELŐREJELZÉS.ESIM.STAT +FORECAST.LINEAR = ELŐREJELZÉS.LINEÁRIS +FREQUENCY = GYAKORISÁG +GAMMA = GAMMA +GAMMA.DIST = GAMMA.ELOSZL +GAMMA.INV = GAMMA.INVERZ +GAMMALN = GAMMALN +GAMMALN.PRECISE = GAMMALN.PONTOS +GAUSS = GAUSS +GEOMEAN = MÉRTANI.KÖZÉP +GROWTH = NÖV +HARMEAN = HARM.KÖZÉP +HYPGEOM.DIST = HIPGEOM.ELOSZLÁS +INTERCEPT = METSZ +KURT = CSÚCSOSSÁG +LARGE = NAGY +LINEST = LIN.ILL +LOGEST = LOG.ILL +LOGNORM.DIST = LOGNORM.ELOSZLÁS +LOGNORM.INV = LOGNORM.INVERZ +MAX = MAX +MAXA = MAXA +MAXIFS = MAXHA +MEDIAN = MEDIÁN +MIN = MIN +MINA = MIN2 +MINIFS = MINHA +MODE.MULT = MÓDUSZ.TÖBB +MODE.SNGL = MÓDUSZ.EGY +NEGBINOM.DIST = NEGBINOM.ELOSZLÁS +NORM.DIST = NORM.ELOSZLÁS +NORM.INV = NORM.INVERZ +NORM.S.DIST = NORM.S.ELOSZLÁS +NORM.S.INV = NORM.S.INVERZ +PEARSON = PEARSON +PERCENTILE.EXC = PERCENTILIS.KIZÁR +PERCENTILE.INC = PERCENTILIS.TARTALMAZ +PERCENTRANK.EXC = SZÁZALÉKRANG.KIZÁR +PERCENTRANK.INC = SZÁZALÉKRANG.TARTALMAZ +PERMUT = VARIÁCIÓK +PERMUTATIONA = VARIÁCIÓK.ISM +PHI = FI +POISSON.DIST = POISSON.ELOSZLÁS +PROB = VALÓSZÍNŰSÉG +QUARTILE.EXC = KVARTILIS.KIZÁR +QUARTILE.INC = KVARTILIS.TARTALMAZ +RANK.AVG = RANG.ÁTL +RANK.EQ = RANG.EGY +RSQ = RNÉGYZET +SKEW = FERDESÉG +SKEW.P = FERDESÉG.P +SLOPE = MEREDEKSÉG +SMALL = KICSI +STANDARDIZE = NORMALIZÁLÁS +STDEV.P = SZÓR.S +STDEV.S = SZÓR.M +STDEVA = SZÓRÁSA +STDEVPA = SZÓRÁSPA +STEYX = STHIBAYX +T.DIST = T.ELOSZL +T.DIST.2T = T.ELOSZLÁS.2SZ +T.DIST.RT = T.ELOSZLÁS.JOBB +T.INV = T.INVERZ +T.INV.2T = T.INVERZ.2SZ +T.TEST = T.PRÓB +TREND = TREND +TRIMMEAN = RÉSZÁTLAG +VAR.P = VAR.S +VAR.S = VAR.M +VARA = VARA +VARPA = VARPA +WEIBULL.DIST = WEIBULL.ELOSZLÁS +Z.TEST = Z.PRÓB ## -## Statistical functions Statisztikai függvények +## Szövegműveletekhez használható függvények (Text Functions) ## -AVEDEV = ÁTL.ELTÉRÉS ## Az adatpontoknak átlaguktól való átlagos abszolút eltérését számítja ki. -AVERAGE = ÁTLAG ## Argumentumai átlagát számítja ki. -AVERAGEA = ÁTLAGA ## Argumentumai átlagát számítja ki (beleértve a számokat, szöveget és logikai értékeket). -AVERAGEIF = ÁTLAGHA ## A megadott feltételnek eleget tévő tartomány celláinak átlagát (számtani közepét) adja eredményül. -AVERAGEIFS = ÁTLAGHATÖBB ## A megadott feltételeknek eleget tévő cellák átlagát (számtani közepét) adja eredményül. -BETADIST = BÉTA.ELOSZLÁS ## A béta-eloszlás függvényt számítja ki. -BETAINV = INVERZ.BÉTA ## Adott béta-eloszláshoz kiszámítja a béta eloszlásfüggvény inverzét. -BINOMDIST = BINOM.ELOSZLÁS ## A diszkrét binomiális eloszlás valószínűségértékét számítja ki. -CHIDIST = KHI.ELOSZLÁS ## A khi-négyzet-eloszlás egyszélű valószínűségértékét számítja ki. -CHIINV = INVERZ.KHI ## A khi-négyzet-eloszlás egyszélű valószínűségértékének inverzét számítja ki. -CHITEST = KHI.PRÓBA ## Függetlenségvizsgálatot hajt végre. -CONFIDENCE = MEGBÍZHATÓSÁG ## Egy statisztikai sokaság várható értékének megbízhatósági intervallumát adja eredményül. -CORREL = KORREL ## Két adathalmaz korrelációs együtthatóját számítja ki. -COUNT = DARAB ## Megszámolja, hogy argumentumlistájában hány szám található. -COUNTA = DARAB2 ## Megszámolja, hogy argumentumlistájában hány érték található. -COUNTBLANK = DARABÜRES ## Egy tartományban összeszámolja az üres cellákat. -COUNTIF = DARABTELI ## Egy tartományban összeszámolja azokat a cellákat, amelyek eleget tesznek a megadott feltételnek. -COUNTIFS = DARABHATÖBB ## Egy tartományban összeszámolja azokat a cellákat, amelyek eleget tesznek több feltételnek. -COVAR = KOVAR ## A kovarianciát, azaz a páronkénti eltérések szorzatának átlagát számítja ki. -CRITBINOM = KRITBINOM ## Azt a legkisebb számot adja eredményül, amelyre a binomiális eloszlásfüggvény értéke nem kisebb egy adott határértéknél. -DEVSQ = SQ ## Az átlagtól való eltérések négyzetének összegét számítja ki. -EXPONDIST = EXP.ELOSZLÁS ## Az exponenciális eloszlás értékét számítja ki. -FDIST = F.ELOSZLÁS ## Az F-eloszlás értékét számítja ki. -FINV = INVERZ.F ## Az F-eloszlás inverzének értékét számítja ki. -FISHER = FISHER ## Fisher-transzformációt hajt végre. -FISHERINV = INVERZ.FISHER ## A Fisher-transzformáció inverzét hajtja végre. -FORECAST = ELŐREJELZÉS ## Az ismert értékek alapján lineáris regresszióval becsült értéket ad eredményül. -FREQUENCY = GYAKORISÁG ## A gyakorisági vagy empirikus eloszlás értékét függőleges tömbként adja eredményül. -FTEST = F.PRÓBA ## Az F-próba értékét adja eredményül. -GAMMADIST = GAMMA.ELOSZLÁS ## A gamma-eloszlás értékét számítja ki. -GAMMAINV = INVERZ.GAMMA ## A gamma-eloszlás eloszlásfüggvénye inverzének értékét számítja ki. -GAMMALN = GAMMALN ## A gamma-függvény természetes logaritmusát számítja ki. -GEOMEAN = MÉRTANI.KÖZÉP ## Argumentumai mértani középértékét számítja ki. -GROWTH = NÖV ## Exponenciális regresszió alapján ad becslést. -HARMEAN = HARM.KÖZÉP ## Argumentumai harmonikus átlagát számítja ki. -HYPGEOMDIST = HIPERGEOM.ELOSZLÁS ## A hipergeometriai eloszlás értékét számítja ki. -INTERCEPT = METSZ ## A regressziós egyenes y tengellyel való metszéspontját határozza meg. -KURT = CSÚCSOSSÁG ## Egy adathalmaz csúcsosságát számítja ki. -LARGE = NAGY ## Egy adathalmaz k-adik legnagyobb elemét adja eredményül. -LINEST = LIN.ILL ## A legkisebb négyzetek módszerével az adatokra illesztett egyenes paramétereit határozza meg. -LOGEST = LOG.ILL ## Az adatokra illesztett exponenciális görbe paramétereit határozza meg. -LOGINV = INVERZ.LOG.ELOSZLÁS ## A lognormális eloszlás inverzét számítja ki. -LOGNORMDIST = LOG.ELOSZLÁS ## A lognormális eloszlásfüggvény értékét számítja ki. -MAX = MAX ## Az argumentumai között szereplő legnagyobb számot adja meg. -MAXA = MAX2 ## Az argumentumai között szereplő legnagyobb számot adja meg (beleértve a számokat, szöveget és logikai értékeket). -MEDIAN = MEDIÁN ## Adott számhalmaz mediánját számítja ki. -MIN = MIN ## Az argumentumai között szereplő legkisebb számot adja meg. -MINA = MIN2 ## Az argumentumai között szereplő legkisebb számot adja meg, beleértve a számokat, szöveget és logikai értékeket. -MODE = MÓDUSZ ## Egy adathalmazból kiválasztja a leggyakrabban előforduló számot. -NEGBINOMDIST = NEGBINOM.ELOSZL ## A negatív binomiális eloszlás értékét számítja ki. -NORMDIST = NORM.ELOSZL ## A normális eloszlás értékét számítja ki. -NORMINV = INVERZ.NORM ## A normális eloszlás eloszlásfüggvénye inverzének értékét számítja ki. -NORMSDIST = STNORMELOSZL ## A standard normális eloszlás eloszlásfüggvényének értékét számítja ki. -NORMSINV = INVERZ.STNORM ## A standard normális eloszlás eloszlásfüggvénye inverzének értékét számítja ki. -PEARSON = PEARSON ## A Pearson-féle korrelációs együtthatót számítja ki. -PERCENTILE = PERCENTILIS ## Egy tartományban található értékek k-adik percentilisét, azaz százalékosztályát adja eredményül. -PERCENTRANK = SZÁZALÉKRANG ## Egy értéknek egy adathalmazon belül vett százalékos rangját (elhelyezkedését) számítja ki. -PERMUT = VARIÁCIÓK ## Adott számú objektum k-ad osztályú ismétlés nélküli variációinak számát számítja ki. -POISSON = POISSON ## A Poisson-eloszlás értékét számítja ki. -PROB = VALÓSZÍNŰSÉG ## Annak valószínűségét számítja ki, hogy adott értékek két határérték közé esnek. -QUARTILE = KVARTILIS ## Egy adathalmaz kvartilisét (negyedszintjét) számítja ki. -RANK = SORSZÁM ## Kiszámítja, hogy egy szám hányadik egy számsorozatban. -RSQ = RNÉGYZET ## Kiszámítja a Pearson-féle szorzatmomentum korrelációs együtthatójának négyzetét. -SKEW = FERDESÉG ## Egy eloszlás ferdeségét határozza meg. -SLOPE = MEREDEKSÉG ## Egy lineáris regressziós egyenes meredekségét számítja ki. -SMALL = KICSI ## Egy adathalmaz k-adik legkisebb elemét adja meg. -STANDARDIZE = NORMALIZÁLÁS ## Normalizált értéket ad eredményül. -STDEV = SZÓRÁS ## Egy statisztikai sokaság mintájából kiszámítja annak szórását. -STDEVA = SZÓRÁSA ## Egy statisztikai sokaság mintájából kiszámítja annak szórását (beleértve a számokat, szöveget és logikai értékeket). -STDEVP = SZÓRÁSP ## Egy statisztikai sokaság egészéből kiszámítja annak szórását. -STDEVPA = SZÓRÁSPA ## Egy statisztikai sokaság egészéből kiszámítja annak szórását (beleértve számokat, szöveget és logikai értékeket). -STEYX = STHIBAYX ## Egy regresszió esetén az egyes x-értékek alapján meghatározott y-értékek standard hibáját számítja ki. -TDIST = T.ELOSZLÁS ## A Student-féle t-eloszlás értékét számítja ki. -TINV = INVERZ.T ## A Student-féle t-eloszlás inverzét számítja ki. -TREND = TREND ## Lineáris trend értékeit számítja ki. -TRIMMEAN = RÉSZÁTLAG ## Egy adathalmaz középső részének átlagát számítja ki. -TTEST = T.PRÓBA ## A Student-féle t-próbához tartozó valószínűséget számítja ki. -VAR = VAR ## Minta alapján becslést ad a varianciára. -VARA = VARA ## Minta alapján becslést ad a varianciára (beleértve számokat, szöveget és logikai értékeket). -VARP = VARP ## Egy statisztikai sokaság varianciáját számítja ki. -VARPA = VARPA ## Egy statisztikai sokaság varianciáját számítja ki (beleértve számokat, szöveget és logikai értékeket). -WEIBULL = WEIBULL ## A Weibull-féle eloszlás értékét számítja ki. -ZTEST = Z.PRÓBA ## Az egyszélű z-próbával kapott valószínűségértéket számítja ki. - +BAHTTEXT = BAHTSZÖVEG +CHAR = KARAKTER +CLEAN = TISZTÍT +CODE = KÓD +CONCAT = FŰZ +DOLLAR = FORINT +EXACT = AZONOS +FIND = SZÖVEG.TALÁL +FIXED = FIX +ISTHAIDIGIT = ON.THAI.NUMERO +LEFT = BAL +LEN = HOSSZ +LOWER = KISBETŰ +MID = KÖZÉP +NUMBERSTRING = SZÁM.BETŰVEL +NUMBERVALUE = SZÁMÉRTÉK +PHONETIC = FONETIKUS +PROPER = TNÉV +REPLACE = CSERE +REPT = SOKSZOR +RIGHT = JOBB +SEARCH = SZÖVEG.KERES +SUBSTITUTE = HELYETTE +T = T +TEXT = SZÖVEG +TEXTJOIN = SZÖVEGÖSSZEFŰZÉS +THAIDIGIT = THAISZÁM +THAINUMSOUND = THAISZÁMHANG +THAINUMSTRING = THAISZÁMKAR +THAISTRINGLENGTH = THAIKARHOSSZ +TRIM = KIMETSZ +UNICHAR = UNIKARAKTER +UNICODE = UNICODE +UPPER = NAGYBETŰS +VALUE = ÉRTÉK ## -## Text functions Szövegműveletekhez használható függvények +## Webes függvények (Web Functions) ## -ASC = ASC ## Szöveg teljes szélességű (kétbájtos) latin és katakana karaktereit félszélességű (egybájtos) karakterekké alakítja. -BAHTTEXT = BAHTSZÖVEG ## Számot szöveggé alakít a ß (baht) pénznemformátum használatával. -CHAR = KARAKTER ## A kódszámmal meghatározott karaktert adja eredményül. -CLEAN = TISZTÍT ## A szövegből eltávolítja az összes nem nyomtatható karaktert. -CODE = KÓD ## Karaktersorozat első karakterének numerikus kódját adja eredményül. -CONCATENATE = ÖSSZEFŰZ ## Több szövegelemet egyetlen szöveges elemmé fűz össze. -DOLLAR = FORINT ## Számot pénznem formátumú szöveggé alakít át. -EXACT = AZONOS ## Megvizsgálja, hogy két érték azonos-e. -FIND = SZÖVEG.TALÁL ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk megkülönböztetésével). -FINDB = SZÖVEG.TALÁL2 ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk megkülönböztetésével). -FIXED = FIX ## Számot szöveges formátumúra alakít adott számú tizedesjegyre kerekítve. -JIS = JIS ## A félszélességű (egybájtos) latin és a katakana karaktereket teljes szélességű (kétbájtos) karakterekké alakítja. -LEFT = BAL ## Szöveg bal szélső karaktereit adja eredményül. -LEFTB = BAL2 ## Szöveg bal szélső karaktereit adja eredményül. -LEN = HOSSZ ## Szöveg karakterekben mért hosszát adja eredményül. -LENB = HOSSZ2 ## Szöveg karakterekben mért hosszát adja eredményül. -LOWER = KISBETŰ ## Szöveget kisbetűssé alakít át. -MID = KÖZÉP ## A szöveg adott pozíciójától kezdve megadott számú karaktert ad vissza eredményként. -MIDB = KÖZÉP2 ## A szöveg adott pozíciójától kezdve megadott számú karaktert ad vissza eredményként. -PHONETIC = PHONETIC ## Szöveg furigana (fonetikus) karaktereit adja vissza. -PROPER = TNÉV ## Szöveg minden szavának kezdőbetűjét nagybetűsre cseréli. -REPLACE = CSERE ## A szövegen belül karaktereket cserél. -REPLACEB = CSERE2 ## A szövegen belül karaktereket cserél. -REPT = SOKSZOR ## Megadott számú alkalommal megismétel egy szövegrészt. -RIGHT = JOBB ## Szövegrész jobb szélső karaktereit adja eredményül. -RIGHTB = JOBB2 ## Szövegrész jobb szélső karaktereit adja eredményül. -SEARCH = SZÖVEG.KERES ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk között nem tesz különbséget). -SEARCHB = SZÖVEG.KERES2 ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk között nem tesz különbséget). -SUBSTITUTE = HELYETTE ## Szövegben adott karaktereket másikra cserél. -T = T ## Argumentumát szöveggé alakítja át. -TEXT = SZÖVEG ## Számértéket alakít át adott számformátumú szöveggé. -TRIM = TRIM ## A szövegből eltávolítja a szóközöket. -UPPER = NAGYBETŰS ## Szöveget nagybetűssé alakít át. -VALUE = ÉRTÉK ## Szöveget számmá alakít át. +ENCODEURL = URL.KÓDOL +FILTERXML = XMLSZŰRÉS +WEBSERVICE = WEBSZOLGÁLTATÁS + +## +## Kompatibilitási függvények (Compatibility Functions) +## +BETADIST = BÉTA.ELOSZLÁS +BETAINV = INVERZ.BÉTA +BINOMDIST = BINOM.ELOSZLÁS +CEILING = PLAFON +CHIDIST = KHI.ELOSZLÁS +CHIINV = INVERZ.KHI +CHITEST = KHI.PRÓBA +CONCATENATE = ÖSSZEFŰZ +CONFIDENCE = MEGBÍZHATÓSÁG +COVAR = KOVAR +CRITBINOM = KRITBINOM +EXPONDIST = EXP.ELOSZLÁS +FDIST = F.ELOSZLÁS +FINV = INVERZ.F +FLOOR = PADLÓ +FORECAST = ELŐREJELZÉS +FTEST = F.PRÓBA +GAMMADIST = GAMMA.ELOSZLÁS +GAMMAINV = INVERZ.GAMMA +HYPGEOMDIST = HIPERGEOM.ELOSZLÁS +LOGINV = INVERZ.LOG.ELOSZLÁS +LOGNORMDIST = LOG.ELOSZLÁS +MODE = MÓDUSZ +NEGBINOMDIST = NEGBINOM.ELOSZL +NORMDIST = NORM.ELOSZL +NORMINV = INVERZ.NORM +NORMSDIST = STNORMELOSZL +NORMSINV = INVERZ.STNORM +PERCENTILE = PERCENTILIS +PERCENTRANK = SZÁZALÉKRANG +POISSON = POISSON +QUARTILE = KVARTILIS +RANK = SORSZÁM +STDEV = SZÓRÁS +STDEVP = SZÓRÁSP +TDIST = T.ELOSZLÁS +TINV = INVERZ.T +TTEST = T.PRÓBA +VAR = VAR +VARP = VARP +WEIBULL = WEIBULL +ZTEST = Z.PRÓBA diff --git a/src/PhpSpreadsheet/Calculation/locale/it/config b/src/PhpSpreadsheet/Calculation/locale/it/config index 6cc013ae..5c1e4955 100644 --- a/src/PhpSpreadsheet/Calculation/locale/it/config +++ b/src/PhpSpreadsheet/Calculation/locale/it/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## +## Italiano (Italian) +## +############################################################ -ArgumentSeparator = ; - +ArgumentSeparator = ; ## -## (For future use) +## Error Codes ## -currencySymbol = € - - -## -## Excel Error Codes (For future use) - -## -NULL = #NULLO! -DIV0 = #DIV/0! -VALUE = #VALORE! -REF = #RIF! -NAME = #NOME? -NUM = #NUM! -NA = #N/D +NULL +DIV0 +VALUE = #VALORE! +REF = #RIF! +NAME = #NOME? +NUM +NA = #N/D diff --git a/src/PhpSpreadsheet/Calculation/locale/it/functions b/src/PhpSpreadsheet/Calculation/locale/it/functions index 1901bafa..c14ed85f 100644 --- a/src/PhpSpreadsheet/Calculation/locale/it/functions +++ b/src/PhpSpreadsheet/Calculation/locale/it/functions @@ -1,416 +1,537 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Italiano (Italian) ## +############################################################ ## -## Add-in and Automation functions Funzioni di automazione e dei componenti aggiuntivi +## Funzioni cubo (Cube Functions) ## -GETPIVOTDATA = INFO.DATI.TAB.PIVOT ## Restituisce i dati memorizzati in un rapporto di tabella pivot - +CUBEKPIMEMBER = MEMBRO.KPI.CUBO +CUBEMEMBER = MEMBRO.CUBO +CUBEMEMBERPROPERTY = PROPRIETÀ.MEMBRO.CUBO +CUBERANKEDMEMBER = MEMBRO.CUBO.CON.RANGO +CUBESET = SET.CUBO +CUBESETCOUNT = CONTA.SET.CUBO +CUBEVALUE = VALORE.CUBO ## -## Cube functions Funzioni cubo +## Funzioni di database (Database Functions) ## -CUBEKPIMEMBER = MEMBRO.KPI.CUBO ## Restituisce il nome, la proprietà e la misura di un indicatore di prestazioni chiave (KPI) e visualizza il nome e la proprietà nella cella. Un KPI è una misura quantificabile, ad esempio l'utile lordo mensile o il fatturato trimestrale dei dipendenti, utilizzata per il monitoraggio delle prestazioni di un'organizzazione. -CUBEMEMBER = MEMBRO.CUBO ## Restituisce un membro o una tupla in una gerarchia di cubi. Consente di verificare l'esistenza del membro o della tupla nel cubo. -CUBEMEMBERPROPERTY = PROPRIETÀ.MEMBRO.CUBO ## Restituisce il valore di una proprietà di un membro del cubo. Consente di verificare l'esistenza di un nome di membro all'interno del cubo e di restituire la proprietà specificata per tale membro. -CUBERANKEDMEMBER = MEMBRO.CUBO.CON.RANGO ## Restituisce l'n-esimo membro o il membro ordinato di un insieme. Consente di restituire uno o più elementi in un insieme, ad esempio l'agente di vendita migliore o i primi 10 studenti. -CUBESET = SET.CUBO ## Definisce un insieme di tuple o membri calcolati mediante l'invio di un'espressione di insieme al cubo sul server. In questo modo l'insieme viene creato e restituito a Microsoft Office Excel. -CUBESETCOUNT = CONTA.SET.CUBO ## Restituisce il numero di elementi di un insieme. -CUBEVALUE = VALORE.CUBO ## Restituisce un valore aggregato da un cubo. - +DAVERAGE = DB.MEDIA +DCOUNT = DB.CONTA.NUMERI +DCOUNTA = DB.CONTA.VALORI +DGET = DB.VALORI +DMAX = DB.MAX +DMIN = DB.MIN +DPRODUCT = DB.PRODOTTO +DSTDEV = DB.DEV.ST +DSTDEVP = DB.DEV.ST.POP +DSUM = DB.SOMMA +DVAR = DB.VAR +DVARP = DB.VAR.POP ## -## Database functions Funzioni di database +## Funzioni data e ora (Date & Time Functions) ## -DAVERAGE = DB.MEDIA ## Restituisce la media di voci del database selezionate -DCOUNT = DB.CONTA.NUMERI ## Conta le celle di un database contenenti numeri -DCOUNTA = DB.CONTA.VALORI ## Conta le celle non vuote in un database -DGET = DB.VALORI ## Estrae da un database un singolo record che soddisfa i criteri specificati -DMAX = DB.MAX ## Restituisce il valore massimo dalle voci selezionate in un database -DMIN = DB.MIN ## Restituisce il valore minimo dalle voci di un database selezionate -DPRODUCT = DB.PRODOTTO ## Moltiplica i valori in un determinato campo di record che soddisfano i criteri del database -DSTDEV = DB.DEV.ST ## Restituisce una stima della deviazione standard sulla base di un campione di voci di un database selezionate -DSTDEVP = DB.DEV.ST.POP ## Calcola la deviazione standard sulla base di tutte le voci di un database selezionate -DSUM = DB.SOMMA ## Aggiunge i numeri nel campo colonna di record del database che soddisfa determinati criteri -DVAR = DB.VAR ## Restituisce una stima della varianza sulla base di un campione da voci di un database selezionate -DVARP = DB.VAR.POP ## Calcola la varianza sulla base di tutte le voci di un database selezionate - +DATE = DATA +DATEDIF = DATA.DIFF +DATESTRING = DATA.STRINGA +DATEVALUE = DATA.VALORE +DAY = GIORNO +DAYS = GIORNI +DAYS360 = GIORNO360 +EDATE = DATA.MESE +EOMONTH = FINE.MESE +HOUR = ORA +ISOWEEKNUM = NUM.SETTIMANA.ISO +MINUTE = MINUTO +MONTH = MESE +NETWORKDAYS = GIORNI.LAVORATIVI.TOT +NETWORKDAYS.INTL = GIORNI.LAVORATIVI.TOT.INTL +NOW = ADESSO +SECOND = SECONDO +THAIDAYOFWEEK = THAIGIORNODELLASETTIMANA +THAIMONTHOFYEAR = THAIMESEDELLANNO +THAIYEAR = THAIANNO +TIME = ORARIO +TIMEVALUE = ORARIO.VALORE +TODAY = OGGI +WEEKDAY = GIORNO.SETTIMANA +WEEKNUM = NUM.SETTIMANA +WORKDAY = GIORNO.LAVORATIVO +WORKDAY.INTL = GIORNO.LAVORATIVO.INTL +YEAR = ANNO +YEARFRAC = FRAZIONE.ANNO ## -## Date and time functions Funzioni data e ora +## Funzioni ingegneristiche (Engineering Functions) ## -DATE = DATA ## Restituisce il numero seriale di una determinata data -DATEVALUE = DATA.VALORE ## Converte una data sotto forma di testo in un numero seriale -DAY = GIORNO ## Converte un numero seriale in un giorno del mese -DAYS360 = GIORNO360 ## Calcola il numero di giorni compreso tra due date basandosi su un anno di 360 giorni -EDATE = DATA.MESE ## Restituisce il numero seriale della data che rappresenta il numero di mesi prima o dopo la data di inizio -EOMONTH = FINE.MESE ## Restituisce il numero seriale dell'ultimo giorno del mese, prima o dopo un determinato numero di mesi -HOUR = ORA ## Converte un numero seriale in un'ora -MINUTE = MINUTO ## Converte un numero seriale in un minuto -MONTH = MESE ## Converte un numero seriale in un mese -NETWORKDAYS = GIORNI.LAVORATIVI.TOT ## Restituisce il numero di tutti i giorni lavorativi compresi fra due date -NOW = ADESSO ## Restituisce il numero seriale della data e dell'ora corrente -SECOND = SECONDO ## Converte un numero seriale in un secondo -TIME = ORARIO ## Restituisce il numero seriale di una determinata ora -TIMEVALUE = ORARIO.VALORE ## Converte un orario in forma di testo in un numero seriale -TODAY = OGGI ## Restituisce il numero seriale relativo alla data odierna -WEEKDAY = GIORNO.SETTIMANA ## Converte un numero seriale in un giorno della settimana -WEEKNUM = NUM.SETTIMANA ## Converte un numero seriale in un numero che rappresenta la posizione numerica di una settimana nell'anno -WORKDAY = GIORNO.LAVORATIVO ## Restituisce il numero della data prima o dopo un determinato numero di giorni lavorativi -YEAR = ANNO ## Converte un numero seriale in un anno -YEARFRAC = FRAZIONE.ANNO ## Restituisce la frazione dell'anno che rappresenta il numero dei giorni compresi tra una data_ iniziale e una data_finale - +BESSELI = BESSEL.I +BESSELJ = BESSEL.J +BESSELK = BESSEL.K +BESSELY = BESSEL.Y +BIN2DEC = BINARIO.DECIMALE +BIN2HEX = BINARIO.HEX +BIN2OCT = BINARIO.OCT +BITAND = BITAND +BITLSHIFT = BIT.SPOSTA.SX +BITOR = BITOR +BITRSHIFT = BIT.SPOSTA.DX +BITXOR = BITXOR +COMPLEX = COMPLESSO +CONVERT = CONVERTI +DEC2BIN = DECIMALE.BINARIO +DEC2HEX = DECIMALE.HEX +DEC2OCT = DECIMALE.OCT +DELTA = DELTA +ERF = FUNZ.ERRORE +ERF.PRECISE = FUNZ.ERRORE.PRECISA +ERFC = FUNZ.ERRORE.COMP +ERFC.PRECISE = FUNZ.ERRORE.COMP.PRECISA +GESTEP = SOGLIA +HEX2BIN = HEX.BINARIO +HEX2DEC = HEX.DECIMALE +HEX2OCT = HEX.OCT +IMABS = COMP.MODULO +IMAGINARY = COMP.IMMAGINARIO +IMARGUMENT = COMP.ARGOMENTO +IMCONJUGATE = COMP.CONIUGATO +IMCOS = COMP.COS +IMCOSH = COMP.COSH +IMCOT = COMP.COT +IMCSC = COMP.CSC +IMCSCH = COMP.CSCH +IMDIV = COMP.DIV +IMEXP = COMP.EXP +IMLN = COMP.LN +IMLOG10 = COMP.LOG10 +IMLOG2 = COMP.LOG2 +IMPOWER = COMP.POTENZA +IMPRODUCT = COMP.PRODOTTO +IMREAL = COMP.PARTE.REALE +IMSEC = COMP.SEC +IMSECH = COMP.SECH +IMSIN = COMP.SEN +IMSINH = COMP.SENH +IMSQRT = COMP.RADQ +IMSUB = COMP.DIFF +IMSUM = COMP.SOMMA +IMTAN = COMP.TAN +OCT2BIN = OCT.BINARIO +OCT2DEC = OCT.DECIMALE +OCT2HEX = OCT.HEX ## -## Engineering functions Funzioni ingegneristiche +## Funzioni finanziarie (Financial Functions) ## -BESSELI = BESSEL.I ## Restituisce la funzione di Bessel modificata In(x) -BESSELJ = BESSEL.J ## Restituisce la funzione di Bessel Jn(x) -BESSELK = BESSEL.K ## Restituisce la funzione di Bessel modificata Kn(x) -BESSELY = BESSEL.Y ## Restituisce la funzione di Bessel Yn(x) -BIN2DEC = BINARIO.DECIMALE ## Converte un numero binario in decimale -BIN2HEX = BINARIO.HEX ## Converte un numero binario in esadecimale -BIN2OCT = BINARIO.OCT ## Converte un numero binario in ottale -COMPLEX = COMPLESSO ## Converte i coefficienti reali e immaginari in numeri complessi -CONVERT = CONVERTI ## Converte un numero da un sistema di misura in un altro -DEC2BIN = DECIMALE.BINARIO ## Converte un numero decimale in binario -DEC2HEX = DECIMALE.HEX ## Converte un numero decimale in esadecimale -DEC2OCT = DECIMALE.OCT ## Converte un numero decimale in ottale -DELTA = DELTA ## Verifica se due valori sono uguali -ERF = FUNZ.ERRORE ## Restituisce la funzione di errore -ERFC = FUNZ.ERRORE.COMP ## Restituisce la funzione di errore complementare -GESTEP = SOGLIA ## Verifica se un numero è maggiore del valore di soglia -HEX2BIN = HEX.BINARIO ## Converte un numero esadecimale in binario -HEX2DEC = HEX.DECIMALE ## Converte un numero esadecimale in decimale -HEX2OCT = HEX.OCT ## Converte un numero esadecimale in ottale -IMABS = COMP.MODULO ## Restituisce il valore assoluto (modulo) di un numero complesso -IMAGINARY = COMP.IMMAGINARIO ## Restituisce il coefficiente immaginario di un numero complesso -IMARGUMENT = COMP.ARGOMENTO ## Restituisce l'argomento theta, un angolo espresso in radianti -IMCONJUGATE = COMP.CONIUGATO ## Restituisce il complesso coniugato del numero complesso -IMCOS = COMP.COS ## Restituisce il coseno di un numero complesso -IMDIV = COMP.DIV ## Restituisce il quoziente di due numeri complessi -IMEXP = COMP.EXP ## Restituisce il valore esponenziale di un numero complesso -IMLN = COMP.LN ## Restituisce il logaritmo naturale di un numero complesso -IMLOG10 = COMP.LOG10 ## Restituisce il logaritmo in base 10 di un numero complesso -IMLOG2 = COMP.LOG2 ## Restituisce un logaritmo in base 2 di un numero complesso -IMPOWER = COMP.POTENZA ## Restituisce il numero complesso elevato a una potenza intera -IMPRODUCT = COMP.PRODOTTO ## Restituisce il prodotto di numeri complessi compresi tra 2 e 29 -IMREAL = COMP.PARTE.REALE ## Restituisce il coefficiente reale di un numero complesso -IMSIN = COMP.SEN ## Restituisce il seno di un numero complesso -IMSQRT = COMP.RADQ ## Restituisce la radice quadrata di un numero complesso -IMSUB = COMP.DIFF ## Restituisce la differenza fra due numeri complessi -IMSUM = COMP.SOMMA ## Restituisce la somma di numeri complessi -OCT2BIN = OCT.BINARIO ## Converte un numero ottale in binario -OCT2DEC = OCT.DECIMALE ## Converte un numero ottale in decimale -OCT2HEX = OCT.HEX ## Converte un numero ottale in esadecimale - +ACCRINT = INT.MATURATO.PER +ACCRINTM = INT.MATURATO.SCAD +AMORDEGRC = AMMORT.DEGR +AMORLINC = AMMORT.PER +COUPDAYBS = GIORNI.CED.INIZ.LIQ +COUPDAYS = GIORNI.CED +COUPDAYSNC = GIORNI.CED.NUOVA +COUPNCD = DATA.CED.SUCC +COUPNUM = NUM.CED +COUPPCD = DATA.CED.PREC +CUMIPMT = INT.CUMUL +CUMPRINC = CAP.CUM +DB = AMMORT.FISSO +DDB = AMMORT +DISC = TASSO.SCONTO +DOLLARDE = VALUTA.DEC +DOLLARFR = VALUTA.FRAZ +DURATION = DURATA +EFFECT = EFFETTIVO +FV = VAL.FUT +FVSCHEDULE = VAL.FUT.CAPITALE +INTRATE = TASSO.INT +IPMT = INTERESSI +IRR = TIR.COST +ISPMT = INTERESSE.RATA +MDURATION = DURATA.M +MIRR = TIR.VAR +NOMINAL = NOMINALE +NPER = NUM.RATE +NPV = VAN +ODDFPRICE = PREZZO.PRIMO.IRR +ODDFYIELD = REND.PRIMO.IRR +ODDLPRICE = PREZZO.ULTIMO.IRR +ODDLYIELD = REND.ULTIMO.IRR +PDURATION = DURATA.P +PMT = RATA +PPMT = P.RATA +PRICE = PREZZO +PRICEDISC = PREZZO.SCONT +PRICEMAT = PREZZO.SCAD +PV = VA +RATE = TASSO +RECEIVED = RICEV.SCAD +RRI = RIT.INVEST.EFFETT +SLN = AMMORT.COST +SYD = AMMORT.ANNUO +TBILLEQ = BOT.EQUIV +TBILLPRICE = BOT.PREZZO +TBILLYIELD = BOT.REND +VDB = AMMORT.VAR +XIRR = TIR.X +XNPV = VAN.X +YIELD = REND +YIELDDISC = REND.TITOLI.SCONT +YIELDMAT = REND.SCAD ## -## Financial functions Funzioni finanziarie +## Funzioni relative alle informazioni (Information Functions) ## -ACCRINT = INT.MATURATO.PER ## Restituisce l'interesse maturato di un titolo che paga interessi periodici -ACCRINTM = INT.MATURATO.SCAD ## Restituisce l'interesse maturato di un titolo che paga interessi alla scadenza -AMORDEGRC = AMMORT.DEGR ## Restituisce l'ammortamento per ogni periodo contabile utilizzando un coefficiente di ammortamento -AMORLINC = AMMORT.PER ## Restituisce l'ammortamento per ogni periodo contabile -COUPDAYBS = GIORNI.CED.INIZ.LIQ ## Restituisce il numero dei giorni che vanno dall'inizio del periodo di durata della cedola alla data di liquidazione -COUPDAYS = GIORNI.CED ## Restituisce il numero dei giorni relativi al periodo della cedola che contiene la data di liquidazione -COUPDAYSNC = GIORNI.CED.NUOVA ## Restituisce il numero di giorni che vanno dalla data di liquidazione alla data della cedola successiva -COUPNCD = DATA.CED.SUCC ## Restituisce un numero che rappresenta la data della cedola successiva alla data di liquidazione -COUPNUM = NUM.CED ## Restituisce il numero di cedole pagabili fra la data di liquidazione e la data di scadenza -COUPPCD = DATA.CED.PREC ## Restituisce un numero che rappresenta la data della cedola precedente alla data di liquidazione -CUMIPMT = INT.CUMUL ## Restituisce l'interesse cumulativo pagato fra due periodi -CUMPRINC = CAP.CUM ## Restituisce il capitale cumulativo pagato per estinguere un debito fra due periodi -DB = DB ## Restituisce l'ammortamento di un bene per un periodo specificato utilizzando il metodo di ammortamento a quote fisse decrescenti -DDB = AMMORT ## Restituisce l'ammortamento di un bene per un periodo specificato utilizzando il metodo di ammortamento a doppie quote decrescenti o altri metodi specificati -DISC = TASSO.SCONTO ## Restituisce il tasso di sconto per un titolo -DOLLARDE = VALUTA.DEC ## Converte un prezzo valuta, espresso come frazione, in prezzo valuta, espresso come numero decimale -DOLLARFR = VALUTA.FRAZ ## Converte un prezzo valuta, espresso come numero decimale, in prezzo valuta, espresso come frazione -DURATION = DURATA ## Restituisce la durata annuale di un titolo con i pagamenti di interesse periodico -EFFECT = EFFETTIVO ## Restituisce l'effettivo tasso di interesse annuo -FV = VAL.FUT ## Restituisce il valore futuro di un investimento -FVSCHEDULE = VAL.FUT.CAPITALE ## Restituisce il valore futuro di un capitale iniziale dopo aver applicato una serie di tassi di interesse composti -INTRATE = TASSO.INT ## Restituisce il tasso di interesse per un titolo interamente investito -IPMT = INTERESSI ## Restituisce il valore degli interessi per un investimento relativo a un periodo specifico -IRR = TIR.COST ## Restituisce il tasso di rendimento interno per una serie di flussi di cassa -ISPMT = INTERESSE.RATA ## Calcola l'interesse di un investimento pagato durante un periodo specifico -MDURATION = DURATA.M ## Restituisce la durata Macauley modificata per un titolo con un valore presunto di € 100 -MIRR = TIR.VAR ## Restituisce il tasso di rendimento interno in cui i flussi di cassa positivi e negativi sono finanziati a tassi differenti -NOMINAL = NOMINALE ## Restituisce il tasso di interesse nominale annuale -NPER = NUM.RATE ## Restituisce un numero di periodi relativi a un investimento -NPV = VAN ## Restituisce il valore attuale netto di un investimento basato su una serie di flussi di cassa periodici e sul tasso di sconto -ODDFPRICE = PREZZO.PRIMO.IRR ## Restituisce il prezzo di un titolo dal valore nominale di € 100 avente il primo periodo di durata irregolare -ODDFYIELD = REND.PRIMO.IRR ## Restituisce il rendimento di un titolo avente il primo periodo di durata irregolare -ODDLPRICE = PREZZO.ULTIMO.IRR ## Restituisce il prezzo di un titolo dal valore nominale di € 100 avente l'ultimo periodo di durata irregolare -ODDLYIELD = REND.ULTIMO.IRR ## Restituisce il rendimento di un titolo avente l'ultimo periodo di durata irregolare -PMT = RATA ## Restituisce il pagamento periodico di una rendita annua -PPMT = P.RATA ## Restituisce il pagamento sul capitale di un investimento per un dato periodo -PRICE = PREZZO ## Restituisce il prezzo di un titolo dal valore nominale di € 100 che paga interessi periodici -PRICEDISC = PREZZO.SCONT ## Restituisce il prezzo di un titolo scontato dal valore nominale di € 100 -PRICEMAT = PREZZO.SCAD ## Restituisce il prezzo di un titolo dal valore nominale di € 100 che paga gli interessi alla scadenza -PV = VA ## Restituisce il valore attuale di un investimento -RATE = TASSO ## Restituisce il tasso di interesse per un periodo di un'annualità -RECEIVED = RICEV.SCAD ## Restituisce l'ammontare ricevuto alla scadenza di un titolo interamente investito -SLN = AMMORT.COST ## Restituisce l'ammortamento a quote costanti di un bene per un singolo periodo -SYD = AMMORT.ANNUO ## Restituisce l'ammortamento a somma degli anni di un bene per un periodo specificato -TBILLEQ = BOT.EQUIV ## Restituisce il rendimento equivalente ad un'obbligazione per un Buono ordinario del Tesoro -TBILLPRICE = BOT.PREZZO ## Restituisce il prezzo di un Buono del Tesoro dal valore nominale di € 100 -TBILLYIELD = BOT.REND ## Restituisce il rendimento di un Buono del Tesoro -VDB = AMMORT.VAR ## Restituisce l'ammortamento di un bene per un periodo specificato o parziale utilizzando il metodo a doppie quote proporzionali ai valori residui -XIRR = TIR.X ## Restituisce il tasso di rendimento interno di un impiego di flussi di cassa -XNPV = VAN.X ## Restituisce il valore attuale netto di un impiego di flussi di cassa non necessariamente periodici -YIELD = REND ## Restituisce il rendimento di un titolo che frutta interessi periodici -YIELDDISC = REND.TITOLI.SCONT ## Restituisce il rendimento annuale di un titolo scontato, ad esempio un Buono del Tesoro -YIELDMAT = REND.SCAD ## Restituisce il rendimento annuo di un titolo che paga interessi alla scadenza - +CELL = CELLA +ERROR.TYPE = ERRORE.TIPO +INFO = AMBIENTE.INFO +ISBLANK = VAL.VUOTO +ISERR = VAL.ERR +ISERROR = VAL.ERRORE +ISEVEN = VAL.PARI +ISFORMULA = VAL.FORMULA +ISLOGICAL = VAL.LOGICO +ISNA = VAL.NON.DISP +ISNONTEXT = VAL.NON.TESTO +ISNUMBER = VAL.NUMERO +ISODD = VAL.DISPARI +ISREF = VAL.RIF +ISTEXT = VAL.TESTO +N = NUM +NA = NON.DISP +SHEET = FOGLIO +SHEETS = FOGLI +TYPE = TIPO ## -## Information functions Funzioni relative alle informazioni +## Funzioni logiche (Logical Functions) ## -CELL = CELLA ## Restituisce le informazioni sulla formattazione, la posizione o i contenuti di una cella -ERROR.TYPE = ERRORE.TIPO ## Restituisce un numero che corrisponde a un tipo di errore -INFO = INFO ## Restituisce le informazioni sull'ambiente operativo corrente -ISBLANK = VAL.VUOTO ## Restituisce VERO se il valore è vuoto -ISERR = VAL.ERR ## Restituisce VERO se il valore è un valore di errore qualsiasi tranne #N/D -ISERROR = VAL.ERRORE ## Restituisce VERO se il valore è un valore di errore qualsiasi -ISEVEN = VAL.PARI ## Restituisce VERO se il numero è pari -ISLOGICAL = VAL.LOGICO ## Restituisce VERO se il valore è un valore logico -ISNA = VAL.NON.DISP ## Restituisce VERO se il valore è un valore di errore #N/D -ISNONTEXT = VAL.NON.TESTO ## Restituisce VERO se il valore non è in formato testo -ISNUMBER = VAL.NUMERO ## Restituisce VERO se il valore è un numero -ISODD = VAL.DISPARI ## Restituisce VERO se il numero è dispari -ISREF = VAL.RIF ## Restituisce VERO se il valore è un riferimento -ISTEXT = VAL.TESTO ## Restituisce VERO se il valore è in formato testo -N = NUM ## Restituisce un valore convertito in numero -NA = NON.DISP ## Restituisce il valore di errore #N/D -TYPE = TIPO ## Restituisce un numero che indica il tipo di dati relativi a un valore - +AND = E +FALSE = FALSO +IF = SE +IFERROR = SE.ERRORE +IFNA = SE.NON.DISP. +IFS = PIÙ.SE +NOT = NON +OR = O +SWITCH = SWITCH +TRUE = VERO +XOR = XOR ## -## Logical functions Funzioni logiche +## Funzioni di ricerca e di riferimento (Lookup & Reference Functions) ## -AND = E ## Restituisce VERO se tutti gli argomenti sono VERO -FALSE = FALSO ## Restituisce il valore logico FALSO -IF = SE ## Specifica un test logico da eseguire -IFERROR = SE.ERRORE ## Restituisce un valore specificato se una formula fornisce un errore come risultato; in caso contrario, restituisce il risultato della formula -NOT = NON ## Inverte la logica degli argomenti -OR = O ## Restituisce VERO se un argomento qualsiasi è VERO -TRUE = VERO ## Restituisce il valore logico VERO - +ADDRESS = INDIRIZZO +AREAS = AREE +CHOOSE = SCEGLI +COLUMN = RIF.COLONNA +COLUMNS = COLONNE +FORMULATEXT = TESTO.FORMULA +GETPIVOTDATA = INFO.DATI.TAB.PIVOT +HLOOKUP = CERCA.ORIZZ +HYPERLINK = COLLEG.IPERTESTUALE +INDEX = INDICE +INDIRECT = INDIRETTO +LOOKUP = CERCA +MATCH = CONFRONTA +OFFSET = SCARTO +ROW = RIF.RIGA +ROWS = RIGHE +RTD = DATITEMPOREALE +TRANSPOSE = MATR.TRASPOSTA +VLOOKUP = CERCA.VERT ## -## Lookup and reference functions Funzioni di ricerca e di riferimento +## Funzioni matematiche e trigonometriche (Math & Trig Functions) ## -ADDRESS = INDIRIZZO ## Restituisce un riferimento come testo in una singola cella di un foglio di lavoro -AREAS = AREE ## Restituisce il numero di aree in un riferimento -CHOOSE = SCEGLI ## Sceglie un valore da un elenco di valori -COLUMN = RIF.COLONNA ## Restituisce il numero di colonna di un riferimento -COLUMNS = COLONNE ## Restituisce il numero di colonne in un riferimento -HLOOKUP = CERCA.ORIZZ ## Effettua una ricerca nella riga superiore di una matrice e restituisce il valore della cella specificata -HYPERLINK = COLLEG.IPERTESTUALE ## Crea un collegamento che apre un documento memorizzato in un server di rete, una rete Intranet o Internet -INDEX = INDICE ## Utilizza un indice per scegliere un valore da un riferimento o da una matrice -INDIRECT = INDIRETTO ## Restituisce un riferimento specificato da un valore testo -LOOKUP = CERCA ## Ricerca i valori in un vettore o in una matrice -MATCH = CONFRONTA ## Ricerca i valori in un riferimento o in una matrice -OFFSET = SCARTO ## Restituisce uno scarto di riferimento da un riferimento dato -ROW = RIF.RIGA ## Restituisce il numero di riga di un riferimento -ROWS = RIGHE ## Restituisce il numero delle righe in un riferimento -RTD = DATITEMPOREALE ## Recupera dati in tempo reale da un programma che supporta l'automazione COM (automazione: Metodo per utilizzare gli oggetti di un'applicazione da un'altra applicazione o da un altro strumento di sviluppo. Precedentemente nota come automazione OLE, l'automazione è uno standard del settore e una caratteristica del modello COM (Component Object Model).) -TRANSPOSE = MATR.TRASPOSTA ## Restituisce la trasposizione di una matrice -VLOOKUP = CERCA.VERT ## Effettua una ricerca nella prima colonna di una matrice e si sposta attraverso la riga per restituire il valore di una cella - +ABS = ASS +ACOS = ARCCOS +ACOSH = ARCCOSH +ACOT = ARCCOT +ACOTH = ARCCOTH +AGGREGATE = AGGREGA +ARABIC = ARABO +ASIN = ARCSEN +ASINH = ARCSENH +ATAN = ARCTAN +ATAN2 = ARCTAN.2 +ATANH = ARCTANH +BASE = BASE +CEILING.MATH = ARROTONDA.ECCESSO.MAT +CEILING.PRECISE = ARROTONDA.ECCESSO.PRECISA +COMBIN = COMBINAZIONE +COMBINA = COMBINAZIONE.VALORI +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = DECIMALE +DEGREES = GRADI +ECMA.CEILING = ECMA.ARROTONDA.ECCESSO +EVEN = PARI +EXP = EXP +FACT = FATTORIALE +FACTDOUBLE = FATT.DOPPIO +FLOOR.MATH = ARROTONDA.DIFETTO.MAT +FLOOR.PRECISE = ARROTONDA.DIFETTO.PRECISA +GCD = MCD +INT = INT +ISO.CEILING = ISO.ARROTONDA.ECCESSO +LCM = MCM +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = MATR.DETERM +MINVERSE = MATR.INVERSA +MMULT = MATR.PRODOTTO +MOD = RESTO +MROUND = ARROTONDA.MULTIPLO +MULTINOMIAL = MULTINOMIALE +MUNIT = MATR.UNIT +ODD = DISPARI +PI = PI.GRECO +POWER = POTENZA +PRODUCT = PRODOTTO +QUOTIENT = QUOZIENTE +RADIANS = RADIANTI +RAND = CASUALE +RANDBETWEEN = CASUALE.TRA +ROMAN = ROMANO +ROUND = ARROTONDA +ROUNDBAHTDOWN = ARROTBAHTGIU +ROUNDBAHTUP = ARROTBAHTSU +ROUNDDOWN = ARROTONDA.PER.DIF +ROUNDUP = ARROTONDA.PER.ECC +SEC = SEC +SECH = SECH +SERIESSUM = SOMMA.SERIE +SIGN = SEGNO +SIN = SEN +SINH = SENH +SQRT = RADQ +SQRTPI = RADQ.PI.GRECO +SUBTOTAL = SUBTOTALE +SUM = SOMMA +SUMIF = SOMMA.SE +SUMIFS = SOMMA.PIÙ.SE +SUMPRODUCT = MATR.SOMMA.PRODOTTO +SUMSQ = SOMMA.Q +SUMX2MY2 = SOMMA.DIFF.Q +SUMX2PY2 = SOMMA.SOMMA.Q +SUMXMY2 = SOMMA.Q.DIFF +TAN = TAN +TANH = TANH +TRUNC = TRONCA ## -## Math and trigonometry functions Funzioni matematiche e trigonometriche +## Funzioni statistiche (Statistical Functions) ## -ABS = ASS ## Restituisce il valore assoluto di un numero. -ACOS = ARCCOS ## Restituisce l'arcocoseno di un numero -ACOSH = ARCCOSH ## Restituisce l'inverso del coseno iperbolico di un numero -ASIN = ARCSEN ## Restituisce l'arcoseno di un numero -ASINH = ARCSENH ## Restituisce l'inverso del seno iperbolico di un numero -ATAN = ARCTAN ## Restituisce l'arcotangente di un numero -ATAN2 = ARCTAN.2 ## Restituisce l'arcotangente delle coordinate x e y specificate -ATANH = ARCTANH ## Restituisce l'inverso della tangente iperbolica di un numero -CEILING = ARROTONDA.ECCESSO ## Arrotonda un numero per eccesso all'intero più vicino o al multiplo più vicino a peso -COMBIN = COMBINAZIONE ## Restituisce il numero di combinazioni possibili per un numero assegnato di elementi -COS = COS ## Restituisce il coseno dell'angolo specificato -COSH = COSH ## Restituisce il coseno iperbolico di un numero -DEGREES = GRADI ## Converte i radianti in gradi -EVEN = PARI ## Arrotonda il valore assoluto di un numero per eccesso al più vicino intero pari -EXP = ESP ## Restituisce il numero e elevato alla potenza di num -FACT = FATTORIALE ## Restituisce il fattoriale di un numero -FACTDOUBLE = FATT.DOPPIO ## Restituisce il fattoriale doppio di un numero -FLOOR = ARROTONDA.DIFETTO ## Arrotonda un numero per difetto al multiplo più vicino a zero -GCD = MCD ## Restituisce il massimo comune divisore -INT = INT ## Arrotonda un numero per difetto al numero intero più vicino -LCM = MCM ## Restituisce il minimo comune multiplo -LN = LN ## Restituisce il logaritmo naturale di un numero -LOG = LOG ## Restituisce il logaritmo di un numero in una specificata base -LOG10 = LOG10 ## Restituisce il logaritmo in base 10 di un numero -MDETERM = MATR.DETERM ## Restituisce il determinante di una matrice -MINVERSE = MATR.INVERSA ## Restituisce l'inverso di una matrice -MMULT = MATR.PRODOTTO ## Restituisce il prodotto di due matrici -MOD = RESTO ## Restituisce il resto della divisione -MROUND = ARROTONDA.MULTIPLO ## Restituisce un numero arrotondato al multiplo desiderato -MULTINOMIAL = MULTINOMIALE ## Restituisce il multinomiale di un insieme di numeri -ODD = DISPARI ## Arrotonda un numero per eccesso al più vicino intero dispari -PI = PI.GRECO ## Restituisce il valore di pi greco -POWER = POTENZA ## Restituisce il risultato di un numero elevato a potenza -PRODUCT = PRODOTTO ## Moltiplica i suoi argomenti -QUOTIENT = QUOZIENTE ## Restituisce la parte intera di una divisione -RADIANS = RADIANTI ## Converte i gradi in radianti -RAND = CASUALE ## Restituisce un numero casuale compreso tra 0 e 1 -RANDBETWEEN = CASUALE.TRA ## Restituisce un numero casuale compreso tra i numeri specificati -ROMAN = ROMANO ## Restituisce il numero come numero romano sotto forma di testo -ROUND = ARROTONDA ## Arrotonda il numero al numero di cifre specificato -ROUNDDOWN = ARROTONDA.PER.DIF ## Arrotonda il valore assoluto di un numero per difetto -ROUNDUP = ARROTONDA.PER.ECC ## Arrotonda il valore assoluto di un numero per eccesso -SERIESSUM = SOMMA.SERIE ## Restituisce la somma di una serie di potenze in base alla formula -SIGN = SEGNO ## Restituisce il segno di un numero -SIN = SEN ## Restituisce il seno di un dato angolo -SINH = SENH ## Restituisce il seno iperbolico di un numero -SQRT = RADQ ## Restituisce una radice quadrata -SQRTPI = RADQ.PI.GRECO ## Restituisce la radice quadrata di un numero (numero * pi greco) -SUBTOTAL = SUBTOTALE ## Restituisce un subtotale in un elenco o in un database -SUM = SOMMA ## Somma i suoi argomenti -SUMIF = SOMMA.SE ## Somma le celle specificate da un dato criterio -SUMIFS = SOMMA.PIÙ.SE ## Somma le celle in un intervallo che soddisfano più criteri -SUMPRODUCT = MATR.SOMMA.PRODOTTO ## Restituisce la somma dei prodotti dei componenti corrispondenti della matrice -SUMSQ = SOMMA.Q ## Restituisce la somma dei quadrati degli argomenti -SUMX2MY2 = SOMMA.DIFF.Q ## Restituisce la somma della differenza dei quadrati dei corrispondenti elementi in due matrici -SUMX2PY2 = SOMMA.SOMMA.Q ## Restituisce la somma della somma dei quadrati dei corrispondenti elementi in due matrici -SUMXMY2 = SOMMA.Q.DIFF ## Restituisce la somma dei quadrati delle differenze dei corrispondenti elementi in due matrici -TAN = TAN ## Restituisce la tangente di un numero -TANH = TANH ## Restituisce la tangente iperbolica di un numero -TRUNC = TRONCA ## Tronca la parte decimale di un numero - +AVEDEV = MEDIA.DEV +AVERAGE = MEDIA +AVERAGEA = MEDIA.VALORI +AVERAGEIF = MEDIA.SE +AVERAGEIFS = MEDIA.PIÙ.SE +BETA.DIST = DISTRIB.BETA.N +BETA.INV = INV.BETA.N +BINOM.DIST = DISTRIB.BINOM.N +BINOM.DIST.RANGE = INTERVALLO.DISTRIB.BINOM.N. +BINOM.INV = INV.BINOM +CHISQ.DIST = DISTRIB.CHI.QUAD +CHISQ.DIST.RT = DISTRIB.CHI.QUAD.DS +CHISQ.INV = INV.CHI.QUAD +CHISQ.INV.RT = INV.CHI.QUAD.DS +CHISQ.TEST = TEST.CHI.QUAD +CONFIDENCE.NORM = CONFIDENZA.NORM +CONFIDENCE.T = CONFIDENZA.T +CORREL = CORRELAZIONE +COUNT = CONTA.NUMERI +COUNTA = CONTA.VALORI +COUNTBLANK = CONTA.VUOTE +COUNTIF = CONTA.SE +COUNTIFS = CONTA.PIÙ.SE +COVARIANCE.P = COVARIANZA.P +COVARIANCE.S = COVARIANZA.C +DEVSQ = DEV.Q +EXPON.DIST = DISTRIB.EXP.N +F.DIST = DISTRIBF +F.DIST.RT = DISTRIB.F.DS +F.INV = INVF +F.INV.RT = INV.F.DS +F.TEST = TESTF +FISHER = FISHER +FISHERINV = INV.FISHER +FORECAST.ETS = PREVISIONE.ETS +FORECAST.ETS.CONFINT = PREVISIONE.ETS.INTCONF +FORECAST.ETS.SEASONALITY = PREVISIONE.ETS.STAGIONALITÀ +FORECAST.ETS.STAT = PREVISIONE.ETS.STAT +FORECAST.LINEAR = PREVISIONE.LINEARE +FREQUENCY = FREQUENZA +GAMMA = GAMMA +GAMMA.DIST = DISTRIB.GAMMA.N +GAMMA.INV = INV.GAMMA.N +GAMMALN = LN.GAMMA +GAMMALN.PRECISE = LN.GAMMA.PRECISA +GAUSS = GAUSS +GEOMEAN = MEDIA.GEOMETRICA +GROWTH = CRESCITA +HARMEAN = MEDIA.ARMONICA +HYPGEOM.DIST = DISTRIB.IPERGEOM.N +INTERCEPT = INTERCETTA +KURT = CURTOSI +LARGE = GRANDE +LINEST = REGR.LIN +LOGEST = REGR.LOG +LOGNORM.DIST = DISTRIB.LOGNORM.N +LOGNORM.INV = INV.LOGNORM.N +MAX = MAX +MAXA = MAX.VALORI +MAXIFS = MAX.PIÙ.SE +MEDIAN = MEDIANA +MIN = MIN +MINA = MIN.VALORI +MINIFS = MIN.PIÙ.SE +MODE.MULT = MODA.MULT +MODE.SNGL = MODA.SNGL +NEGBINOM.DIST = DISTRIB.BINOM.NEG.N +NORM.DIST = DISTRIB.NORM.N +NORM.INV = INV.NORM.N +NORM.S.DIST = DISTRIB.NORM.ST.N +NORM.S.INV = INV.NORM.S +PEARSON = PEARSON +PERCENTILE.EXC = ESC.PERCENTILE +PERCENTILE.INC = INC.PERCENTILE +PERCENTRANK.EXC = ESC.PERCENT.RANGO +PERCENTRANK.INC = INC.PERCENT.RANGO +PERMUT = PERMUTAZIONE +PERMUTATIONA = PERMUTAZIONE.VALORI +PHI = PHI +POISSON.DIST = DISTRIB.POISSON +PROB = PROBABILITÀ +QUARTILE.EXC = ESC.QUARTILE +QUARTILE.INC = INC.QUARTILE +RANK.AVG = RANGO.MEDIA +RANK.EQ = RANGO.UG +RSQ = RQ +SKEW = ASIMMETRIA +SKEW.P = ASIMMETRIA.P +SLOPE = PENDENZA +SMALL = PICCOLO +STANDARDIZE = NORMALIZZA +STDEV.P = DEV.ST.P +STDEV.S = DEV.ST.C +STDEVA = DEV.ST.VALORI +STDEVPA = DEV.ST.POP.VALORI +STEYX = ERR.STD.YX +T.DIST = DISTRIB.T.N +T.DIST.2T = DISTRIB.T.2T +T.DIST.RT = DISTRIB.T.DS +T.INV = INVT +T.INV.2T = INV.T.2T +T.TEST = TESTT +TREND = TENDENZA +TRIMMEAN = MEDIA.TRONCATA +VAR.P = VAR.P +VAR.S = VAR.C +VARA = VAR.VALORI +VARPA = VAR.POP.VALORI +WEIBULL.DIST = DISTRIB.WEIBULL +Z.TEST = TESTZ ## -## Statistical functions Funzioni statistiche +## Funzioni di testo (Text Functions) ## -AVEDEV = MEDIA.DEV ## Restituisce la media delle deviazioni assolute delle coordinate rispetto alla loro media -AVERAGE = MEDIA ## Restituisce la media degli argomenti -AVERAGEA = MEDIA.VALORI ## Restituisce la media degli argomenti, inclusi i numeri, il testo e i valori logici -AVERAGEIF = MEDIA.SE ## Restituisce la media aritmetica di tutte le celle in un intervallo che soddisfano un determinato criterio -AVERAGEIFS = MEDIA.PIÙ.SE ## Restituisce la media aritmetica di tutte le celle che soddisfano più criteri -BETADIST = DISTRIB.BETA ## Restituisce la funzione di distribuzione cumulativa beta -BETAINV = INV.BETA ## Restituisce l'inverso della funzione di distribuzione cumulativa per una distribuzione beta specificata -BINOMDIST = DISTRIB.BINOM ## Restituisce la distribuzione binomiale per il termine individuale -CHIDIST = DISTRIB.CHI ## Restituisce la probabilità a una coda per la distribuzione del chi quadrato -CHIINV = INV.CHI ## Restituisce l'inverso della probabilità ad una coda per la distribuzione del chi quadrato -CHITEST = TEST.CHI ## Restituisce il test per l'indipendenza -CONFIDENCE = CONFIDENZA ## Restituisce l'intervallo di confidenza per una popolazione -CORREL = CORRELAZIONE ## Restituisce il coefficiente di correlazione tra due insiemi di dati -COUNT = CONTA.NUMERI ## Conta la quantità di numeri nell'elenco di argomenti -COUNTA = CONTA.VALORI ## Conta il numero di valori nell'elenco di argomenti -COUNTBLANK = CONTA.VUOTE ## Conta il numero di celle vuote all'interno di un intervallo -COUNTIF = CONTA.SE ## Conta il numero di celle all'interno di un intervallo che soddisfa i criteri specificati -COUNTIFS = CONTA.PIÙ.SE ## Conta il numero di celle in un intervallo che soddisfano più criteri. -COVAR = COVARIANZA ## Calcola la covarianza, la media dei prodotti delle deviazioni accoppiate -CRITBINOM = CRIT.BINOM ## Restituisce il più piccolo valore per il quale la distribuzione cumulativa binomiale risulta maggiore o uguale ad un valore di criterio -DEVSQ = DEV.Q ## Restituisce la somma dei quadrati delle deviazioni -EXPONDIST = DISTRIB.EXP ## Restituisce la distribuzione esponenziale -FDIST = DISTRIB.F ## Restituisce la distribuzione di probabilità F -FINV = INV.F ## Restituisce l'inverso della distribuzione della probabilità F -FISHER = FISHER ## Restituisce la trasformazione di Fisher -FISHERINV = INV.FISHER ## Restituisce l'inverso della trasformazione di Fisher -FORECAST = PREVISIONE ## Restituisce i valori lungo una tendenza lineare -FREQUENCY = FREQUENZA ## Restituisce la distribuzione di frequenza come matrice verticale -FTEST = TEST.F ## Restituisce il risultato di un test F -GAMMADIST = DISTRIB.GAMMA ## Restituisce la distribuzione gamma -GAMMAINV = INV.GAMMA ## Restituisce l'inverso della distribuzione cumulativa gamma -GAMMALN = LN.GAMMA ## Restituisce il logaritmo naturale della funzione gamma, G(x) -GEOMEAN = MEDIA.GEOMETRICA ## Restituisce la media geometrica -GROWTH = CRESCITA ## Restituisce i valori lungo una linea di tendenza esponenziale -HARMEAN = MEDIA.ARMONICA ## Restituisce la media armonica -HYPGEOMDIST = DISTRIB.IPERGEOM ## Restituisce la distribuzione ipergeometrica -INTERCEPT = INTERCETTA ## Restituisce l'intercetta della retta di regressione lineare -KURT = CURTOSI ## Restituisce la curtosi di un insieme di dati -LARGE = GRANDE ## Restituisce il k-esimo valore più grande in un insieme di dati -LINEST = REGR.LIN ## Restituisce i parametri di una tendenza lineare -LOGEST = REGR.LOG ## Restituisce i parametri di una linea di tendenza esponenziale -LOGINV = INV.LOGNORM ## Restituisce l'inverso di una distribuzione lognormale -LOGNORMDIST = DISTRIB.LOGNORM ## Restituisce la distribuzione lognormale cumulativa -MAX = MAX ## Restituisce il valore massimo in un elenco di argomenti -MAXA = MAX.VALORI ## Restituisce il valore massimo in un elenco di argomenti, inclusi i numeri, il testo e i valori logici -MEDIAN = MEDIANA ## Restituisce la mediana dei numeri specificati -MIN = MIN ## Restituisce il valore minimo in un elenco di argomenti -MINA = MIN.VALORI ## Restituisce il più piccolo valore in un elenco di argomenti, inclusi i numeri, il testo e i valori logici -MODE = MODA ## Restituisce il valore più comune in un insieme di dati -NEGBINOMDIST = DISTRIB.BINOM.NEG ## Restituisce la distribuzione binomiale negativa -NORMDIST = DISTRIB.NORM ## Restituisce la distribuzione cumulativa normale -NORMINV = INV.NORM ## Restituisce l'inverso della distribuzione cumulativa normale standard -NORMSDIST = DISTRIB.NORM.ST ## Restituisce la distribuzione cumulativa normale standard -NORMSINV = INV.NORM.ST ## Restituisce l'inverso della distribuzione cumulativa normale -PEARSON = PEARSON ## Restituisce il coefficiente del momento di correlazione di Pearson -PERCENTILE = PERCENTILE ## Restituisce il k-esimo dato percentile di valori in un intervallo -PERCENTRANK = PERCENT.RANGO ## Restituisce il rango di un valore in un insieme di dati come percentuale -PERMUT = PERMUTAZIONE ## Restituisce il numero delle permutazioni per un determinato numero di oggetti -POISSON = POISSON ## Restituisce la distribuzione di Poisson -PROB = PROBABILITÀ ## Calcola la probabilità che dei valori in un intervallo siano compresi tra due limiti -QUARTILE = QUARTILE ## Restituisce il quartile di un insieme di dati -RANK = RANGO ## Restituisce il rango di un numero in un elenco di numeri -RSQ = RQ ## Restituisce la radice quadrata del coefficiente di momento di correlazione di Pearson -SKEW = ASIMMETRIA ## Restituisce il grado di asimmetria di una distribuzione -SLOPE = PENDENZA ## Restituisce la pendenza di una retta di regressione lineare -SMALL = PICCOLO ## Restituisce il k-esimo valore più piccolo in un insieme di dati -STANDARDIZE = NORMALIZZA ## Restituisce un valore normalizzato -STDEV = DEV.ST ## Restituisce una stima della deviazione standard sulla base di un campione -STDEVA = DEV.ST.VALORI ## Restituisce una stima della deviazione standard sulla base di un campione, inclusi i numeri, il testo e i valori logici -STDEVP = DEV.ST.POP ## Calcola la deviazione standard sulla base di un'intera popolazione -STDEVPA = DEV.ST.POP.VALORI ## Calcola la deviazione standard sulla base sull'intera popolazione, inclusi i numeri, il testo e i valori logici -STEYX = ERR.STD.YX ## Restituisce l'errore standard del valore previsto per y per ogni valore x nella regressione -TDIST = DISTRIB.T ## Restituisce la distribuzione t di Student -TINV = INV.T ## Restituisce l'inversa della distribuzione t di Student -TREND = TENDENZA ## Restituisce i valori lungo una linea di tendenza lineare -TRIMMEAN = MEDIA.TRONCATA ## Restituisce la media della parte interna di un insieme di dati -TTEST = TEST.T ## Restituisce la probabilità associata ad un test t di Student -VAR = VAR ## Stima la varianza sulla base di un campione -VARA = VAR.VALORI ## Stima la varianza sulla base di un campione, inclusi i numeri, il testo e i valori logici -VARP = VAR.POP ## Calcola la varianza sulla base dell'intera popolazione -VARPA = VAR.POP.VALORI ## Calcola la deviazione standard sulla base sull'intera popolazione, inclusi i numeri, il testo e i valori logici -WEIBULL = WEIBULL ## Restituisce la distribuzione di Weibull -ZTEST = TEST.Z ## Restituisce il valore di probabilità a una coda per un test z - +BAHTTEXT = BAHTTESTO +CHAR = CODICE.CARATT +CLEAN = LIBERA +CODE = CODICE +CONCAT = CONCAT +DOLLAR = VALUTA +EXACT = IDENTICO +FIND = TROVA +FIXED = FISSO +ISTHAIDIGIT = ÈTHAICIFRA +LEFT = SINISTRA +LEN = LUNGHEZZA +LOWER = MINUSC +MID = STRINGA.ESTRAI +NUMBERSTRING = NUMERO.STRINGA +NUMBERVALUE = NUMERO.VALORE +PHONETIC = FURIGANA +PROPER = MAIUSC.INIZ +REPLACE = RIMPIAZZA +REPT = RIPETI +RIGHT = DESTRA +SEARCH = RICERCA +SUBSTITUTE = SOSTITUISCI +T = T +TEXT = TESTO +TEXTJOIN = TESTO.UNISCI +THAIDIGIT = THAICIFRA +THAINUMSOUND = THAINUMSUONO +THAINUMSTRING = THAISZÁMKAR +THAISTRINGLENGTH = THAILUNGSTRINGA +TRIM = ANNULLA.SPAZI +UNICHAR = CARATT.UNI +UNICODE = UNICODE +UPPER = MAIUSC +VALUE = VALORE ## -## Text functions Funzioni di testo +## Funzioni Web (Web Functions) ## -ASC = ASC ## Modifica le lettere inglesi o il katakana a doppio byte all'interno di una stringa di caratteri in caratteri a singolo byte -BAHTTEXT = BAHTTESTO ## Converte un numero in testo, utilizzando il formato valuta ß (baht) -CHAR = CODICE.CARATT ## Restituisce il carattere specificato dal numero di codice -CLEAN = LIBERA ## Elimina dal testo tutti i caratteri che non è possibile stampare -CODE = CODICE ## Restituisce il codice numerico del primo carattere di una stringa di testo -CONCATENATE = CONCATENA ## Unisce diversi elementi di testo in un unico elemento di testo -DOLLAR = VALUTA ## Converte un numero in testo, utilizzando il formato valuta € (euro) -EXACT = IDENTICO ## Verifica se due valori di testo sono uguali -FIND = TROVA ## Rileva un valore di testo all'interno di un altro (distinzione tra maiuscole e minuscole) -FINDB = TROVA.B ## Rileva un valore di testo all'interno di un altro (distinzione tra maiuscole e minuscole) -FIXED = FISSO ## Formatta un numero come testo con un numero fisso di decimali -JIS = ORDINAMENTO.JIS ## Modifica le lettere inglesi o i caratteri katakana a byte singolo all'interno di una stringa di caratteri in caratteri a byte doppio. -LEFT = SINISTRA ## Restituisce il carattere più a sinistra di un valore di testo -LEFTB = SINISTRA.B ## Restituisce il carattere più a sinistra di un valore di testo -LEN = LUNGHEZZA ## Restituisce il numero di caratteri di una stringa di testo -LENB = LUNB ## Restituisce il numero di caratteri di una stringa di testo -LOWER = MINUSC ## Converte il testo in lettere minuscole -MID = MEDIA ## Restituisce un numero specifico di caratteri di una stringa di testo a partire dalla posizione specificata -MIDB = MEDIA.B ## Restituisce un numero specifico di caratteri di una stringa di testo a partire dalla posizione specificata -PHONETIC = FURIGANA ## Estrae i caratteri fonetici (furigana) da una stringa di testo. -PROPER = MAIUSC.INIZ ## Converte in maiuscolo la prima lettera di ogni parola di un valore di testo -REPLACE = RIMPIAZZA ## Sostituisce i caratteri all'interno di un testo -REPLACEB = SOSTITUISCI.B ## Sostituisce i caratteri all'interno di un testo -REPT = RIPETI ## Ripete un testo per un dato numero di volte -RIGHT = DESTRA ## Restituisce il carattere più a destra di un valore di testo -RIGHTB = DESTRA.B ## Restituisce il carattere più a destra di un valore di testo -SEARCH = RICERCA ## Rileva un valore di testo all'interno di un altro (non è sensibile alle maiuscole e minuscole) -SEARCHB = CERCA.B ## Rileva un valore di testo all'interno di un altro (non è sensibile alle maiuscole e minuscole) -SUBSTITUTE = SOSTITUISCI ## Sostituisce il nuovo testo al testo contenuto in una stringa -T = T ## Converte gli argomenti in testo -TEXT = TESTO ## Formatta un numero e lo converte in testo -TRIM = ANNULLA.SPAZI ## Elimina gli spazi dal testo -UPPER = MAIUSC ## Converte il testo in lettere maiuscole -VALUE = VALORE ## Converte un argomento di testo in numero +ENCODEURL = CODIFICA.URL +FILTERXML = FILTRO.XML +WEBSERVICE = SERVIZIO.WEB + +## +## Funzioni di compatibilità (Compatibility Functions) +## +BETADIST = DISTRIB.BETA +BETAINV = INV.BETA +BINOMDIST = DISTRIB.BINOM +CEILING = ARROTONDA.ECCESSO +CHIDIST = DISTRIB.CHI +CHIINV = INV.CHI +CHITEST = TEST.CHI +CONCATENATE = CONCATENA +CONFIDENCE = CONFIDENZA +COVAR = COVARIANZA +CRITBINOM = CRIT.BINOM +EXPONDIST = DISTRIB.EXP +FDIST = DISTRIB.F +FINV = INV.F +FLOOR = ARROTONDA.DIFETTO +FORECAST = PREVISIONE +FTEST = TEST.F +GAMMADIST = DISTRIB.GAMMA +GAMMAINV = INV.GAMMA +HYPGEOMDIST = DISTRIB.IPERGEOM +LOGINV = INV.LOGNORM +LOGNORMDIST = DISTRIB.LOGNORM +MODE = MODA +NEGBINOMDIST = DISTRIB.BINOM.NEG +NORMDIST = DISTRIB.NORM +NORMINV = INV.NORM +NORMSDIST = DISTRIB.NORM.ST +NORMSINV = INV.NORM.ST +PERCENTILE = PERCENTILE +PERCENTRANK = PERCENT.RANGO +POISSON = POISSON +QUARTILE = QUARTILE +RANK = RANGO +STDEV = DEV.ST +STDEVP = DEV.ST.POP +TDIST = DISTRIB.T +TINV = INV.T +TTEST = TEST.T +VAR = VAR +VARP = VAR.POP +WEIBULL = WEIBULL +ZTEST = TEST.Z diff --git a/src/PhpSpreadsheet/Calculation/locale/nb/config b/src/PhpSpreadsheet/Calculation/locale/nb/config new file mode 100644 index 00000000..a7f3be17 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/locale/nb/config @@ -0,0 +1,20 @@ +############################################################ +## +## PhpSpreadsheet - locale settings +## +## Norsk Bokmål (Norwegian Bokmål) +## +############################################################ + +ArgumentSeparator = ; + +## +## Error Codes +## +NULL +DIV0 +VALUE = #VERDI! +REF +NAME = #NAVN? +NUM +NA = #N/D diff --git a/src/PhpSpreadsheet/Calculation/locale/nb/functions b/src/PhpSpreadsheet/Calculation/locale/nb/functions new file mode 100644 index 00000000..b0a0f949 --- /dev/null +++ b/src/PhpSpreadsheet/Calculation/locale/nb/functions @@ -0,0 +1,538 @@ +############################################################ +## +## PhpSpreadsheet - function name translations +## +## Norsk Bokmål (Norwegian Bokmål) +## +############################################################ + + +## +## Kubefunksjoner (Cube Functions) +## +CUBEKPIMEMBER = KUBEKPIMEDLEM +CUBEMEMBER = KUBEMEDLEM +CUBEMEMBERPROPERTY = KUBEMEDLEMEGENSKAP +CUBERANKEDMEMBER = KUBERANGERTMEDLEM +CUBESET = KUBESETT +CUBESETCOUNT = KUBESETTANTALL +CUBEVALUE = KUBEVERDI + +## +## Databasefunksjoner (Database Functions) +## +DAVERAGE = DGJENNOMSNITT +DCOUNT = DANTALL +DCOUNTA = DANTALLA +DGET = DHENT +DMAX = DMAKS +DMIN = DMIN +DPRODUCT = DPRODUKT +DSTDEV = DSTDAV +DSTDEVP = DSTDAVP +DSUM = DSUMMER +DVAR = DVARIANS +DVARP = DVARIANSP + +## +## Dato- og tidsfunksjoner (Date & Time Functions) +## +DATE = DATO +DATEDIF = DATODIFF +DATESTRING = DATOSTRENG +DATEVALUE = DATOVERDI +DAY = DAG +DAYS = DAGER +DAYS360 = DAGER360 +EDATE = DAG.ETTER +EOMONTH = MÅNEDSSLUTT +HOUR = TIME +ISOWEEKNUM = ISOUKENR +MINUTE = MINUTT +MONTH = MÅNED +NETWORKDAYS = NETT.ARBEIDSDAGER +NETWORKDAYS.INTL = NETT.ARBEIDSDAGER.INTL +NOW = NÅ +SECOND = SEKUND +THAIDAYOFWEEK = THAIUKEDAG +THAIMONTHOFYEAR = THAIMÅNED +THAIYEAR = THAIÅR +TIME = TID +TIMEVALUE = TIDSVERDI +TODAY = IDAG +WEEKDAY = UKEDAG +WEEKNUM = UKENR +WORKDAY = ARBEIDSDAG +WORKDAY.INTL = ARBEIDSDAG.INTL +YEAR = ÅR +YEARFRAC = ÅRDEL + +## +## Tekniske funksjoner (Engineering Functions) +## +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BINTILDES +BIN2HEX = BINTILHEKS +BIN2OCT = BINTILOKT +BITAND = BITOG +BITLSHIFT = BITVFORSKYV +BITOR = BITELLER +BITRSHIFT = BITHFORSKYV +BITXOR = BITEKSKLUSIVELLER +COMPLEX = KOMPLEKS +CONVERT = KONVERTER +DEC2BIN = DESTILBIN +DEC2HEX = DESTILHEKS +DEC2OCT = DESTILOKT +DELTA = DELTA +ERF = FEILF +ERF.PRECISE = FEILF.PRESIS +ERFC = FEILFK +ERFC.PRECISE = FEILFK.PRESIS +GESTEP = GRENSEVERDI +HEX2BIN = HEKSTILBIN +HEX2DEC = HEKSTILDES +HEX2OCT = HEKSTILOKT +IMABS = IMABS +IMAGINARY = IMAGINÆR +IMARGUMENT = IMARGUMENT +IMCONJUGATE = IMKONJUGERT +IMCOS = IMCOS +IMCOSH = IMCOSH +IMCOT = IMCOT +IMCSC = IMCSC +IMCSCH = IMCSCH +IMDIV = IMDIV +IMEXP = IMEKSP +IMLN = IMLN +IMLOG10 = IMLOG10 +IMLOG2 = IMLOG2 +IMPOWER = IMOPPHØY +IMPRODUCT = IMPRODUKT +IMREAL = IMREELL +IMSEC = IMSEC +IMSECH = IMSECH +IMSIN = IMSIN +IMSINH = IMSINH +IMSQRT = IMROT +IMSUB = IMSUB +IMSUM = IMSUMMER +IMTAN = IMTAN +OCT2BIN = OKTTILBIN +OCT2DEC = OKTTILDES +OCT2HEX = OKTTILHEKS + +## +## Økonomiske funksjoner (Financial Functions) +## +ACCRINT = PÅLØPT.PERIODISK.RENTE +ACCRINTM = PÅLØPT.FORFALLSRENTE +AMORDEGRC = AMORDEGRC +AMORLINC = AMORLINC +COUPDAYBS = OBLIG.DAGER.FF +COUPDAYS = OBLIG.DAGER +COUPDAYSNC = OBLIG.DAGER.NF +COUPNCD = OBLIG.DAGER.EF +COUPNUM = OBLIG.ANTALL +COUPPCD = OBLIG.DAG.FORRIGE +CUMIPMT = SAMLET.RENTE +CUMPRINC = SAMLET.HOVEDSTOL +DB = DAVSKR +DDB = DEGRAVS +DISC = DISKONTERT +DOLLARDE = DOLLARDE +DOLLARFR = DOLLARBR +DURATION = VARIGHET +EFFECT = EFFEKTIV.RENTE +FV = SLUTTVERDI +FVSCHEDULE = SVPLAN +INTRATE = RENTESATS +IPMT = RAVDRAG +IRR = IR +ISPMT = ER.AVDRAG +MDURATION = MVARIGHET +MIRR = MODIR +NOMINAL = NOMINELL +NPER = PERIODER +NPV = NNV +ODDFPRICE = AVVIKFP.PRIS +ODDFYIELD = AVVIKFP.AVKASTNING +ODDLPRICE = AVVIKSP.PRIS +ODDLYIELD = AVVIKSP.AVKASTNING +PDURATION = PVARIGHET +PMT = AVDRAG +PPMT = AMORT +PRICE = PRIS +PRICEDISC = PRIS.DISKONTERT +PRICEMAT = PRIS.FORFALL +PV = NÅVERDI +RATE = RENTE +RECEIVED = MOTTATT.AVKAST +RRI = REALISERT.AVKASTNING +SLN = LINAVS +SYD = ÅRSAVS +TBILLEQ = TBILLEKV +TBILLPRICE = TBILLPRIS +TBILLYIELD = TBILLAVKASTNING +VDB = VERDIAVS +XIRR = XIR +XNPV = XNNV +YIELD = AVKAST +YIELDDISC = AVKAST.DISKONTERT +YIELDMAT = AVKAST.FORFALL + +## +## Informasjonsfunksjoner (Information Functions) +## +CELL = CELLE +ERROR.TYPE = FEIL.TYPE +INFO = INFO +ISBLANK = ERTOM +ISERR = ERF +ISERROR = ERFEIL +ISEVEN = ERPARTALL +ISFORMULA = ERFORMEL +ISLOGICAL = ERLOGISK +ISNA = ERIT +ISNONTEXT = ERIKKETEKST +ISNUMBER = ERTALL +ISODD = ERODDE +ISREF = ERREF +ISTEXT = ERTEKST +N = N +NA = IT +SHEET = ARK +SHEETS = ANTALL.ARK +TYPE = VERDITYPE + +## +## Logiske funksjoner (Logical Functions) +## +AND = OG +FALSE = USANN +IF = HVIS +IFERROR = HVISFEIL +IFNA = HVIS.IT +IFS = HVIS.SETT +NOT = IKKE +OR = ELLER +SWITCH = BRYTER +TRUE = SANN +XOR = EKSKLUSIVELLER + +## +## Oppslag- og referansefunksjoner (Lookup & Reference Functions) +## +ADDRESS = ADRESSE +AREAS = OMRÅDER +CHOOSE = VELG +COLUMN = KOLONNE +COLUMNS = KOLONNER +FORMULATEXT = FORMELTEKST +GETPIVOTDATA = HENTPIVOTDATA +HLOOKUP = FINN.KOLONNE +HYPERLINK = HYPERKOBLING +INDEX = INDEKS +INDIRECT = INDIREKTE +LOOKUP = SLÅ.OPP +MATCH = SAMMENLIGNE +OFFSET = FORSKYVNING +ROW = RAD +ROWS = RADER +RTD = RTD +TRANSPOSE = TRANSPONER +VLOOKUP = FINN.RAD + +## +## Matematikk- og trigonometrifunksjoner (Math & Trig Functions) +## +ABS = ABS +ACOS = ARCCOS +ACOSH = ARCCOSH +ACOT = ACOT +ACOTH = ACOTH +AGGREGATE = MENGDE +ARABIC = ARABISK +ASIN = ARCSIN +ASINH = ARCSINH +ATAN = ARCTAN +ATAN2 = ARCTAN2 +ATANH = ARCTANH +BASE = GRUNNTALL +CEILING.MATH = AVRUND.GJELDENDE.MULTIPLUM.OPP.MATEMATISK +CEILING.PRECISE = AVRUND.GJELDENDE.MULTIPLUM.PRESIS +COMBIN = KOMBINASJON +COMBINA = KOMBINASJONA +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = DESIMAL +DEGREES = GRADER +ECMA.CEILING = ECMA.AVRUND.GJELDENDE.MULTIPLUM +EVEN = AVRUND.TIL.PARTALL +EXP = EKSP +FACT = FAKULTET +FACTDOUBLE = DOBBELFAKT +FLOOR.MATH = AVRUND.GJELDENDE.MULTIPLUM.NED.MATEMATISK +FLOOR.PRECISE = AVRUND.GJELDENDE.MULTIPLUM.NED.PRESIS +GCD = SFF +INT = HELTALL +ISO.CEILING = ISO.AVRUND.GJELDENDE.MULTIPLUM +LCM = MFM +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = MDETERM +MINVERSE = MINVERS +MMULT = MMULT +MOD = REST +MROUND = MRUND +MULTINOMIAL = MULTINOMINELL +MUNIT = MENHET +ODD = AVRUND.TIL.ODDETALL +PI = PI +POWER = OPPHØYD.I +PRODUCT = PRODUKT +QUOTIENT = KVOTIENT +RADIANS = RADIANER +RAND = TILFELDIG +RANDBETWEEN = TILFELDIGMELLOM +ROMAN = ROMERTALL +ROUND = AVRUND +ROUNDBAHTDOWN = RUNDAVBAHTNEDOVER +ROUNDBAHTUP = RUNDAVBAHTOPPOVER +ROUNDDOWN = AVRUND.NED +ROUNDUP = AVRUND.OPP +SEC = SEC +SECH = SECH +SERIESSUM = SUMMER.REKKE +SIGN = FORTEGN +SIN = SIN +SINH = SINH +SQRT = ROT +SQRTPI = ROTPI +SUBTOTAL = DELSUM +SUM = SUMMER +SUMIF = SUMMERHVIS +SUMIFS = SUMMER.HVIS.SETT +SUMPRODUCT = SUMMERPRODUKT +SUMSQ = SUMMERKVADRAT +SUMX2MY2 = SUMMERX2MY2 +SUMX2PY2 = SUMMERX2PY2 +SUMXMY2 = SUMMERXMY2 +TAN = TAN +TANH = TANH +TRUNC = AVKORT + +## +## Statistiske funksjoner (Statistical Functions) +## +AVEDEV = GJENNOMSNITTSAVVIK +AVERAGE = GJENNOMSNITT +AVERAGEA = GJENNOMSNITTA +AVERAGEIF = GJENNOMSNITTHVIS +AVERAGEIFS = GJENNOMSNITT.HVIS.SETT +BETA.DIST = BETA.FORDELING.N +BETA.INV = BETA.INV +BINOM.DIST = BINOM.FORDELING.N +BINOM.DIST.RANGE = BINOM.FORDELING.OMRÅDE +BINOM.INV = BINOM.INV +CHISQ.DIST = KJIKVADRAT.FORDELING +CHISQ.DIST.RT = KJIKVADRAT.FORDELING.H +CHISQ.INV = KJIKVADRAT.INV +CHISQ.INV.RT = KJIKVADRAT.INV.H +CHISQ.TEST = KJIKVADRAT.TEST +CONFIDENCE.NORM = KONFIDENS.NORM +CONFIDENCE.T = KONFIDENS.T +CORREL = KORRELASJON +COUNT = ANTALL +COUNTA = ANTALLA +COUNTBLANK = TELLBLANKE +COUNTIF = ANTALL.HVIS +COUNTIFS = ANTALL.HVIS.SETT +COVARIANCE.P = KOVARIANS.P +COVARIANCE.S = KOVARIANS.S +DEVSQ = AVVIK.KVADRERT +EXPON.DIST = EKSP.FORDELING.N +F.DIST = F.FORDELING +F.DIST.RT = F.FORDELING.H +F.INV = F.INV +F.INV.RT = F.INV.H +F.TEST = F.TEST +FISHER = FISHER +FISHERINV = FISHERINV +FORECAST.ETS = PROGNOSE.ETS +FORECAST.ETS.CONFINT = PROGNOSE.ETS.CONFINT +FORECAST.ETS.SEASONALITY = PROGNOSE.ETS.SESONGAVHENGIGHET +FORECAST.ETS.STAT = PROGNOSE.ETS.STAT +FORECAST.LINEAR = PROGNOSE.LINEÆR +FREQUENCY = FREKVENS +GAMMA = GAMMA +GAMMA.DIST = GAMMA.FORDELING +GAMMA.INV = GAMMA.INV +GAMMALN = GAMMALN +GAMMALN.PRECISE = GAMMALN.PRESIS +GAUSS = GAUSS +GEOMEAN = GJENNOMSNITT.GEOMETRISK +GROWTH = VEKST +HARMEAN = GJENNOMSNITT.HARMONISK +HYPGEOM.DIST = HYPGEOM.FORDELING.N +INTERCEPT = SKJÆRINGSPUNKT +KURT = KURT +LARGE = N.STØRST +LINEST = RETTLINJE +LOGEST = KURVE +LOGNORM.DIST = LOGNORM.FORDELING +LOGNORM.INV = LOGNORM.INV +MAX = STØRST +MAXA = MAKSA +MAXIFS = MAKS.HVIS.SETT +MEDIAN = MEDIAN +MIN = MIN +MINA = MINA +MINIFS = MIN.HVIS.SETT +MODE.MULT = MODUS.MULT +MODE.SNGL = MODUS.SNGL +NEGBINOM.DIST = NEGBINOM.FORDELING.N +NORM.DIST = NORM.FORDELING +NORM.INV = NORM.INV +NORM.S.DIST = NORM.S.FORDELING +NORM.S.INV = NORM.S.INV +PEARSON = PEARSON +PERCENTILE.EXC = PERSENTIL.EKS +PERCENTILE.INC = PERSENTIL.INK +PERCENTRANK.EXC = PROSENTDEL.EKS +PERCENTRANK.INC = PROSENTDEL.INK +PERMUT = PERMUTER +PERMUTATIONA = PERMUTASJONA +PHI = PHI +POISSON.DIST = POISSON.FORDELING +PROB = SANNSYNLIG +QUARTILE.EXC = KVARTIL.EKS +QUARTILE.INC = KVARTIL.INK +RANK.AVG = RANG.GJSN +RANK.EQ = RANG.EKV +RSQ = RKVADRAT +SKEW = SKJEVFORDELING +SKEW.P = SKJEVFORDELING.P +SLOPE = STIGNINGSTALL +SMALL = N.MINST +STANDARDIZE = NORMALISER +STDEV.P = STDAV.P +STDEV.S = STDAV.S +STDEVA = STDAVVIKA +STDEVPA = STDAVVIKPA +STEYX = STANDARDFEIL +T.DIST = T.FORDELING +T.DIST.2T = T.FORDELING.2T +T.DIST.RT = T.FORDELING.H +T.INV = T.INV +T.INV.2T = T.INV.2T +T.TEST = T.TEST +TREND = TREND +TRIMMEAN = TRIMMET.GJENNOMSNITT +VAR.P = VARIANS.P +VAR.S = VARIANS.S +VARA = VARIANSA +VARPA = VARIANSPA +WEIBULL.DIST = WEIBULL.DIST.N +Z.TEST = Z.TEST + +## +## Tekstfunksjoner (Text Functions) +## +ASC = STIGENDE +BAHTTEXT = BAHTTEKST +CHAR = TEGNKODE +CLEAN = RENSK +CODE = KODE +CONCAT = KJED.SAMMEN +DOLLAR = VALUTA +EXACT = EKSAKT +FIND = FINN +FIXED = FASTSATT +ISTHAIDIGIT = ERTHAISIFFER +LEFT = VENSTRE +LEN = LENGDE +LOWER = SMÅ +MID = DELTEKST +NUMBERSTRING = TALLSTRENG +NUMBERVALUE = TALLVERDI +PHONETIC = FURIGANA +PROPER = STOR.FORBOKSTAV +REPLACE = ERSTATT +REPT = GJENTA +RIGHT = HØYRE +SEARCH = SØK +SUBSTITUTE = BYTT.UT +T = T +TEXT = TEKST +TEXTJOIN = TEKST.KOMBINER +THAIDIGIT = THAISIFFER +THAINUMSOUND = THAINUMLYD +THAINUMSTRING = THAINUMSTRENG +THAISTRINGLENGTH = THAISTRENGLENGDE +TRIM = TRIMME +UNICHAR = UNICODETEGN +UNICODE = UNICODE +UPPER = STORE +VALUE = VERDI + +## +## Nettfunksjoner (Web Functions) +## +ENCODEURL = URL.KODE +FILTERXML = FILTRERXML +WEBSERVICE = NETTJENESTE + +## +## Kompatibilitetsfunksjoner (Compatibility Functions) +## +BETADIST = BETA.FORDELING +BETAINV = INVERS.BETA.FORDELING +BINOMDIST = BINOM.FORDELING +CEILING = AVRUND.GJELDENDE.MULTIPLUM +CHIDIST = KJI.FORDELING +CHIINV = INVERS.KJI.FORDELING +CHITEST = KJI.TEST +CONCATENATE = KJEDE.SAMMEN +CONFIDENCE = KONFIDENS +COVAR = KOVARIANS +CRITBINOM = GRENSE.BINOM +EXPONDIST = EKSP.FORDELING +FDIST = FFORDELING +FINV = FFORDELING.INVERS +FLOOR = AVRUND.GJELDENDE.MULTIPLUM.NED +FORECAST = PROGNOSE +FTEST = FTEST +GAMMADIST = GAMMAFORDELING +GAMMAINV = GAMMAINV +HYPGEOMDIST = HYPGEOM.FORDELING +LOGINV = LOGINV +LOGNORMDIST = LOGNORMFORD +MODE = MODUS +NEGBINOMDIST = NEGBINOM.FORDELING +NORMDIST = NORMALFORDELING +NORMINV = NORMINV +NORMSDIST = NORMSFORDELING +NORMSINV = NORMSINV +PERCENTILE = PERSENTIL +PERCENTRANK = PROSENTDEL +POISSON = POISSON +QUARTILE = KVARTIL +RANK = RANG +STDEV = STDAV +STDEVP = STDAVP +TDIST = TFORDELING +TINV = TINV +TTEST = TTEST +VAR = VARIANS +VARP = VARIANSP +WEIBULL = WEIBULL.FORDELING +ZTEST = ZTEST diff --git a/src/PhpSpreadsheet/Calculation/locale/nl/config b/src/PhpSpreadsheet/Calculation/locale/nl/config index 8376022d..370567a7 100644 --- a/src/PhpSpreadsheet/Calculation/locale/nl/config +++ b/src/PhpSpreadsheet/Calculation/locale/nl/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## +## Nederlands (Dutch) +## +############################################################ -ArgumentSeparator = ; - +ArgumentSeparator = ; ## -## (For future use) +## Error Codes ## -currencySymbol = € - - -## -## Excel Error Codes (For future use) - -## -NULL = #LEEG! -DIV0 = #DEEL/0! -VALUE = #WAARDE! -REF = #VERW! -NAME = #NAAM? -NUM = #GETAL! -NA = #N/B +NULL = #LEEG! +DIV0 = #DEEL/0! +VALUE = #WAARDE! +REF = #VERW! +NAME = #NAAM? +NUM = #GETAL! +NA = #N/B diff --git a/src/PhpSpreadsheet/Calculation/locale/nl/functions b/src/PhpSpreadsheet/Calculation/locale/nl/functions index 2518f421..0e4f1597 100644 --- a/src/PhpSpreadsheet/Calculation/locale/nl/functions +++ b/src/PhpSpreadsheet/Calculation/locale/nl/functions @@ -1,416 +1,536 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Nederlands (Dutch) ## +############################################################ ## -## Add-in and Automation functions Automatiseringsfuncties en functies in invoegtoepassingen +## Kubusfuncties (Cube Functions) ## -GETPIVOTDATA = DRAAITABEL.OPHALEN ## Geeft gegevens uit een draaitabelrapport als resultaat - +CUBEKPIMEMBER = KUBUSKPILID +CUBEMEMBER = KUBUSLID +CUBEMEMBERPROPERTY = KUBUSLIDEIGENSCHAP +CUBERANKEDMEMBER = KUBUSGERANGSCHIKTLID +CUBESET = KUBUSSET +CUBESETCOUNT = KUBUSSETAANTAL +CUBEVALUE = KUBUSWAARDE ## -## Cube functions Kubusfuncties +## Databasefuncties (Database Functions) ## -CUBEKPIMEMBER = KUBUSKPILID ## Retourneert de naam, eigenschap en waarde van een KPI (prestatie-indicator) en geeft de naam en de eigenschap in de cel weer. Een KPI is een meetbare waarde, zoals de maandelijkse brutowinst of de omzet per kwartaal per werknemer, die wordt gebruikt om de prestaties van een organisatie te bewaken -CUBEMEMBER = KUBUSLID ## Retourneert een lid of tupel in een kubushiërarchie. Wordt gebruikt om te controleren of het lid of de tupel in de kubus aanwezig is -CUBEMEMBERPROPERTY = KUBUSLIDEIGENSCHAP ## Retourneert de waarde van een lideigenschap in de kubus. Wordt gebruikt om te controleren of de lidnaam in de kubus bestaat en retourneert de opgegeven eigenschap voor dit lid -CUBERANKEDMEMBER = KUBUSGERANGCHIKTLID ## Retourneert het zoveelste, gerangschikte lid in een set. Wordt gebruikt om een of meer elementen in een set te retourneren, zoals de tien beste verkopers of de tien beste studenten -CUBESET = KUBUSSET ## Definieert een berekende set leden of tupels door een ingestelde expressie naar de kubus op de server te sturen, alwaar de set wordt gemaakt en vervolgens wordt geretourneerd naar Microsoft Office Excel -CUBESETCOUNT = KUBUSSETAANTAL ## Retourneert het aantal onderdelen in een set -CUBEVALUE = KUBUSWAARDE ## Retourneert een samengestelde waarde van een kubus - +DAVERAGE = DBGEMIDDELDE +DCOUNT = DBAANTAL +DCOUNTA = DBAANTALC +DGET = DBLEZEN +DMAX = DBMAX +DMIN = DBMIN +DPRODUCT = DBPRODUCT +DSTDEV = DBSTDEV +DSTDEVP = DBSTDEVP +DSUM = DBSOM +DVAR = DBVAR +DVARP = DBVARP ## -## Database functions Databasefuncties +## Datum- en tijdfuncties (Date & Time Functions) ## -DAVERAGE = DBGEMIDDELDE ## Berekent de gemiddelde waarde in geselecteerde databasegegevens -DCOUNT = DBAANTAL ## Telt de cellen met getallen in een database -DCOUNTA = DBAANTALC ## Telt de niet-lege cellen in een database -DGET = DBLEZEN ## Retourneert één record dat voldoet aan de opgegeven criteria uit een database -DMAX = DBMAX ## Retourneert de maximumwaarde in de geselecteerde databasegegevens -DMIN = DBMIN ## Retourneert de minimumwaarde in de geselecteerde databasegegevens -DPRODUCT = DBPRODUCT ## Vermenigvuldigt de waarden in een bepaald veld van de records die voldoen aan de criteria in een database -DSTDEV = DBSTDEV ## Maakt een schatting van de standaarddeviatie op basis van een steekproef uit geselecteerde databasegegevens -DSTDEVP = DBSTDEVP ## Berekent de standaarddeviatie op basis van de volledige populatie van geselecteerde databasegegevens -DSUM = DBSOM ## Telt de getallen uit een kolom records in de database op die voldoen aan de criteria -DVAR = DBVAR ## Maakt een schatting van de variantie op basis van een steekproef uit geselecteerde databasegegevens -DVARP = DBVARP ## Berekent de variantie op basis van de volledige populatie van geselecteerde databasegegevens - +DATE = DATUM +DATESTRING = DATUMNOTATIE +DATEVALUE = DATUMWAARDE +DAY = DAG +DAYS = DAGEN +DAYS360 = DAGEN360 +EDATE = ZELFDE.DAG +EOMONTH = LAATSTE.DAG +HOUR = UUR +ISOWEEKNUM = ISO.WEEKNUMMER +MINUTE = MINUUT +MONTH = MAAND +NETWORKDAYS = NETTO.WERKDAGEN +NETWORKDAYS.INTL = NETWERKDAGEN.INTL +NOW = NU +SECOND = SECONDE +THAIDAYOFWEEK = THAIS.WEEKDAG +THAIMONTHOFYEAR = THAIS.MAAND.VAN.JAAR +THAIYEAR = THAIS.JAAR +TIME = TIJD +TIMEVALUE = TIJDWAARDE +TODAY = VANDAAG +WEEKDAY = WEEKDAG +WEEKNUM = WEEKNUMMER +WORKDAY = WERKDAG +WORKDAY.INTL = WERKDAG.INTL +YEAR = JAAR +YEARFRAC = JAAR.DEEL ## -## Date and time functions Datum- en tijdfuncties +## Technische functies (Engineering Functions) ## -DATE = DATUM ## Geeft als resultaat het seriële getal van een opgegeven datum -DATEVALUE = DATUMWAARDE ## Converteert een datum in de vorm van tekst naar een serieel getal -DAY = DAG ## Converteert een serieel getal naar een dag van de maand -DAYS360 = DAGEN360 ## Berekent het aantal dagen tussen twee datums op basis van een jaar met 360 dagen -EDATE = ZELFDE.DAG ## Geeft als resultaat het seriële getal van een datum die het opgegeven aantal maanden voor of na de begindatum ligt -EOMONTH = LAATSTE.DAG ## Geeft als resultaat het seriële getal van de laatste dag van de maand voor of na het opgegeven aantal maanden -HOUR = UUR ## Converteert een serieel getal naar uren -MINUTE = MINUUT ## Converteert een serieel naar getal minuten -MONTH = MAAND ## Converteert een serieel getal naar een maand -NETWORKDAYS = NETTO.WERKDAGEN ## Geeft als resultaat het aantal hele werkdagen tussen twee datums -NOW = NU ## Geeft als resultaat het seriële getal van de huidige datum en tijd -SECOND = SECONDE ## Converteert een serieel getal naar seconden -TIME = TIJD ## Geeft als resultaat het seriële getal van een bepaald tijdstip -TIMEVALUE = TIJDWAARDE ## Converteert de tijd in de vorm van tekst naar een serieel getal -TODAY = VANDAAG ## Geeft als resultaat het seriële getal van de huidige datum -WEEKDAY = WEEKDAG ## Converteert een serieel getal naar een weekdag -WEEKNUM = WEEKNUMMER ## Converteert een serieel getal naar een weeknummer -WORKDAY = WERKDAG ## Geeft als resultaat het seriële getal van de datum voor of na een bepaald aantal werkdagen -YEAR = JAAR ## Converteert een serieel getal naar een jaar -YEARFRAC = JAAR.DEEL ## Geeft als resultaat het gedeelte van het jaar, uitgedrukt in het aantal hele dagen tussen begindatum en einddatum - +BESSELI = BESSEL.I +BESSELJ = BESSEL.J +BESSELK = BESSEL.K +BESSELY = BESSEL.Y +BIN2DEC = BIN.N.DEC +BIN2HEX = BIN.N.HEX +BIN2OCT = BIN.N.OCT +BITAND = BIT.EN +BITLSHIFT = BIT.VERSCHUIF.LINKS +BITOR = BIT.OF +BITRSHIFT = BIT.VERSCHUIF.RECHTS +BITXOR = BIT.EX.OF +COMPLEX = COMPLEX +CONVERT = CONVERTEREN +DEC2BIN = DEC.N.BIN +DEC2HEX = DEC.N.HEX +DEC2OCT = DEC.N.OCT +DELTA = DELTA +ERF = FOUTFUNCTIE +ERF.PRECISE = FOUTFUNCTIE.NAUWKEURIG +ERFC = FOUT.COMPLEMENT +ERFC.PRECISE = FOUT.COMPLEMENT.NAUWKEURIG +GESTEP = GROTER.DAN +HEX2BIN = HEX.N.BIN +HEX2DEC = HEX.N.DEC +HEX2OCT = HEX.N.OCT +IMABS = C.ABS +IMAGINARY = C.IM.DEEL +IMARGUMENT = C.ARGUMENT +IMCONJUGATE = C.TOEGEVOEGD +IMCOS = C.COS +IMCOSH = C.COSH +IMCOT = C.COT +IMCSC = C.COSEC +IMCSCH = C.COSECH +IMDIV = C.QUOTIENT +IMEXP = C.EXP +IMLN = C.LN +IMLOG10 = C.LOG10 +IMLOG2 = C.LOG2 +IMPOWER = C.MACHT +IMPRODUCT = C.PRODUCT +IMREAL = C.REEEL.DEEL +IMSEC = C.SEC +IMSECH = C.SECH +IMSIN = C.SIN +IMSINH = C.SINH +IMSQRT = C.WORTEL +IMSUB = C.VERSCHIL +IMSUM = C.SOM +IMTAN = C.TAN +OCT2BIN = OCT.N.BIN +OCT2DEC = OCT.N.DEC +OCT2HEX = OCT.N.HEX ## -## Engineering functions Technische functies +## Financiële functies (Financial Functions) ## -BESSELI = BESSEL.Y ## Geeft als resultaat de gewijzigde Bessel-functie In(x) -BESSELJ = BESSEL.J ## Geeft als resultaat de Bessel-functie Jn(x) -BESSELK = BESSEL.K ## Geeft als resultaat de gewijzigde Bessel-functie Kn(x) -BESSELY = BESSEL.Y ## Geeft als resultaat de gewijzigde Bessel-functie Yn(x) -BIN2DEC = BIN.N.DEC ## Converteert een binair getal naar een decimaal getal -BIN2HEX = BIN.N.HEX ## Converteert een binair getal naar een hexadecimaal getal -BIN2OCT = BIN.N.OCT ## Converteert een binair getal naar een octaal getal -COMPLEX = COMPLEX ## Converteert reële en imaginaire coëfficiënten naar een complex getal -CONVERT = CONVERTEREN ## Converteert een getal in de ene maateenheid naar een getal in een andere maateenheid -DEC2BIN = DEC.N.BIN ## Converteert een decimaal getal naar een binair getal -DEC2HEX = DEC.N.HEX ## Converteert een decimaal getal naar een hexadecimaal getal -DEC2OCT = DEC.N.OCT ## Converteert een decimaal getal naar een octaal getal -DELTA = DELTA ## Test of twee waarden gelijk zijn -ERF = FOUTFUNCTIE ## Geeft als resultaat de foutfunctie -ERFC = FOUT.COMPLEMENT ## Geeft als resultaat de complementaire foutfunctie -GESTEP = GROTER.DAN ## Test of een getal groter is dan de drempelwaarde -HEX2BIN = HEX.N.BIN ## Converteert een hexadecimaal getal naar een binair getal -HEX2DEC = HEX.N.DEC ## Converteert een hexadecimaal getal naar een decimaal getal -HEX2OCT = HEX.N.OCT ## Converteert een hexadecimaal getal naar een octaal getal -IMABS = C.ABS ## Geeft als resultaat de absolute waarde (modulus) van een complex getal -IMAGINARY = C.IM.DEEL ## Geeft als resultaat de imaginaire coëfficiënt van een complex getal -IMARGUMENT = C.ARGUMENT ## Geeft als resultaat het argument thèta, een hoek uitgedrukt in radialen -IMCONJUGATE = C.TOEGEVOEGD ## Geeft als resultaat het complexe toegevoegde getal van een complex getal -IMCOS = C.COS ## Geeft als resultaat de cosinus van een complex getal -IMDIV = C.QUOTIENT ## Geeft als resultaat het quotiënt van twee complexe getallen -IMEXP = C.EXP ## Geeft als resultaat de exponent van een complex getal -IMLN = C.LN ## Geeft als resultaat de natuurlijke logaritme van een complex getal -IMLOG10 = C.LOG10 ## Geeft als resultaat de logaritme met grondtal 10 van een complex getal -IMLOG2 = C.LOG2 ## Geeft als resultaat de logaritme met grondtal 2 van een complex getal -IMPOWER = C.MACHT ## Geeft als resultaat een complex getal dat is verheven tot de macht van een geheel getal -IMPRODUCT = C.PRODUCT ## Geeft als resultaat het product van complexe getallen -IMREAL = C.REEEL.DEEL ## Geeft als resultaat de reële coëfficiënt van een complex getal -IMSIN = C.SIN ## Geeft als resultaat de sinus van een complex getal -IMSQRT = C.WORTEL ## Geeft als resultaat de vierkantswortel van een complex getal -IMSUB = C.VERSCHIL ## Geeft als resultaat het verschil tussen twee complexe getallen -IMSUM = C.SOM ## Geeft als resultaat de som van complexe getallen -OCT2BIN = OCT.N.BIN ## Converteert een octaal getal naar een binair getal -OCT2DEC = OCT.N.DEC ## Converteert een octaal getal naar een decimaal getal -OCT2HEX = OCT.N.HEX ## Converteert een octaal getal naar een hexadecimaal getal - +ACCRINT = SAMENG.RENTE +ACCRINTM = SAMENG.RENTE.V +AMORDEGRC = AMORDEGRC +AMORLINC = AMORLINC +COUPDAYBS = COUP.DAGEN.BB +COUPDAYS = COUP.DAGEN +COUPDAYSNC = COUP.DAGEN.VV +COUPNCD = COUP.DATUM.NB +COUPNUM = COUP.AANTAL +COUPPCD = COUP.DATUM.VB +CUMIPMT = CUM.RENTE +CUMPRINC = CUM.HOOFDSOM +DB = DB +DDB = DDB +DISC = DISCONTO +DOLLARDE = EURO.DE +DOLLARFR = EURO.BR +DURATION = DUUR +EFFECT = EFFECT.RENTE +FV = TW +FVSCHEDULE = TOEK.WAARDE2 +INTRATE = RENTEPERCENTAGE +IPMT = IBET +IRR = IR +ISPMT = ISBET +MDURATION = AANG.DUUR +MIRR = GIR +NOMINAL = NOMINALE.RENTE +NPER = NPER +NPV = NHW +ODDFPRICE = AFW.ET.PRIJS +ODDFYIELD = AFW.ET.REND +ODDLPRICE = AFW.LT.PRIJS +ODDLYIELD = AFW.LT.REND +PDURATION = PDUUR +PMT = BET +PPMT = PBET +PRICE = PRIJS.NOM +PRICEDISC = PRIJS.DISCONTO +PRICEMAT = PRIJS.VERVALDAG +PV = HW +RATE = RENTE +RECEIVED = OPBRENGST +RRI = RRI +SLN = LIN.AFSCHR +SYD = SYD +TBILLEQ = SCHATK.OBL +TBILLPRICE = SCHATK.PRIJS +TBILLYIELD = SCHATK.REND +VDB = VDB +XIRR = IR.SCHEMA +XNPV = NHW2 +YIELD = RENDEMENT +YIELDDISC = REND.DISCONTO +YIELDMAT = REND.VERVAL ## -## Financial functions Financiële functies +## Informatiefuncties (Information Functions) ## -ACCRINT = SAMENG.RENTE ## Berekent de opgelopen rente voor een waardepapier waarvan de rente periodiek wordt uitgekeerd -ACCRINTM = SAMENG.RENTE.V ## Berekent de opgelopen rente voor een waardepapier waarvan de rente op de vervaldatum wordt uitgekeerd -AMORDEGRC = AMORDEGRC ## Geeft als resultaat de afschrijving voor elke boekingsperiode door een afschrijvingscoëfficiënt toe te passen -AMORLINC = AMORLINC ## Berekent de afschrijving voor elke boekingsperiode -COUPDAYBS = COUP.DAGEN.BB ## Berekent het aantal dagen vanaf het begin van de coupontermijn tot de stortingsdatum -COUPDAYS = COUP.DAGEN ## Geeft als resultaat het aantal dagen in de coupontermijn waarin de stortingsdatum valt -COUPDAYSNC = COUP.DAGEN.VV ## Geeft als resultaat het aantal dagen vanaf de stortingsdatum tot de volgende couponvervaldatum -COUPNCD = COUP.DATUM.NB ## Geeft als resultaat de volgende coupondatum na de stortingsdatum -COUPNUM = COUP.AANTAL ## Geeft als resultaat het aantal coupons dat nog moet worden uitbetaald tussen de stortingsdatum en de vervaldatum -COUPPCD = COUP.DATUM.VB ## Geeft als resultaat de vorige couponvervaldatum vóór de stortingsdatum -CUMIPMT = CUM.RENTE ## Geeft als resultaat de cumulatieve rente die tussen twee termijnen is uitgekeerd -CUMPRINC = CUM.HOOFDSOM ## Geeft als resultaat de cumulatieve hoofdsom van een lening die tussen twee termijnen is terugbetaald -DB = DB ## Geeft als resultaat de afschrijving van activa voor een bepaalde periode met behulp van de 'fixed declining balance'-methode -DDB = DDB ## Geeft als resultaat de afschrijving van activa over een bepaalde termijn met behulp van de 'double declining balance'-methode of een andere methode die u opgeeft -DISC = DISCONTO ## Geeft als resultaat het discontopercentage voor een waardepapier -DOLLARDE = EURO.DE ## Converteert een prijs in euro's, uitgedrukt in een breuk, naar een prijs in euro's, uitgedrukt in een decimaal getal -DOLLARFR = EURO.BR ## Converteert een prijs in euro's, uitgedrukt in een decimaal getal, naar een prijs in euro's, uitgedrukt in een breuk -DURATION = DUUR ## Geeft als resultaat de gewogen gemiddelde looptijd voor een waardepapier met periodieke rentebetalingen -EFFECT = EFFECT.RENTE ## Geeft als resultaat het effectieve jaarlijkse rentepercentage -FV = TW ## Geeft als resultaat de toekomstige waarde van een investering -FVSCHEDULE = TOEK.WAARDE2 ## Geeft als resultaat de toekomstige waarde van een bepaalde hoofdsom na het toepassen van een reeks samengestelde rentepercentages -INTRATE = RENTEPERCENTAGE ## Geeft als resultaat het rentepercentage voor een volgestort waardepapier -IPMT = IBET ## Geeft als resultaat de te betalen rente voor een investering over een bepaalde termijn -IRR = IR ## Geeft als resultaat de interne rentabiliteit voor een reeks cashflows -ISPMT = ISBET ## Geeft als resultaat de rente die is betaald tijdens een bepaalde termijn van een investering -MDURATION = AANG.DUUR ## Geeft als resultaat de aangepaste Macauley-looptijd voor een waardepapier, aangenomen dat de nominale waarde € 100 bedraagt -MIRR = GIR ## Geeft als resultaat de interne rentabiliteit voor een serie cashflows, waarbij voor betalingen een ander rentepercentage geldt dan voor inkomsten -NOMINAL = NOMINALE.RENTE ## Geeft als resultaat het nominale jaarlijkse rentepercentage -NPER = NPER ## Geeft als resultaat het aantal termijnen van een investering -NPV = NHW ## Geeft als resultaat de netto huidige waarde van een investering op basis van een reeks periodieke cashflows en een discontopercentage -ODDFPRICE = AFW.ET.PRIJS ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier met een afwijkende eerste termijn -ODDFYIELD = AFW.ET.REND ## Geeft als resultaat het rendement voor een waardepapier met een afwijkende eerste termijn -ODDLPRICE = AFW.LT.PRIJS ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier met een afwijkende laatste termijn -ODDLYIELD = AFW.LT.REND ## Geeft als resultaat het rendement voor een waardepapier met een afwijkende laatste termijn -PMT = BET ## Geeft als resultaat de periodieke betaling voor een annuïteit -PPMT = PBET ## Geeft als resultaat de afbetaling op de hoofdsom voor een bepaalde termijn -PRICE = PRIJS.NOM ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier waarvan de rente periodiek wordt uitgekeerd -PRICEDISC = PRIJS.DISCONTO ## Geeft als resultaat de prijs per € 100 nominale waarde voor een verdisconteerd waardepapier -PRICEMAT = PRIJS.VERVALDAG ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier waarvan de rente wordt uitgekeerd op de vervaldatum -PV = HW ## Geeft als resultaat de huidige waarde van een investering -RATE = RENTE ## Geeft als resultaat het periodieke rentepercentage voor een annuïteit -RECEIVED = OPBRENGST ## Geeft als resultaat het bedrag dat op de vervaldatum wordt uitgekeerd voor een volgestort waardepapier -SLN = LIN.AFSCHR ## Geeft als resultaat de lineaire afschrijving van activa over één termijn -SYD = SYD ## Geeft als resultaat de afschrijving van activa over een bepaalde termijn met behulp van de 'Sum-Of-Years-Digits'-methode -TBILLEQ = SCHATK.OBL ## Geeft als resultaat het rendement op schatkistpapier, dat op dezelfde manier wordt berekend als het rendement op obligaties -TBILLPRICE = SCHATK.PRIJS ## Bepaalt de prijs per € 100 nominale waarde voor schatkistpapier -TBILLYIELD = SCHATK.REND ## Berekent het rendement voor schatkistpapier -VDB = VDB ## Geeft als resultaat de afschrijving van activa over een gehele of gedeeltelijke termijn met behulp van de 'declining balance'-methode -XIRR = IR.SCHEMA ## Berekent de interne rentabiliteit voor een betalingsschema van cashflows -XNPV = NHW2 ## Berekent de huidige nettowaarde voor een betalingsschema van cashflows -YIELD = RENDEMENT ## Geeft als resultaat het rendement voor een waardepapier waarvan de rente periodiek wordt uitgekeerd -YIELDDISC = REND.DISCONTO ## Geeft als resultaat het jaarlijkse rendement voor een verdisconteerd waardepapier, bijvoorbeeld schatkistpapier -YIELDMAT = REND.VERVAL ## Geeft als resultaat het jaarlijkse rendement voor een waardepapier waarvan de rente wordt uitgekeerd op de vervaldatum - +CELL = CEL +ERROR.TYPE = TYPE.FOUT +INFO = INFO +ISBLANK = ISLEEG +ISERR = ISFOUT2 +ISERROR = ISFOUT +ISEVEN = IS.EVEN +ISFORMULA = ISFORMULE +ISLOGICAL = ISLOGISCH +ISNA = ISNB +ISNONTEXT = ISGEENTEKST +ISNUMBER = ISGETAL +ISODD = IS.ONEVEN +ISREF = ISVERWIJZING +ISTEXT = ISTEKST +N = N +NA = NB +SHEET = BLAD +SHEETS = BLADEN +TYPE = TYPE ## -## Information functions Informatiefuncties +## Logische functies (Logical Functions) ## -CELL = CEL ## Geeft als resultaat informatie over de opmaak, locatie of inhoud van een cel -ERROR.TYPE = TYPE.FOUT ## Geeft als resultaat een getal dat overeenkomt met een van de foutwaarden van Microsoft Excel -INFO = INFO ## Geeft als resultaat informatie over de huidige besturingsomgeving -ISBLANK = ISLEEG ## Geeft als resultaat WAAR als de waarde leeg is -ISERR = ISFOUT2 ## Geeft als resultaat WAAR als de waarde een foutwaarde is, met uitzondering van #N/B -ISERROR = ISFOUT ## Geeft als resultaat WAAR als de waarde een foutwaarde is -ISEVEN = IS.EVEN ## Geeft als resultaat WAAR als het getal even is -ISLOGICAL = ISLOGISCH ## Geeft als resultaat WAAR als de waarde een logische waarde is -ISNA = ISNB ## Geeft als resultaat WAAR als de waarde de foutwaarde #N/B is -ISNONTEXT = ISGEENTEKST ## Geeft als resultaat WAAR als de waarde geen tekst is -ISNUMBER = ISGETAL ## Geeft als resultaat WAAR als de waarde een getal is -ISODD = IS.ONEVEN ## Geeft als resultaat WAAR als het getal oneven is -ISREF = ISVERWIJZING ## Geeft als resultaat WAAR als de waarde een verwijzing is -ISTEXT = ISTEKST ## Geeft als resultaat WAAR als de waarde tekst is -N = N ## Geeft als resultaat een waarde die is geconverteerd naar een getal -NA = NB ## Geeft als resultaat de foutwaarde #N/B -TYPE = TYPE ## Geeft als resultaat een getal dat het gegevenstype van een waarde aangeeft - +AND = EN +FALSE = ONWAAR +IF = ALS +IFERROR = ALS.FOUT +IFNA = ALS.NB +IFS = ALS.VOORWAARDEN +NOT = NIET +OR = OF +SWITCH = SCHAKELEN +TRUE = WAAR +XOR = EX.OF ## -## Logical functions Logische functies +## Zoek- en verwijzingsfuncties (Lookup & Reference Functions) ## -AND = EN ## Geeft als resultaat WAAR als alle argumenten WAAR zijn -FALSE = ONWAAR ## Geeft als resultaat de logische waarde ONWAAR -IF = ALS ## Geeft een logische test aan -IFERROR = ALS.FOUT ## Retourneert een waarde die u opgeeft als een formule een fout oplevert, anders wordt het resultaat van de formule geretourneerd -NOT = NIET ## Keert de logische waarde van het argument om -OR = OF ## Geeft als resultaat WAAR als minimaal een van de argumenten WAAR is -TRUE = WAAR ## Geeft als resultaat de logische waarde WAAR - +ADDRESS = ADRES +AREAS = BEREIKEN +CHOOSE = KIEZEN +COLUMN = KOLOM +COLUMNS = KOLOMMEN +FORMULATEXT = FORMULETEKST +GETPIVOTDATA = DRAAITABEL.OPHALEN +HLOOKUP = HORIZ.ZOEKEN +HYPERLINK = HYPERLINK +INDEX = INDEX +INDIRECT = INDIRECT +LOOKUP = ZOEKEN +MATCH = VERGELIJKEN +OFFSET = VERSCHUIVING +ROW = RIJ +ROWS = RIJEN +RTD = RTG +TRANSPOSE = TRANSPONEREN +VLOOKUP = VERT.ZOEKEN ## -## Lookup and reference functions Zoek- en verwijzingsfuncties +## Wiskundige en trigonometrische functies (Math & Trig Functions) ## -ADDRESS = ADRES ## Geeft als resultaat een verwijzing, in de vorm van tekst, naar één bepaalde cel in een werkblad -AREAS = BEREIKEN ## Geeft als resultaat het aantal bereiken in een verwijzing -CHOOSE = KIEZEN ## Kiest een waarde uit een lijst met waarden -COLUMN = KOLOM ## Geeft als resultaat het kolomnummer van een verwijzing -COLUMNS = KOLOMMEN ## Geeft als resultaat het aantal kolommen in een verwijzing -HLOOKUP = HORIZ.ZOEKEN ## Zoekt in de bovenste rij van een matrix naar een bepaalde waarde en geeft als resultaat de gevonden waarde in de opgegeven cel -HYPERLINK = HYPERLINK ## Maakt een snelkoppeling of een sprong waarmee een document wordt geopend dat is opgeslagen op een netwerkserver, een intranet of op internet -INDEX = INDEX ## Kiest met een index een waarde uit een verwijzing of een matrix -INDIRECT = INDIRECT ## Geeft als resultaat een verwijzing die wordt aangegeven met een tekstwaarde -LOOKUP = ZOEKEN ## Zoekt naar bepaalde waarden in een vector of een matrix -MATCH = VERGELIJKEN ## Zoekt naar bepaalde waarden in een verwijzing of een matrix -OFFSET = VERSCHUIVING ## Geeft als resultaat een nieuwe verwijzing die is verschoven ten opzichte van een bepaalde verwijzing -ROW = RIJ ## Geeft als resultaat het rijnummer van een verwijzing -ROWS = RIJEN ## Geeft als resultaat het aantal rijen in een verwijzing -RTD = RTG ## Haalt realtimegegevens op uit een programma dat COM-automatisering (automatisering: een methode waarmee de ene toepassing objecten van een andere toepassing of ontwikkelprogramma kan besturen. Automatisering werd vroeger OLE-automatisering genoemd. Automatisering is een industrienorm die deel uitmaakt van het Component Object Model (COM).) ondersteunt -TRANSPOSE = TRANSPONEREN ## Geeft als resultaat de getransponeerde van een matrix -VLOOKUP = VERT.ZOEKEN ## Zoekt in de meest linkse kolom van een matrix naar een bepaalde waarde en geeft als resultaat de waarde in de opgegeven cel - +ABS = ABS +ACOS = BOOGCOS +ACOSH = BOOGCOSH +ACOT = BOOGCOT +ACOTH = BOOGCOTH +AGGREGATE = AGGREGAAT +ARABIC = ARABISCH +ASIN = BOOGSIN +ASINH = BOOGSINH +ATAN = BOOGTAN +ATAN2 = BOOGTAN2 +ATANH = BOOGTANH +BASE = BASIS +CEILING.MATH = AFRONDEN.BOVEN.WISK +CEILING.PRECISE = AFRONDEN.BOVEN.NAUWKEURIG +COMBIN = COMBINATIES +COMBINA = COMBIN.A +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = COSEC +CSCH = COSECH +DECIMAL = DECIMAAL +DEGREES = GRADEN +ECMA.CEILING = ECMA.AFRONDEN.BOVEN +EVEN = EVEN +EXP = EXP +FACT = FACULTEIT +FACTDOUBLE = DUBBELE.FACULTEIT +FLOOR.MATH = AFRONDEN.BENEDEN.WISK +FLOOR.PRECISE = AFRONDEN.BENEDEN.NAUWKEURIG +GCD = GGD +INT = INTEGER +ISO.CEILING = ISO.AFRONDEN.BOVEN +LCM = KGV +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = DETERMINANTMAT +MINVERSE = INVERSEMAT +MMULT = PRODUCTMAT +MOD = REST +MROUND = AFRONDEN.N.VEELVOUD +MULTINOMIAL = MULTINOMIAAL +MUNIT = EENHEIDMAT +ODD = ONEVEN +PI = PI +POWER = MACHT +PRODUCT = PRODUCT +QUOTIENT = QUOTIENT +RADIANS = RADIALEN +RAND = ASELECT +RANDBETWEEN = ASELECTTUSSEN +ROMAN = ROMEINS +ROUND = AFRONDEN +ROUNDBAHTDOWN = BAHT.AFR.NAAR.BENEDEN +ROUNDBAHTUP = BAHT.AFR.NAAR.BOVEN +ROUNDDOWN = AFRONDEN.NAAR.BENEDEN +ROUNDUP = AFRONDEN.NAAR.BOVEN +SEC = SEC +SECH = SECH +SERIESSUM = SOM.MACHTREEKS +SIGN = POS.NEG +SIN = SIN +SINH = SINH +SQRT = WORTEL +SQRTPI = WORTEL.PI +SUBTOTAL = SUBTOTAAL +SUM = SOM +SUMIF = SOM.ALS +SUMIFS = SOMMEN.ALS +SUMPRODUCT = SOMPRODUCT +SUMSQ = KWADRATENSOM +SUMX2MY2 = SOM.X2MINY2 +SUMX2PY2 = SOM.X2PLUSY2 +SUMXMY2 = SOM.XMINY.2 +TAN = TAN +TANH = TANH +TRUNC = GEHEEL ## -## Math and trigonometry functions Wiskundige en trigonometrische functies +## Statistische functies (Statistical Functions) ## -ABS = ABS ## Geeft als resultaat de absolute waarde van een getal -ACOS = BOOGCOS ## Geeft als resultaat de boogcosinus van een getal -ACOSH = BOOGCOSH ## Geeft als resultaat de inverse cosinus hyperbolicus van een getal -ASIN = BOOGSIN ## Geeft als resultaat de boogsinus van een getal -ASINH = BOOGSINH ## Geeft als resultaat de inverse sinus hyperbolicus van een getal -ATAN = BOOGTAN ## Geeft als resultaat de boogtangens van een getal -ATAN2 = BOOGTAN2 ## Geeft als resultaat de boogtangens van de x- en y-coördinaten -ATANH = BOOGTANH ## Geeft als resultaat de inverse tangens hyperbolicus van een getal -CEILING = AFRONDEN.BOVEN ## Rondt de absolute waarde van een getal naar boven af op het dichtstbijzijnde gehele getal of het dichtstbijzijnde significante veelvoud -COMBIN = COMBINATIES ## Geeft als resultaat het aantal combinaties voor een bepaald aantal objecten -COS = COS ## Geeft als resultaat de cosinus van een getal -COSH = COSH ## Geeft als resultaat de cosinus hyperbolicus van een getal -DEGREES = GRADEN ## Converteert radialen naar graden -EVEN = EVEN ## Rondt het getal af op het dichtstbijzijnde gehele even getal -EXP = EXP ## Verheft e tot de macht van een bepaald getal -FACT = FACULTEIT ## Geeft als resultaat de faculteit van een getal -FACTDOUBLE = DUBBELE.FACULTEIT ## Geeft als resultaat de dubbele faculteit van een getal -FLOOR = AFRONDEN.BENEDEN ## Rondt de absolute waarde van een getal naar beneden af -GCD = GGD ## Geeft als resultaat de grootste gemene deler -INT = INTEGER ## Rondt een getal naar beneden af op het dichtstbijzijnde gehele getal -LCM = KGV ## Geeft als resultaat het kleinste gemene veelvoud -LN = LN ## Geeft als resultaat de natuurlijke logaritme van een getal -LOG = LOG ## Geeft als resultaat de logaritme met het opgegeven grondtal van een getal -LOG10 = LOG10 ## Geeft als resultaat de logaritme met grondtal 10 van een getal -MDETERM = DETERMINANTMAT ## Geeft als resultaat de determinant van een matrix -MINVERSE = INVERSEMAT ## Geeft als resultaat de inverse van een matrix -MMULT = PRODUCTMAT ## Geeft als resultaat het product van twee matrices -MOD = REST ## Geeft als resultaat het restgetal van een deling -MROUND = AFRONDEN.N.VEELVOUD ## Geeft als resultaat een getal afgerond op het gewenste veelvoud -MULTINOMIAL = MULTINOMIAAL ## Geeft als resultaat de multinomiaalcoëfficiënt van een reeks getallen -ODD = ONEVEN ## Rondt de absolute waarde van het getal naar boven af op het dichtstbijzijnde gehele oneven getal -PI = PI ## Geeft als resultaat de waarde van pi -POWER = MACHT ## Verheft een getal tot een macht -PRODUCT = PRODUCT ## Vermenigvuldigt de argumenten met elkaar -QUOTIENT = QUOTIENT ## Geeft als resultaat de uitkomst van een deling als geheel getal -RADIANS = RADIALEN ## Converteert graden naar radialen -RAND = ASELECT ## Geeft als resultaat een willekeurig getal tussen 0 en 1 -RANDBETWEEN = ASELECTTUSSEN ## Geeft een willekeurig getal tussen de getallen die u hebt opgegeven -ROMAN = ROMEINS ## Converteert een Arabisch getal naar een Romeins getal en geeft het resultaat weer in de vorm van tekst -ROUND = AFRONDEN ## Rondt een getal af op het opgegeven aantal decimalen -ROUNDDOWN = AFRONDEN.NAAR.BENEDEN ## Rondt de absolute waarde van een getal naar beneden af -ROUNDUP = AFRONDEN.NAAR.BOVEN ## Rondt de absolute waarde van een getal naar boven af -SERIESSUM = SOM.MACHTREEKS ## Geeft als resultaat de som van een machtreeks die is gebaseerd op de formule -SIGN = POS.NEG ## Geeft als resultaat het teken van een getal -SIN = SIN ## Geeft als resultaat de sinus van de opgegeven hoek -SINH = SINH ## Geeft als resultaat de sinus hyperbolicus van een getal -SQRT = WORTEL ## Geeft als resultaat de positieve vierkantswortel van een getal -SQRTPI = WORTEL.PI ## Geeft als resultaat de vierkantswortel van (getal * pi) -SUBTOTAL = SUBTOTAAL ## Geeft als resultaat een subtotaal voor een bereik -SUM = SOM ## Telt de argumenten op -SUMIF = SOM.ALS ## Telt de getallen bij elkaar op die voldoen aan een bepaald criterium -SUMIFS = SOMMEN.ALS ## Telt de cellen in een bereik op die aan meerdere criteria voldoen -SUMPRODUCT = SOMPRODUCT ## Geeft als resultaat de som van de producten van de corresponderende matrixelementen -SUMSQ = KWADRATENSOM ## Geeft als resultaat de som van de kwadraten van de argumenten -SUMX2MY2 = SOM.X2MINY2 ## Geeft als resultaat de som van het verschil tussen de kwadraten van corresponderende waarden in twee matrices -SUMX2PY2 = SOM.X2PLUSY2 ## Geeft als resultaat de som van de kwadratensom van corresponderende waarden in twee matrices -SUMXMY2 = SOM.XMINY.2 ## Geeft als resultaat de som van de kwadraten van de verschillen tussen de corresponderende waarden in twee matrices -TAN = TAN ## Geeft als resultaat de tangens van een getal -TANH = TANH ## Geeft als resultaat de tangens hyperbolicus van een getal -TRUNC = GEHEEL ## Kapt een getal af tot een geheel getal - +AVEDEV = GEM.DEVIATIE +AVERAGE = GEMIDDELDE +AVERAGEA = GEMIDDELDEA +AVERAGEIF = GEMIDDELDE.ALS +AVERAGEIFS = GEMIDDELDEN.ALS +BETA.DIST = BETA.VERD +BETA.INV = BETA.INV +BINOM.DIST = BINOM.VERD +BINOM.DIST.RANGE = BINOM.VERD.BEREIK +BINOM.INV = BINOMIALE.INV +CHISQ.DIST = CHIKW.VERD +CHISQ.DIST.RT = CHIKW.VERD.RECHTS +CHISQ.INV = CHIKW.INV +CHISQ.INV.RT = CHIKW.INV.RECHTS +CHISQ.TEST = CHIKW.TEST +CONFIDENCE.NORM = VERTROUWELIJKHEID.NORM +CONFIDENCE.T = VERTROUWELIJKHEID.T +CORREL = CORRELATIE +COUNT = AANTAL +COUNTA = AANTALARG +COUNTBLANK = AANTAL.LEGE.CELLEN +COUNTIF = AANTAL.ALS +COUNTIFS = AANTALLEN.ALS +COVARIANCE.P = COVARIANTIE.P +COVARIANCE.S = COVARIANTIE.S +DEVSQ = DEV.KWAD +EXPON.DIST = EXPON.VERD.N +F.DIST = F.VERD +F.DIST.RT = F.VERD.RECHTS +F.INV = F.INV +F.INV.RT = F.INV.RECHTS +F.TEST = F.TEST +FISHER = FISHER +FISHERINV = FISHER.INV +FORECAST.ETS = VOORSPELLEN.ETS +FORECAST.ETS.CONFINT = VOORSPELLEN.ETS.CONFINT +FORECAST.ETS.SEASONALITY = VOORSPELLEN.ETS.SEASONALITY +FORECAST.ETS.STAT = FORECAST.ETS.STAT +FORECAST.LINEAR = VOORSPELLEN.LINEAR +FREQUENCY = INTERVAL +GAMMA = GAMMA +GAMMA.DIST = GAMMA.VERD.N +GAMMA.INV = GAMMA.INV.N +GAMMALN = GAMMA.LN +GAMMALN.PRECISE = GAMMA.LN.NAUWKEURIG +GAUSS = GAUSS +GEOMEAN = MEETK.GEM +GROWTH = GROEI +HARMEAN = HARM.GEM +HYPGEOM.DIST = HYPGEOM.VERD +INTERCEPT = SNIJPUNT +KURT = KURTOSIS +LARGE = GROOTSTE +LINEST = LIJNSCH +LOGEST = LOGSCH +LOGNORM.DIST = LOGNORM.VERD +LOGNORM.INV = LOGNORM.INV +MAX = MAX +MAXA = MAXA +MAXIFS = MAX.ALS.VOORWAARDEN +MEDIAN = MEDIAAN +MIN = MIN +MINA = MINA +MINIFS = MIN.ALS.VOORWAARDEN +MODE.MULT = MODUS.MEERV +MODE.SNGL = MODUS.ENKELV +NEGBINOM.DIST = NEGBINOM.VERD +NORM.DIST = NORM.VERD.N +NORM.INV = NORM.INV.N +NORM.S.DIST = NORM.S.VERD +NORM.S.INV = NORM.S.INV +PEARSON = PEARSON +PERCENTILE.EXC = PERCENTIEL.EXC +PERCENTILE.INC = PERCENTIEL.INC +PERCENTRANK.EXC = PROCENTRANG.EXC +PERCENTRANK.INC = PROCENTRANG.INC +PERMUT = PERMUTATIES +PERMUTATIONA = PERMUTATIE.A +PHI = PHI +POISSON.DIST = POISSON.VERD +PROB = KANS +QUARTILE.EXC = KWARTIEL.EXC +QUARTILE.INC = KWARTIEL.INC +RANK.AVG = RANG.GEMIDDELDE +RANK.EQ = RANG.GELIJK +RSQ = R.KWADRAAT +SKEW = SCHEEFHEID +SKEW.P = SCHEEFHEID.P +SLOPE = RICHTING +SMALL = KLEINSTE +STANDARDIZE = NORMALISEREN +STDEV.P = STDEV.P +STDEV.S = STDEV.S +STDEVA = STDEVA +STDEVPA = STDEVPA +STEYX = STAND.FOUT.YX +T.DIST = T.DIST +T.DIST.2T = T.VERD.2T +T.DIST.RT = T.VERD.RECHTS +T.INV = T.INV +T.INV.2T = T.INV.2T +T.TEST = T.TEST +TREND = TREND +TRIMMEAN = GETRIMD.GEM +VAR.P = VAR.P +VAR.S = VAR.S +VARA = VARA +VARPA = VARPA +WEIBULL.DIST = WEIBULL.VERD +Z.TEST = Z.TEST ## -## Statistical functions Statistische functies +## Tekstfuncties (Text Functions) ## -AVEDEV = GEM.DEVIATIE ## Geeft als resultaat het gemiddelde van de absolute deviaties van gegevenspunten ten opzichte van hun gemiddelde waarde -AVERAGE = GEMIDDELDE ## Geeft als resultaat het gemiddelde van de argumenten -AVERAGEA = GEMIDDELDEA ## Geeft als resultaat het gemiddelde van de argumenten, inclusief getallen, tekst en logische waarden -AVERAGEIF = GEMIDDELDE.ALS ## Geeft het gemiddelde (rekenkundig gemiddelde) als resultaat van alle cellen in een bereik die voldoen aan de opgegeven criteria -AVERAGEIFS = GEMIDDELDEN.ALS ## Geeft het gemiddelde (rekenkundig gemiddelde) als resultaat van alle cellen die aan meerdere criteria voldoen -BETADIST = BETA.VERD ## Geeft als resultaat de cumulatieve bèta-verdelingsfunctie -BETAINV = BETA.INV ## Geeft als resultaat de inverse van de cumulatieve verdelingsfunctie voor een gegeven bèta-verdeling -BINOMDIST = BINOMIALE.VERD ## Geeft als resultaat de binomiale verdeling -CHIDIST = CHI.KWADRAAT ## Geeft als resultaat de eenzijdige kans van de chi-kwadraatverdeling -CHIINV = CHI.KWADRAAT.INV ## Geeft als resultaat de inverse van een eenzijdige kans van de chi-kwadraatverdeling -CHITEST = CHI.TOETS ## Geeft als resultaat de onafhankelijkheidstoets -CONFIDENCE = BETROUWBAARHEID ## Geeft als resultaat het betrouwbaarheidsinterval van een gemiddelde waarde voor de elementen van een populatie -CORREL = CORRELATIE ## Geeft als resultaat de correlatiecoëfficiënt van twee gegevensverzamelingen -COUNT = AANTAL ## Telt het aantal getallen in de argumentenlijst -COUNTA = AANTALARG ## Telt het aantal waarden in de argumentenlijst -COUNTBLANK = AANTAL.LEGE.CELLEN ## Telt het aantal lege cellen in een bereik -COUNTIF = AANTAL.ALS ## Telt in een bereik het aantal cellen die voldoen aan een bepaald criterium -COUNTIFS = AANTALLEN.ALS ## Telt in een bereik het aantal cellen die voldoen aan meerdere criteria -COVAR = COVARIANTIE ## Geeft als resultaat de covariantie, het gemiddelde van de producten van de gepaarde deviaties -CRITBINOM = CRIT.BINOM ## Geeft als resultaat de kleinste waarde waarvoor de binomiale verdeling kleiner is dan of gelijk is aan het criterium -DEVSQ = DEV.KWAD ## Geeft als resultaat de som van de deviaties in het kwadraat -EXPONDIST = EXPON.VERD ## Geeft als resultaat de exponentiële verdeling -FDIST = F.VERDELING ## Geeft als resultaat de F-verdeling -FINV = F.INVERSE ## Geeft als resultaat de inverse van de F-verdeling -FISHER = FISHER ## Geeft als resultaat de Fisher-transformatie -FISHERINV = FISHER.INV ## Geeft als resultaat de inverse van de Fisher-transformatie -FORECAST = VOORSPELLEN ## Geeft als resultaat een waarde op basis van een lineaire trend -FREQUENCY = FREQUENTIE ## Geeft als resultaat een frequentieverdeling in de vorm van een verticale matrix -FTEST = F.TOETS ## Geeft als resultaat een F-toets -GAMMADIST = GAMMA.VERD ## Geeft als resultaat de gamma-verdeling -GAMMAINV = GAMMA.INV ## Geeft als resultaat de inverse van de cumulatieve gamma-verdeling -GAMMALN = GAMMA.LN ## Geeft als resultaat de natuurlijke logaritme van de gamma-functie, G(x) -GEOMEAN = MEETK.GEM ## Geeft als resultaat het meetkundige gemiddelde -GROWTH = GROEI ## Geeft als resultaat de waarden voor een exponentiële trend -HARMEAN = HARM.GEM ## Geeft als resultaat het harmonische gemiddelde -HYPGEOMDIST = HYPERGEO.VERD ## Geeft als resultaat de hypergeometrische verdeling -INTERCEPT = SNIJPUNT ## Geeft als resultaat het snijpunt van de lineaire regressielijn met de y-as -KURT = KURTOSIS ## Geeft als resultaat de kurtosis van een gegevensverzameling -LARGE = GROOTSTE ## Geeft als resultaat de op k-1 na grootste waarde in een gegevensverzameling -LINEST = LIJNSCH ## Geeft als resultaat de parameters van een lineaire trend -LOGEST = LOGSCH ## Geeft als resultaat de parameters van een exponentiële trend -LOGINV = LOG.NORM.INV ## Geeft als resultaat de inverse van de logaritmische normale verdeling -LOGNORMDIST = LOG.NORM.VERD ## Geeft als resultaat de cumulatieve logaritmische normale verdeling -MAX = MAX ## Geeft als resultaat de maximumwaarde in een lijst met argumenten -MAXA = MAXA ## Geeft als resultaat de maximumwaarde in een lijst met argumenten, inclusief getallen, tekst en logische waarden -MEDIAN = MEDIAAN ## Geeft als resultaat de mediaan van de opgegeven getallen -MIN = MIN ## Geeft als resultaat de minimumwaarde in een lijst met argumenten -MINA = MINA ## Geeft als resultaat de minimumwaarde in een lijst met argumenten, inclusief getallen, tekst en logische waarden -MODE = MODUS ## Geeft als resultaat de meest voorkomende waarde in een gegevensverzameling -NEGBINOMDIST = NEG.BINOM.VERD ## Geeft als resultaat de negatieve binomiaalverdeling -NORMDIST = NORM.VERD ## Geeft als resultaat de cumulatieve normale verdeling -NORMINV = NORM.INV ## Geeft als resultaat de inverse van de cumulatieve standaardnormale verdeling -NORMSDIST = STAND.NORM.VERD ## Geeft als resultaat de cumulatieve standaardnormale verdeling -NORMSINV = STAND.NORM.INV ## Geeft als resultaat de inverse van de cumulatieve normale verdeling -PEARSON = PEARSON ## Geeft als resultaat de correlatiecoëfficiënt van Pearson -PERCENTILE = PERCENTIEL ## Geeft als resultaat het k-de percentiel van waarden in een bereik -PERCENTRANK = PERCENT.RANG ## Geeft als resultaat de positie, in procenten uitgedrukt, van een waarde in de rangorde van een gegevensverzameling -PERMUT = PERMUTATIES ## Geeft als resultaat het aantal permutaties voor een gegeven aantal objecten -POISSON = POISSON ## Geeft als resultaat de Poisson-verdeling -PROB = KANS ## Geeft als resultaat de kans dat waarden zich tussen twee grenzen bevinden -QUARTILE = KWARTIEL ## Geeft als resultaat het kwartiel van een gegevensverzameling -RANK = RANG ## Geeft als resultaat het rangnummer van een getal in een lijst getallen -RSQ = R.KWADRAAT ## Geeft als resultaat het kwadraat van de Pearson-correlatiecoëfficiënt -SKEW = SCHEEFHEID ## Geeft als resultaat de mate van asymmetrie van een verdeling -SLOPE = RICHTING ## Geeft als resultaat de richtingscoëfficiënt van een lineaire regressielijn -SMALL = KLEINSTE ## Geeft als resultaat de op k-1 na kleinste waarde in een gegevensverzameling -STANDARDIZE = NORMALISEREN ## Geeft als resultaat een genormaliseerde waarde -STDEV = STDEV ## Maakt een schatting van de standaarddeviatie op basis van een steekproef -STDEVA = STDEVA ## Maakt een schatting van de standaarddeviatie op basis van een steekproef, inclusief getallen, tekst en logische waarden -STDEVP = STDEVP ## Berekent de standaarddeviatie op basis van de volledige populatie -STDEVPA = STDEVPA ## Berekent de standaarddeviatie op basis van de volledige populatie, inclusief getallen, tekst en logische waarden -STEYX = STAND.FOUT.YX ## Geeft als resultaat de standaardfout in de voorspelde y-waarde voor elke x in een regressie -TDIST = T.VERD ## Geeft als resultaat de Student T-verdeling -TINV = T.INV ## Geeft als resultaat de inverse van de Student T-verdeling -TREND = TREND ## Geeft als resultaat de waarden voor een lineaire trend -TRIMMEAN = GETRIMD.GEM ## Geeft als resultaat het gemiddelde van waarden in een gegevensverzameling -TTEST = T.TOETS ## Geeft als resultaat de kans met behulp van de Student T-toets -VAR = VAR ## Maakt een schatting van de variantie op basis van een steekproef -VARA = VARA ## Maakt een schatting van de variantie op basis van een steekproef, inclusief getallen, tekst en logische waarden -VARP = VARP ## Berekent de variantie op basis van de volledige populatie -VARPA = VARPA ## Berekent de standaarddeviatie op basis van de volledige populatie, inclusief getallen, tekst en logische waarden -WEIBULL = WEIBULL ## Geeft als resultaat de Weibull-verdeling -ZTEST = Z.TOETS ## Geeft als resultaat de eenzijdige kanswaarde van een Z-toets - +BAHTTEXT = BAHT.TEKST +CHAR = TEKEN +CLEAN = WISSEN.CONTROL +CODE = CODE +CONCAT = TEKST.SAMENV +DOLLAR = EURO +EXACT = GELIJK +FIND = VIND.ALLES +FIXED = VAST +ISTHAIDIGIT = IS.THAIS.CIJFER +LEFT = LINKS +LEN = LENGTE +LOWER = KLEINE.LETTERS +MID = DEEL +NUMBERSTRING = GETALNOTATIE +NUMBERVALUE = NUMERIEKE.WAARDE +PHONETIC = FONETISCH +PROPER = BEGINLETTERS +REPLACE = VERVANGEN +REPT = HERHALING +RIGHT = RECHTS +SEARCH = VIND.SPEC +SUBSTITUTE = SUBSTITUEREN +T = T +TEXT = TEKST +TEXTJOIN = TEKST.COMBINEREN +THAIDIGIT = THAIS.CIJFER +THAINUMSOUND = THAIS.GETAL.GELUID +THAINUMSTRING = THAIS.GETAL.REEKS +THAISTRINGLENGTH = THAIS.REEKS.LENGTE +TRIM = SPATIES.WISSEN +UNICHAR = UNITEKEN +UNICODE = UNICODE +UPPER = HOOFDLETTERS +VALUE = WAARDE ## -## Text functions Tekstfuncties +## Webfuncties (Web Functions) ## -ASC = ASC ## Wijzigt Nederlandse letters of katakanatekens over de volle breedte (dubbel-bytetekens) binnen een tekenreeks in tekens over de halve breedte (enkel-bytetekens) -BAHTTEXT = BAHT.TEKST ## Converteert een getal naar tekst met de valutanotatie ß (baht) -CHAR = TEKEN ## Geeft als resultaat het teken dat hoort bij de opgegeven code -CLEAN = WISSEN.CONTROL ## Verwijdert alle niet-afdrukbare tekens uit een tekst -CODE = CODE ## Geeft als resultaat de numerieke code voor het eerste teken in een tekenreeks -CONCATENATE = TEKST.SAMENVOEGEN ## Voegt verschillende tekstfragmenten samen tot één tekstfragment -DOLLAR = EURO ## Converteert een getal naar tekst met de valutanotatie € (euro) -EXACT = GELIJK ## Controleert of twee tekenreeksen identiek zijn -FIND = VIND.ALLES ## Zoekt een bepaalde tekenreeks in een tekst (waarbij onderscheid wordt gemaakt tussen hoofdletters en kleine letters) -FINDB = VIND.ALLES.B ## Zoekt een bepaalde tekenreeks in een tekst (waarbij onderscheid wordt gemaakt tussen hoofdletters en kleine letters) -FIXED = VAST ## Maakt een getal als tekst met een vast aantal decimalen op -JIS = JIS ## Wijzigt Nederlandse letters of katakanatekens over de halve breedte (enkel-bytetekens) binnen een tekenreeks in tekens over de volle breedte (dubbel-bytetekens) -LEFT = LINKS ## Geeft als resultaat de meest linkse tekens in een tekenreeks -LEFTB = LINKSB ## Geeft als resultaat de meest linkse tekens in een tekenreeks -LEN = LENGTE ## Geeft als resultaat het aantal tekens in een tekenreeks -LENB = LENGTEB ## Geeft als resultaat het aantal tekens in een tekenreeks -LOWER = KLEINE.LETTERS ## Zet tekst om in kleine letters -MID = MIDDEN ## Geeft als resultaat een bepaald aantal tekens van een tekenreeks vanaf de positie die u opgeeft -MIDB = DEELB ## Geeft als resultaat een bepaald aantal tekens van een tekenreeks vanaf de positie die u opgeeft -PHONETIC = FONETISCH ## Haalt de fonetische tekens (furigana) uit een tekenreeks op -PROPER = BEGINLETTERS ## Zet de eerste letter van elk woord in een tekst om in een hoofdletter -REPLACE = VERVANG ## Vervangt tekens binnen een tekst -REPLACEB = VERVANGENB ## Vervangt tekens binnen een tekst -REPT = HERHALING ## Herhaalt een tekst een aantal malen -RIGHT = RECHTS ## Geeft als resultaat de meest rechtse tekens in een tekenreeks -RIGHTB = RECHTSB ## Geeft als resultaat de meest rechtse tekens in een tekenreeks -SEARCH = VIND.SPEC ## Zoekt een bepaalde tekenreeks in een tekst (waarbij geen onderscheid wordt gemaakt tussen hoofdletters en kleine letters) -SEARCHB = VIND.SPEC.B ## Zoekt een bepaalde tekenreeks in een tekst (waarbij geen onderscheid wordt gemaakt tussen hoofdletters en kleine letters) -SUBSTITUTE = SUBSTITUEREN ## Vervangt oude tekst door nieuwe tekst in een tekenreeks -T = T ## Converteert de argumenten naar tekst -TEXT = TEKST ## Maakt een getal op en converteert het getal naar tekst -TRIM = SPATIES.WISSEN ## Verwijdert de spaties uit een tekst -UPPER = HOOFDLETTERS ## Zet tekst om in hoofdletters -VALUE = WAARDE ## Converteert tekst naar een getal +ENCODEURL = URL.CODEREN +FILTERXML = XML.FILTEREN +WEBSERVICE = WEBSERVICE + +## +## Compatibiliteitsfuncties (Compatibility Functions) +## +BETADIST = BETAVERD +BETAINV = BETAINV +BINOMDIST = BINOMIALE.VERD +CEILING = AFRONDEN.BOVEN +CHIDIST = CHI.KWADRAAT +CHIINV = CHI.KWADRAAT.INV +CHITEST = CHI.TOETS +CONCATENATE = TEKST.SAMENVOEGEN +CONFIDENCE = BETROUWBAARHEID +COVAR = COVARIANTIE +CRITBINOM = CRIT.BINOM +EXPONDIST = EXPON.VERD +FDIST = F.VERDELING +FINV = F.INVERSE +FLOOR = AFRONDEN.BENEDEN +FORECAST = VOORSPELLEN +FTEST = F.TOETS +GAMMADIST = GAMMA.VERD +GAMMAINV = GAMMA.INV +HYPGEOMDIST = HYPERGEO.VERD +LOGINV = LOG.NORM.INV +LOGNORMDIST = LOG.NORM.VERD +MODE = MODUS +NEGBINOMDIST = NEG.BINOM.VERD +NORMDIST = NORM.VERD +NORMINV = NORM.INV +NORMSDIST = STAND.NORM.VERD +NORMSINV = STAND.NORM.INV +PERCENTILE = PERCENTIEL +PERCENTRANK = PERCENT.RANG +POISSON = POISSON +QUARTILE = KWARTIEL +RANK = RANG +STDEV = STDEV +STDEVP = STDEVP +TDIST = T.VERD +TINV = TINV +TTEST = T.TOETS +VAR = VAR +VARP = VARP +WEIBULL = WEIBULL +ZTEST = Z.TOETS diff --git a/src/PhpSpreadsheet/Calculation/locale/no/config b/src/PhpSpreadsheet/Calculation/locale/no/config deleted file mode 100644 index c7f4152a..00000000 --- a/src/PhpSpreadsheet/Calculation/locale/no/config +++ /dev/null @@ -1,24 +0,0 @@ -## -## PhpSpreadsheet -## - -ArgumentSeparator = ; - - -## -## (For future use) -## -currencySymbol = kr - - -## -## Excel Error Codes (For future use) - -## -NULL = #NULL! -DIV0 = #DIV/0! -VALUE = #VERDI! -REF = #REF! -NAME = #NAVN? -NUM = #NUM! -NA = #I/T diff --git a/src/PhpSpreadsheet/Calculation/locale/no/functions b/src/PhpSpreadsheet/Calculation/locale/no/functions deleted file mode 100644 index ab2a3793..00000000 --- a/src/PhpSpreadsheet/Calculation/locale/no/functions +++ /dev/null @@ -1,416 +0,0 @@ -## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ -## -## - - -## -## Add-in and Automation functions Funksjonene Tillegg og Automatisering -## -GETPIVOTDATA = HENTPIVOTDATA ## Returnerer data som er lagret i en pivottabellrapport - - -## -## Cube functions Kubefunksjoner -## -CUBEKPIMEMBER = KUBEKPIMEDLEM ## Returnerer navnet, egenskapen og målet for en viktig ytelsesindikator (KPI), og viser navnet og egenskapen i cellen. En KPI er en målbar enhet, for eksempel månedlig bruttoinntjening eller kvartalsvis inntjening per ansatt, og brukes til å overvåke ytelsen i en organisasjon. -CUBEMEMBER = KUBEMEDLEM ## Returnerer et medlem eller en tuppel i et kubehierarki. Brukes til å validere at medlemmet eller tuppelen finnes i kuben. -CUBEMEMBERPROPERTY = KUBEMEDLEMEGENSKAP ## Returnerer verdien til en medlemsegenskap i kuben. Brukes til å validere at et medlemsnavn finnes i kuben, og til å returnere den angitte egenskapen for dette medlemmet. -CUBERANKEDMEMBER = KUBERANGERTMEDLEM ## Returnerer det n-te, eller rangerte, medlemmet i et sett. Brukes til å returnere ett eller flere elementer i et sett, for eksempel de 10 beste studentene. -CUBESET = KUBESETT ## Definerer et beregnet sett av medlemmer eller tuppeler ved å sende et settuttrykk til kuben på serveren, noe som oppretter settet og deretter returnerer dette settet til Microsoft Office Excel. -CUBESETCOUNT = KUBESETTANTALL ## Returnerer antallet elementer i et sett. -CUBEVALUE = KUBEVERDI ## Returnerer en aggregert verdi fra en kube. - - -## -## Database functions Databasefunksjoner -## -DAVERAGE = DGJENNOMSNITT ## Returnerer gjennomsnittet av merkede databaseposter -DCOUNT = DANTALL ## Teller celler som inneholder tall i en database -DCOUNTA = DANTALLA ## Teller celler som ikke er tomme i en database -DGET = DHENT ## Trekker ut fra en database en post som oppfyller angitte vilkår -DMAX = DMAKS ## Returnerer maksimumsverdien fra merkede databaseposter -DMIN = DMIN ## Returnerer minimumsverdien fra merkede databaseposter -DPRODUCT = DPRODUKT ## Multipliserer verdiene i et bestemt felt med poster som oppfyller vilkårene i en database -DSTDEV = DSTDAV ## Estimerer standardavviket basert på et utvalg av merkede databaseposter -DSTDEVP = DSTAVP ## Beregner standardavviket basert på at merkede databaseposter utgjør hele populasjonen -DSUM = DSUMMER ## Legger til tallene i feltkolonnen med poster, i databasen som oppfyller vilkårene -DVAR = DVARIANS ## Estimerer variansen basert på et utvalg av merkede databaseposter -DVARP = DVARIANSP ## Beregner variansen basert på at merkede databaseposter utgjør hele populasjonen - - -## -## Date and time functions Dato- og tidsfunksjoner -## -DATE = DATO ## Returnerer serienummeret som svarer til en bestemt dato -DATEVALUE = DATOVERDI ## Konverterer en dato med tekstformat til et serienummer -DAY = DAG ## Konverterer et serienummer til en dag i måneden -DAYS360 = DAGER360 ## Beregner antall dager mellom to datoer basert på et år med 360 dager -EDATE = DAG.ETTER ## Returnerer serienummeret som svarer til datoen som er det indikerte antall måneder før eller etter startdatoen -EOMONTH = MÅNEDSSLUTT ## Returnerer serienummeret som svarer til siste dag i måneden, før eller etter et angitt antall måneder -HOUR = TIME ## Konverterer et serienummer til en time -MINUTE = MINUTT ## Konverterer et serienummer til et minutt -MONTH = MÅNED ## Konverterer et serienummer til en måned -NETWORKDAYS = NETT.ARBEIDSDAGER ## Returnerer antall hele arbeidsdager mellom to datoer -NOW = NÅ ## Returnerer serienummeret som svarer til gjeldende dato og klokkeslett -SECOND = SEKUND ## Konverterer et serienummer til et sekund -TIME = TID ## Returnerer serienummeret som svarer til et bestemt klokkeslett -TIMEVALUE = TIDSVERDI ## Konverterer et klokkeslett i tekstformat til et serienummer -TODAY = IDAG ## Returnerer serienummeret som svarer til dagens dato -WEEKDAY = UKEDAG ## Konverterer et serienummer til en ukedag -WEEKNUM = UKENR ## Konverterer et serienummer til et tall som representerer hvilket nummer uken har i et år -WORKDAY = ARBEIDSDAG ## Returnerer serienummeret som svarer til datoen før eller etter et angitt antall arbeidsdager -YEAR = ÅR ## Konverterer et serienummer til et år -YEARFRAC = ÅRDEL ## Returnerer brøkdelen for året, som svarer til antall hele dager mellom startdato og sluttdato - - -## -## Engineering functions Tekniske funksjoner -## -BESSELI = BESSELI ## Returnerer den endrede Bessel-funksjonen In(x) -BESSELJ = BESSELJ ## Returnerer Bessel-funksjonen Jn(x) -BESSELK = BESSELK ## Returnerer den endrede Bessel-funksjonen Kn(x) -BESSELY = BESSELY ## Returnerer Bessel-funksjonen Yn(x) -BIN2DEC = BINTILDES ## Konverterer et binært tall til et desimaltall -BIN2HEX = BINTILHEKS ## Konverterer et binært tall til et heksadesimaltall -BIN2OCT = BINTILOKT ## Konverterer et binært tall til et oktaltall -COMPLEX = KOMPLEKS ## Konverterer reelle og imaginære koeffisienter til et komplekst tall -CONVERT = KONVERTER ## Konverterer et tall fra ett målsystem til et annet -DEC2BIN = DESTILBIN ## Konverterer et desimaltall til et binærtall -DEC2HEX = DESTILHEKS ## Konverterer et heltall i 10-tallsystemet til et heksadesimalt tall -DEC2OCT = DESTILOKT ## Konverterer et heltall i 10-tallsystemet til et oktaltall -DELTA = DELTA ## Undersøker om to verdier er like -ERF = FEILF ## Returnerer feilfunksjonen -ERFC = FEILFK ## Returnerer den komplementære feilfunksjonen -GESTEP = GRENSEVERDI ## Tester om et tall er større enn en terskelverdi -HEX2BIN = HEKSTILBIN ## Konverterer et heksadesimaltall til et binært tall -HEX2DEC = HEKSTILDES ## Konverterer et heksadesimalt tall til et heltall i 10-tallsystemet -HEX2OCT = HEKSTILOKT ## Konverterer et heksadesimalt tall til et oktaltall -IMABS = IMABS ## Returnerer absoluttverdien (koeffisienten) til et komplekst tall -IMAGINARY = IMAGINÆR ## Returnerer den imaginære koeffisienten til et komplekst tall -IMARGUMENT = IMARGUMENT ## Returnerer argumentet theta, som er en vinkel uttrykt i radianer -IMCONJUGATE = IMKONJUGERT ## Returnerer den komplekse konjugaten til et komplekst tall -IMCOS = IMCOS ## Returnerer cosinus til et komplekst tall -IMDIV = IMDIV ## Returnerer kvotienten til to komplekse tall -IMEXP = IMEKSP ## Returnerer eksponenten til et komplekst tall -IMLN = IMLN ## Returnerer den naturlige logaritmen for et komplekst tall -IMLOG10 = IMLOG10 ## Returnerer logaritmen med grunntall 10 for et komplekst tall -IMLOG2 = IMLOG2 ## Returnerer logaritmen med grunntall 2 for et komplekst tall -IMPOWER = IMOPPHØY ## Returnerer et komplekst tall opphøyd til en heltallspotens -IMPRODUCT = IMPRODUKT ## Returnerer produktet av komplekse tall -IMREAL = IMREELL ## Returnerer den reelle koeffisienten til et komplekst tall -IMSIN = IMSIN ## Returnerer sinus til et komplekst tall -IMSQRT = IMROT ## Returnerer kvadratroten av et komplekst tall -IMSUB = IMSUB ## Returnerer differansen mellom to komplekse tall -IMSUM = IMSUMMER ## Returnerer summen av komplekse tall -OCT2BIN = OKTTILBIN ## Konverterer et oktaltall til et binært tall -OCT2DEC = OKTTILDES ## Konverterer et oktaltall til et desimaltall -OCT2HEX = OKTTILHEKS ## Konverterer et oktaltall til et heksadesimaltall - - -## -## Financial functions Økonomiske funksjoner -## -ACCRINT = PÅLØPT.PERIODISK.RENTE ## Returnerer påløpte renter for et verdipapir som betaler periodisk rente -ACCRINTM = PÅLØPT.FORFALLSRENTE ## Returnerer den påløpte renten for et verdipapir som betaler rente ved forfall -AMORDEGRC = AMORDEGRC ## Returnerer avskrivningen for hver regnskapsperiode ved hjelp av en avskrivingskoeffisient -AMORLINC = AMORLINC ## Returnerer avskrivingen for hver regnskapsperiode -COUPDAYBS = OBLIG.DAGER.FF ## Returnerer antall dager fra begynnelsen av den rentebærende perioden til innløsningsdatoen -COUPDAYS = OBLIG.DAGER ## Returnerer antall dager i den rentebærende perioden som inneholder innløsningsdatoen -COUPDAYSNC = OBLIG.DAGER.NF ## Returnerer antall dager fra betalingsdato til neste renteinnbetalingsdato -COUPNCD = OBLIG.DAGER.EF ## Returnerer obligasjonsdatoen som kommer etter oppgjørsdatoen -COUPNUM = OBLIG.ANTALL ## Returnerer antall obligasjoner som skal betales mellom oppgjørsdatoen og forfallsdatoen -COUPPCD = OBLIG.DAG.FORRIGE ## Returnerer obligasjonsdatoen som kommer før oppgjørsdatoen -CUMIPMT = SAMLET.RENTE ## Returnerer den kumulative renten som er betalt mellom to perioder -CUMPRINC = SAMLET.HOVEDSTOL ## Returnerer den kumulative hovedstolen som er betalt for et lån mellom to perioder -DB = DAVSKR ## Returnerer avskrivningen for et aktivum i en angitt periode, foretatt med fast degressiv avskrivning -DDB = DEGRAVS ## Returnerer avskrivningen for et aktivum for en gitt periode, ved hjelp av dobbel degressiv avskrivning eller en metode som du selv angir -DISC = DISKONTERT ## Returnerer diskonteringsraten for et verdipapir -DOLLARDE = DOLLARDE ## Konverterer en valutapris uttrykt som en brøk, til en valutapris uttrykt som et desimaltall -DOLLARFR = DOLLARBR ## Konverterer en valutapris uttrykt som et desimaltall, til en valutapris uttrykt som en brøk -DURATION = VARIGHET ## Returnerer årlig varighet for et verdipapir med renter som betales periodisk -EFFECT = EFFEKTIV.RENTE ## Returnerer den effektive årlige rentesatsen -FV = SLUTTVERDI ## Returnerer fremtidig verdi for en investering -FVSCHEDULE = SVPLAN ## Returnerer den fremtidige verdien av en inngående hovedstol etter å ha anvendt en serie med sammensatte rentesatser -INTRATE = RENTESATS ## Returnerer rentefoten av et fullfinansiert verdipapir -IPMT = RAVDRAG ## Returnerer betalte renter på en investering for en gitt periode -IRR = IR ## Returnerer internrenten for en serie kontantstrømmer -ISPMT = ER.AVDRAG ## Beregner renten som er betalt for en investering i løpet av en bestemt periode -MDURATION = MVARIGHET ## Returnerer Macauleys modifiserte varighet for et verdipapir med en antatt pålydende verdi på kr 100,00 -MIRR = MODIR ## Returnerer internrenten der positive og negative kontantstrømmer finansieres med forskjellige satser -NOMINAL = NOMINELL ## Returnerer årlig nominell rentesats -NPER = PERIODER ## Returnerer antall perioder for en investering -NPV = NNV ## Returnerer netto nåverdi for en investering, basert på en serie periodiske kontantstrømmer og en rentesats -ODDFPRICE = AVVIKFP.PRIS ## Returnerer pris pålydende kr 100 for et verdipapir med en odde første periode -ODDFYIELD = AVVIKFP.AVKASTNING ## Returnerer avkastingen for et verdipapir med en odde første periode -ODDLPRICE = AVVIKSP.PRIS ## Returnerer pris pålydende kr 100 for et verdipapir med en odde siste periode -ODDLYIELD = AVVIKSP.AVKASTNING ## Returnerer avkastingen for et verdipapir med en odde siste periode -PMT = AVDRAG ## Returnerer periodisk betaling for en annuitet -PPMT = AMORT ## Returnerer betalingen på hovedstolen for en investering i en gitt periode -PRICE = PRIS ## Returnerer prisen per pålydende kr 100 for et verdipapir som gir periodisk avkastning -PRICEDISC = PRIS.DISKONTERT ## Returnerer prisen per pålydende kr 100 for et diskontert verdipapir -PRICEMAT = PRIS.FORFALL ## Returnerer prisen per pålydende kr 100 av et verdipapir som betaler rente ved forfall -PV = NÅVERDI ## Returnerer nåverdien av en investering -RATE = RENTE ## Returnerer rentesatsen per periode for en annuitet -RECEIVED = MOTTATT.AVKAST ## Returnerer summen som mottas ved forfallsdato for et fullinvestert verdipapir -SLN = LINAVS ## Returnerer den lineære avskrivningen for et aktivum i én periode -SYD = ÅRSAVS ## Returnerer årsavskrivningen for et aktivum i en angitt periode -TBILLEQ = TBILLEKV ## Returnerer den obligasjonsekvivalente avkastningen for en statsobligasjon -TBILLPRICE = TBILLPRIS ## Returnerer prisen per pålydende kr 100 for en statsobligasjon -TBILLYIELD = TBILLAVKASTNING ## Returnerer avkastningen til en statsobligasjon -VDB = VERDIAVS ## Returnerer avskrivningen for et aktivum i en angitt periode eller delperiode, ved hjelp av degressiv avskrivning -XIRR = XIR ## Returnerer internrenten for en serie kontantstrømmer som ikke nødvendigvis er periodiske -XNPV = XNNV ## Returnerer netto nåverdi for en serie kontantstrømmer som ikke nødvendigvis er periodiske -YIELD = AVKAST ## Returnerer avkastningen på et verdipapir som betaler periodisk rente -YIELDDISC = AVKAST.DISKONTERT ## Returnerer årlig avkastning for et diskontert verdipapir, for eksempel en statskasseveksel -YIELDMAT = AVKAST.FORFALL ## Returnerer den årlige avkastningen for et verdipapir som betaler rente ved forfallsdato - - -## -## Information functions Informasjonsfunksjoner -## -CELL = CELLE ## Returnerer informasjon om formatering, plassering eller innholdet til en celle -ERROR.TYPE = FEIL.TYPE ## Returnerer et tall som svarer til en feiltype -INFO = INFO ## Returnerer informasjon om gjeldende operativmiljø -ISBLANK = ERTOM ## Returnerer SANN hvis verdien er tom -ISERR = ERFEIL ## Returnerer SANN hvis verdien er en hvilken som helst annen feilverdi enn #I/T -ISERROR = ERFEIL ## Returnerer SANN hvis verdien er en hvilken som helst feilverdi -ISEVEN = ERPARTALL ## Returnerer SANN hvis tallet er et partall -ISLOGICAL = ERLOGISK ## Returnerer SANN hvis verdien er en logisk verdi -ISNA = ERIT ## Returnerer SANN hvis verdien er feilverdien #I/T -ISNONTEXT = ERIKKETEKST ## Returnerer SANN hvis verdien ikke er tekst -ISNUMBER = ERTALL ## Returnerer SANN hvis verdien er et tall -ISODD = ERODDETALL ## Returnerer SANN hvis tallet er et oddetall -ISREF = ERREF ## Returnerer SANN hvis verdien er en referanse -ISTEXT = ERTEKST ## Returnerer SANN hvis verdien er tekst -N = N ## Returnerer en verdi som er konvertert til et tall -NA = IT ## Returnerer feilverdien #I/T -TYPE = VERDITYPE ## Returnerer et tall som indikerer datatypen til en verdi - - -## -## Logical functions Logiske funksjoner -## -AND = OG ## Returnerer SANN hvis alle argumentene er lik SANN -FALSE = USANN ## Returnerer den logiske verdien USANN -IF = HVIS ## Angir en logisk test som skal utføres -IFERROR = HVISFEIL ## Returnerer en verdi du angir hvis en formel evaluerer til en feil. Ellers returnerer den resultatet av formelen. -NOT = IKKE ## Reverserer logikken til argumentet -OR = ELLER ## Returnerer SANN hvis ett eller flere argumenter er lik SANN -TRUE = SANN ## Returnerer den logiske verdien SANN - - -## -## Lookup and reference functions Oppslag- og referansefunksjoner -## -ADDRESS = ADRESSE ## Returnerer en referanse som tekst til en enkelt celle i et regneark -AREAS = OMRÅDER ## Returnerer antall områder i en referanse -CHOOSE = VELG ## Velger en verdi fra en liste med verdier -COLUMN = KOLONNE ## Returnerer kolonnenummeret for en referanse -COLUMNS = KOLONNER ## Returnerer antall kolonner i en referanse -HLOOKUP = FINN.KOLONNE ## Leter i den øverste raden i en matrise og returnerer verdien for den angitte cellen -HYPERLINK = HYPERKOBLING ## Oppretter en snarvei eller et hopp som åpner et dokument som er lagret på en nettverksserver, et intranett eller Internett -INDEX = INDEKS ## Bruker en indeks til å velge en verdi fra en referanse eller matrise -INDIRECT = INDIREKTE ## Returnerer en referanse angitt av en tekstverdi -LOOKUP = SLÅ.OPP ## Slår opp verdier i en vektor eller matrise -MATCH = SAMMENLIGNE ## Slår opp verdier i en referanse eller matrise -OFFSET = FORSKYVNING ## Returnerer en referanseforskyvning fra en gitt referanse -ROW = RAD ## Returnerer radnummeret for en referanse -ROWS = RADER ## Returnerer antall rader i en referanse -RTD = RTD ## Henter sanntidsdata fra et program som støtter COM-automatisering (automatisering: En måte å arbeide på med programobjekter fra et annet program- eller utviklingsverktøy. Tidligere kalt OLE-automatisering. Automatisering er en bransjestandard og en funksjon i Component Object Model (COM).) -TRANSPOSE = TRANSPONER ## Returnerer transponeringen av en matrise -VLOOKUP = FINN.RAD ## Leter i den første kolonnen i en matrise og flytter bortover raden for å returnere verdien til en celle - - -## -## Math and trigonometry functions Matematikk- og trigonometrifunksjoner -## -ABS = ABS ## Returnerer absoluttverdien til et tall -ACOS = ARCCOS ## Returnerer arcus cosinus til et tall -ACOSH = ARCCOSH ## Returnerer den inverse hyperbolske cosinus til et tall -ASIN = ARCSIN ## Returnerer arcus sinus til et tall -ASINH = ARCSINH ## Returnerer den inverse hyperbolske sinus til et tall -ATAN = ARCTAN ## Returnerer arcus tangens til et tall -ATAN2 = ARCTAN2 ## Returnerer arcus tangens fra x- og y-koordinater -ATANH = ARCTANH ## Returnerer den inverse hyperbolske tangens til et tall -CEILING = AVRUND.GJELDENDE.MULTIPLUM ## Runder av et tall til nærmeste heltall eller til nærmeste signifikante multiplum -COMBIN = KOMBINASJON ## Returnerer antall kombinasjoner for ett gitt antall objekter -COS = COS ## Returnerer cosinus til et tall -COSH = COSH ## Returnerer den hyperbolske cosinus til et tall -DEGREES = GRADER ## Konverterer radianer til grader -EVEN = AVRUND.TIL.PARTALL ## Runder av et tall oppover til nærmeste heltall som er et partall -EXP = EKSP ## Returnerer e opphøyd i en angitt potens -FACT = FAKULTET ## Returnerer fakultet til et tall -FACTDOUBLE = DOBBELFAKT ## Returnerer et talls doble fakultet -FLOOR = AVRUND.GJELDENDE.MULTIPLUM.NED ## Avrunder et tall nedover, mot null -GCD = SFF ## Returnerer høyeste felles divisor -INT = HELTALL ## Avrunder et tall nedover til nærmeste heltall -LCM = MFM ## Returnerer minste felles multiplum -LN = LN ## Returnerer den naturlige logaritmen til et tall -LOG = LOG ## Returnerer logaritmen for et tall til et angitt grunntall -LOG10 = LOG10 ## Returnerer logaritmen med grunntall 10 for et tall -MDETERM = MDETERM ## Returnerer matrisedeterminanten til en matrise -MINVERSE = MINVERS ## Returnerer den inverse matrisen til en matrise -MMULT = MMULT ## Returnerer matriseproduktet av to matriser -MOD = REST ## Returnerer resten fra en divisjon -MROUND = MRUND ## Returnerer et tall avrundet til det ønskede multiplum -MULTINOMIAL = MULTINOMINELL ## Returnerer det multinominelle for et sett med tall -ODD = AVRUND.TIL.ODDETALL ## Runder av et tall oppover til nærmeste heltall som er et oddetall -PI = PI ## Returnerer verdien av pi -POWER = OPPHØYD.I ## Returnerer resultatet av et tall opphøyd i en potens -PRODUCT = PRODUKT ## Multipliserer argumentene -QUOTIENT = KVOTIENT ## Returnerer heltallsdelen av en divisjon -RADIANS = RADIANER ## Konverterer grader til radianer -RAND = TILFELDIG ## Returnerer et tilfeldig tall mellom 0 og 1 -RANDBETWEEN = TILFELDIGMELLOM ## Returnerer et tilfeldig tall innenfor et angitt område -ROMAN = ROMERTALL ## Konverterer vanlige tall til romertall, som tekst -ROUND = AVRUND ## Avrunder et tall til et angitt antall sifre -ROUNDDOWN = AVRUND.NED ## Avrunder et tall nedover, mot null -ROUNDUP = AVRUND.OPP ## Runder av et tall oppover, bort fra null -SERIESSUM = SUMMER.REKKE ## Returnerer summen av en geometrisk rekke, basert på formelen -SIGN = FORTEGN ## Returnerer fortegnet for et tall -SIN = SIN ## Returnerer sinus til en gitt vinkel -SINH = SINH ## Returnerer den hyperbolske sinus til et tall -SQRT = ROT ## Returnerer en positiv kvadratrot -SQRTPI = ROTPI ## Returnerer kvadratroten av (tall * pi) -SUBTOTAL = DELSUM ## Returnerer en delsum i en liste eller database -SUM = SUMMER ## Legger sammen argumentene -SUMIF = SUMMERHVIS ## Legger sammen cellene angitt ved et gitt vilkår -SUMIFS = SUMMER.HVIS.SETT ## Legger sammen cellene i et område som oppfyller flere vilkår -SUMPRODUCT = SUMMERPRODUKT ## Returnerer summen av produktene av tilsvarende matrisekomponenter -SUMSQ = SUMMERKVADRAT ## Returnerer kvadratsummen av argumentene -SUMX2MY2 = SUMMERX2MY2 ## Returnerer summen av differansen av kvadratene for tilsvarende verdier i to matriser -SUMX2PY2 = SUMMERX2PY2 ## Returnerer summen av kvadratsummene for tilsvarende verdier i to matriser -SUMXMY2 = SUMMERXMY2 ## Returnerer summen av kvadratene av differansen for tilsvarende verdier i to matriser -TAN = TAN ## Returnerer tangens for et tall -TANH = TANH ## Returnerer den hyperbolske tangens for et tall -TRUNC = AVKORT ## Korter av et tall til et heltall - - -## -## Statistical functions Statistiske funksjoner -## -AVEDEV = GJENNOMSNITTSAVVIK ## Returnerer datapunktenes gjennomsnittlige absoluttavvik fra middelverdien -AVERAGE = GJENNOMSNITT ## Returnerer gjennomsnittet for argumentene -AVERAGEA = GJENNOMSNITTA ## Returnerer gjennomsnittet for argumentene, inkludert tall, tekst og logiske verdier -AVERAGEIF = GJENNOMSNITTHVIS ## Returnerer gjennomsnittet (aritmetisk gjennomsnitt) av alle cellene i et område som oppfyller et bestemt vilkår -AVERAGEIFS = GJENNOMSNITT.HVIS.SETT ## Returnerer gjennomsnittet (aritmetisk middelverdi) av alle celler som oppfyller flere vilkår. -BETADIST = BETA.FORDELING ## Returnerer den kumulative betafordelingsfunksjonen -BETAINV = INVERS.BETA.FORDELING ## Returnerer den inverse verdien til fordelingsfunksjonen for en angitt betafordeling -BINOMDIST = BINOM.FORDELING ## Returnerer den individuelle binomiske sannsynlighetsfordelingen -CHIDIST = KJI.FORDELING ## Returnerer den ensidige sannsynligheten for en kjikvadrert fordeling -CHIINV = INVERS.KJI.FORDELING ## Returnerer den inverse av den ensidige sannsynligheten for den kjikvadrerte fordelingen -CHITEST = KJI.TEST ## Utfører testen for uavhengighet -CONFIDENCE = KONFIDENS ## Returnerer konfidensintervallet til gjennomsnittet for en populasjon -CORREL = KORRELASJON ## Returnerer korrelasjonskoeffisienten mellom to datasett -COUNT = ANTALL ## Teller hvor mange tall som er i argumentlisten -COUNTA = ANTALLA ## Teller hvor mange verdier som er i argumentlisten -COUNTBLANK = TELLBLANKE ## Teller antall tomme celler i et område. -COUNTIF = ANTALL.HVIS ## Teller antall celler i et område som oppfyller gitte vilkår -COUNTIFS = ANTALL.HVIS.SETT ## Teller antallet ikke-tomme celler i et område som oppfyller flere vilkår -COVAR = KOVARIANS ## Returnerer kovariansen, gjennomsnittet av produktene av parvise avvik -CRITBINOM = GRENSE.BINOM ## Returnerer den minste verdien der den kumulative binomiske fordelingen er mindre enn eller lik en vilkårsverdi -DEVSQ = AVVIK.KVADRERT ## Returnerer summen av kvadrerte avvik -EXPONDIST = EKSP.FORDELING ## Returnerer eksponentialfordelingen -FDIST = FFORDELING ## Returnerer F-sannsynlighetsfordelingen -FINV = FFORDELING.INVERS ## Returnerer den inverse av den sannsynlige F-fordelingen -FISHER = FISHER ## Returnerer Fisher-transformasjonen -FISHERINV = FISHERINV ## Returnerer den inverse av Fisher-transformasjonen -FORECAST = PROGNOSE ## Returnerer en verdi langs en lineær trend -FREQUENCY = FREKVENS ## Returnerer en frekvensdistribusjon som en loddrett matrise -FTEST = FTEST ## Returnerer resultatet av en F-test -GAMMADIST = GAMMAFORDELING ## Returnerer gammafordelingen -GAMMAINV = GAMMAINV ## Returnerer den inverse av den gammakumulative fordelingen -GAMMALN = GAMMALN ## Returnerer den naturlige logaritmen til gammafunksjonen G(x) -GEOMEAN = GJENNOMSNITT.GEOMETRISK ## Returnerer den geometriske middelverdien -GROWTH = VEKST ## Returnerer verdier langs en eksponentiell trend -HARMEAN = GJENNOMSNITT.HARMONISK ## Returnerer den harmoniske middelverdien -HYPGEOMDIST = HYPGEOM.FORDELING ## Returnerer den hypergeometriske fordelingen -INTERCEPT = SKJÆRINGSPUNKT ## Returnerer skjæringspunktet til den lineære regresjonslinjen -KURT = KURT ## Returnerer kurtosen til et datasett -LARGE = N.STØRST ## Returnerer den n-te største verdien i et datasett -LINEST = RETTLINJE ## Returnerer parameterne til en lineær trend -LOGEST = KURVE ## Returnerer parameterne til en eksponentiell trend -LOGINV = LOGINV ## Returnerer den inverse lognormale fordelingen -LOGNORMDIST = LOGNORMFORD ## Returnerer den kumulative lognormale fordelingen -MAX = STØRST ## Returnerer maksimumsverdien i en argumentliste -MAXA = MAKSA ## Returnerer maksimumsverdien i en argumentliste, inkludert tall, tekst og logiske verdier -MEDIAN = MEDIAN ## Returnerer medianen til tallene som er gitt -MIN = MIN ## Returnerer minimumsverdien i en argumentliste -MINA = MINA ## Returnerer den minste verdien i en argumentliste, inkludert tall, tekst og logiske verdier -MODE = MODUS ## Returnerer den vanligste verdien i et datasett -NEGBINOMDIST = NEGBINOM.FORDELING ## Returnerer den negative binomiske fordelingen -NORMDIST = NORMALFORDELING ## Returnerer den kumulative normalfordelingen -NORMINV = NORMINV ## Returnerer den inverse kumulative normalfordelingen -NORMSDIST = NORMSFORDELING ## Returnerer standard kumulativ normalfordeling -NORMSINV = NORMSINV ## Returnerer den inverse av den den kumulative standard normalfordelingen -PEARSON = PEARSON ## Returnerer produktmomentkorrelasjonskoeffisienten, Pearson -PERCENTILE = PERSENTIL ## Returnerer den n-te persentil av verdiene i et område -PERCENTRANK = PROSENTDEL ## Returnerer prosentrangeringen av en verdi i et datasett -PERMUT = PERMUTER ## Returnerer antall permutasjoner for et gitt antall objekter -POISSON = POISSON ## Returnerer Poissons sannsynlighetsfordeling -PROB = SANNSYNLIG ## Returnerer sannsynligheten for at verdier i et område ligger mellom to grenser -QUARTILE = KVARTIL ## Returnerer kvartilen til et datasett -RANK = RANG ## Returnerer rangeringen av et tall, eller plassen tallet har i en rekke -RSQ = RKVADRAT ## Returnerer kvadratet av produktmomentkorrelasjonskoeffisienten (Pearsons r) -SKEW = SKJEVFORDELING ## Returnerer skjevheten i en fordeling -SLOPE = STIGNINGSTALL ## Returnerer stigningtallet for den lineære regresjonslinjen -SMALL = N.MINST ## Returnerer den n-te minste verdien i et datasett -STANDARDIZE = NORMALISER ## Returnerer en normalisert verdi -STDEV = STDAV ## Estimere standardavvik på grunnlag av et utvalg -STDEVA = STDAVVIKA ## Estimerer standardavvik basert på et utvalg, inkludert tall, tekst og logiske verdier -STDEVP = STDAVP ## Beregner standardavvik basert på hele populasjonen -STDEVPA = STDAVVIKPA ## Beregner standardavvik basert på hele populasjonen, inkludert tall, tekst og logiske verdier -STEYX = STANDARDFEIL ## Returnerer standardfeilen for den predikerte y-verdien for hver x i regresjonen -TDIST = TFORDELING ## Returnerer en Student t-fordeling -TINV = TINV ## Returnerer den inverse Student t-fordelingen -TREND = TREND ## Returnerer verdier langs en lineær trend -TRIMMEAN = TRIMMET.GJENNOMSNITT ## Returnerer den interne middelverdien til et datasett -TTEST = TTEST ## Returnerer sannsynligheten assosiert med en Student t-test -VAR = VARIANS ## Estimerer varians basert på et utvalg -VARA = VARIANSA ## Estimerer varians basert på et utvalg, inkludert tall, tekst og logiske verdier -VARP = VARIANSP ## Beregner varians basert på hele populasjonen -VARPA = VARIANSPA ## Beregner varians basert på hele populasjonen, inkludert tall, tekst og logiske verdier -WEIBULL = WEIBULL.FORDELING ## Returnerer Weibull-fordelingen -ZTEST = ZTEST ## Returnerer den ensidige sannsynlighetsverdien for en z-test - - -## -## Text functions Tekstfunksjoner -## -ASC = STIGENDE ## Endrer fullbreddes (dobbeltbyte) engelske bokstaver eller katakana i en tegnstreng, til halvbreddes (enkeltbyte) tegn -BAHTTEXT = BAHTTEKST ## Konverterer et tall til tekst, og bruker valutaformatet ß (baht) -CHAR = TEGNKODE ## Returnerer tegnet som svarer til kodenummeret -CLEAN = RENSK ## Fjerner alle tegn som ikke kan skrives ut, fra teksten -CODE = KODE ## Returnerer en numerisk kode for det første tegnet i en tekststreng -CONCATENATE = KJEDE.SAMMEN ## Slår sammen flere tekstelementer til ett tekstelement -DOLLAR = VALUTA ## Konverterer et tall til tekst, og bruker valutaformatet $ (dollar) -EXACT = EKSAKT ## Kontrollerer om to tekstverdier er like -FIND = FINN ## Finner en tekstverdi inne i en annen (skiller mellom store og små bokstaver) -FINDB = FINNB ## Finner en tekstverdi inne i en annen (skiller mellom store og små bokstaver) -FIXED = FASTSATT ## Formaterer et tall som tekst med et bestemt antall desimaler -JIS = JIS ## Endrer halvbreddes (enkeltbyte) engelske bokstaver eller katakana i en tegnstreng, til fullbreddes (dobbeltbyte) tegn -LEFT = VENSTRE ## Returnerer tegnene lengst til venstre i en tekstverdi -LEFTB = VENSTREB ## Returnerer tegnene lengst til venstre i en tekstverdi -LEN = LENGDE ## Returnerer antall tegn i en tekststreng -LENB = LENGDEB ## Returnerer antall tegn i en tekststreng -LOWER = SMÅ ## Konverterer tekst til små bokstaver -MID = DELTEKST ## Returnerer et angitt antall tegn fra en tekststreng, og begynner fra posisjonen du angir -MIDB = DELTEKSTB ## Returnerer et angitt antall tegn fra en tekststreng, og begynner fra posisjonen du angir -PHONETIC = FURIGANA ## Trekker ut fonetiske tegn (furigana) fra en tekststreng -PROPER = STOR.FORBOKSTAV ## Gir den første bokstaven i hvert ord i en tekstverdi stor forbokstav -REPLACE = ERSTATT ## Erstatter tegn i en tekst -REPLACEB = ERSTATTB ## Erstatter tegn i en tekst -REPT = GJENTA ## Gjentar tekst et gitt antall ganger -RIGHT = HØYRE ## Returnerer tegnene lengst til høyre i en tekstverdi -RIGHTB = HØYREB ## Returnerer tegnene lengst til høyre i en tekstverdi -SEARCH = SØK ## Finner en tekstverdi inne i en annen (skiller ikke mellom store og små bokstaver) -SEARCHB = SØKB ## Finner en tekstverdi inne i en annen (skiller ikke mellom store og små bokstaver) -SUBSTITUTE = BYTT.UT ## Bytter ut gammel tekst med ny tekst i en tekststreng -T = T ## Konverterer argumentene til tekst -TEXT = TEKST ## Formaterer et tall og konverterer det til tekst -TRIM = TRIMME ## Fjerner mellomrom fra tekst -UPPER = STORE ## Konverterer tekst til store bokstaver -VALUE = VERDI ## Konverterer et tekstargument til et tall diff --git a/src/PhpSpreadsheet/Calculation/locale/pl/config b/src/PhpSpreadsheet/Calculation/locale/pl/config index 00f8b9a3..1d8468ba 100644 --- a/src/PhpSpreadsheet/Calculation/locale/pl/config +++ b/src/PhpSpreadsheet/Calculation/locale/pl/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## +## Jezyk polski (Polish) +## +############################################################ -ArgumentSeparator = ; - +ArgumentSeparator = ; ## -## (For future use) +## Error Codes ## -currencySymbol = zł - - -## -## Excel Error Codes (For future use) - -## -NULL = #ZERO! -DIV0 = #DZIEL/0! -VALUE = #ARG! -REF = #ADR! -NAME = #NAZWA? -NUM = #LICZBA! -NA = #N/D! +NULL = #ZERO! +DIV0 = #DZIEL/0! +VALUE = #ARG! +REF = #ADR! +NAME = #NAZWA? +NUM = #LICZBA! +NA = #N/D! diff --git a/src/PhpSpreadsheet/Calculation/locale/pl/functions b/src/PhpSpreadsheet/Calculation/locale/pl/functions index 907a4ff0..d1b43b2e 100644 --- a/src/PhpSpreadsheet/Calculation/locale/pl/functions +++ b/src/PhpSpreadsheet/Calculation/locale/pl/functions @@ -1,416 +1,536 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Jezyk polski (Polish) ## +############################################################ ## -## Add-in and Automation functions Funkcje dodatków i automatyzacji +## Funkcje baz danych (Cube Functions) ## -GETPIVOTDATA = WEŹDANETABELI ## Zwraca dane przechowywane w raporcie tabeli przestawnej. - +CUBEKPIMEMBER = ELEMENT.KPI.MODUŁU +CUBEMEMBER = ELEMENT.MODUŁU +CUBEMEMBERPROPERTY = WŁAŚCIWOŚĆ.ELEMENTU.MODUŁU +CUBERANKEDMEMBER = USZEREGOWANY.ELEMENT.MODUŁU +CUBESET = ZESTAW.MODUŁÓW +CUBESETCOUNT = LICZNIK.MODUŁÓW.ZESTAWU +CUBEVALUE = WARTOŚĆ.MODUŁU ## -## Cube functions Funkcje modułów +## Funkcje baz danych (Database Functions) ## -CUBEKPIMEMBER = ELEMENT.KPI.MODUŁU ## Zwraca nazwę, właściwość i miarę kluczowego wskaźnika wydajności (KPI) oraz wyświetla nazwę i właściwość w komórce. Wskaźnik KPI jest miarą ilościową, taką jak miesięczny zysk brutto lub kwartalna fluktuacja pracowników, używaną do monitorowania wydajności organizacji. -CUBEMEMBER = ELEMENT.MODUŁU ## Zwraca element lub krotkę z hierarchii modułu. Służy do sprawdzania, czy element lub krotka istnieje w module. -CUBEMEMBERPROPERTY = WŁAŚCIWOŚĆ.ELEMENTU.MODUŁU ## Zwraca wartość właściwości elementu w module. Służy do sprawdzania, czy nazwa elementu istnieje w module, i zwracania określonej właściwości dla tego elementu. -CUBERANKEDMEMBER = USZEREGOWANY.ELEMENT.MODUŁU ## Zwraca n-ty (albo uszeregowany) element zestawu. Służy do zwracania elementu lub elementów zestawu, na przykład najlepszego sprzedawcy lub 10 najlepszych studentów. -CUBESET = ZESTAW.MODUŁÓW ## Definiuje obliczony zestaw elementów lub krotek, wysyłając wyrażenie zestawu do serwera modułu, który tworzy zestaw i zwraca go do programu Microsoft Office Excel. -CUBESETCOUNT = LICZNIK.MODUŁÓW.ZESTAWU ## Zwraca liczbę elementów zestawu. -CUBEVALUE = WARTOŚĆ.MODUŁU ## Zwraca zagregowaną wartość z modułu. - +DAVERAGE = BD.ŚREDNIA +DCOUNT = BD.ILE.REKORDÓW +DCOUNTA = BD.ILE.REKORDÓW.A +DGET = BD.POLE +DMAX = BD.MAX +DMIN = BD.MIN +DPRODUCT = BD.ILOCZYN +DSTDEV = BD.ODCH.STANDARD +DSTDEVP = BD.ODCH.STANDARD.POPUL +DSUM = BD.SUMA +DVAR = BD.WARIANCJA +DVARP = BD.WARIANCJA.POPUL ## -## Database functions Funkcje baz danych +## Funkcje daty i godziny (Date & Time Functions) ## -DAVERAGE = BD.ŚREDNIA ## Zwraca wartość średniej wybranych wpisów bazy danych. -DCOUNT = BD.ILE.REKORDÓW ## Zlicza komórki zawierające liczby w bazie danych. -DCOUNTA = BD.ILE.REKORDÓW.A ## Zlicza niepuste komórki w bazie danych. -DGET = BD.POLE ## Wyodrębnia z bazy danych jeden rekord spełniający określone kryteria. -DMAX = BD.MAX ## Zwraca wartość maksymalną z wybranych wpisów bazy danych. -DMIN = BD.MIN ## Zwraca wartość minimalną z wybranych wpisów bazy danych. -DPRODUCT = BD.ILOCZYN ## Mnoży wartości w konkretnym, spełniającym kryteria polu rekordów bazy danych. -DSTDEV = BD.ODCH.STANDARD ## Szacuje odchylenie standardowe na podstawie próbki z wybranych wpisów bazy danych. -DSTDEVP = BD.ODCH.STANDARD.POPUL ## Oblicza odchylenie standardowe na podstawie całej populacji wybranych wpisów bazy danych. -DSUM = BD.SUMA ## Dodaje liczby w kolumnie pól rekordów bazy danych, które spełniają kryteria. -DVAR = BD.WARIANCJA ## Szacuje wariancję na podstawie próbki z wybranych wpisów bazy danych. -DVARP = BD.WARIANCJA.POPUL ## Oblicza wariancję na podstawie całej populacji wybranych wpisów bazy danych. - +DATE = DATA +DATEDIF = DATA.RÓŻNICA +DATESTRING = DATA.CIĄG.ZNAK +DATEVALUE = DATA.WARTOŚĆ +DAY = DZIEŃ +DAYS = DNI +DAYS360 = DNI.360 +EDATE = NR.SER.DATY +EOMONTH = NR.SER.OST.DN.MIES +HOUR = GODZINA +ISOWEEKNUM = ISO.NUM.TYG +MINUTE = MINUTA +MONTH = MIESIĄC +NETWORKDAYS = DNI.ROBOCZE +NETWORKDAYS.INTL = DNI.ROBOCZE.NIESTAND +NOW = TERAZ +SECOND = SEKUNDA +THAIDAYOFWEEK = TAJ.DZIEŃ.TYGODNIA +THAIMONTHOFYEAR = TAJ.MIESIĄC.ROKU +THAIYEAR = TAJ.ROK +TIME = CZAS +TIMEVALUE = CZAS.WARTOŚĆ +TODAY = DZIŚ +WEEKDAY = DZIEŃ.TYG +WEEKNUM = NUM.TYG +WORKDAY = DZIEŃ.ROBOCZY +WORKDAY.INTL = DZIEŃ.ROBOCZY.NIESTAND +YEAR = ROK +YEARFRAC = CZĘŚĆ.ROKU ## -## Date and time functions Funkcje dat, godzin i czasu +## Funkcje inżynierskie (Engineering Functions) ## -DATE = DATA ## Zwraca liczbę seryjną dla wybranej daty. -DATEVALUE = DATA.WARTOŚĆ ## Konwertuje datę w formie tekstu na liczbę seryjną. -DAY = DZIEŃ ## Konwertuje liczbę seryjną na dzień miesiąca. -DAYS360 = DNI.360 ## Oblicza liczbę dni między dwiema datami na podstawie roku 360-dniowego. -EDATE = UPŁDNI ## Zwraca liczbę seryjną daty jako wskazaną liczbę miesięcy przed określoną datą początkową lub po niej. -EOMONTH = EOMONTH ## Zwraca liczbę seryjną ostatniego dnia miesiąca przed określoną liczbą miesięcy lub po niej. -HOUR = GODZINA ## Konwertuje liczbę seryjną na godzinę. -MINUTE = MINUTA ## Konwertuje liczbę seryjną na minutę. -MONTH = MIESIĄC ## Konwertuje liczbę seryjną na miesiąc. -NETWORKDAYS = NETWORKDAYS ## Zwraca liczbę pełnych dni roboczych między dwiema datami. -NOW = TERAZ ## Zwraca liczbę seryjną bieżącej daty i godziny. -SECOND = SEKUNDA ## Konwertuje liczbę seryjną na sekundę. -TIME = CZAS ## Zwraca liczbę seryjną określonego czasu. -TIMEVALUE = CZAS.WARTOŚĆ ## Konwertuje czas w formie tekstu na liczbę seryjną. -TODAY = DZIŚ ## Zwraca liczbę seryjną dla daty bieżącej. -WEEKDAY = DZIEŃ.TYG ## Konwertuje liczbę seryjną na dzień tygodnia. -WEEKNUM = WEEKNUM ## Konwertuje liczbę seryjną na liczbę reprezentującą numer tygodnia w roku. -WORKDAY = WORKDAY ## Zwraca liczbę seryjną dla daty przed określoną liczbą dni roboczych lub po niej. -YEAR = ROK ## Konwertuje liczbę seryjną na rok. -YEARFRAC = YEARFRAC ## Zwraca część roku reprezentowaną przez pełną liczbę dni między datą początkową a datą końcową. - +BESSELI = BESSEL.I +BESSELJ = BESSEL.J +BESSELK = BESSEL.K +BESSELY = BESSEL.Y +BIN2DEC = DWÓJK.NA.DZIES +BIN2HEX = DWÓJK.NA.SZESN +BIN2OCT = DWÓJK.NA.ÓSM +BITAND = BITAND +BITLSHIFT = BIT.PRZESUNIĘCIE.W.LEWO +BITOR = BITOR +BITRSHIFT = BIT.PRZESUNIĘCIE.W.PRAWO +BITXOR = BITXOR +COMPLEX = LICZBA.ZESP +CONVERT = KONWERTUJ +DEC2BIN = DZIES.NA.DWÓJK +DEC2HEX = DZIES.NA.SZESN +DEC2OCT = DZIES.NA.ÓSM +DELTA = CZY.RÓWNE +ERF = FUNKCJA.BŁ +ERF.PRECISE = FUNKCJA.BŁ.DOKŁ +ERFC = KOMP.FUNKCJA.BŁ +ERFC.PRECISE = KOMP.FUNKCJA.BŁ.DOKŁ +GESTEP = SPRAWDŹ.PRÓG +HEX2BIN = SZESN.NA.DWÓJK +HEX2DEC = SZESN.NA.DZIES +HEX2OCT = SZESN.NA.ÓSM +IMABS = MODUŁ.LICZBY.ZESP +IMAGINARY = CZ.UROJ.LICZBY.ZESP +IMARGUMENT = ARG.LICZBY.ZESP +IMCONJUGATE = SPRZĘŻ.LICZBY.ZESP +IMCOS = COS.LICZBY.ZESP +IMCOSH = COSH.LICZBY.ZESP +IMCOT = COT.LICZBY.ZESP +IMCSC = CSC.LICZBY.ZESP +IMCSCH = CSCH.LICZBY.ZESP +IMDIV = ILORAZ.LICZB.ZESP +IMEXP = EXP.LICZBY.ZESP +IMLN = LN.LICZBY.ZESP +IMLOG10 = LOG10.LICZBY.ZESP +IMLOG2 = LOG2.LICZBY.ZESP +IMPOWER = POTĘGA.LICZBY.ZESP +IMPRODUCT = ILOCZYN.LICZB.ZESP +IMREAL = CZ.RZECZ.LICZBY.ZESP +IMSEC = SEC.LICZBY.ZESP +IMSECH = SECH.LICZBY.ZESP +IMSIN = SIN.LICZBY.ZESP +IMSINH = SINH.LICZBY.ZESP +IMSQRT = PIERWIASTEK.LICZBY.ZESP +IMSUB = RÓŻN.LICZB.ZESP +IMSUM = SUMA.LICZB.ZESP +IMTAN = TAN.LICZBY.ZESP +OCT2BIN = ÓSM.NA.DWÓJK +OCT2DEC = ÓSM.NA.DZIES +OCT2HEX = ÓSM.NA.SZESN ## -## Engineering functions Funkcje inżynierskie +## Funkcje finansowe (Financial Functions) ## -BESSELI = BESSELI ## Zwraca wartość zmodyfikowanej funkcji Bessela In(x). -BESSELJ = BESSELJ ## Zwraca wartość funkcji Bessela Jn(x). -BESSELK = BESSELK ## Zwraca wartość zmodyfikowanej funkcji Bessela Kn(x). -BESSELY = BESSELY ## Zwraca wartość funkcji Bessela Yn(x). -BIN2DEC = BIN2DEC ## Konwertuje liczbę w postaci dwójkowej na liczbę w postaci dziesiętnej. -BIN2HEX = BIN2HEX ## Konwertuje liczbę w postaci dwójkowej na liczbę w postaci szesnastkowej. -BIN2OCT = BIN2OCT ## Konwertuje liczbę w postaci dwójkowej na liczbę w postaci ósemkowej. -COMPLEX = COMPLEX ## Konwertuje część rzeczywistą i urojoną na liczbę zespoloną. -CONVERT = CONVERT ## Konwertuje liczbę z jednego systemu miar na inny. -DEC2BIN = DEC2BIN ## Konwertuje liczbę w postaci dziesiętnej na postać dwójkową. -DEC2HEX = DEC2HEX ## Konwertuje liczbę w postaci dziesiętnej na liczbę w postaci szesnastkowej. -DEC2OCT = DEC2OCT ## Konwertuje liczbę w postaci dziesiętnej na liczbę w postaci ósemkowej. -DELTA = DELTA ## Sprawdza, czy dwie wartości są równe. -ERF = ERF ## Zwraca wartość funkcji błędu. -ERFC = ERFC ## Zwraca wartość komplementarnej funkcji błędu. -GESTEP = GESTEP ## Sprawdza, czy liczba jest większa niż wartość progowa. -HEX2BIN = HEX2BIN ## Konwertuje liczbę w postaci szesnastkowej na liczbę w postaci dwójkowej. -HEX2DEC = HEX2DEC ## Konwertuje liczbę w postaci szesnastkowej na liczbę w postaci dziesiętnej. -HEX2OCT = HEX2OCT ## Konwertuje liczbę w postaci szesnastkowej na liczbę w postaci ósemkowej. -IMABS = IMABS ## Zwraca wartość bezwzględną (moduł) liczby zespolonej. -IMAGINARY = IMAGINARY ## Zwraca wartość części urojonej liczby zespolonej. -IMARGUMENT = IMARGUMENT ## Zwraca wartość argumentu liczby zespolonej, przy czym kąt wyrażony jest w radianach. -IMCONJUGATE = IMCONJUGATE ## Zwraca wartość liczby sprzężonej danej liczby zespolonej. -IMCOS = IMCOS ## Zwraca wartość cosinusa liczby zespolonej. -IMDIV = IMDIV ## Zwraca wartość ilorazu dwóch liczb zespolonych. -IMEXP = IMEXP ## Zwraca postać wykładniczą liczby zespolonej. -IMLN = IMLN ## Zwraca wartość logarytmu naturalnego liczby zespolonej. -IMLOG10 = IMLOG10 ## Zwraca wartość logarytmu dziesiętnego liczby zespolonej. -IMLOG2 = IMLOG2 ## Zwraca wartość logarytmu liczby zespolonej przy podstawie 2. -IMPOWER = IMPOWER ## Zwraca wartość liczby zespolonej podniesionej do potęgi całkowitej. -IMPRODUCT = IMPRODUCT ## Zwraca wartość iloczynu liczb zespolonych. -IMREAL = IMREAL ## Zwraca wartość części rzeczywistej liczby zespolonej. -IMSIN = IMSIN ## Zwraca wartość sinusa liczby zespolonej. -IMSQRT = IMSQRT ## Zwraca wartość pierwiastka kwadratowego z liczby zespolonej. -IMSUB = IMSUB ## Zwraca wartość różnicy dwóch liczb zespolonych. -IMSUM = IMSUM ## Zwraca wartość sumy liczb zespolonych. -OCT2BIN = OCT2BIN ## Konwertuje liczbę w postaci ósemkowej na liczbę w postaci dwójkowej. -OCT2DEC = OCT2DEC ## Konwertuje liczbę w postaci ósemkowej na liczbę w postaci dziesiętnej. -OCT2HEX = OCT2HEX ## Konwertuje liczbę w postaci ósemkowej na liczbę w postaci szesnastkowej. - +ACCRINT = NAL.ODS +ACCRINTM = NAL.ODS.WYKUP +AMORDEGRC = AMORT.NIELIN +AMORLINC = AMORT.LIN +COUPDAYBS = WYPŁ.DNI.OD.POCZ +COUPDAYS = WYPŁ.DNI +COUPDAYSNC = WYPŁ.DNI.NAST +COUPNCD = WYPŁ.DATA.NAST +COUPNUM = WYPŁ.LICZBA +COUPPCD = WYPŁ.DATA.POPRZ +CUMIPMT = SPŁAC.ODS +CUMPRINC = SPŁAC.KAPIT +DB = DB +DDB = DDB +DISC = STOPA.DYSK +DOLLARDE = CENA.DZIES +DOLLARFR = CENA.UŁAM +DURATION = ROCZ.PRZYCH +EFFECT = EFEKTYWNA +FV = FV +FVSCHEDULE = WART.PRZYSZŁ.KAP +INTRATE = STOPA.PROC +IPMT = IPMT +IRR = IRR +ISPMT = ISPMT +MDURATION = ROCZ.PRZYCH.M +MIRR = MIRR +NOMINAL = NOMINALNA +NPER = NPER +NPV = NPV +ODDFPRICE = CENA.PIERW.OKR +ODDFYIELD = RENT.PIERW.OKR +ODDLPRICE = CENA.OST.OKR +ODDLYIELD = RENT.OST.OKR +PDURATION = O.CZAS.TRWANIA +PMT = PMT +PPMT = PPMT +PRICE = CENA +PRICEDISC = CENA.DYSK +PRICEMAT = CENA.WYKUP +PV = PV +RATE = RATE +RECEIVED = KWOTA.WYKUP +RRI = RÓWNOW.STOPA.PROC +SLN = SLN +SYD = SYD +TBILLEQ = RENT.EKW.BS +TBILLPRICE = CENA.BS +TBILLYIELD = RENT.BS +VDB = VDB +XIRR = XIRR +XNPV = XNPV +YIELD = RENTOWNOŚĆ +YIELDDISC = RENT.DYSK +YIELDMAT = RENT.WYKUP ## -## Financial functions Funkcje finansowe +## Funkcje informacyjne (Information Functions) ## -ACCRINT = ACCRINT ## Zwraca narosłe odsetki dla papieru wartościowego z oprocentowaniem okresowym. -ACCRINTM = ACCRINTM ## Zwraca narosłe odsetki dla papieru wartościowego z oprocentowaniem w terminie wykupu. -AMORDEGRC = AMORDEGRC ## Zwraca amortyzację dla każdego okresu rozliczeniowego z wykorzystaniem współczynnika amortyzacji. -AMORLINC = AMORLINC ## Zwraca amortyzację dla każdego okresu rozliczeniowego. -COUPDAYBS = COUPDAYBS ## Zwraca liczbę dni od początku okresu dywidendy do dnia rozliczeniowego. -COUPDAYS = COUPDAYS ## Zwraca liczbę dni w okresie dywidendy, z uwzględnieniem dnia rozliczeniowego. -COUPDAYSNC = COUPDAYSNC ## Zwraca liczbę dni od dnia rozliczeniowego do daty następnego dnia dywidendy. -COUPNCD = COUPNCD ## Zwraca dzień następnej dywidendy po dniu rozliczeniowym. -COUPNUM = COUPNUM ## Zwraca liczbę dywidend płatnych między dniem rozliczeniowym a dniem wykupu. -COUPPCD = COUPPCD ## Zwraca dzień poprzedniej dywidendy przed dniem rozliczeniowym. -CUMIPMT = CUMIPMT ## Zwraca wartość procentu składanego płatnego między dwoma okresami. -CUMPRINC = CUMPRINC ## Zwraca wartość kapitału skumulowanego spłaty pożyczki między dwoma okresami. -DB = DB ## Zwraca amortyzację środka trwałego w danym okresie metodą degresywną z zastosowaniem stałej bazowej. -DDB = DDB ## Zwraca amortyzację środka trwałego za podany okres metodą degresywną z zastosowaniem podwójnej bazowej lub metodą określoną przez użytkownika. -DISC = DISC ## Zwraca wartość stopy dyskontowej papieru wartościowego. -DOLLARDE = DOLLARDE ## Konwertuje cenę w postaci ułamkowej na cenę wyrażoną w postaci dziesiętnej. -DOLLARFR = DOLLARFR ## Konwertuje cenę wyrażoną w postaci dziesiętnej na cenę wyrażoną w postaci ułamkowej. -DURATION = DURATION ## Zwraca wartość rocznego przychodu z papieru wartościowego o okresowych wypłatach oprocentowania. -EFFECT = EFFECT ## Zwraca wartość efektywnej rocznej stopy procentowej. -FV = FV ## Zwraca przyszłą wartość lokaty. -FVSCHEDULE = FVSCHEDULE ## Zwraca przyszłą wartość kapitału początkowego wraz z szeregiem procentów składanych. -INTRATE = INTRATE ## Zwraca wartość stopy procentowej papieru wartościowego całkowicie ulokowanego. -IPMT = IPMT ## Zwraca wysokość spłaty oprocentowania lokaty za dany okres. -IRR = IRR ## Zwraca wartość wewnętrznej stopy zwrotu dla serii przepływów gotówkowych. -ISPMT = ISPMT ## Oblicza wysokość spłaty oprocentowania za dany okres lokaty. -MDURATION = MDURATION ## Zwraca wartość zmodyfikowanego okresu Macauleya dla papieru wartościowego o założonej wartości nominalnej 100 zł. -MIRR = MIRR ## Zwraca wartość wewnętrznej stopy zwrotu dla przypadku, gdy dodatnie i ujemne przepływy gotówkowe mają różne stopy. -NOMINAL = NOMINAL ## Zwraca wysokość nominalnej rocznej stopy procentowej. -NPER = NPER ## Zwraca liczbę okresów dla lokaty. -NPV = NPV ## Zwraca wartość bieżącą netto lokaty na podstawie szeregu okresowych przepływów gotówkowych i stopy dyskontowej. -ODDFPRICE = ODDFPRICE ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z nietypowym pierwszym okresem. -ODDFYIELD = ODDFYIELD ## Zwraca rentowność papieru wartościowego z nietypowym pierwszym okresem. -ODDLPRICE = ODDLPRICE ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z nietypowym ostatnim okresem. -ODDLYIELD = ODDLYIELD ## Zwraca rentowność papieru wartościowego z nietypowym ostatnim okresem. -PMT = PMT ## Zwraca wartość okresowej płatności raty rocznej. -PPMT = PPMT ## Zwraca wysokość spłaty kapitału w przypadku lokaty dla danego okresu. -PRICE = PRICE ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z oprocentowaniem okresowym. -PRICEDISC = PRICEDISC ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego zdyskontowanego. -PRICEMAT = PRICEMAT ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z oprocentowaniem w terminie wykupu. -PV = PV ## Zwraca wartość bieżącą lokaty. -RATE = RATE ## Zwraca wysokość stopy procentowej w okresie raty rocznej. -RECEIVED = RECEIVED ## Zwraca wartość kapitału otrzymanego przy wykupie papieru wartościowego całkowicie ulokowanego. -SLN = SLN ## Zwraca amortyzację środka trwałego za jeden okres metodą liniową. -SYD = SYD ## Zwraca amortyzację środka trwałego za dany okres metodą sumy cyfr lat amortyzacji. -TBILLEQ = TBILLEQ ## Zwraca rentowność ekwiwalentu obligacji dla bonu skarbowego. -TBILLPRICE = TBILLPRICE ## Zwraca cenę za 100 zł wartości nominalnej bonu skarbowego. -TBILLYIELD = TBILLYIELD ## Zwraca rentowność bonu skarbowego. -VDB = VDB ## Oblicza amortyzację środka trwałego w danym okresie lub jego części metodą degresywną. -XIRR = XIRR ## Zwraca wartość wewnętrznej stopy zwrotu dla serii rozłożonych w czasie przepływów gotówkowych, niekoniecznie okresowych. -XNPV = XNPV ## Zwraca wartość bieżącą netto dla serii rozłożonych w czasie przepływów gotówkowych, niekoniecznie okresowych. -YIELD = YIELD ## Zwraca rentowność papieru wartościowego z oprocentowaniem okresowym. -YIELDDISC = YIELDDISC ## Zwraca roczną rentowność zdyskontowanego papieru wartościowego, na przykład bonu skarbowego. -YIELDMAT = YIELDMAT ## Zwraca roczną rentowność papieru wartościowego oprocentowanego przy wykupie. - +CELL = KOMÓRKA +ERROR.TYPE = NR.BŁĘDU +INFO = INFO +ISBLANK = CZY.PUSTA +ISERR = CZY.BŁ +ISERROR = CZY.BŁĄD +ISEVEN = CZY.PARZYSTE +ISFORMULA = CZY.FORMUŁA +ISLOGICAL = CZY.LOGICZNA +ISNA = CZY.BRAK +ISNONTEXT = CZY.NIE.TEKST +ISNUMBER = CZY.LICZBA +ISODD = CZY.NIEPARZYSTE +ISREF = CZY.ADR +ISTEXT = CZY.TEKST +N = N +NA = BRAK +SHEET = ARKUSZ +SHEETS = ARKUSZE +TYPE = TYP ## -## Information functions Funkcje informacyjne +## Funkcje logiczne (Logical Functions) ## -CELL = KOMÓRKA ## Zwraca informacje o formacie, położeniu lub zawartości komórki. -ERROR.TYPE = NR.BŁĘDU ## Zwraca liczbę odpowiadającą typowi błędu. -INFO = INFO ## Zwraca informację o aktualnym środowisku pracy. -ISBLANK = CZY.PUSTA ## Zwraca wartość PRAWDA, jeśli wartość jest pusta. -ISERR = CZY.BŁ ## Zwraca wartość PRAWDA, jeśli wartość jest dowolną wartością błędu, z wyjątkiem #N/D!. -ISERROR = CZY.BŁĄD ## Zwraca wartość PRAWDA, jeśli wartość jest dowolną wartością błędu. -ISEVEN = ISEVEN ## Zwraca wartość PRAWDA, jeśli liczba jest parzysta. -ISLOGICAL = CZY.LOGICZNA ## Zwraca wartość PRAWDA, jeśli wartość jest wartością logiczną. -ISNA = CZY.BRAK ## Zwraca wartość PRAWDA, jeśli wartość jest wartością błędu #N/D!. -ISNONTEXT = CZY.NIE.TEKST ## Zwraca wartość PRAWDA, jeśli wartość nie jest tekstem. -ISNUMBER = CZY.LICZBA ## Zwraca wartość PRAWDA, jeśli wartość jest liczbą. -ISODD = ISODD ## Zwraca wartość PRAWDA, jeśli liczba jest nieparzysta. -ISREF = CZY.ADR ## Zwraca wartość PRAWDA, jeśli wartość jest odwołaniem. -ISTEXT = CZY.TEKST ## Zwraca wartość PRAWDA, jeśli wartość jest tekstem. -N = L ## Zwraca wartość przekonwertowaną na postać liczbową. -NA = BRAK ## Zwraca wartość błędu #N/D!. -TYPE = TYP ## Zwraca liczbę wskazującą typ danych wartości. - +AND = ORAZ +FALSE = FAŁSZ +IF = JEŻELI +IFERROR = JEŻELI.BŁĄD +IFNA = JEŻELI.ND +IFS = WARUNKI +NOT = NIE +OR = LUB +SWITCH = PRZEŁĄCZ +TRUE = PRAWDA +XOR = XOR ## -## Logical functions Funkcje logiczne +## Funkcje wyszukiwania i odwołań (Lookup & Reference Functions) ## -AND = ORAZ ## Zwraca wartość PRAWDA, jeśli wszystkie argumenty mają wartość PRAWDA. -FALSE = FAŁSZ ## Zwraca wartość logiczną FAŁSZ. -IF = JEŻELI ## Określa warunek logiczny do sprawdzenia. -IFERROR = JEŻELI.BŁĄD ## Zwraca określoną wartość, jeśli wynikiem obliczenia formuły jest błąd; w przeciwnym przypadku zwraca wynik formuły. -NOT = NIE ## Odwraca wartość logiczną argumentu. -OR = LUB ## Zwraca wartość PRAWDA, jeśli co najmniej jeden z argumentów ma wartość PRAWDA. -TRUE = PRAWDA ## Zwraca wartość logiczną PRAWDA. - +ADDRESS = ADRES +AREAS = OBSZARY +CHOOSE = WYBIERZ +COLUMN = NR.KOLUMNY +COLUMNS = LICZBA.KOLUMN +FORMULATEXT = FORMUŁA.TEKST +GETPIVOTDATA = WEŹDANETABELI +HLOOKUP = WYSZUKAJ.POZIOMO +HYPERLINK = HIPERŁĄCZE +INDEX = INDEKS +INDIRECT = ADR.POŚR +LOOKUP = WYSZUKAJ +MATCH = PODAJ.POZYCJĘ +OFFSET = PRZESUNIĘCIE +ROW = WIERSZ +ROWS = ILE.WIERSZY +RTD = DANE.CZASU.RZECZ +TRANSPOSE = TRANSPONUJ +VLOOKUP = WYSZUKAJ.PIONOWO ## -## Lookup and reference functions Funkcje wyszukiwania i odwołań +## Funkcje matematyczne i trygonometryczne (Math & Trig Functions) ## -ADDRESS = ADRES ## Zwraca odwołanie do jednej komórki w arkuszu jako wartość tekstową. -AREAS = OBSZARY ## Zwraca liczbę obszarów występujących w odwołaniu. -CHOOSE = WYBIERZ ## Wybiera wartość z listy wartości. -COLUMN = NR.KOLUMNY ## Zwraca numer kolumny z odwołania. -COLUMNS = LICZBA.KOLUMN ## Zwraca liczbę kolumn dla danego odwołania. -HLOOKUP = WYSZUKAJ.POZIOMO ## Przegląda górny wiersz tablicy i zwraca wartość wskazanej komórki. -HYPERLINK = HIPERŁĄCZE ## Tworzy skrót lub skok, który pozwala otwierać dokument przechowywany na serwerze sieciowym, w sieci intranet lub w Internecie. -INDEX = INDEKS ## Używa indeksu do wybierania wartości z odwołania lub tablicy. -INDIRECT = ADR.POŚR ## Zwraca odwołanie określone przez wartość tekstową. -LOOKUP = WYSZUKAJ ## Wyszukuje wartości w wektorze lub tablicy. -MATCH = PODAJ.POZYCJĘ ## Wyszukuje wartości w odwołaniu lub w tablicy. -OFFSET = PRZESUNIĘCIE ## Zwraca adres przesunięty od danego odwołania. -ROW = WIERSZ ## Zwraca numer wiersza odwołania. -ROWS = ILE.WIERSZY ## Zwraca liczbę wierszy dla danego odwołania. -RTD = RTD ## Pobiera dane w czasie rzeczywistym z programu obsługującego automatyzację COM (Automatyzacja: Sposób pracy z obiektami aplikacji pochodzącymi z innej aplikacji lub narzędzia projektowania. Nazywana wcześniej Automatyzacją OLE, Automatyzacja jest standardem przemysłowym i funkcją obiektowego modelu składników (COM, Component Object Model).). -TRANSPOSE = TRANSPONUJ ## Zwraca transponowaną tablicę. -VLOOKUP = WYSZUKAJ.PIONOWO ## Przeszukuje pierwszą kolumnę tablicy i przechodzi wzdłuż wiersza, aby zwrócić wartość komórki. - +ABS = MODUŁ.LICZBY +ACOS = ACOS +ACOSH = ACOSH +ACOT = ACOT +ACOTH = ACOTH +AGGREGATE = AGREGUJ +ARABIC = ARABSKIE +ASIN = ASIN +ASINH = ASINH +ATAN = ATAN +ATAN2 = ATAN2 +ATANH = ATANH +BASE = PODSTAWA +CEILING.MATH = ZAOKR.W.GÓRĘ.MATEMATYCZNE +CEILING.PRECISE = ZAOKR.W.GÓRĘ.DOKŁ +COMBIN = KOMBINACJE +COMBINA = KOMBINACJE.A +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = DZIESIĘTNA +DEGREES = STOPNIE +ECMA.CEILING = ECMA.ZAOKR.W.GÓRĘ +EVEN = ZAOKR.DO.PARZ +EXP = EXP +FACT = SILNIA +FACTDOUBLE = SILNIA.DWUKR +FLOOR.MATH = ZAOKR.W.DÓŁ.MATEMATYCZNE +FLOOR.PRECISE = ZAOKR.W.DÓŁ.DOKŁ +GCD = NAJW.WSP.DZIEL +INT = ZAOKR.DO.CAŁK +ISO.CEILING = ISO.ZAOKR.W.GÓRĘ +LCM = NAJMN.WSP.WIEL +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = WYZNACZNIK.MACIERZY +MINVERSE = MACIERZ.ODW +MMULT = MACIERZ.ILOCZYN +MOD = MOD +MROUND = ZAOKR.DO.WIELOKR +MULTINOMIAL = WIELOMIAN +MUNIT = MACIERZ.JEDNOSTKOWA +ODD = ZAOKR.DO.NPARZ +PI = PI +POWER = POTĘGA +PRODUCT = ILOCZYN +QUOTIENT = CZ.CAŁK.DZIELENIA +RADIANS = RADIANY +RAND = LOS +RANDBETWEEN = LOS.ZAKR +ROMAN = RZYMSKIE +ROUND = ZAOKR +ROUNDBAHTDOWN = ZAOKR.DÓŁ.BAT +ROUNDBAHTUP = ZAOKR.GÓRA.BAT +ROUNDDOWN = ZAOKR.DÓŁ +ROUNDUP = ZAOKR.GÓRA +SEC = SEC +SECH = SECH +SERIESSUM = SUMA.SZER.POT +SIGN = ZNAK.LICZBY +SIN = SIN +SINH = SINH +SQRT = PIERWIASTEK +SQRTPI = PIERW.PI +SUBTOTAL = SUMY.CZĘŚCIOWE +SUM = SUMA +SUMIF = SUMA.JEŻELI +SUMIFS = SUMA.WARUNKÓW +SUMPRODUCT = SUMA.ILOCZYNÓW +SUMSQ = SUMA.KWADRATÓW +SUMX2MY2 = SUMA.X2.M.Y2 +SUMX2PY2 = SUMA.X2.P.Y2 +SUMXMY2 = SUMA.XMY.2 +TAN = TAN +TANH = TANH +TRUNC = LICZBA.CAŁK ## -## Math and trigonometry functions Funkcje matematyczne i trygonometryczne +## Funkcje statystyczne (Statistical Functions) ## -ABS = MODUŁ.LICZBY ## Zwraca wartość absolutną liczby. -ACOS = ACOS ## Zwraca arcus cosinus liczby. -ACOSH = ACOSH ## Zwraca arcus cosinus hiperboliczny liczby. -ASIN = ASIN ## Zwraca arcus sinus liczby. -ASINH = ASINH ## Zwraca arcus sinus hiperboliczny liczby. -ATAN = ATAN ## Zwraca arcus tangens liczby. -ATAN2 = ATAN2 ## Zwraca arcus tangens liczby na podstawie współrzędnych x i y. -ATANH = ATANH ## Zwraca arcus tangens hiperboliczny liczby. -CEILING = ZAOKR.W.GÓRĘ ## Zaokrągla liczbę do najbliższej liczby całkowitej lub do najbliższej wielokrotności dokładności. -COMBIN = KOMBINACJE ## Zwraca liczbę kombinacji dla danej liczby obiektów. -COS = COS ## Zwraca cosinus liczby. -COSH = COSH ## Zwraca cosinus hiperboliczny liczby. -DEGREES = STOPNIE ## Konwertuje radiany na stopnie. -EVEN = ZAOKR.DO.PARZ ## Zaokrągla liczbę w górę do najbliższej liczby parzystej. -EXP = EXP ## Zwraca wartość liczby e podniesionej do potęgi określonej przez podaną liczbę. -FACT = SILNIA ## Zwraca silnię liczby. -FACTDOUBLE = FACTDOUBLE ## Zwraca podwójną silnię liczby. -FLOOR = ZAOKR.W.DÓŁ ## Zaokrągla liczbę w dół, w kierunku zera. -GCD = GCD ## Zwraca największy wspólny dzielnik. -INT = ZAOKR.DO.CAŁK ## Zaokrągla liczbę w dół do najbliższej liczby całkowitej. -LCM = LCM ## Zwraca najmniejszą wspólną wielokrotność. -LN = LN ## Zwraca logarytm naturalny podanej liczby. -LOG = LOG ## Zwraca logarytm danej liczby przy zadanej podstawie. -LOG10 = LOG10 ## Zwraca logarytm dziesiętny liczby. -MDETERM = WYZNACZNIK.MACIERZY ## Zwraca wyznacznik macierzy tablicy. -MINVERSE = MACIERZ.ODW ## Zwraca odwrotność macierzy tablicy. -MMULT = MACIERZ.ILOCZYN ## Zwraca iloczyn macierzy dwóch tablic. -MOD = MOD ## Zwraca resztę z dzielenia. -MROUND = MROUND ## Zwraca liczbę zaokrągloną do żądanej wielokrotności. -MULTINOMIAL = MULTINOMIAL ## Zwraca wielomian dla zbioru liczb. -ODD = ZAOKR.DO.NPARZ ## Zaokrągla liczbę w górę do najbliższej liczby nieparzystej. -PI = PI ## Zwraca wartość liczby Pi. -POWER = POTĘGA ## Zwraca liczbę podniesioną do potęgi. -PRODUCT = ILOCZYN ## Mnoży argumenty. -QUOTIENT = QUOTIENT ## Zwraca iloraz (całkowity). -RADIANS = RADIANY ## Konwertuje stopnie na radiany. -RAND = LOS ## Zwraca liczbę pseudolosową z zakresu od 0 do 1. -RANDBETWEEN = RANDBETWEEN ## Zwraca liczbę pseudolosową z zakresu określonego przez podane argumenty. -ROMAN = RZYMSKIE ## Konwertuje liczbę arabską na rzymską jako tekst. -ROUND = ZAOKR ## Zaokrągla liczbę do określonej liczby cyfr. -ROUNDDOWN = ZAOKR.DÓŁ ## Zaokrągla liczbę w dół, w kierunku zera. -ROUNDUP = ZAOKR.GÓRA ## Zaokrągla liczbę w górę, w kierunku od zera. -SERIESSUM = SERIESSUM ## Zwraca sumę szeregu potęgowego na podstawie wzoru. -SIGN = ZNAK.LICZBY ## Zwraca znak liczby. -SIN = SIN ## Zwraca sinus danego kąta. -SINH = SINH ## Zwraca sinus hiperboliczny liczby. -SQRT = PIERWIASTEK ## Zwraca dodatni pierwiastek kwadratowy. -SQRTPI = SQRTPI ## Zwraca pierwiastek kwadratowy iloczynu (liczba * Pi). -SUBTOTAL = SUMY.POŚREDNIE ## Zwraca sumę częściową listy lub bazy danych. -SUM = SUMA ## Dodaje argumenty. -SUMIF = SUMA.JEŻELI ## Dodaje komórki określone przez podane kryterium. -SUMIFS = SUMA.WARUNKÓW ## Dodaje komórki w zakresie, które spełniają wiele kryteriów. -SUMPRODUCT = SUMA.ILOCZYNÓW ## Zwraca sumę iloczynów odpowiednich elementów tablicy. -SUMSQ = SUMA.KWADRATÓW ## Zwraca sumę kwadratów argumentów. -SUMX2MY2 = SUMA.X2.M.Y2 ## Zwraca sumę różnic kwadratów odpowiednich wartości w dwóch tablicach. -SUMX2PY2 = SUMA.X2.P.Y2 ## Zwraca sumę sum kwadratów odpowiednich wartości w dwóch tablicach. -SUMXMY2 = SUMA.XMY.2 ## Zwraca sumę kwadratów różnic odpowiednich wartości w dwóch tablicach. -TAN = TAN ## Zwraca tangens liczby. -TANH = TANH ## Zwraca tangens hiperboliczny liczby. -TRUNC = LICZBA.CAŁK ## Przycina liczbę do wartości całkowitej. - +AVEDEV = ODCH.ŚREDNIE +AVERAGE = ŚREDNIA +AVERAGEA = ŚREDNIA.A +AVERAGEIF = ŚREDNIA.JEŻELI +AVERAGEIFS = ŚREDNIA.WARUNKÓW +BETA.DIST = ROZKŁ.BETA +BETA.INV = ROZKŁ.BETA.ODWR +BINOM.DIST = ROZKŁ.DWUM +BINOM.DIST.RANGE = ROZKŁ.DWUM.ZAKRES +BINOM.INV = ROZKŁ.DWUM.ODWR +CHISQ.DIST = ROZKŁ.CHI +CHISQ.DIST.RT = ROZKŁ.CHI.PS +CHISQ.INV = ROZKŁ.CHI.ODWR +CHISQ.INV.RT = ROZKŁ.CHI.ODWR.PS +CHISQ.TEST = CHI.TEST +CONFIDENCE.NORM = UFNOŚĆ.NORM +CONFIDENCE.T = UFNOŚĆ.T +CORREL = WSP.KORELACJI +COUNT = ILE.LICZB +COUNTA = ILE.NIEPUSTYCH +COUNTBLANK = LICZ.PUSTE +COUNTIF = LICZ.JEŻELI +COUNTIFS = LICZ.WARUNKI +COVARIANCE.P = KOWARIANCJA.POPUL +COVARIANCE.S = KOWARIANCJA.PRÓBKI +DEVSQ = ODCH.KWADRATOWE +EXPON.DIST = ROZKŁ.EXP +F.DIST = ROZKŁ.F +F.DIST.RT = ROZKŁ.F.PS +F.INV = ROZKŁ.F.ODWR +F.INV.RT = ROZKŁ.F.ODWR.PS +F.TEST = F.TEST +FISHER = ROZKŁAD.FISHER +FISHERINV = ROZKŁAD.FISHER.ODW +FORECAST.ETS = REGLINX.ETS +FORECAST.ETS.CONFINT = REGLINX.ETS.CONFINT +FORECAST.ETS.SEASONALITY = REGLINX.ETS.SEZONOWOŚĆ +FORECAST.ETS.STAT = REGLINX.ETS.STATYSTYKA +FORECAST.LINEAR = REGLINX.LINIOWA +FREQUENCY = CZĘSTOŚĆ +GAMMA = GAMMA +GAMMA.DIST = ROZKŁ.GAMMA +GAMMA.INV = ROZKŁ.GAMMA.ODWR +GAMMALN = ROZKŁAD.LIN.GAMMA +GAMMALN.PRECISE = ROZKŁAD.LIN.GAMMA.DOKŁ +GAUSS = GAUSS +GEOMEAN = ŚREDNIA.GEOMETRYCZNA +GROWTH = REGEXPW +HARMEAN = ŚREDNIA.HARMONICZNA +HYPGEOM.DIST = ROZKŁ.HIPERGEOM +INTERCEPT = ODCIĘTA +KURT = KURTOZA +LARGE = MAX.K +LINEST = REGLINP +LOGEST = REGEXPP +LOGNORM.DIST = ROZKŁ.LOG +LOGNORM.INV = ROZKŁ.LOG.ODWR +MAX = MAX +MAXA = MAX.A +MAXIFS = MAKS.WARUNKÓW +MEDIAN = MEDIANA +MIN = MIN +MINA = MIN.A +MINIFS = MIN.WARUNKÓW +MODE.MULT = WYST.NAJCZĘŚCIEJ.TABL +MODE.SNGL = WYST.NAJCZĘŚCIEJ.WART +NEGBINOM.DIST = ROZKŁ.DWUM.PRZEC +NORM.DIST = ROZKŁ.NORMALNY +NORM.INV = ROZKŁ.NORMALNY.ODWR +NORM.S.DIST = ROZKŁ.NORMALNY.S +NORM.S.INV = ROZKŁ.NORMALNY.S.ODWR +PEARSON = PEARSON +PERCENTILE.EXC = PERCENTYL.PRZEDZ.OTW +PERCENTILE.INC = PERCENTYL.PRZEDZ.ZAMK +PERCENTRANK.EXC = PROC.POZ.PRZEDZ.OTW +PERCENTRANK.INC = PROC.POZ.PRZEDZ.ZAMK +PERMUT = PERMUTACJE +PERMUTATIONA = PERMUTACJE.A +PHI = PHI +POISSON.DIST = ROZKŁ.POISSON +PROB = PRAWDPD +QUARTILE.EXC = KWARTYL.PRZEDZ.OTW +QUARTILE.INC = KWARTYL.PRZEDZ.ZAMK +RANK.AVG = POZYCJA.ŚR +RANK.EQ = POZYCJA.NAJW +RSQ = R.KWADRAT +SKEW = SKOŚNOŚĆ +SKEW.P = SKOŚNOŚĆ.P +SLOPE = NACHYLENIE +SMALL = MIN.K +STANDARDIZE = NORMALIZUJ +STDEV.P = ODCH.STAND.POPUL +STDEV.S = ODCH.STANDARD.PRÓBKI +STDEVA = ODCH.STANDARDOWE.A +STDEVPA = ODCH.STANDARD.POPUL.A +STEYX = REGBŁSTD +T.DIST = ROZKŁ.T +T.DIST.2T = ROZKŁ.T.DS +T.DIST.RT = ROZKŁ.T.PS +T.INV = ROZKŁ.T.ODWR +T.INV.2T = ROZKŁ.T.ODWR.DS +T.TEST = T.TEST +TREND = REGLINW +TRIMMEAN = ŚREDNIA.WEWN +VAR.P = WARIANCJA.POP +VAR.S = WARIANCJA.PRÓBKI +VARA = WARIANCJA.A +VARPA = WARIANCJA.POPUL.A +WEIBULL.DIST = ROZKŁ.WEIBULL +Z.TEST = Z.TEST ## -## Statistical functions Funkcje statystyczne +## Funkcje tekstowe (Text Functions) ## -AVEDEV = ODCH.ŚREDNIE ## Zwraca średnią wartość odchyleń absolutnych punktów danych od ich wartości średniej. -AVERAGE = ŚREDNIA ## Zwraca wartość średnią argumentów. -AVERAGEA = ŚREDNIA.A ## Zwraca wartość średnią argumentów, z uwzględnieniem liczb, tekstów i wartości logicznych. -AVERAGEIF = ŚREDNIA.JEŻELI ## Zwraca średnią (średnią arytmetyczną) wszystkich komórek w zakresie, które spełniają podane kryteria. -AVERAGEIFS = ŚREDNIA.WARUNKÓW ## Zwraca średnią (średnią arytmetyczną) wszystkich komórek, które spełniają jedno lub więcej kryteriów. -BETADIST = ROZKŁAD.BETA ## Zwraca skumulowaną funkcję gęstości prawdopodobieństwa beta. -BETAINV = ROZKŁAD.BETA.ODW ## Zwraca odwrotność skumulowanej funkcji gęstości prawdopodobieństwa beta. -BINOMDIST = ROZKŁAD.DWUM ## Zwraca pojedynczy składnik dwumianowego rozkładu prawdopodobieństwa. -CHIDIST = ROZKŁAD.CHI ## Zwraca wartość jednostronnego prawdopodobieństwa rozkładu chi-kwadrat. -CHIINV = ROZKŁAD.CHI.ODW ## Zwraca odwrotność wartości jednostronnego prawdopodobieństwa rozkładu chi-kwadrat. -CHITEST = TEST.CHI ## Zwraca test niezależności. -CONFIDENCE = UFNOŚĆ ## Zwraca interwał ufności dla średniej populacji. -CORREL = WSP.KORELACJI ## Zwraca współczynnik korelacji dwóch zbiorów danych. -COUNT = ILE.LICZB ## Zlicza liczby znajdujące się na liście argumentów. -COUNTA = ILE.NIEPUSTYCH ## Zlicza wartości znajdujące się na liście argumentów. -COUNTBLANK = LICZ.PUSTE ## Zwraca liczbę pustych komórek w pewnym zakresie. -COUNTIF = LICZ.JEŻELI ## Zlicza komórki wewnątrz zakresu, które spełniają podane kryteria. -COUNTIFS = LICZ.WARUNKI ## Zlicza komórki wewnątrz zakresu, które spełniają wiele kryteriów. -COVAR = KOWARIANCJA ## Zwraca kowariancję, czyli średnią wartość iloczynów odpowiednich odchyleń. -CRITBINOM = PRÓG.ROZKŁAD.DWUM ## Zwraca najmniejszą wartość, dla której skumulowany rozkład dwumianowy jest mniejszy niż wartość kryterium lub równy jej. -DEVSQ = ODCH.KWADRATOWE ## Zwraca sumę kwadratów odchyleń. -EXPONDIST = ROZKŁAD.EXP ## Zwraca rozkład wykładniczy. -FDIST = ROZKŁAD.F ## Zwraca rozkład prawdopodobieństwa F. -FINV = ROZKŁAD.F.ODW ## Zwraca odwrotność rozkładu prawdopodobieństwa F. -FISHER = ROZKŁAD.FISHER ## Zwraca transformację Fishera. -FISHERINV = ROZKŁAD.FISHER.ODW ## Zwraca odwrotność transformacji Fishera. -FORECAST = REGLINX ## Zwraca wartość trendu liniowego. -FREQUENCY = CZĘSTOŚĆ ## Zwraca rozkład częstotliwości jako tablicę pionową. -FTEST = TEST.F ## Zwraca wynik testu F. -GAMMADIST = ROZKŁAD.GAMMA ## Zwraca rozkład gamma. -GAMMAINV = ROZKŁAD.GAMMA.ODW ## Zwraca odwrotność skumulowanego rozkładu gamma. -GAMMALN = ROZKŁAD.LIN.GAMMA ## Zwraca logarytm naturalny funkcji gamma, Γ(x). -GEOMEAN = ŚREDNIA.GEOMETRYCZNA ## Zwraca średnią geometryczną. -GROWTH = REGEXPW ## Zwraca wartości trendu wykładniczego. -HARMEAN = ŚREDNIA.HARMONICZNA ## Zwraca średnią harmoniczną. -HYPGEOMDIST = ROZKŁAD.HIPERGEOM ## Zwraca rozkład hipergeometryczny. -INTERCEPT = ODCIĘTA ## Zwraca punkt przecięcia osi pionowej z linią regresji liniowej. -KURT = KURTOZA ## Zwraca kurtozę zbioru danych. -LARGE = MAX.K ## Zwraca k-tą największą wartość ze zbioru danych. -LINEST = REGLINP ## Zwraca parametry trendu liniowego. -LOGEST = REGEXPP ## Zwraca parametry trendu wykładniczego. -LOGINV = ROZKŁAD.LOG.ODW ## Zwraca odwrotność rozkładu logarytmu naturalnego. -LOGNORMDIST = ROZKŁAD.LOG ## Zwraca skumulowany rozkład logarytmu naturalnego. -MAX = MAX ## Zwraca maksymalną wartość listy argumentów. -MAXA = MAX.A ## Zwraca maksymalną wartość listy argumentów, z uwzględnieniem liczb, tekstów i wartości logicznych. -MEDIAN = MEDIANA ## Zwraca medianę podanych liczb. -MIN = MIN ## Zwraca minimalną wartość listy argumentów. -MINA = MIN.A ## Zwraca najmniejszą wartość listy argumentów, z uwzględnieniem liczb, tekstów i wartości logicznych. -MODE = WYST.NAJCZĘŚCIEJ ## Zwraca wartość najczęściej występującą w zbiorze danych. -NEGBINOMDIST = ROZKŁAD.DWUM.PRZEC ## Zwraca ujemny rozkład dwumianowy. -NORMDIST = ROZKŁAD.NORMALNY ## Zwraca rozkład normalny skumulowany. -NORMINV = ROZKŁAD.NORMALNY.ODW ## Zwraca odwrotność rozkładu normalnego skumulowanego. -NORMSDIST = ROZKŁAD.NORMALNY.S ## Zwraca standardowy rozkład normalny skumulowany. -NORMSINV = ROZKŁAD.NORMALNY.S.ODW ## Zwraca odwrotność standardowego rozkładu normalnego skumulowanego. -PEARSON = PEARSON ## Zwraca współczynnik korelacji momentu iloczynu Pearsona. -PERCENTILE = PERCENTYL ## Wyznacza k-ty percentyl wartości w zakresie. -PERCENTRANK = PROCENT.POZYCJA ## Zwraca procentową pozycję wartości w zbiorze danych. -PERMUT = PERMUTACJE ## Zwraca liczbę permutacji dla danej liczby obiektów. -POISSON = ROZKŁAD.POISSON ## Zwraca rozkład Poissona. -PROB = PRAWDPD ## Zwraca prawdopodobieństwo, że wartości w zakresie leżą pomiędzy dwiema granicami. -QUARTILE = KWARTYL ## Wyznacza kwartyl zbioru danych. -RANK = POZYCJA ## Zwraca pozycję liczby na liście liczb. -RSQ = R.KWADRAT ## Zwraca kwadrat współczynnika korelacji momentu iloczynu Pearsona. -SKEW = SKOŚNOŚĆ ## Zwraca skośność rozkładu. -SLOPE = NACHYLENIE ## Zwraca nachylenie linii regresji liniowej. -SMALL = MIN.K ## Zwraca k-tą najmniejszą wartość ze zbioru danych. -STANDARDIZE = NORMALIZUJ ## Zwraca wartość znormalizowaną. -STDEV = ODCH.STANDARDOWE ## Szacuje odchylenie standardowe na podstawie próbki. -STDEVA = ODCH.STANDARDOWE.A ## Szacuje odchylenie standardowe na podstawie próbki, z uwzględnieniem liczb, tekstów i wartości logicznych. -STDEVP = ODCH.STANDARD.POPUL ## Oblicza odchylenie standardowe na podstawie całej populacji. -STDEVPA = ODCH.STANDARD.POPUL.A ## Oblicza odchylenie standardowe na podstawie całej populacji, z uwzględnieniem liczb, teksów i wartości logicznych. -STEYX = REGBŁSTD ## Zwraca błąd standardowy przewidzianej wartości y dla każdej wartości x w regresji. -TDIST = ROZKŁAD.T ## Zwraca rozkład t-Studenta. -TINV = ROZKŁAD.T.ODW ## Zwraca odwrotność rozkładu t-Studenta. -TREND = REGLINW ## Zwraca wartości trendu liniowego. -TRIMMEAN = ŚREDNIA.WEWN ## Zwraca średnią wartość dla wnętrza zbioru danych. -TTEST = TEST.T ## Zwraca prawdopodobieństwo związane z testem t-Studenta. -VAR = WARIANCJA ## Szacuje wariancję na podstawie próbki. -VARA = WARIANCJA.A ## Szacuje wariancję na podstawie próbki, z uwzględnieniem liczb, tekstów i wartości logicznych. -VARP = WARIANCJA.POPUL ## Oblicza wariancję na podstawie całej populacji. -VARPA = WARIANCJA.POPUL.A ## Oblicza wariancję na podstawie całej populacji, z uwzględnieniem liczb, tekstów i wartości logicznych. -WEIBULL = ROZKŁAD.WEIBULL ## Zwraca rozkład Weibulla. -ZTEST = TEST.Z ## Zwraca wartość jednostronnego prawdopodobieństwa testu z. - +BAHTTEXT = BAT.TEKST +CHAR = ZNAK +CLEAN = OCZYŚĆ +CODE = KOD +CONCAT = ZŁĄCZ.TEKST +DOLLAR = KWOTA +EXACT = PORÓWNAJ +FIND = ZNAJDŹ +FIXED = ZAOKR.DO.TEKST +ISTHAIDIGIT = CZY.CYFRA.TAJ +LEFT = LEWY +LEN = DŁ +LOWER = LITERY.MAŁE +MID = FRAGMENT.TEKSTU +NUMBERSTRING = LICZBA.CIĄG.ZNAK +NUMBERVALUE = WARTOŚĆ.LICZBOWA +PROPER = Z.WIELKIEJ.LITERY +REPLACE = ZASTĄP +REPT = POWT +RIGHT = PRAWY +SEARCH = SZUKAJ.TEKST +SUBSTITUTE = PODSTAW +T = T +TEXT = TEKST +TEXTJOIN = POŁĄCZ.TEKSTY +THAIDIGIT = TAJ.CYFRA +THAINUMSOUND = TAJ.DŹWIĘK.NUM +THAINUMSTRING = TAJ.CIĄG.NUM +THAISTRINGLENGTH = TAJ.DŁUGOŚĆ.CIĄGU +TRIM = USUŃ.ZBĘDNE.ODSTĘPY +UNICHAR = ZNAK.UNICODE +UNICODE = UNICODE +UPPER = LITERY.WIELKIE +VALUE = WARTOŚĆ ## -## Text functions Funkcje tekstowe +## Funkcje sieci Web (Web Functions) ## -ASC = ASC ## Zamienia litery angielskie lub katakana o pełnej szerokości (dwubajtowe) w ciągu znaków na znaki o szerokości połówkowej (jednobajtowe). -BAHTTEXT = BAHTTEXT ## Konwertuje liczbę na tekst, stosując format walutowy ß (baht). -CHAR = ZNAK ## Zwraca znak o podanym numerze kodu. -CLEAN = OCZYŚĆ ## Usuwa z tekstu wszystkie znaki, które nie mogą być drukowane. -CODE = KOD ## Zwraca kod numeryczny pierwszego znaku w ciągu tekstowym. -CONCATENATE = ZŁĄCZ.TEKSTY ## Łączy kilka oddzielnych tekstów w jeden tekst. -DOLLAR = KWOTA ## Konwertuje liczbę na tekst, stosując format walutowy $ (dolar). -EXACT = PORÓWNAJ ## Sprawdza identyczność dwóch wartości tekstowych. -FIND = ZNAJDŹ ## Znajduje jedną wartość tekstową wewnątrz innej (z uwzględnieniem wielkich i małych liter). -FINDB = ZNAJDŹB ## Znajduje jedną wartość tekstową wewnątrz innej (z uwzględnieniem wielkich i małych liter). -FIXED = ZAOKR.DO.TEKST ## Formatuje liczbę jako tekst przy stałej liczbie miejsc dziesiętnych. -JIS = JIS ## Zmienia litery angielskie lub katakana o szerokości połówkowej (jednobajtowe) w ciągu znaków na znaki o pełnej szerokości (dwubajtowe). -LEFT = LEWY ## Zwraca skrajne lewe znaki z wartości tekstowej. -LEFTB = LEWYB ## Zwraca skrajne lewe znaki z wartości tekstowej. -LEN = DŁ ## Zwraca liczbę znaków ciągu tekstowego. -LENB = DŁ.B ## Zwraca liczbę znaków ciągu tekstowego. -LOWER = LITERY.MAŁE ## Konwertuje wielkie litery tekstu na małe litery. -MID = FRAGMENT.TEKSTU ## Zwraca określoną liczbę znaków z ciągu tekstowego, zaczynając od zadanej pozycji. -MIDB = FRAGMENT.TEKSTU.B ## Zwraca określoną liczbę znaków z ciągu tekstowego, zaczynając od zadanej pozycji. -PHONETIC = PHONETIC ## Wybiera znaki fonetyczne (furigana) z ciągu tekstowego. -PROPER = Z.WIELKIEJ.LITERY ## Zastępuje pierwszą literę każdego wyrazu tekstu wielką literą. -REPLACE = ZASTĄP ## Zastępuje znaki w tekście. -REPLACEB = ZASTĄP.B ## Zastępuje znaki w tekście. -REPT = POWT ## Powiela tekst daną liczbę razy. -RIGHT = PRAWY ## Zwraca skrajne prawe znaki z wartości tekstowej. -RIGHTB = PRAWYB ## Zwraca skrajne prawe znaki z wartości tekstowej. -SEARCH = SZUKAJ.TEKST ## Wyszukuje jedną wartość tekstową wewnątrz innej (bez uwzględniania wielkości liter). -SEARCHB = SZUKAJ.TEKST.B ## Wyszukuje jedną wartość tekstową wewnątrz innej (bez uwzględniania wielkości liter). -SUBSTITUTE = PODSTAW ## Podstawia nowy tekst w miejsce poprzedniego tekstu w ciągu tekstowym. -T = T ## Konwertuje argumenty na tekst. -TEXT = TEKST ## Formatuje liczbę i konwertuje ją na tekst. -TRIM = USUŃ.ZBĘDNE.ODSTĘPY ## Usuwa spacje z tekstu. -UPPER = LITERY.WIELKIE ## Konwertuje znaki tekstu na wielkie litery. -VALUE = WARTOŚĆ ## Konwertuje argument tekstowy na liczbę. +ENCODEURL = ENCODEURL +FILTERXML = FILTERXML +WEBSERVICE = WEBSERVICE + +## +## Funkcje zgodności (Compatibility Functions) +## +BETADIST = ROZKŁAD.BETA +BETAINV = ROZKŁAD.BETA.ODW +BINOMDIST = ROZKŁAD.DWUM +CEILING = ZAOKR.W.GÓRĘ +CHIDIST = ROZKŁAD.CHI +CHIINV = ROZKŁAD.CHI.ODW +CHITEST = TEST.CHI +CONCATENATE = ZŁĄCZ.TEKSTY +CONFIDENCE = UFNOŚĆ +COVAR = KOWARIANCJA +CRITBINOM = PRÓG.ROZKŁAD.DWUM +EXPONDIST = ROZKŁAD.EXP +FDIST = ROZKŁAD.F +FINV = ROZKŁAD.F.ODW +FLOOR = ZAOKR.W.DÓŁ +FORECAST = REGLINX +FTEST = TEST.F +GAMMADIST = ROZKŁAD.GAMMA +GAMMAINV = ROZKŁAD.GAMMA.ODW +HYPGEOMDIST = ROZKŁAD.HIPERGEOM +LOGINV = ROZKŁAD.LOG.ODW +LOGNORMDIST = ROZKŁAD.LOG +MODE = WYST.NAJCZĘŚCIEJ +NEGBINOMDIST = ROZKŁAD.DWUM.PRZEC +NORMDIST = ROZKŁAD.NORMALNY +NORMINV = ROZKŁAD.NORMALNY.ODW +NORMSDIST = ROZKŁAD.NORMALNY.S +NORMSINV = ROZKŁAD.NORMALNY.S.ODW +PERCENTILE = PERCENTYL +PERCENTRANK = PROCENT.POZYCJA +POISSON = ROZKŁAD.POISSON +QUARTILE = KWARTYL +RANK = POZYCJA +STDEV = ODCH.STANDARDOWE +STDEVP = ODCH.STANDARD.POPUL +TDIST = ROZKŁAD.T +TINV = ROZKŁAD.T.ODW +TTEST = TEST.T +VAR = WARIANCJA +VARP = WARIANCJA.POPUL +WEIBULL = ROZKŁAD.WEIBULL +ZTEST = TEST.Z diff --git a/src/PhpSpreadsheet/Calculation/locale/pt/br/config b/src/PhpSpreadsheet/Calculation/locale/pt/br/config index 904f99f1..c39057c7 100644 --- a/src/PhpSpreadsheet/Calculation/locale/pt/br/config +++ b/src/PhpSpreadsheet/Calculation/locale/pt/br/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## +## Português Brasileiro (Brazilian Portuguese) +## +############################################################ -ArgumentSeparator = ; - +ArgumentSeparator = ; ## -## (For future use) +## Error Codes ## -currencySymbol = R$ - - -## -## Excel Error Codes (For future use) - -## -NULL = #NULO! -DIV0 = #DIV/0! -VALUE = #VALOR! -REF = #REF! -NAME = #NOME? -NUM = #NÚM! -NA = #N/D +NULL = #NULO! +DIV0 +VALUE = #VALOR! +REF +NAME = #NOME? +NUM = #NÚM! +NA = #N/D diff --git a/src/PhpSpreadsheet/Calculation/locale/pt/br/functions b/src/PhpSpreadsheet/Calculation/locale/pt/br/functions index a062a7fa..feba30d9 100644 --- a/src/PhpSpreadsheet/Calculation/locale/pt/br/functions +++ b/src/PhpSpreadsheet/Calculation/locale/pt/br/functions @@ -1,408 +1,527 @@ +############################################################ ## -## Add-in and Automation functions Funções Suplemento e Automação +## PhpSpreadsheet - function name translations ## -GETPIVOTDATA = INFODADOSTABELADINÂMICA ## Retorna os dados armazenados em um relatório de tabela dinâmica +## Português Brasileiro (Brazilian Portuguese) +## +############################################################ ## -## Cube functions Funções de Cubo +## Funções de cubo (Cube Functions) ## -CUBEKPIMEMBER = MEMBROKPICUBO ## Retorna o nome de um KPI (indicador de desempenho-chave), uma propriedade e uma medida e exibe o nome e a propriedade na célula. Um KPI é uma medida quantificável, como o lucro bruto mensal ou a rotatividade trimestral dos funcionários, usada para monitorar o desempenho de uma organização. -CUBEMEMBER = MEMBROCUBO ## Retorna um membro ou tupla em uma hierarquia de cubo. Use para validar se o membro ou tupla existe no cubo. -CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO ## Retorna o valor da propriedade de um membro no cubo. Usada para validar a existência do nome do membro no cubo e para retornar a propriedade especificada para esse membro. -CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO ## Retorna o enésimo membro, ou o membro ordenado, em um conjunto. Use para retornar um ou mais elementos em um conjunto, assim como o melhor vendedor ou os dez melhores alunos. -CUBESET = CONJUNTOCUBO ## Define um conjunto calculado de membros ou tuplas enviando uma expressão do conjunto para o cubo no servidor, que cria o conjunto e o retorna para o Microsoft Office Excel. -CUBESETCOUNT = CONTAGEMCONJUNTOCUBO ## Retorna o número de itens em um conjunto. -CUBEVALUE = VALORCUBO ## Retorna um valor agregado de um cubo. - +CUBEKPIMEMBER = MEMBROKPICUBO +CUBEMEMBER = MEMBROCUBO +CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO +CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO +CUBESET = CONJUNTOCUBO +CUBESETCOUNT = CONTAGEMCONJUNTOCUBO +CUBEVALUE = VALORCUBO ## -## Database functions Funções de banco de dados +## Funções de banco de dados (Database Functions) ## -DAVERAGE = BDMÉDIA ## Retorna a média das entradas selecionadas de um banco de dados -DCOUNT = BDCONTAR ## Conta as células que contêm números em um banco de dados -DCOUNTA = BDCONTARA ## Conta células não vazias em um banco de dados -DGET = BDEXTRAIR ## Extrai de um banco de dados um único registro que corresponde a um critério específico -DMAX = BDMÁX ## Retorna o valor máximo de entradas selecionadas de um banco de dados -DMIN = BDMÍN ## Retorna o valor mínimo de entradas selecionadas de um banco de dados -DPRODUCT = BDMULTIPL ## Multiplica os valores em um campo específico de registros que correspondem ao critério em um banco de dados -DSTDEV = BDEST ## Estima o desvio padrão com base em uma amostra de entradas selecionadas de um banco de dados -DSTDEVP = BDDESVPA ## Calcula o desvio padrão com base na população inteira de entradas selecionadas de um banco de dados -DSUM = BDSOMA ## Adiciona os números à coluna de campos de registros do banco de dados que correspondem ao critério -DVAR = BDVAREST ## Estima a variância com base em uma amostra de entradas selecionadas de um banco de dados -DVARP = BDVARP ## Calcula a variância com base na população inteira de entradas selecionadas de um banco de dados - +DAVERAGE = BDMÉDIA +DCOUNT = BDCONTAR +DCOUNTA = BDCONTARA +DGET = BDEXTRAIR +DMAX = BDMÁX +DMIN = BDMÍN +DPRODUCT = BDMULTIPL +DSTDEV = BDEST +DSTDEVP = BDDESVPA +DSUM = BDSOMA +DVAR = BDVAREST +DVARP = BDVARP ## -## Date and time functions Funções de data e hora +## Funções de data e hora (Date & Time Functions) ## -DATE = DATA ## Retorna o número de série de uma data específica -DATEVALUE = DATA.VALOR ## Converte uma data na forma de texto para um número de série -DAY = DIA ## Converte um número de série em um dia do mês -DAYS360 = DIAS360 ## Calcula o número de dias entre duas datas com base em um ano de 360 dias -EDATE = DATAM ## Retorna o número de série da data que é o número indicado de meses antes ou depois da data inicial -EOMONTH = FIMMÊS ## Retorna o número de série do último dia do mês antes ou depois de um número especificado de meses -HOUR = HORA ## Converte um número de série em uma hora -MINUTE = MINUTO ## Converte um número de série em um minuto -MONTH = MÊS ## Converte um número de série em um mês -NETWORKDAYS = DIATRABALHOTOTAL ## Retorna o número de dias úteis inteiros entre duas datas -NOW = AGORA ## Retorna o número de série seqüencial da data e hora atuais -SECOND = SEGUNDO ## Converte um número de série em um segundo -TIME = HORA ## Retorna o número de série de uma hora específica -TIMEVALUE = VALOR.TEMPO ## Converte um horário na forma de texto para um número de série -TODAY = HOJE ## Retorna o número de série da data de hoje -WEEKDAY = DIA.DA.SEMANA ## Converte um número de série em um dia da semana -WEEKNUM = NÚMSEMANA ## Converte um número de série em um número que representa onde a semana cai numericamente em um ano -WORKDAY = DIATRABALHO ## Retorna o número de série da data antes ou depois de um número específico de dias úteis -YEAR = ANO ## Converte um número de série em um ano -YEARFRAC = FRAÇÃOANO ## Retorna a fração do ano que representa o número de dias entre data_inicial e data_final - +DATE = DATA +DATEDIF = DATADIF +DATESTRING = DATA.SÉRIE +DATEVALUE = DATA.VALOR +DAY = DIA +DAYS = DIAS +DAYS360 = DIAS360 +EDATE = DATAM +EOMONTH = FIMMÊS +HOUR = HORA +ISOWEEKNUM = NÚMSEMANAISO +MINUTE = MINUTO +MONTH = MÊS +NETWORKDAYS = DIATRABALHOTOTAL +NETWORKDAYS.INTL = DIATRABALHOTOTAL.INTL +NOW = AGORA +SECOND = SEGUNDO +TIME = TEMPO +TIMEVALUE = VALOR.TEMPO +TODAY = HOJE +WEEKDAY = DIA.DA.SEMANA +WEEKNUM = NÚMSEMANA +WORKDAY = DIATRABALHO +WORKDAY.INTL = DIATRABALHO.INTL +YEAR = ANO +YEARFRAC = FRAÇÃOANO ## -## Engineering functions Funções de engenharia +## Funções de engenharia (Engineering Functions) ## -BESSELI = BESSELI ## Retorna a função de Bessel In(x) modificada -BESSELJ = BESSELJ ## Retorna a função de Bessel Jn(x) -BESSELK = BESSELK ## Retorna a função de Bessel Kn(x) modificada -BESSELY = BESSELY ## Retorna a função de Bessel Yn(x) -BIN2DEC = BIN2DEC ## Converte um número binário em decimal -BIN2HEX = BIN2HEX ## Converte um número binário em hexadecimal -BIN2OCT = BIN2OCT ## Converte um número binário em octal -COMPLEX = COMPLEX ## Converte coeficientes reais e imaginários e um número complexo -CONVERT = CONVERTER ## Converte um número de um sistema de medida para outro -DEC2BIN = DECABIN ## Converte um número decimal em binário -DEC2HEX = DECAHEX ## Converte um número decimal em hexadecimal -DEC2OCT = DECAOCT ## Converte um número decimal em octal -DELTA = DELTA ## Testa se dois valores são iguais -ERF = FUNERRO ## Retorna a função de erro -ERFC = FUNERROCOMPL ## Retorna a função de erro complementar -GESTEP = DEGRAU ## Testa se um número é maior do que um valor limite -HEX2BIN = HEXABIN ## Converte um número hexadecimal em binário -HEX2DEC = HEXADEC ## Converte um número hexadecimal em decimal -HEX2OCT = HEXAOCT ## Converte um número hexadecimal em octal -IMABS = IMABS ## Retorna o valor absoluto (módulo) de um número complexo -IMAGINARY = IMAGINÁRIO ## Retorna o coeficiente imaginário de um número complexo -IMARGUMENT = IMARG ## Retorna o argumento teta, um ângulo expresso em radianos -IMCONJUGATE = IMCONJ ## Retorna o conjugado complexo de um número complexo -IMCOS = IMCOS ## Retorna o cosseno de um número complexo -IMDIV = IMDIV ## Retorna o quociente de dois números complexos -IMEXP = IMEXP ## Retorna o exponencial de um número complexo -IMLN = IMLN ## Retorna o logaritmo natural de um número complexo -IMLOG10 = IMLOG10 ## Retorna o logaritmo de base 10 de um número complexo -IMLOG2 = IMLOG2 ## Retorna o logaritmo de base 2 de um número complexo -IMPOWER = IMPOT ## Retorna um número complexo elevado a uma potência inteira -IMPRODUCT = IMPROD ## Retorna o produto de números complexos -IMREAL = IMREAL ## Retorna o coeficiente real de um número complexo -IMSIN = IMSENO ## Retorna o seno de um número complexo -IMSQRT = IMRAIZ ## Retorna a raiz quadrada de um número complexo -IMSUB = IMSUBTR ## Retorna a diferença entre dois números complexos -IMSUM = IMSOMA ## Retorna a soma de números complexos -OCT2BIN = OCTABIN ## Converte um número octal em binário -OCT2DEC = OCTADEC ## Converte um número octal em decimal -OCT2HEX = OCTAHEX ## Converte um número octal em hexadecimal - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BINADEC +BIN2HEX = BINAHEX +BIN2OCT = BINAOCT +BITAND = BITAND +BITLSHIFT = DESLOCESQBIT +BITOR = BITOR +BITRSHIFT = DESLOCDIRBIT +BITXOR = BITXOR +COMPLEX = COMPLEXO +CONVERT = CONVERTER +DEC2BIN = DECABIN +DEC2HEX = DECAHEX +DEC2OCT = DECAOCT +DELTA = DELTA +ERF = FUNERRO +ERF.PRECISE = FUNERRO.PRECISO +ERFC = FUNERROCOMPL +ERFC.PRECISE = FUNERROCOMPL.PRECISO +GESTEP = DEGRAU +HEX2BIN = HEXABIN +HEX2DEC = HEXADEC +HEX2OCT = HEXAOCT +IMABS = IMABS +IMAGINARY = IMAGINÁRIO +IMARGUMENT = IMARG +IMCONJUGATE = IMCONJ +IMCOS = IMCOS +IMCOSH = IMCOSH +IMCOT = IMCOT +IMCSC = IMCOSEC +IMCSCH = IMCOSECH +IMDIV = IMDIV +IMEXP = IMEXP +IMLN = IMLN +IMLOG10 = IMLOG10 +IMLOG2 = IMLOG2 +IMPOWER = IMPOT +IMPRODUCT = IMPROD +IMREAL = IMREAL +IMSEC = IMSEC +IMSECH = IMSECH +IMSIN = IMSENO +IMSINH = IMSENH +IMSQRT = IMRAIZ +IMSUB = IMSUBTR +IMSUM = IMSOMA +IMTAN = IMTAN +OCT2BIN = OCTABIN +OCT2DEC = OCTADEC +OCT2HEX = OCTAHEX ## -## Financial functions Funções financeiras +## Funções financeiras (Financial Functions) ## -ACCRINT = JUROSACUM ## Retorna a taxa de juros acumulados de um título que paga uma taxa periódica de juros -ACCRINTM = JUROSACUMV ## Retorna os juros acumulados de um título que paga juros no vencimento -AMORDEGRC = AMORDEGRC ## Retorna a depreciação para cada período contábil usando o coeficiente de depreciação -AMORLINC = AMORLINC ## Retorna a depreciação para cada período contábil -COUPDAYBS = CUPDIASINLIQ ## Retorna o número de dias do início do período de cupom até a data de liquidação -COUPDAYS = CUPDIAS ## Retorna o número de dias no período de cupom que contém a data de quitação -COUPDAYSNC = CUPDIASPRÓX ## Retorna o número de dias da data de liquidação até a data do próximo cupom -COUPNCD = CUPDATAPRÓX ## Retorna a próxima data de cupom após a data de quitação -COUPNUM = CUPNÚM ## Retorna o número de cupons pagáveis entre as datas de quitação e vencimento -COUPPCD = CUPDATAANT ## Retorna a data de cupom anterior à data de quitação -CUMIPMT = PGTOJURACUM ## Retorna os juros acumulados pagos entre dois períodos -CUMPRINC = PGTOCAPACUM ## Retorna o capital acumulado pago sobre um empréstimo entre dois períodos -DB = BD ## Retorna a depreciação de um ativo para um período especificado, usando o método de balanço de declínio fixo -DDB = BDD ## Retorna a depreciação de um ativo com relação a um período especificado usando o método de saldos decrescentes duplos ou qualquer outro método especificado por você -DISC = DESC ## Retorna a taxa de desconto de um título -DOLLARDE = MOEDADEC ## Converte um preço em formato de moeda, na forma fracionária, em um preço na forma decimal -DOLLARFR = MOEDAFRA ## Converte um preço, apresentado na forma decimal, em um preço apresentado na forma fracionária -DURATION = DURAÇÃO ## Retorna a duração anual de um título com pagamentos de juros periódicos -EFFECT = EFETIVA ## Retorna a taxa de juros anual efetiva -FV = VF ## Retorna o valor futuro de um investimento -FVSCHEDULE = VFPLANO ## Retorna o valor futuro de um capital inicial após a aplicação de uma série de taxas de juros compostas -INTRATE = TAXAJUROS ## Retorna a taxa de juros de um título totalmente investido -IPMT = IPGTO ## Retorna o pagamento de juros para um investimento em um determinado período -IRR = TIR ## Retorna a taxa interna de retorno de uma série de fluxos de caixa -ISPMT = ÉPGTO ## Calcula os juros pagos durante um período específico de um investimento -MDURATION = MDURAÇÃO ## Retorna a duração de Macauley modificada para um título com um valor de paridade equivalente a R$ 100 -MIRR = MTIR ## Calcula a taxa interna de retorno em que fluxos de caixa positivos e negativos são financiados com diferentes taxas -NOMINAL = NOMINAL ## Retorna a taxa de juros nominal anual -NPER = NPER ## Retorna o número de períodos de um investimento -NPV = VPL ## Retorna o valor líquido atual de um investimento com base em uma série de fluxos de caixa periódicos e em uma taxa de desconto -ODDFPRICE = PREÇOPRIMINC ## Retorna o preço por R$ 100 de valor nominal de um título com um primeiro período indefinido -ODDFYIELD = LUCROPRIMINC ## Retorna o rendimento de um título com um primeiro período indefinido -ODDLPRICE = PREÇOÚLTINC ## Retorna o preço por R$ 100 de valor nominal de um título com um último período de cupom indefinido -ODDLYIELD = LUCROÚLTINC ## Retorna o rendimento de um título com um último período indefinido -PMT = PGTO ## Retorna o pagamento periódico de uma anuidade -PPMT = PPGTO ## Retorna o pagamento de capital para determinado período de investimento -PRICE = PREÇO ## Retorna a preço por R$ 100,00 de valor nominal de um título que paga juros periódicos -PRICEDISC = PREÇODESC ## Retorna o preço por R$ 100,00 de valor nominal de um título descontado -PRICEMAT = PREÇOVENC ## Retorna o preço por R$ 100,00 de valor nominal de um título que paga juros no vencimento -PV = VP ## Retorna o valor presente de um investimento -RATE = TAXA ## Retorna a taxa de juros por período de uma anuidade -RECEIVED = RECEBER ## Retorna a quantia recebida no vencimento de um título totalmente investido -SLN = DPD ## Retorna a depreciação em linha reta de um ativo durante um período -SYD = SDA ## Retorna a depreciação dos dígitos da soma dos anos de um ativo para um período especificado -TBILLEQ = OTN ## Retorna o rendimento de um título equivalente a uma obrigação do Tesouro -TBILLPRICE = OTNVALOR ## Retorna o preço por R$ 100,00 de valor nominal de uma obrigação do Tesouro -TBILLYIELD = OTNLUCRO ## Retorna o rendimento de uma obrigação do Tesouro -VDB = BDV ## Retorna a depreciação de um ativo para um período especificado ou parcial usando um método de balanço declinante -XIRR = XTIR ## Fornece a taxa interna de retorno para um programa de fluxos de caixa que não é necessariamente periódico -XNPV = XVPL ## Retorna o valor presente líquido de um programa de fluxos de caixa que não é necessariamente periódico -YIELD = LUCRO ## Retorna o lucro de um título que paga juros periódicos -YIELDDISC = LUCRODESC ## Retorna o rendimento anual de um título descontado. Por exemplo, uma obrigação do Tesouro -YIELDMAT = LUCROVENC ## Retorna o lucro anual de um título que paga juros no vencimento - +ACCRINT = JUROSACUM +ACCRINTM = JUROSACUMV +AMORDEGRC = AMORDEGRC +AMORLINC = AMORLINC +COUPDAYBS = CUPDIASINLIQ +COUPDAYS = CUPDIAS +COUPDAYSNC = CUPDIASPRÓX +COUPNCD = CUPDATAPRÓX +COUPNUM = CUPNÚM +COUPPCD = CUPDATAANT +CUMIPMT = PGTOJURACUM +CUMPRINC = PGTOCAPACUM +DB = BD +DDB = BDD +DISC = DESC +DOLLARDE = MOEDADEC +DOLLARFR = MOEDAFRA +DURATION = DURAÇÃO +EFFECT = EFETIVA +FV = VF +FVSCHEDULE = VFPLANO +INTRATE = TAXAJUROS +IPMT = IPGTO +IRR = TIR +ISPMT = ÉPGTO +MDURATION = MDURAÇÃO +MIRR = MTIR +NOMINAL = NOMINAL +NPER = NPER +NPV = VPL +ODDFPRICE = PREÇOPRIMINC +ODDFYIELD = LUCROPRIMINC +ODDLPRICE = PREÇOÚLTINC +ODDLYIELD = LUCROÚLTINC +PDURATION = DURAÇÃOP +PMT = PGTO +PPMT = PPGTO +PRICE = PREÇO +PRICEDISC = PREÇODESC +PRICEMAT = PREÇOVENC +PV = VP +RATE = TAXA +RECEIVED = RECEBER +RRI = TAXAJURO +SLN = DPD +SYD = SDA +TBILLEQ = OTN +TBILLPRICE = OTNVALOR +TBILLYIELD = OTNLUCRO +VDB = BDV +XIRR = XTIR +XNPV = XVPL +YIELD = LUCRO +YIELDDISC = LUCRODESC +YIELDMAT = LUCROVENC ## -## Information functions Funções de informação +## Funções de informação (Information Functions) ## -CELL = CÉL ## Retorna informações sobre formatação, localização ou conteúdo de uma célula -ERROR.TYPE = TIPO.ERRO ## Retorna um número correspondente a um tipo de erro -INFO = INFORMAÇÃO ## Retorna informações sobre o ambiente operacional atual -ISBLANK = ÉCÉL.VAZIA ## Retorna VERDADEIRO se o valor for vazio -ISERR = ÉERRO ## Retorna VERDADEIRO se o valor for um valor de erro diferente de #N/D -ISERROR = ÉERROS ## Retorna VERDADEIRO se o valor for um valor de erro -ISEVEN = ÉPAR ## Retorna VERDADEIRO se o número for par -ISLOGICAL = ÉLÓGICO ## Retorna VERDADEIRO se o valor for um valor lógico -ISNA = É.NÃO.DISP ## Retorna VERDADEIRO se o valor for o valor de erro #N/D -ISNONTEXT = É.NÃO.TEXTO ## Retorna VERDADEIRO se o valor for diferente de texto -ISNUMBER = ÉNÚM ## Retorna VERDADEIRO se o valor for um número -ISODD = ÉIMPAR ## Retorna VERDADEIRO se o número for ímpar -ISREF = ÉREF ## Retorna VERDADEIRO se o valor for uma referência -ISTEXT = ÉTEXTO ## Retorna VERDADEIRO se o valor for texto -N = N ## Retorna um valor convertido em um número -NA = NÃO.DISP ## Retorna o valor de erro #N/D -TYPE = TIPO ## Retorna um número indicando o tipo de dados de um valor - +CELL = CÉL +ERROR.TYPE = TIPO.ERRO +INFO = INFORMAÇÃO +ISBLANK = ÉCÉL.VAZIA +ISERR = ÉERRO +ISERROR = ÉERROS +ISEVEN = ÉPAR +ISFORMULA = ÉFÓRMULA +ISLOGICAL = ÉLÓGICO +ISNA = É.NÃO.DISP +ISNONTEXT = É.NÃO.TEXTO +ISNUMBER = ÉNÚM +ISODD = ÉIMPAR +ISREF = ÉREF +ISTEXT = ÉTEXTO +N = N +NA = NÃO.DISP +SHEET = PLAN +SHEETS = PLANS +TYPE = TIPO ## -## Logical functions Funções lógicas +## Funções lógicas (Logical Functions) ## -AND = E ## Retorna VERDADEIRO se todos os seus argumentos forem VERDADEIROS -FALSE = FALSO ## Retorna o valor lógico FALSO -IF = SE ## Especifica um teste lógico a ser executado -IFERROR = SEERRO ## Retornará um valor que você especifica se uma fórmula for avaliada para um erro; do contrário, retornará o resultado da fórmula -NOT = NÃO ## Inverte o valor lógico do argumento -OR = OU ## Retorna VERDADEIRO se um dos argumentos for VERDADEIRO -TRUE = VERDADEIRO ## Retorna o valor lógico VERDADEIRO - +AND = E +FALSE = FALSO +IF = SE +IFERROR = SEERRO +IFNA = SENÃODISP +IFS = SES +NOT = NÃO +OR = OU +SWITCH = PARÂMETRO +TRUE = VERDADEIRO +XOR = XOR ## -## Lookup and reference functions Funções de pesquisa e referência +## Funções de pesquisa e referência (Lookup & Reference Functions) ## -ADDRESS = ENDEREÇO ## Retorna uma referência como texto para uma única célula em uma planilha -AREAS = ÁREAS ## Retorna o número de áreas em uma referência -CHOOSE = ESCOLHER ## Escolhe um valor a partir de uma lista de valores -COLUMN = COL ## Retorna o número da coluna de uma referência -COLUMNS = COLS ## Retorna o número de colunas em uma referência -HLOOKUP = PROCH ## Procura na linha superior de uma matriz e retorna o valor da célula especificada -HYPERLINK = HYPERLINK ## Cria um atalho ou salto que abre um documento armazenado em um servidor de rede, uma intranet ou na Internet -INDEX = ÍNDICE ## Usa um índice para escolher um valor de uma referência ou matriz -INDIRECT = INDIRETO ## Retorna uma referência indicada por um valor de texto -LOOKUP = PROC ## Procura valores em um vetor ou em uma matriz -MATCH = CORRESP ## Procura valores em uma referência ou em uma matriz -OFFSET = DESLOC ## Retorna um deslocamento de referência com base em uma determinada referência -ROW = LIN ## Retorna o número da linha de uma referência -ROWS = LINS ## Retorna o número de linhas em uma referência -RTD = RTD ## Recupera dados em tempo real de um programa que ofereça suporte a automação COM (automação: uma forma de trabalhar com objetos de um aplicativo a partir de outro aplicativo ou ferramenta de desenvolvimento. Chamada inicialmente de automação OLE, a automação é um padrão industrial e um recurso do modelo de objeto componente (COM).) -TRANSPOSE = TRANSPOR ## Retorna a transposição de uma matriz -VLOOKUP = PROCV ## Procura na primeira coluna de uma matriz e move ao longo da linha para retornar o valor de uma célula - +ADDRESS = ENDEREÇO +AREAS = ÁREAS +CHOOSE = ESCOLHER +COLUMN = COL +COLUMNS = COLS +FORMULATEXT = FÓRMULATEXTO +GETPIVOTDATA = INFODADOSTABELADINÂMICA +HLOOKUP = PROCH +HYPERLINK = HIPERLINK +INDEX = ÍNDICE +INDIRECT = INDIRETO +LOOKUP = PROC +MATCH = CORRESP +OFFSET = DESLOC +ROW = LIN +ROWS = LINS +RTD = RTD +TRANSPOSE = TRANSPOR +VLOOKUP = PROCV ## -## Math and trigonometry functions Funções matemáticas e trigonométricas +## Funções matemáticas e trigonométricas (Math & Trig Functions) ## -ABS = ABS ## Retorna o valor absoluto de um número -ACOS = ACOS ## Retorna o arco cosseno de um número -ACOSH = ACOSH ## Retorna o cosseno hiperbólico inverso de um número -ASIN = ASEN ## Retorna o arco seno de um número -ASINH = ASENH ## Retorna o seno hiperbólico inverso de um número -ATAN = ATAN ## Retorna o arco tangente de um número -ATAN2 = ATAN2 ## Retorna o arco tangente das coordenadas x e y especificadas -ATANH = ATANH ## Retorna a tangente hiperbólica inversa de um número -CEILING = TETO ## Arredonda um número para o inteiro mais próximo ou para o múltiplo mais próximo de significância -COMBIN = COMBIN ## Retorna o número de combinações de um determinado número de objetos -COS = COS ## Retorna o cosseno de um número -COSH = COSH ## Retorna o cosseno hiperbólico de um número -DEGREES = GRAUS ## Converte radianos em graus -EVEN = PAR ## Arredonda um número para cima até o inteiro par mais próximo -EXP = EXP ## Retorna e elevado à potência de um número especificado -FACT = FATORIAL ## Retorna o fatorial de um número -FACTDOUBLE = FATDUPLO ## Retorna o fatorial duplo de um número -FLOOR = ARREDMULTB ## Arredonda um número para baixo até zero -GCD = MDC ## Retorna o máximo divisor comum -INT = INT ## Arredonda um número para baixo até o número inteiro mais próximo -LCM = MMC ## Retorna o mínimo múltiplo comum -LN = LN ## Retorna o logaritmo natural de um número -LOG = LOG ## Retorna o logaritmo de um número de uma base especificada -LOG10 = LOG10 ## Retorna o logaritmo de base 10 de um número -MDETERM = MATRIZ.DETERM ## Retorna o determinante de uma matriz de uma variável do tipo matriz -MINVERSE = MATRIZ.INVERSO ## Retorna a matriz inversa de uma matriz -MMULT = MATRIZ.MULT ## Retorna o produto de duas matrizes -MOD = RESTO ## Retorna o resto da divisão -MROUND = MARRED ## Retorna um número arredondado ao múltiplo desejado -MULTINOMIAL = MULTINOMIAL ## Retorna o multinomial de um conjunto de números -ODD = ÍMPAR ## Arredonda um número para cima até o inteiro ímpar mais próximo -PI = PI ## Retorna o valor de Pi -POWER = POTÊNCIA ## Fornece o resultado de um número elevado a uma potência -PRODUCT = MULT ## Multiplica seus argumentos -QUOTIENT = QUOCIENTE ## Retorna a parte inteira de uma divisão -RADIANS = RADIANOS ## Converte graus em radianos -RAND = ALEATÓRIO ## Retorna um número aleatório entre 0 e 1 -RANDBETWEEN = ALEATÓRIOENTRE ## Retorna um número aleatório entre os números especificados -ROMAN = ROMANO ## Converte um algarismo arábico em romano, como texto -ROUND = ARRED ## Arredonda um número até uma quantidade especificada de dígitos -ROUNDDOWN = ARREDONDAR.PARA.BAIXO ## Arredonda um número para baixo até zero -ROUNDUP = ARREDONDAR.PARA.CIMA ## Arredonda um número para cima, afastando-o de zero -SERIESSUM = SOMASEQÜÊNCIA ## Retorna a soma de uma série polinomial baseada na fórmula -SIGN = SINAL ## Retorna o sinal de um número -SIN = SEN ## Retorna o seno de um ângulo dado -SINH = SENH ## Retorna o seno hiperbólico de um número -SQRT = RAIZ ## Retorna uma raiz quadrada positiva -SQRTPI = RAIZPI ## Retorna a raiz quadrada de (núm* pi) -SUBTOTAL = SUBTOTAL ## Retorna um subtotal em uma lista ou em um banco de dados -SUM = SOMA ## Soma seus argumentos -SUMIF = SOMASE ## Adiciona as células especificadas por um determinado critério -SUMIFS = SOMASE ## Adiciona as células em um intervalo que atende a vários critérios -SUMPRODUCT = SOMARPRODUTO ## Retorna a soma dos produtos de componentes correspondentes de matrizes -SUMSQ = SOMAQUAD ## Retorna a soma dos quadrados dos argumentos -SUMX2MY2 = SOMAX2DY2 ## Retorna a soma da diferença dos quadrados dos valores correspondentes em duas matrizes -SUMX2PY2 = SOMAX2SY2 ## Retorna a soma da soma dos quadrados dos valores correspondentes em duas matrizes -SUMXMY2 = SOMAXMY2 ## Retorna a soma dos quadrados das diferenças dos valores correspondentes em duas matrizes -TAN = TAN ## Retorna a tangente de um número -TANH = TANH ## Retorna a tangente hiperbólica de um número -TRUNC = TRUNCAR ## Trunca um número para um inteiro - +ABS = ABS +ACOS = ACOS +ACOSH = ACOSH +ACOT = ACOT +ACOTH = ACOTH +AGGREGATE = AGREGAR +ARABIC = ARÁBICO +ASIN = ASEN +ASINH = ASENH +ATAN = ATAN +ATAN2 = ATAN2 +ATANH = ATANH +BASE = BASE +CEILING.MATH = TETO.MAT +CEILING.PRECISE = TETO.PRECISO +COMBIN = COMBIN +COMBINA = COMBINA +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = COSEC +CSCH = COSECH +DECIMAL = DECIMAL +DEGREES = GRAUS +ECMA.CEILING = ECMA.TETO +EVEN = PAR +EXP = EXP +FACT = FATORIAL +FACTDOUBLE = FATDUPLO +FLOOR.MATH = ARREDMULTB.MAT +FLOOR.PRECISE = ARREDMULTB.PRECISO +GCD = MDC +INT = INT +ISO.CEILING = ISO.TETO +LCM = MMC +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = MATRIZ.DETERM +MINVERSE = MATRIZ.INVERSO +MMULT = MATRIZ.MULT +MOD = MOD +MROUND = MARRED +MULTINOMIAL = MULTINOMIAL +MUNIT = MUNIT +ODD = ÍMPAR +PI = PI +POWER = POTÊNCIA +PRODUCT = MULT +QUOTIENT = QUOCIENTE +RADIANS = RADIANOS +RAND = ALEATÓRIO +RANDBETWEEN = ALEATÓRIOENTRE +ROMAN = ROMANO +ROUND = ARRED +ROUNDDOWN = ARREDONDAR.PARA.BAIXO +ROUNDUP = ARREDONDAR.PARA.CIMA +SEC = SEC +SECH = SECH +SERIESSUM = SOMASEQÜÊNCIA +SIGN = SINAL +SIN = SEN +SINH = SENH +SQRT = RAIZ +SQRTPI = RAIZPI +SUBTOTAL = SUBTOTAL +SUM = SOMA +SUMIF = SOMASE +SUMIFS = SOMASES +SUMPRODUCT = SOMARPRODUTO +SUMSQ = SOMAQUAD +SUMX2MY2 = SOMAX2DY2 +SUMX2PY2 = SOMAX2SY2 +SUMXMY2 = SOMAXMY2 +TAN = TAN +TANH = TANH +TRUNC = TRUNCAR ## -## Statistical functions Funções estatísticas +## Funções estatísticas (Statistical Functions) ## -AVEDEV = DESV.MÉDIO ## Retorna a média aritmética dos desvios médios dos pontos de dados a partir de sua média -AVERAGE = MÉDIA ## Retorna a média dos argumentos -AVERAGEA = MÉDIAA ## Retorna a média dos argumentos, inclusive números, texto e valores lógicos -AVERAGEIF = MÉDIASE ## Retorna a média (média aritmética) de todas as células em um intervalo que atendem a um determinado critério -AVERAGEIFS = MÉDIASES ## Retorna a média (média aritmética) de todas as células que atendem a múltiplos critérios. -BETADIST = DISTBETA ## Retorna a função de distribuição cumulativa beta -BETAINV = BETA.ACUM.INV ## Retorna o inverso da função de distribuição cumulativa para uma distribuição beta especificada -BINOMDIST = DISTRBINOM ## Retorna a probabilidade de distribuição binomial do termo individual -CHIDIST = DIST.QUI ## Retorna a probabilidade unicaudal da distribuição qui-quadrada -CHIINV = INV.QUI ## Retorna o inverso da probabilidade uni-caudal da distribuição qui-quadrada -CHITEST = TESTE.QUI ## Retorna o teste para independência -CONFIDENCE = INT.CONFIANÇA ## Retorna o intervalo de confiança para uma média da população -CORREL = CORREL ## Retorna o coeficiente de correlação entre dois conjuntos de dados -COUNT = CONT.NÚM ## Calcula quantos números há na lista de argumentos -COUNTA = CONT.VALORES ## Calcula quantos valores há na lista de argumentos -COUNTBLANK = CONTAR.VAZIO ## Conta o número de células vazias no intervalo especificado -COUNTIF = CONT.SE ## Calcula o número de células não vazias em um intervalo que corresponde a determinados critérios -COUNTIFS = CONT.SES ## Conta o número de células dentro de um intervalo que atende a múltiplos critérios -COVAR = COVAR ## Retorna a covariância, a média dos produtos dos desvios pares -CRITBINOM = CRIT.BINOM ## Retorna o menor valor para o qual a distribuição binomial cumulativa é menor ou igual ao valor padrão -DEVSQ = DESVQ ## Retorna a soma dos quadrados dos desvios -EXPONDIST = DISTEXPON ## Retorna a distribuição exponencial -FDIST = DISTF ## Retorna a distribuição de probabilidade F -FINV = INVF ## Retorna o inverso da distribuição de probabilidades F -FISHER = FISHER ## Retorna a transformação Fisher -FISHERINV = FISHERINV ## Retorna o inverso da transformação Fisher -FORECAST = PREVISÃO ## Retorna um valor ao longo de uma linha reta -FREQUENCY = FREQÜÊNCIA ## Retorna uma distribuição de freqüência como uma matriz vertical -FTEST = TESTEF ## Retorna o resultado de um teste F -GAMMADIST = DISTGAMA ## Retorna a distribuição gama -GAMMAINV = INVGAMA ## Retorna o inverso da distribuição cumulativa gama -GAMMALN = LNGAMA ## Retorna o logaritmo natural da função gama, G(x) -GEOMEAN = MÉDIA.GEOMÉTRICA ## Retorna a média geométrica -GROWTH = CRESCIMENTO ## Retorna valores ao longo de uma tendência exponencial -HARMEAN = MÉDIA.HARMÔNICA ## Retorna a média harmônica -HYPGEOMDIST = DIST.HIPERGEOM ## Retorna a distribuição hipergeométrica -INTERCEPT = INTERCEPÇÃO ## Retorna a intercepção da linha de regressão linear -KURT = CURT ## Retorna a curtose de um conjunto de dados -LARGE = MAIOR ## Retorna o maior valor k-ésimo de um conjunto de dados -LINEST = PROJ.LIN ## Retorna os parâmetros de uma tendência linear -LOGEST = PROJ.LOG ## Retorna os parâmetros de uma tendência exponencial -LOGINV = INVLOG ## Retorna o inverso da distribuição lognormal -LOGNORMDIST = DIST.LOGNORMAL ## Retorna a distribuição lognormal cumulativa -MAX = MÁXIMO ## Retorna o valor máximo em uma lista de argumentos -MAXA = MÁXIMOA ## Retorna o maior valor em uma lista de argumentos, inclusive números, texto e valores lógicos -MEDIAN = MED ## Retorna a mediana dos números indicados -MIN = MÍNIMO ## Retorna o valor mínimo em uma lista de argumentos -MINA = MÍNIMOA ## Retorna o menor valor em uma lista de argumentos, inclusive números, texto e valores lógicos -MODE = MODO ## Retorna o valor mais comum em um conjunto de dados -NEGBINOMDIST = DIST.BIN.NEG ## Retorna a distribuição binomial negativa -NORMDIST = DIST.NORM ## Retorna a distribuição cumulativa normal -NORMINV = INV.NORM ## Retorna o inverso da distribuição cumulativa normal -NORMSDIST = DIST.NORMP ## Retorna a distribuição cumulativa normal padrão -NORMSINV = INV.NORMP ## Retorna o inverso da distribuição cumulativa normal padrão -PEARSON = PEARSON ## Retorna o coeficiente de correlação do momento do produto Pearson -PERCENTILE = PERCENTIL ## Retorna o k-ésimo percentil de valores em um intervalo -PERCENTRANK = ORDEM.PORCENTUAL ## Retorna a ordem percentual de um valor em um conjunto de dados -PERMUT = PERMUT ## Retorna o número de permutações de um determinado número de objetos -POISSON = POISSON ## Retorna a distribuição Poisson -PROB = PROB ## Retorna a probabilidade de valores em um intervalo estarem entre dois limites -QUARTILE = QUARTIL ## Retorna o quartil do conjunto de dados -RANK = ORDEM ## Retorna a posição de um número em uma lista de números -RSQ = RQUAD ## Retorna o quadrado do coeficiente de correlação do momento do produto de Pearson -SKEW = DISTORÇÃO ## Retorna a distorção de uma distribuição -SLOPE = INCLINAÇÃO ## Retorna a inclinação da linha de regressão linear -SMALL = MENOR ## Retorna o menor valor k-ésimo do conjunto de dados -STANDARDIZE = PADRONIZAR ## Retorna um valor normalizado -STDEV = DESVPAD ## Estima o desvio padrão com base em uma amostra -STDEVA = DESVPADA ## Estima o desvio padrão com base em uma amostra, inclusive números, texto e valores lógicos -STDEVP = DESVPADP ## Calcula o desvio padrão com base na população total -STDEVPA = DESVPADPA ## Calcula o desvio padrão com base na população total, inclusive números, texto e valores lógicos -STEYX = EPADYX ## Retorna o erro padrão do valor-y previsto para cada x da regressão -TDIST = DISTT ## Retorna a distribuição t de Student -TINV = INVT ## Retorna o inverso da distribuição t de Student -TREND = TENDÊNCIA ## Retorna valores ao longo de uma tendência linear -TRIMMEAN = MÉDIA.INTERNA ## Retorna a média do interior de um conjunto de dados -TTEST = TESTET ## Retorna a probabilidade associada ao teste t de Student -VAR = VAR ## Estima a variância com base em uma amostra -VARA = VARA ## Estima a variância com base em uma amostra, inclusive números, texto e valores lógicos -VARP = VARP ## Calcula a variância com base na população inteira -VARPA = VARPA ## Calcula a variância com base na população total, inclusive números, texto e valores lógicos -WEIBULL = WEIBULL ## Retorna a distribuição Weibull -ZTEST = TESTEZ ## Retorna o valor de probabilidade uni-caudal de um teste-z - +AVEDEV = DESV.MÉDIO +AVERAGE = MÉDIA +AVERAGEA = MÉDIAA +AVERAGEIF = MÉDIASE +AVERAGEIFS = MÉDIASES +BETA.DIST = DIST.BETA +BETA.INV = INV.BETA +BINOM.DIST = DISTR.BINOM +BINOM.DIST.RANGE = INTERV.DISTR.BINOM +BINOM.INV = INV.BINOM +CHISQ.DIST = DIST.QUIQUA +CHISQ.DIST.RT = DIST.QUIQUA.CD +CHISQ.INV = INV.QUIQUA +CHISQ.INV.RT = INV.QUIQUA.CD +CHISQ.TEST = TESTE.QUIQUA +CONFIDENCE.NORM = INT.CONFIANÇA.NORM +CONFIDENCE.T = INT.CONFIANÇA.T +CORREL = CORREL +COUNT = CONT.NÚM +COUNTA = CONT.VALORES +COUNTBLANK = CONTAR.VAZIO +COUNTIF = CONT.SE +COUNTIFS = CONT.SES +COVARIANCE.P = COVARIAÇÃO.P +COVARIANCE.S = COVARIAÇÃO.S +DEVSQ = DESVQ +EXPON.DIST = DISTR.EXPON +F.DIST = DIST.F +F.DIST.RT = DIST.F.CD +F.INV = INV.F +F.INV.RT = INV.F.CD +F.TEST = TESTE.F +FISHER = FISHER +FISHERINV = FISHERINV +FORECAST.ETS = PREVISÃO.ETS +FORECAST.ETS.CONFINT = PREVISÃO.ETS.CONFINT +FORECAST.ETS.SEASONALITY = PREVISÃO.ETS.SAZONALIDADE +FORECAST.ETS.STAT = PREVISÃO.ETS.STAT +FORECAST.LINEAR = PREVISÃO.LINEAR +FREQUENCY = FREQÜÊNCIA +GAMMA = GAMA +GAMMA.DIST = DIST.GAMA +GAMMA.INV = INV.GAMA +GAMMALN = LNGAMA +GAMMALN.PRECISE = LNGAMA.PRECISO +GAUSS = GAUSS +GEOMEAN = MÉDIA.GEOMÉTRICA +GROWTH = CRESCIMENTO +HARMEAN = MÉDIA.HARMÔNICA +HYPGEOM.DIST = DIST.HIPERGEOM.N +INTERCEPT = INTERCEPÇÃO +KURT = CURT +LARGE = MAIOR +LINEST = PROJ.LIN +LOGEST = PROJ.LOG +LOGNORM.DIST = DIST.LOGNORMAL.N +LOGNORM.INV = INV.LOGNORMAL +MAX = MÁXIMO +MAXA = MÁXIMOA +MAXIFS = MÁXIMOSES +MEDIAN = MED +MIN = MÍNIMO +MINA = MÍNIMOA +MINIFS = MÍNIMOSES +MODE.MULT = MODO.MULT +MODE.SNGL = MODO.ÚNICO +NEGBINOM.DIST = DIST.BIN.NEG.N +NORM.DIST = DIST.NORM.N +NORM.INV = INV.NORM.N +NORM.S.DIST = DIST.NORMP.N +NORM.S.INV = INV.NORMP.N +PEARSON = PEARSON +PERCENTILE.EXC = PERCENTIL.EXC +PERCENTILE.INC = PERCENTIL.INC +PERCENTRANK.EXC = ORDEM.PORCENTUAL.EXC +PERCENTRANK.INC = ORDEM.PORCENTUAL.INC +PERMUT = PERMUT +PERMUTATIONA = PERMUTAS +PHI = PHI +POISSON.DIST = DIST.POISSON +PROB = PROB +QUARTILE.EXC = QUARTIL.EXC +QUARTILE.INC = QUARTIL.INC +RANK.AVG = ORDEM.MÉD +RANK.EQ = ORDEM.EQ +RSQ = RQUAD +SKEW = DISTORÇÃO +SKEW.P = DISTORÇÃO.P +SLOPE = INCLINAÇÃO +SMALL = MENOR +STANDARDIZE = PADRONIZAR +STDEV.P = DESVPAD.P +STDEV.S = DESVPAD.A +STDEVA = DESVPADA +STDEVPA = DESVPADPA +STEYX = EPADYX +T.DIST = DIST.T +T.DIST.2T = DIST.T.BC +T.DIST.RT = DIST.T.CD +T.INV = INV.T +T.INV.2T = INV.T.BC +T.TEST = TESTE.T +TREND = TENDÊNCIA +TRIMMEAN = MÉDIA.INTERNA +VAR.P = VAR.P +VAR.S = VAR.A +VARA = VARA +VARPA = VARPA +WEIBULL.DIST = DIST.WEIBULL +Z.TEST = TESTE.Z ## -## Text functions Funções de texto +## Funções de texto (Text Functions) ## -ASC = ASC ## Altera letras do inglês ou katakana de largura total (bytes duplos) dentro de uma seqüência de caracteres para caracteres de meia largura (byte único) -BAHTTEXT = BAHTTEXT ## Converte um número em um texto, usando o formato de moeda ß (baht) -CHAR = CARACT ## Retorna o caractere especificado pelo número de código -CLEAN = TIRAR ## Remove todos os caracteres do texto que não podem ser impressos -CODE = CÓDIGO ## Retorna um código numérico para o primeiro caractere de uma seqüência de caracteres de texto -CONCATENATE = CONCATENAR ## Agrupa vários itens de texto em um único item de texto -DOLLAR = MOEDA ## Converte um número em texto, usando o formato de moeda $ (dólar) -EXACT = EXATO ## Verifica se dois valores de texto são idênticos -FIND = PROCURAR ## Procura um valor de texto dentro de outro (diferencia maiúsculas de minúsculas) -FINDB = PROCURARB ## Procura um valor de texto dentro de outro (diferencia maiúsculas de minúsculas) -FIXED = DEF.NÚM.DEC ## Formata um número como texto com um número fixo de decimais -JIS = JIS ## Altera letras do inglês ou katakana de meia largura (byte único) dentro de uma seqüência de caracteres para caracteres de largura total (bytes duplos) -LEFT = ESQUERDA ## Retorna os caracteres mais à esquerda de um valor de texto -LEFTB = ESQUERDAB ## Retorna os caracteres mais à esquerda de um valor de texto -LEN = NÚM.CARACT ## Retorna o número de caracteres em uma seqüência de texto -LENB = NÚM.CARACTB ## Retorna o número de caracteres em uma seqüência de texto -LOWER = MINÚSCULA ## Converte texto para minúsculas -MID = EXT.TEXTO ## Retorna um número específico de caracteres de uma seqüência de texto começando na posição especificada -MIDB = EXT.TEXTOB ## Retorna um número específico de caracteres de uma seqüência de texto começando na posição especificada -PHONETIC = FONÉTICA ## Extrai os caracteres fonéticos (furigana) de uma seqüência de caracteres de texto -PROPER = PRI.MAIÚSCULA ## Coloca a primeira letra de cada palavra em maiúscula em um valor de texto -REPLACE = MUDAR ## Muda os caracteres dentro do texto -REPLACEB = MUDARB ## Muda os caracteres dentro do texto -REPT = REPT ## Repete o texto um determinado número de vezes -RIGHT = DIREITA ## Retorna os caracteres mais à direita de um valor de texto -RIGHTB = DIREITAB ## Retorna os caracteres mais à direita de um valor de texto -SEARCH = LOCALIZAR ## Localiza um valor de texto dentro de outro (não diferencia maiúsculas de minúsculas) -SEARCHB = LOCALIZARB ## Localiza um valor de texto dentro de outro (não diferencia maiúsculas de minúsculas) -SUBSTITUTE = SUBSTITUIR ## Substitui um novo texto por um texto antigo em uma seqüência de texto -T = T ## Converte os argumentos em texto -TEXT = TEXTO ## Formata um número e o converte em texto -TRIM = ARRUMAR ## Remove espaços do texto -UPPER = MAIÚSCULA ## Converte o texto em maiúsculas -VALUE = VALOR ## Converte um argumento de texto em um número +BAHTTEXT = BAHTTEXT +CHAR = CARACT +CLEAN = TIRAR +CODE = CÓDIGO +CONCAT = CONCAT +DOLLAR = MOEDA +EXACT = EXATO +FIND = PROCURAR +FIXED = DEF.NÚM.DEC +LEFT = ESQUERDA +LEN = NÚM.CARACT +LOWER = MINÚSCULA +MID = EXT.TEXTO +NUMBERSTRING = SEQÜÊNCIA.NÚMERO +NUMBERVALUE = VALORNUMÉRICO +PHONETIC = FONÉTICA +PROPER = PRI.MAIÚSCULA +REPLACE = MUDAR +REPT = REPT +RIGHT = DIREITA +SEARCH = LOCALIZAR +SUBSTITUTE = SUBSTITUIR +T = T +TEXT = TEXTO +TEXTJOIN = UNIRTEXTO +TRIM = ARRUMAR +UNICHAR = CARACTUNICODE +UNICODE = UNICODE +UPPER = MAIÚSCULA +VALUE = VALOR + +## +## Funções da Web (Web Functions) +## +ENCODEURL = CODIFURL +FILTERXML = FILTROXML +WEBSERVICE = SERVIÇOWEB + +## +## Funções de compatibilidade (Compatibility Functions) +## +BETADIST = DISTBETA +BETAINV = BETA.ACUM.INV +BINOMDIST = DISTRBINOM +CEILING = TETO +CHIDIST = DIST.QUI +CHIINV = INV.QUI +CHITEST = TESTE.QUI +CONCATENATE = CONCATENAR +CONFIDENCE = INT.CONFIANÇA +COVAR = COVAR +CRITBINOM = CRIT.BINOM +EXPONDIST = DISTEXPON +FDIST = DISTF +FINV = INVF +FLOOR = ARREDMULTB +FORECAST = PREVISÃO +FTEST = TESTEF +GAMMADIST = DISTGAMA +GAMMAINV = INVGAMA +HYPGEOMDIST = DIST.HIPERGEOM +LOGINV = INVLOG +LOGNORMDIST = DIST.LOGNORMAL +MODE = MODO +NEGBINOMDIST = DIST.BIN.NEG +NORMDIST = DISTNORM +NORMINV = INV.NORM +NORMSDIST = DISTNORMP +NORMSINV = INV.NORMP +PERCENTILE = PERCENTIL +PERCENTRANK = ORDEM.PORCENTUAL +POISSON = POISSON +QUARTILE = QUARTIL +RANK = ORDEM +STDEV = DESVPAD +STDEVP = DESVPADP +TDIST = DISTT +TINV = INVT +TTEST = TESTET +VAR = VAR +VARP = VARP +WEIBULL = WEIBULL +ZTEST = TESTEZ diff --git a/src/PhpSpreadsheet/Calculation/locale/pt/config b/src/PhpSpreadsheet/Calculation/locale/pt/config index cd85c17a..e661830b 100644 --- a/src/PhpSpreadsheet/Calculation/locale/pt/config +++ b/src/PhpSpreadsheet/Calculation/locale/pt/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## +## Português (Portuguese) +## +############################################################ -ArgumentSeparator = ; - +ArgumentSeparator = ; ## -## (For future use) +## Error Codes ## -currencySymbol = € - - -## -## Excel Error Codes (For future use) - -## -NULL = #NULO! -DIV0 = #DIV/0! -VALUE = #VALOR! -REF = #REF! -NAME = #NOME? -NUM = #NÚM! -NA = #N/D +NULL = #NULO! +DIV0 +VALUE = #VALOR! +REF +NAME = #NOME? +NUM = #NÚM! +NA = #N/D diff --git a/src/PhpSpreadsheet/Calculation/locale/pt/functions b/src/PhpSpreadsheet/Calculation/locale/pt/functions index ba4eb471..8a94d826 100644 --- a/src/PhpSpreadsheet/Calculation/locale/pt/functions +++ b/src/PhpSpreadsheet/Calculation/locale/pt/functions @@ -1,408 +1,537 @@ +############################################################ ## -## Add-in and Automation functions Funções de Suplemento e Automatização +## PhpSpreadsheet - function name translations ## -GETPIVOTDATA = OBTERDADOSDIN ## Devolve dados armazenados num relatório de Tabela Dinâmica +## Português (Portuguese) +## +############################################################ ## -## Cube functions Funções de cubo +## Funções de cubo (Cube Functions) ## -CUBEKPIMEMBER = MEMBROKPICUBO ## Devolve o nome, propriedade e medição de um KPI (key performance indicator) e apresenta o nome e a propriedade na célula. Um KPI é uma medida quantificável, como, por exemplo, o lucro mensal bruto ou a rotatividade trimestral de pessoal, utilizada para monitorizar o desempenho de uma organização. -CUBEMEMBER = MEMBROCUBO ## Devolve um membro ou cadeia de identificação numa hierarquia de cubo. Utilizada para validar a existência do membro ou cadeia de identificação no cubo. -CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO ## Devolve o valor de uma propriedade de membro no cubo. Utilizada para validar a existência de um nome de membro no cubo e para devolver a propriedade especificada para esse membro. -CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO ## Devolve o enésimo ou a classificação mais alta num conjunto. Utilizada para devolver um ou mais elementos num conjunto, tal como o melhor vendedor ou os 10 melhores alunos. -CUBESET = CONJUNTOCUBO ## Define um conjunto calculado de membros ou cadeias de identificação enviando uma expressão de conjunto para o cubo no servidor, que cria o conjunto e, em seguida, devolve o conjunto ao Microsoft Office Excel. -CUBESETCOUNT = CONTARCONJUNTOCUBO ## Devolve o número de itens num conjunto. -CUBEVALUE = VALORCUBO ## Devolve um valor agregado do cubo. - +CUBEKPIMEMBER = MEMBROKPICUBO +CUBEMEMBER = MEMBROCUBO +CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO +CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO +CUBESET = CONJUNTOCUBO +CUBESETCOUNT = CONTARCONJUNTOCUBO +CUBEVALUE = VALORCUBO ## -## Database functions Funções de base de dados +## Funções de base de dados (Database Functions) ## -DAVERAGE = BDMÉDIA ## Devolve a média das entradas da base de dados seleccionadas -DCOUNT = BDCONTAR ## Conta as células que contêm números numa base de dados -DCOUNTA = BDCONTAR.VAL ## Conta as células que não estejam em branco numa base de dados -DGET = BDOBTER ## Extrai de uma base de dados um único registo que corresponde aos critérios especificados -DMAX = BDMÁX ## Devolve o valor máximo das entradas da base de dados seleccionadas -DMIN = BDMÍN ## Devolve o valor mínimo das entradas da base de dados seleccionadas -DPRODUCT = BDMULTIPL ## Multiplica os valores de um determinado campo de registos que correspondem aos critérios numa base de dados -DSTDEV = BDDESVPAD ## Calcula o desvio-padrão com base numa amostra de entradas da base de dados seleccionadas -DSTDEVP = BDDESVPADP ## Calcula o desvio-padrão com base na população total das entradas da base de dados seleccionadas -DSUM = BDSOMA ## Adiciona os números na coluna de campo dos registos de base de dados que correspondem aos critérios -DVAR = BDVAR ## Calcula a variância com base numa amostra das entradas de base de dados seleccionadas -DVARP = BDVARP ## Calcula a variância com base na população total das entradas de base de dados seleccionadas - +DAVERAGE = BDMÉDIA +DCOUNT = BDCONTAR +DCOUNTA = BDCONTAR.VAL +DGET = BDOBTER +DMAX = BDMÁX +DMIN = BDMÍN +DPRODUCT = BDMULTIPL +DSTDEV = BDDESVPAD +DSTDEVP = BDDESVPADP +DSUM = BDSOMA +DVAR = BDVAR +DVARP = BDVARP ## -## Date and time functions Funções de data e hora +## Funções de data e hora (Date & Time Functions) ## -DATE = DATA ## Devolve o número de série de uma determinada data -DATEVALUE = DATA.VALOR ## Converte uma data em forma de texto num número de série -DAY = DIA ## Converte um número de série num dia do mês -DAYS360 = DIAS360 ## Calcula o número de dias entre duas datas com base num ano com 360 dias -EDATE = DATAM ## Devolve um número de série de data que corresponde ao número de meses indicado antes ou depois da data de início -EOMONTH = FIMMÊS ## Devolve o número de série do último dia do mês antes ou depois de um número de meses especificado -HOUR = HORA ## Converte um número de série numa hora -MINUTE = MINUTO ## Converte um número de série num minuto -MONTH = MÊS ## Converte um número de série num mês -NETWORKDAYS = DIATRABALHOTOTAL ## Devolve o número total de dias úteis entre duas datas -NOW = AGORA ## Devolve o número de série da data e hora actuais -SECOND = SEGUNDO ## Converte um número de série num segundo -TIME = TEMPO ## Devolve o número de série de um determinado tempo -TIMEVALUE = VALOR.TEMPO ## Converte um tempo em forma de texto num número de série -TODAY = HOJE ## Devolve o número de série da data actual -WEEKDAY = DIA.SEMANA ## Converte um número de série num dia da semana -WEEKNUM = NÚMSEMANA ## Converte um número de série num número que representa o número da semana num determinado ano -WORKDAY = DIA.TRABALHO ## Devolve o número de série da data antes ou depois de um número de dias úteis especificado -YEAR = ANO ## Converte um número de série num ano -YEARFRAC = FRACÇÃOANO ## Devolve a fracção de ano que representa o número de dias inteiros entre a data_de_início e a data_de_fim - +DATE = DATA +DATEDIF = DATADIF +DATESTRING = DATA.CADEIA +DATEVALUE = DATA.VALOR +DAY = DIA +DAYS = DIAS +DAYS360 = DIAS360 +EDATE = DATAM +EOMONTH = FIMMÊS +HOUR = HORA +ISOWEEKNUM = NUMSEMANAISO +MINUTE = MINUTO +MONTH = MÊS +NETWORKDAYS = DIATRABALHOTOTAL +NETWORKDAYS.INTL = DIATRABALHOTOTAL.INTL +NOW = AGORA +SECOND = SEGUNDO +THAIDAYOFWEEK = DIA.DA.SEMANA.TAILANDÊS +THAIMONTHOFYEAR = MÊS.DO.ANO.TAILANDÊS +THAIYEAR = ANO.TAILANDÊS +TIME = TEMPO +TIMEVALUE = VALOR.TEMPO +TODAY = HOJE +WEEKDAY = DIA.SEMANA +WEEKNUM = NÚMSEMANA +WORKDAY = DIATRABALHO +WORKDAY.INTL = DIATRABALHO.INTL +YEAR = ANO +YEARFRAC = FRAÇÃOANO ## -## Engineering functions Funções de engenharia +## Funções de engenharia (Engineering Functions) ## -BESSELI = BESSELI ## Devolve a função de Bessel modificada In(x) -BESSELJ = BESSELJ ## Devolve a função de Bessel Jn(x) -BESSELK = BESSELK ## Devolve a função de Bessel modificada Kn(x) -BESSELY = BESSELY ## Devolve a função de Bessel Yn(x) -BIN2DEC = BINADEC ## Converte um número binário em decimal -BIN2HEX = BINAHEX ## Converte um número binário em hexadecimal -BIN2OCT = BINAOCT ## Converte um número binário em octal -COMPLEX = COMPLEXO ## Converte coeficientes reais e imaginários num número complexo -CONVERT = CONVERTER ## Converte um número de um sistema de medida noutro -DEC2BIN = DECABIN ## Converte um número decimal em binário -DEC2HEX = DECAHEX ## Converte um número decimal em hexadecimal -DEC2OCT = DECAOCT ## Converte um número decimal em octal -DELTA = DELTA ## Testa se dois valores são iguais -ERF = FUNCERRO ## Devolve a função de erro -ERFC = FUNCERROCOMPL ## Devolve a função de erro complementar -GESTEP = DEGRAU ## Testa se um número é maior do que um valor limite -HEX2BIN = HEXABIN ## Converte um número hexadecimal em binário -HEX2DEC = HEXADEC ## Converte um número hexadecimal em decimal -HEX2OCT = HEXAOCT ## Converte um número hexadecimal em octal -IMABS = IMABS ## Devolve o valor absoluto (módulo) de um número complexo -IMAGINARY = IMAGINÁRIO ## Devolve o coeficiente imaginário de um número complexo -IMARGUMENT = IMARG ## Devolve o argumento Teta, um ângulo expresso em radianos -IMCONJUGATE = IMCONJ ## Devolve o conjugado complexo de um número complexo -IMCOS = IMCOS ## Devolve o co-seno de um número complexo -IMDIV = IMDIV ## Devolve o quociente de dois números complexos -IMEXP = IMEXP ## Devolve o exponencial de um número complexo -IMLN = IMLN ## Devolve o logaritmo natural de um número complexo -IMLOG10 = IMLOG10 ## Devolve o logaritmo de base 10 de um número complexo -IMLOG2 = IMLOG2 ## Devolve o logaritmo de base 2 de um número complexo -IMPOWER = IMPOT ## Devolve um número complexo elevado a uma potência inteira -IMPRODUCT = IMPROD ## Devolve o produto de números complexos -IMREAL = IMREAL ## Devolve o coeficiente real de um número complexo -IMSIN = IMSENO ## Devolve o seno de um número complexo -IMSQRT = IMRAIZ ## Devolve a raiz quadrada de um número complexo -IMSUB = IMSUBTR ## Devolve a diferença entre dois números complexos -IMSUM = IMSOMA ## Devolve a soma de números complexos -OCT2BIN = OCTABIN ## Converte um número octal em binário -OCT2DEC = OCTADEC ## Converte um número octal em decimal -OCT2HEX = OCTAHEX ## Converte um número octal em hexadecimal - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BINADEC +BIN2HEX = BINAHEX +BIN2OCT = BINAOCT +BITAND = BIT.E +BITLSHIFT = BITDESL.ESQ +BITOR = BIT.OU +BITRSHIFT = BITDESL.DIR +BITXOR = BIT.XOU +COMPLEX = COMPLEXO +CONVERT = CONVERTER +DEC2BIN = DECABIN +DEC2HEX = DECAHEX +DEC2OCT = DECAOCT +DELTA = DELTA +ERF = FUNCERRO +ERF.PRECISE = FUNCERRO.PRECISO +ERFC = FUNCERROCOMPL +ERFC.PRECISE = FUNCERROCOMPL.PRECISO +GESTEP = DEGRAU +HEX2BIN = HEXABIN +HEX2DEC = HEXADEC +HEX2OCT = HEXAOCT +IMABS = IMABS +IMAGINARY = IMAGINÁRIO +IMARGUMENT = IMARG +IMCONJUGATE = IMCONJ +IMCOS = IMCOS +IMCOSH = IMCOSH +IMCOT = IMCOT +IMCSC = IMCSC +IMCSCH = IMCSCH +IMDIV = IMDIV +IMEXP = IMEXP +IMLN = IMLN +IMLOG10 = IMLOG10 +IMLOG2 = IMLOG2 +IMPOWER = IMPOT +IMPRODUCT = IMPROD +IMREAL = IMREAL +IMSEC = IMSEC +IMSECH = IMSECH +IMSIN = IMSENO +IMSINH = IMSENOH +IMSQRT = IMRAIZ +IMSUB = IMSUBTR +IMSUM = IMSOMA +IMTAN = IMTAN +OCT2BIN = OCTABIN +OCT2DEC = OCTADEC +OCT2HEX = OCTAHEX ## -## Financial functions Funções financeiras +## Funções financeiras (Financial Functions) ## -ACCRINT = JUROSACUM ## Devolve os juros acumulados de um título que paga juros periódicos -ACCRINTM = JUROSACUMV ## Devolve os juros acumulados de um título que paga juros no vencimento -AMORDEGRC = AMORDEGRC ## Devolve a depreciação correspondente a cada período contabilístico utilizando um coeficiente de depreciação -AMORLINC = AMORLINC ## Devolve a depreciação correspondente a cada período contabilístico -COUPDAYBS = CUPDIASINLIQ ## Devolve o número de dias entre o início do período do cupão e a data de regularização -COUPDAYS = CUPDIAS ## Devolve o número de dias no período do cupão que contém a data de regularização -COUPDAYSNC = CUPDIASPRÓX ## Devolve o número de dias entre a data de regularização e a data do cupão seguinte -COUPNCD = CUPDATAPRÓX ## Devolve a data do cupão seguinte após a data de regularização -COUPNUM = CUPNÚM ## Devolve o número de cupões a serem pagos entre a data de regularização e a data de vencimento -COUPPCD = CUPDATAANT ## Devolve a data do cupão anterior antes da data de regularização -CUMIPMT = PGTOJURACUM ## Devolve os juros cumulativos pagos entre dois períodos -CUMPRINC = PGTOCAPACUM ## Devolve o capital cumulativo pago a título de empréstimo entre dois períodos -DB = BD ## Devolve a depreciação de um activo relativo a um período especificado utilizando o método das quotas degressivas fixas -DDB = BDD ## Devolve a depreciação de um activo relativo a um período especificado utilizando o método das quotas degressivas duplas ou qualquer outro método especificado -DISC = DESC ## Devolve a taxa de desconto de um título -DOLLARDE = MOEDADEC ## Converte um preço em unidade monetária, expresso como uma fracção, num preço em unidade monetária, expresso como um número decimal -DOLLARFR = MOEDAFRA ## Converte um preço em unidade monetária, expresso como um número decimal, num preço em unidade monetária, expresso como uma fracção -DURATION = DURAÇÃO ## Devolve a duração anual de um título com pagamentos de juros periódicos -EFFECT = EFECTIVA ## Devolve a taxa de juros anual efectiva -FV = VF ## Devolve o valor futuro de um investimento -FVSCHEDULE = VFPLANO ## Devolve o valor futuro de um capital inicial após a aplicação de uma série de taxas de juro compostas -INTRATE = TAXAJUROS ## Devolve a taxa de juros de um título investido na totalidade -IPMT = IPGTO ## Devolve o pagamento dos juros de um investimento durante um determinado período -IRR = TIR ## Devolve a taxa de rentabilidade interna para uma série de fluxos monetários -ISPMT = É.PGTO ## Calcula os juros pagos durante um período específico de um investimento -MDURATION = MDURAÇÃO ## Devolve a duração modificada de Macauley de um título com um valor de paridade equivalente a € 100 -MIRR = MTIR ## Devolve a taxa interna de rentabilidade em que os fluxos monetários positivos e negativos são financiados com taxas diferentes -NOMINAL = NOMINAL ## Devolve a taxa de juros nominal anual -NPER = NPER ## Devolve o número de períodos de um investimento -NPV = VAL ## Devolve o valor actual líquido de um investimento com base numa série de fluxos monetários periódicos e numa taxa de desconto -ODDFPRICE = PREÇOPRIMINC ## Devolve o preço por € 100 do valor nominal de um título com um período inicial incompleto -ODDFYIELD = LUCROPRIMINC ## Devolve o lucro de um título com um período inicial incompleto -ODDLPRICE = PREÇOÚLTINC ## Devolve o preço por € 100 do valor nominal de um título com um período final incompleto -ODDLYIELD = LUCROÚLTINC ## Devolve o lucro de um título com um período final incompleto -PMT = PGTO ## Devolve o pagamento periódico de uma anuidade -PPMT = PPGTO ## Devolve o pagamento sobre o capital de um investimento num determinado período -PRICE = PREÇO ## Devolve o preço por € 100 do valor nominal de um título que paga juros periódicos -PRICEDISC = PREÇODESC ## Devolve o preço por € 100 do valor nominal de um título descontado -PRICEMAT = PREÇOVENC ## Devolve o preço por € 100 do valor nominal de um título que paga juros no vencimento -PV = VA ## Devolve o valor actual de um investimento -RATE = TAXA ## Devolve a taxa de juros por período de uma anuidade -RECEIVED = RECEBER ## Devolve o montante recebido no vencimento de um título investido na totalidade -SLN = AMORT ## Devolve uma depreciação linear de um activo durante um período -SYD = AMORTD ## Devolve a depreciação por algarismos da soma dos anos de um activo durante um período especificado -TBILLEQ = OTN ## Devolve o lucro de um título equivalente a uma Obrigação do Tesouro -TBILLPRICE = OTNVALOR ## Devolve o preço por € 100 de valor nominal de uma Obrigação do Tesouro -TBILLYIELD = OTNLUCRO ## Devolve o lucro de uma Obrigação do Tesouro -VDB = BDV ## Devolve a depreciação de um activo relativo a um período específico ou parcial utilizando um método de quotas degressivas -XIRR = XTIR ## Devolve a taxa interna de rentabilidade de um plano de fluxos monetários que não seja necessariamente periódica -XNPV = XVAL ## Devolve o valor actual líquido de um plano de fluxos monetários que não seja necessariamente periódico -YIELD = LUCRO ## Devolve o lucro de um título que paga juros periódicos -YIELDDISC = LUCRODESC ## Devolve o lucro anual de um título emitido abaixo do valor nominal, por exemplo, uma Obrigação do Tesouro -YIELDMAT = LUCROVENC ## Devolve o lucro anual de um título que paga juros na data de vencimento - +ACCRINT = JUROSACUM +ACCRINTM = JUROSACUMV +AMORDEGRC = AMORDEGRC +AMORLINC = AMORLINC +COUPDAYBS = CUPDIASINLIQ +COUPDAYS = CUPDIAS +COUPDAYSNC = CUPDIASPRÓX +COUPNCD = CUPDATAPRÓX +COUPNUM = CUPNÚM +COUPPCD = CUPDATAANT +CUMIPMT = PGTOJURACUM +CUMPRINC = PGTOCAPACUM +DB = BD +DDB = BDD +DISC = DESC +DOLLARDE = MOEDADEC +DOLLARFR = MOEDAFRA +DURATION = DURAÇÃO +EFFECT = EFETIVA +FV = VF +FVSCHEDULE = VFPLANO +INTRATE = TAXAJUROS +IPMT = IPGTO +IRR = TIR +ISPMT = É.PGTO +MDURATION = MDURAÇÃO +MIRR = MTIR +NOMINAL = NOMINAL +NPER = NPER +NPV = VAL +ODDFPRICE = PREÇOPRIMINC +ODDFYIELD = LUCROPRIMINC +ODDLPRICE = PREÇOÚLTINC +ODDLYIELD = LUCROÚLTINC +PDURATION = PDURAÇÃO +PMT = PGTO +PPMT = PPGTO +PRICE = PREÇO +PRICEDISC = PREÇODESC +PRICEMAT = PREÇOVENC +PV = VA +RATE = TAXA +RECEIVED = RECEBER +RRI = DEVOLVERTAXAJUROS +SLN = AMORT +SYD = AMORTD +TBILLEQ = OTN +TBILLPRICE = OTNVALOR +TBILLYIELD = OTNLUCRO +VDB = BDV +XIRR = XTIR +XNPV = XVAL +YIELD = LUCRO +YIELDDISC = LUCRODESC +YIELDMAT = LUCROVENC ## -## Information functions Funções de informação +## Funções de informação (Information Functions) ## -CELL = CÉL ## Devolve informações sobre a formatação, localização ou conteúdo de uma célula -ERROR.TYPE = TIPO.ERRO ## Devolve um número correspondente a um tipo de erro -INFO = INFORMAÇÃO ## Devolve informações sobre o ambiente de funcionamento actual -ISBLANK = É.CÉL.VAZIA ## Devolve VERDADEIRO se o valor estiver em branco -ISERR = É.ERROS ## Devolve VERDADEIRO se o valor for um valor de erro diferente de #N/D -ISERROR = É.ERRO ## Devolve VERDADEIRO se o valor for um valor de erro -ISEVEN = ÉPAR ## Devolve VERDADEIRO se o número for par -ISLOGICAL = É.LÓGICO ## Devolve VERDADEIRO se o valor for lógico -ISNA = É.NÃO.DISP ## Devolve VERDADEIRO se o valor for o valor de erro #N/D -ISNONTEXT = É.NÃO.TEXTO ## Devolve VERDADEIRO se o valor não for texto -ISNUMBER = É.NÚM ## Devolve VERDADEIRO se o valor for um número -ISODD = ÉÍMPAR ## Devolve VERDADEIRO se o número for ímpar -ISREF = É.REF ## Devolve VERDADEIRO se o valor for uma referência -ISTEXT = É.TEXTO ## Devolve VERDADEIRO se o valor for texto -N = N ## Devolve um valor convertido num número -NA = NÃO.DISP ## Devolve o valor de erro #N/D -TYPE = TIPO ## Devolve um número que indica o tipo de dados de um valor - +CELL = CÉL +ERROR.TYPE = TIPO.ERRO +INFO = INFORMAÇÃO +ISBLANK = É.CÉL.VAZIA +ISERR = É.ERROS +ISERROR = É.ERRO +ISEVEN = ÉPAR +ISFORMULA = É.FORMULA +ISLOGICAL = É.LÓGICO +ISNA = É.NÃO.DISP +ISNONTEXT = É.NÃO.TEXTO +ISNUMBER = É.NÚM +ISODD = ÉÍMPAR +ISREF = É.REF +ISTEXT = É.TEXTO +N = N +NA = NÃO.DISP +SHEET = FOLHA +SHEETS = FOLHAS +TYPE = TIPO ## -## Logical functions Funções lógicas +## Funções lógicas (Logical Functions) ## -AND = E ## Devolve VERDADEIRO se todos os respectivos argumentos corresponderem a VERDADEIRO -FALSE = FALSO ## Devolve o valor lógico FALSO -IF = SE ## Especifica um teste lógico a ser executado -IFERROR = SE.ERRO ## Devolve um valor definido pelo utilizador se ocorrer um erro na fórmula, e devolve o resultado da fórmula se não ocorrer nenhum erro -NOT = NÃO ## Inverte a lógica do respectivo argumento -OR = OU ## Devolve VERDADEIRO se qualquer argumento for VERDADEIRO -TRUE = VERDADEIRO ## Devolve o valor lógico VERDADEIRO - +AND = E +FALSE = FALSO +IF = SE +IFERROR = SE.ERRO +IFNA = SEND +IFS = SE.S +NOT = NÃO +OR = OU +SWITCH = PARÂMETRO +TRUE = VERDADEIRO +XOR = XOU ## -## Lookup and reference functions Funções de pesquisa e referência +## Funções de pesquisa e referência (Lookup & Reference Functions) ## -ADDRESS = ENDEREÇO ## Devolve uma referência a uma única célula numa folha de cálculo como texto -AREAS = ÁREAS ## Devolve o número de áreas numa referência -CHOOSE = SELECCIONAR ## Selecciona um valor a partir de uma lista de valores -COLUMN = COL ## Devolve o número da coluna de uma referência -COLUMNS = COLS ## Devolve o número de colunas numa referência -HLOOKUP = PROCH ## Procura na linha superior de uma matriz e devolve o valor da célula indicada -HYPERLINK = HIPERLIGAÇÃO ## Cria um atalho ou hiperligação que abre um documento armazenado num servidor de rede, numa intranet ou na Internet -INDEX = ÍNDICE ## Utiliza um índice para escolher um valor de uma referência ou de uma matriz -INDIRECT = INDIRECTO ## Devolve uma referência indicada por um valor de texto -LOOKUP = PROC ## Procura valores num vector ou numa matriz -MATCH = CORRESP ## Procura valores numa referência ou numa matriz -OFFSET = DESLOCAMENTO ## Devolve o deslocamento de referência de uma determinada referência -ROW = LIN ## Devolve o número da linha de uma referência -ROWS = LINS ## Devolve o número de linhas numa referência -RTD = RTD ## Obtém dados em tempo real a partir de um programa que suporte automatização COM (automatização: modo de trabalhar com objectos de uma aplicação a partir de outra aplicação ou ferramenta de desenvolvimento. Anteriormente conhecida como automatização OLE, a automatização é uma norma da indústria de software e uma funcionalidade COM (Component Object Model).) -TRANSPOSE = TRANSPOR ## Devolve a transposição de uma matriz -VLOOKUP = PROCV ## Procura na primeira coluna de uma matriz e percorre a linha para devolver o valor de uma célula - +ADDRESS = ENDEREÇO +AREAS = ÁREAS +CHOOSE = SELECIONAR +COLUMN = COL +COLUMNS = COLS +FORMULATEXT = FÓRMULA.TEXTO +GETPIVOTDATA = OBTERDADOSDIN +HLOOKUP = PROCH +HYPERLINK = HIPERLIGAÇÃO +INDEX = ÍNDICE +INDIRECT = INDIRETO +LOOKUP = PROC +MATCH = CORRESP +OFFSET = DESLOCAMENTO +ROW = LIN +ROWS = LINS +RTD = RTD +TRANSPOSE = TRANSPOR +VLOOKUP = PROCV ## -## Math and trigonometry functions Funções matemáticas e trigonométricas +## Funções matemáticas e trigonométricas (Math & Trig Functions) ## -ABS = ABS ## Devolve o valor absoluto de um número -ACOS = ACOS ## Devolve o arco de co-seno de um número -ACOSH = ACOSH ## Devolve o co-seno hiperbólico inverso de um número -ASIN = ASEN ## Devolve o arco de seno de um número -ASINH = ASENH ## Devolve o seno hiperbólico inverso de um número -ATAN = ATAN ## Devolve o arco de tangente de um número -ATAN2 = ATAN2 ## Devolve o arco de tangente das coordenadas x e y -ATANH = ATANH ## Devolve a tangente hiperbólica inversa de um número -CEILING = ARRED.EXCESSO ## Arredonda um número para o número inteiro mais próximo ou para o múltiplo de significância mais próximo -COMBIN = COMBIN ## Devolve o número de combinações de um determinado número de objectos -COS = COS ## Devolve o co-seno de um número -COSH = COSH ## Devolve o co-seno hiperbólico de um número -DEGREES = GRAUS ## Converte radianos em graus -EVEN = PAR ## Arredonda um número por excesso para o número inteiro mais próximo -EXP = EXP ## Devolve e elevado à potência de um determinado número -FACT = FACTORIAL ## Devolve o factorial de um número -FACTDOUBLE = FACTDUPLO ## Devolve o factorial duplo de um número -FLOOR = ARRED.DEFEITO ## Arredonda um número por defeito até zero -GCD = MDC ## Devolve o maior divisor comum -INT = INT ## Arredonda um número por defeito para o número inteiro mais próximo -LCM = MMC ## Devolve o mínimo múltiplo comum -LN = LN ## Devolve o logaritmo natural de um número -LOG = LOG ## Devolve o logaritmo de um número com uma base especificada -LOG10 = LOG10 ## Devolve o logaritmo de base 10 de um número -MDETERM = MATRIZ.DETERM ## Devolve o determinante matricial de uma matriz -MINVERSE = MATRIZ.INVERSA ## Devolve o inverso matricial de uma matriz -MMULT = MATRIZ.MULT ## Devolve o produto matricial de duas matrizes -MOD = RESTO ## Devolve o resto da divisão -MROUND = MARRED ## Devolve um número arredondado para o múltiplo pretendido -MULTINOMIAL = POLINOMIAL ## Devolve o polinomial de um conjunto de números -ODD = ÍMPAR ## Arredonda por excesso um número para o número inteiro ímpar mais próximo -PI = PI ## Devolve o valor de pi -POWER = POTÊNCIA ## Devolve o resultado de um número elevado a uma potência -PRODUCT = PRODUTO ## Multiplica os respectivos argumentos -QUOTIENT = QUOCIENTE ## Devolve a parte inteira de uma divisão -RADIANS = RADIANOS ## Converte graus em radianos -RAND = ALEATÓRIO ## Devolve um número aleatório entre 0 e 1 -RANDBETWEEN = ALEATÓRIOENTRE ## Devolve um número aleatório entre os números especificados -ROMAN = ROMANO ## Converte um número árabe em romano, como texto -ROUND = ARRED ## Arredonda um número para um número de dígitos especificado -ROUNDDOWN = ARRED.PARA.BAIXO ## Arredonda um número por defeito até zero -ROUNDUP = ARRED.PARA.CIMA ## Arredonda um número por excesso, afastando-o de zero -SERIESSUM = SOMASÉRIE ## Devolve a soma de uma série de potências baseada na fórmula -SIGN = SINAL ## Devolve o sinal de um número -SIN = SEN ## Devolve o seno de um determinado ângulo -SINH = SENH ## Devolve o seno hiperbólico de um número -SQRT = RAIZQ ## Devolve uma raiz quadrada positiva -SQRTPI = RAIZPI ## Devolve a raiz quadrada de (núm * pi) -SUBTOTAL = SUBTOTAL ## Devolve um subtotal numa lista ou base de dados -SUM = SOMA ## Adiciona os respectivos argumentos -SUMIF = SOMA.SE ## Adiciona as células especificadas por um determinado critério -SUMIFS = SOMA.SE.S ## Adiciona as células num intervalo que cumpre vários critérios -SUMPRODUCT = SOMARPRODUTO ## Devolve a soma dos produtos de componentes de matrizes correspondentes -SUMSQ = SOMARQUAD ## Devolve a soma dos quadrados dos argumentos -SUMX2MY2 = SOMAX2DY2 ## Devolve a soma da diferença dos quadrados dos valores correspondentes em duas matrizes -SUMX2PY2 = SOMAX2SY2 ## Devolve a soma da soma dos quadrados dos valores correspondentes em duas matrizes -SUMXMY2 = SOMAXMY2 ## Devolve a soma dos quadrados da diferença dos valores correspondentes em duas matrizes -TAN = TAN ## Devolve a tangente de um número -TANH = TANH ## Devolve a tangente hiperbólica de um número -TRUNC = TRUNCAR ## Trunca um número para um número inteiro - +ABS = ABS +ACOS = ACOS +ACOSH = ACOSH +ACOT = ACOT +ACOTH = ACOTH +AGGREGATE = AGREGAR +ARABIC = ÁRABE +ASIN = ASEN +ASINH = ASENH +ATAN = ATAN +ATAN2 = ATAN2 +ATANH = ATANH +BASE = BASE +CEILING.MATH = ARRED.EXCESSO.MAT +CEILING.PRECISE = ARRED.EXCESSO.PRECISO +COMBIN = COMBIN +COMBINA = COMBIN.R +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = DECIMAL +DEGREES = GRAUS +ECMA.CEILING = ARRED.EXCESSO.ECMA +EVEN = PAR +EXP = EXP +FACT = FATORIAL +FACTDOUBLE = FATDUPLO +FLOOR.MATH = ARRED.DEFEITO.MAT +FLOOR.PRECISE = ARRED.DEFEITO.PRECISO +GCD = MDC +INT = INT +ISO.CEILING = ARRED.EXCESSO.ISO +LCM = MMC +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = MATRIZ.DETERM +MINVERSE = MATRIZ.INVERSA +MMULT = MATRIZ.MULT +MOD = RESTO +MROUND = MARRED +MULTINOMIAL = POLINOMIAL +MUNIT = UNIDM +ODD = ÍMPAR +PI = PI +POWER = POTÊNCIA +PRODUCT = PRODUTO +QUOTIENT = QUOCIENTE +RADIANS = RADIANOS +RAND = ALEATÓRIO +RANDBETWEEN = ALEATÓRIOENTRE +ROMAN = ROMANO +ROUND = ARRED +ROUNDBAHTDOWN = ARREDOND.BAHT.BAIXO +ROUNDBAHTUP = ARREDOND.BAHT.CIMA +ROUNDDOWN = ARRED.PARA.BAIXO +ROUNDUP = ARRED.PARA.CIMA +SEC = SEC +SECH = SECH +SERIESSUM = SOMASÉRIE +SIGN = SINAL +SIN = SEN +SINH = SENH +SQRT = RAIZQ +SQRTPI = RAIZPI +SUBTOTAL = SUBTOTAL +SUM = SOMA +SUMIF = SOMA.SE +SUMIFS = SOMA.SE.S +SUMPRODUCT = SOMARPRODUTO +SUMSQ = SOMARQUAD +SUMX2MY2 = SOMAX2DY2 +SUMX2PY2 = SOMAX2SY2 +SUMXMY2 = SOMAXMY2 +TAN = TAN +TANH = TANH +TRUNC = TRUNCAR ## -## Statistical functions Funções estatísticas +## Funções estatísticas (Statistical Functions) ## -AVEDEV = DESV.MÉDIO ## Devolve a média aritmética dos desvios absolutos à média dos pontos de dados -AVERAGE = MÉDIA ## Devolve a média dos respectivos argumentos -AVERAGEA = MÉDIAA ## Devolve uma média dos respectivos argumentos, incluindo números, texto e valores lógicos -AVERAGEIF = MÉDIA.SE ## Devolve a média aritmética de todas as células num intervalo que cumprem determinado critério -AVERAGEIFS = MÉDIA.SE.S ## Devolve a média aritmética de todas as células que cumprem múltiplos critérios -BETADIST = DISTBETA ## Devolve a função de distribuição cumulativa beta -BETAINV = BETA.ACUM.INV ## Devolve o inverso da função de distribuição cumulativa relativamente a uma distribuição beta específica -BINOMDIST = DISTRBINOM ## Devolve a probabilidade de distribuição binomial de termo individual -CHIDIST = DIST.CHI ## Devolve a probabilidade unicaudal da distribuição qui-quadrada -CHIINV = INV.CHI ## Devolve o inverso da probabilidade unicaudal da distribuição qui-quadrada -CHITEST = TESTE.CHI ## Devolve o teste para independência -CONFIDENCE = INT.CONFIANÇA ## Devolve o intervalo de confiança correspondente a uma média de população -CORREL = CORREL ## Devolve o coeficiente de correlação entre dois conjuntos de dados -COUNT = CONTAR ## Conta os números que existem na lista de argumentos -COUNTA = CONTAR.VAL ## Conta os valores que existem na lista de argumentos -COUNTBLANK = CONTAR.VAZIO ## Conta o número de células em branco num intervalo -COUNTIF = CONTAR.SE ## Calcula o número de células num intervalo que corresponde aos critérios determinados -COUNTIFS = CONTAR.SE.S ## Conta o número de células num intervalo que cumprem múltiplos critérios -COVAR = COVAR ## Devolve a covariância, que é a média dos produtos de desvios de pares -CRITBINOM = CRIT.BINOM ## Devolve o menor valor em que a distribuição binomial cumulativa é inferior ou igual a um valor de critério -DEVSQ = DESVQ ## Devolve a soma dos quadrados dos desvios -EXPONDIST = DISTEXPON ## Devolve a distribuição exponencial -FDIST = DISTF ## Devolve a distribuição da probabilidade F -FINV = INVF ## Devolve o inverso da distribuição da probabilidade F -FISHER = FISHER ## Devolve a transformação Fisher -FISHERINV = FISHERINV ## Devolve o inverso da transformação Fisher -FORECAST = PREVISÃO ## Devolve um valor ao longo de uma tendência linear -FREQUENCY = FREQUÊNCIA ## Devolve uma distribuição de frequência como uma matriz vertical -FTEST = TESTEF ## Devolve o resultado de um teste F -GAMMADIST = DISTGAMA ## Devolve a distribuição gama -GAMMAINV = INVGAMA ## Devolve o inverso da distribuição gama cumulativa -GAMMALN = LNGAMA ## Devolve o logaritmo natural da função gama, Γ(x) -GEOMEAN = MÉDIA.GEOMÉTRICA ## Devolve a média geométrica -GROWTH = CRESCIMENTO ## Devolve valores ao longo de uma tendência exponencial -HARMEAN = MÉDIA.HARMÓNICA ## Devolve a média harmónica -HYPGEOMDIST = DIST.HIPERGEOM ## Devolve a distribuição hipergeométrica -INTERCEPT = INTERCEPTAR ## Devolve a intercepção da linha de regressão linear -KURT = CURT ## Devolve a curtose de um conjunto de dados -LARGE = MAIOR ## Devolve o maior valor k-ésimo de um conjunto de dados -LINEST = PROJ.LIN ## Devolve os parâmetros de uma tendência linear -LOGEST = PROJ.LOG ## Devolve os parâmetros de uma tendência exponencial -LOGINV = INVLOG ## Devolve o inverso da distribuição normal logarítmica -LOGNORMDIST = DIST.NORMALLOG ## Devolve a distribuição normal logarítmica cumulativa -MAX = MÁXIMO ## Devolve o valor máximo numa lista de argumentos -MAXA = MÁXIMOA ## Devolve o valor máximo numa lista de argumentos, incluindo números, texto e valores lógicos -MEDIAN = MED ## Devolve a mediana dos números indicados -MIN = MÍNIMO ## Devolve o valor mínimo numa lista de argumentos -MINA = MÍNIMOA ## Devolve o valor mínimo numa lista de argumentos, incluindo números, texto e valores lógicos -MODE = MODA ## Devolve o valor mais comum num conjunto de dados -NEGBINOMDIST = DIST.BIN.NEG ## Devolve a distribuição binominal negativa -NORMDIST = DIST.NORM ## Devolve a distribuição cumulativa normal -NORMINV = INV.NORM ## Devolve o inverso da distribuição cumulativa normal -NORMSDIST = DIST.NORMP ## Devolve a distribuição cumulativa normal padrão -NORMSINV = INV.NORMP ## Devolve o inverso da distribuição cumulativa normal padrão -PEARSON = PEARSON ## Devolve o coeficiente de correlação momento/produto de Pearson -PERCENTILE = PERCENTIL ## Devolve o k-ésimo percentil de valores num intervalo -PERCENTRANK = ORDEM.PERCENTUAL ## Devolve a ordem percentual de um valor num conjunto de dados -PERMUT = PERMUTAR ## Devolve o número de permutações de um determinado número de objectos -POISSON = POISSON ## Devolve a distribuição de Poisson -PROB = PROB ## Devolve a probabilidade dos valores num intervalo se encontrarem entre dois limites -QUARTILE = QUARTIL ## Devolve o quartil de um conjunto de dados -RANK = ORDEM ## Devolve a ordem de um número numa lista numérica -RSQ = RQUAD ## Devolve o quadrado do coeficiente de correlação momento/produto de Pearson -SKEW = DISTORÇÃO ## Devolve a distorção de uma distribuição -SLOPE = DECLIVE ## Devolve o declive da linha de regressão linear -SMALL = MENOR ## Devolve o menor valor de k-ésimo de um conjunto de dados -STANDARDIZE = NORMALIZAR ## Devolve um valor normalizado -STDEV = DESVPAD ## Calcula o desvio-padrão com base numa amostra -STDEVA = DESVPADA ## Calcula o desvio-padrão com base numa amostra, incluindo números, texto e valores lógicos -STDEVP = DESVPADP ## Calcula o desvio-padrão com base na população total -STDEVPA = DESVPADPA ## Calcula o desvio-padrão com base na população total, incluindo números, texto e valores lógicos -STEYX = EPADYX ## Devolve o erro-padrão do valor de y previsto para cada x na regressão -TDIST = DISTT ## Devolve a distribuição t de Student -TINV = INVT ## Devolve o inverso da distribuição t de Student -TREND = TENDÊNCIA ## Devolve valores ao longo de uma tendência linear -TRIMMEAN = MÉDIA.INTERNA ## Devolve a média do interior de um conjunto de dados -TTEST = TESTET ## Devolve a probabilidade associada ao teste t de Student -VAR = VAR ## Calcula a variância com base numa amostra -VARA = VARA ## Calcula a variância com base numa amostra, incluindo números, texto e valores lógicos -VARP = VARP ## Calcula a variância com base na população total -VARPA = VARPA ## Calcula a variância com base na população total, incluindo números, texto e valores lógicos -WEIBULL = WEIBULL ## Devolve a distribuição Weibull -ZTEST = TESTEZ ## Devolve o valor de probabilidade unicaudal de um teste-z - +AVEDEV = DESV.MÉDIO +AVERAGE = MÉDIA +AVERAGEA = MÉDIAA +AVERAGEIF = MÉDIA.SE +AVERAGEIFS = MÉDIA.SE.S +BETA.DIST = DIST.BETA +BETA.INV = INV.BETA +BINOM.DIST = DISTR.BINOM +BINOM.DIST.RANGE = DIST.BINOM.INTERVALO +BINOM.INV = INV.BINOM +CHISQ.DIST = DIST.CHIQ +CHISQ.DIST.RT = DIST.CHIQ.DIR +CHISQ.INV = INV.CHIQ +CHISQ.INV.RT = INV.CHIQ.DIR +CHISQ.TEST = TESTE.CHIQ +CONFIDENCE.NORM = INT.CONFIANÇA.NORM +CONFIDENCE.T = INT.CONFIANÇA.T +CORREL = CORREL +COUNT = CONTAR +COUNTA = CONTAR.VAL +COUNTBLANK = CONTAR.VAZIO +COUNTIF = CONTAR.SE +COUNTIFS = CONTAR.SE.S +COVARIANCE.P = COVARIÂNCIA.P +COVARIANCE.S = COVARIÂNCIA.S +DEVSQ = DESVQ +EXPON.DIST = DIST.EXPON +F.DIST = DIST.F +F.DIST.RT = DIST.F.DIR +F.INV = INV.F +F.INV.RT = INV.F.DIR +F.TEST = TESTE.F +FISHER = FISHER +FISHERINV = FISHERINV +FORECAST.ETS = PREVISÃO.ETS +FORECAST.ETS.CONFINT = PREVISÃO.ETS.CONFINT +FORECAST.ETS.SEASONALITY = PREVISÃO.ETS.SAZONALIDADE +FORECAST.ETS.STAT = PREVISÃO.ETS.ESTATÍSTICA +FORECAST.LINEAR = PREVISÃO.LINEAR +FREQUENCY = FREQUÊNCIA +GAMMA = GAMA +GAMMA.DIST = DIST.GAMA +GAMMA.INV = INV.GAMA +GAMMALN = LNGAMA +GAMMALN.PRECISE = LNGAMA.PRECISO +GAUSS = GAUSS +GEOMEAN = MÉDIA.GEOMÉTRICA +GROWTH = CRESCIMENTO +HARMEAN = MÉDIA.HARMÓNICA +HYPGEOM.DIST = DIST.HIPGEOM +INTERCEPT = INTERCETAR +KURT = CURT +LARGE = MAIOR +LINEST = PROJ.LIN +LOGEST = PROJ.LOG +LOGNORM.DIST = DIST.NORMLOG +LOGNORM.INV = INV.NORMALLOG +MAX = MÁXIMO +MAXA = MÁXIMOA +MAXIFS = MÁXIMO.SE.S +MEDIAN = MED +MIN = MÍNIMO +MINA = MÍNIMOA +MINIFS = MÍNIMO.SE.S +MODE.MULT = MODO.MÚLT +MODE.SNGL = MODO.SIMPLES +NEGBINOM.DIST = DIST.BINOM.NEG +NORM.DIST = DIST.NORMAL +NORM.INV = INV.NORMAL +NORM.S.DIST = DIST.S.NORM +NORM.S.INV = INV.S.NORM +PEARSON = PEARSON +PERCENTILE.EXC = PERCENTIL.EXC +PERCENTILE.INC = PERCENTIL.INC +PERCENTRANK.EXC = ORDEM.PERCENTUAL.EXC +PERCENTRANK.INC = ORDEM.PERCENTUAL.INC +PERMUT = PERMUTAR +PERMUTATIONA = PERMUTAR.R +PHI = PHI +POISSON.DIST = DIST.POISSON +PROB = PROB +QUARTILE.EXC = QUARTIL.EXC +QUARTILE.INC = QUARTIL.INC +RANK.AVG = ORDEM.MÉD +RANK.EQ = ORDEM.EQ +RSQ = RQUAD +SKEW = DISTORÇÃO +SKEW.P = DISTORÇÃO.P +SLOPE = DECLIVE +SMALL = MENOR +STANDARDIZE = NORMALIZAR +STDEV.P = DESVPAD.P +STDEV.S = DESVPAD.S +STDEVA = DESVPADA +STDEVPA = DESVPADPA +STEYX = EPADYX +T.DIST = DIST.T +T.DIST.2T = DIST.T.2C +T.DIST.RT = DIST.T.DIR +T.INV = INV.T +T.INV.2T = INV.T.2C +T.TEST = TESTE.T +TREND = TENDÊNCIA +TRIMMEAN = MÉDIA.INTERNA +VAR.P = VAR.P +VAR.S = VAR.S +VARA = VARA +VARPA = VARPA +WEIBULL.DIST = DIST.WEIBULL +Z.TEST = TESTE.Z ## -## Text functions Funções de texto +## Funções de texto (Text Functions) ## -ASC = ASC ## Altera letras ou katakana de largura total (byte duplo) numa cadeia de caracteres para caracteres de largura média (byte único) -BAHTTEXT = TEXTO.BAHT ## Converte um número em texto, utilizando o formato monetário ß (baht) -CHAR = CARÁCT ## Devolve o carácter especificado pelo número de código -CLEAN = LIMPAR ## Remove do texto todos os caracteres não imprimíveis -CODE = CÓDIGO ## Devolve um código numérico correspondente ao primeiro carácter numa cadeia de texto -CONCATENATE = CONCATENAR ## Agrupa vários itens de texto num único item de texto -DOLLAR = MOEDA ## Converte um número em texto, utilizando o formato monetário € (Euro) -EXACT = EXACTO ## Verifica se dois valores de texto são idênticos -FIND = LOCALIZAR ## Localiza um valor de texto dentro de outro (sensível às maiúsculas e minúsculas) -FINDB = LOCALIZARB ## Localiza um valor de texto dentro de outro (sensível às maiúsculas e minúsculas) -FIXED = FIXA ## Formata um número como texto com um número fixo de decimais -JIS = JIS ## Altera letras ou katakana de largura média (byte único) numa cadeia de caracteres para caracteres de largura total (byte duplo) -LEFT = ESQUERDA ## Devolve os caracteres mais à esquerda de um valor de texto -LEFTB = ESQUERDAB ## Devolve os caracteres mais à esquerda de um valor de texto -LEN = NÚM.CARACT ## Devolve o número de caracteres de uma cadeia de texto -LENB = NÚM.CARACTB ## Devolve o número de caracteres de uma cadeia de texto -LOWER = MINÚSCULAS ## Converte o texto em minúsculas -MID = SEG.TEXTO ## Devolve um número específico de caracteres de uma cadeia de texto, a partir da posição especificada -MIDB = SEG.TEXTOB ## Devolve um número específico de caracteres de uma cadeia de texto, a partir da posição especificada -PHONETIC = FONÉTICA ## Retira os caracteres fonéticos (furigana) de uma cadeia de texto -PROPER = INICIAL.MAIÚSCULA ## Coloca em maiúsculas a primeira letra de cada palavra de um valor de texto -REPLACE = SUBSTITUIR ## Substitui caracteres no texto -REPLACEB = SUBSTITUIRB ## Substitui caracteres no texto -REPT = REPETIR ## Repete texto um determinado número de vezes -RIGHT = DIREITA ## Devolve os caracteres mais à direita de um valor de texto -RIGHTB = DIREITAB ## Devolve os caracteres mais à direita de um valor de texto -SEARCH = PROCURAR ## Localiza um valor de texto dentro de outro (não sensível a maiúsculas e minúsculas) -SEARCHB = PROCURARB ## Localiza um valor de texto dentro de outro (não sensível a maiúsculas e minúsculas) -SUBSTITUTE = SUBST ## Substitui texto novo por texto antigo numa cadeia de texto -T = T ## Converte os respectivos argumentos em texto -TEXT = TEXTO ## Formata um número e converte-o em texto -TRIM = COMPACTAR ## Remove espaços do texto -UPPER = MAIÚSCULAS ## Converte texto em maiúsculas -VALUE = VALOR ## Converte um argumento de texto num número +BAHTTEXT = TEXTO.BAHT +CHAR = CARÁT +CLEAN = LIMPARB +CODE = CÓDIGO +CONCAT = CONCAT +DOLLAR = MOEDA +EXACT = EXATO +FIND = LOCALIZAR +FIXED = FIXA +ISTHAIDIGIT = É.DÍGITO.TAILANDÊS +LEFT = ESQUERDA +LEN = NÚM.CARAT +LOWER = MINÚSCULAS +MID = SEG.TEXTO +NUMBERSTRING = NÚMERO.CADEIA +NUMBERVALUE = VALOR.NÚMERO +PHONETIC = FONÉTICA +PROPER = INICIAL.MAIÚSCULA +REPLACE = SUBSTITUIR +REPT = REPETIR +RIGHT = DIREITA +SEARCH = PROCURAR +SUBSTITUTE = SUBST +T = T +TEXT = TEXTO +TEXTJOIN = UNIRTEXTO +THAIDIGIT = DÍGITO.TAILANDÊS +THAINUMSOUND = SOM.NÚM.TAILANDÊS +THAINUMSTRING = CADEIA.NÚM.TAILANDÊS +THAISTRINGLENGTH = COMP.CADEIA.TAILANDÊS +TRIM = COMPACTAR +UNICHAR = UNICARÁT +UNICODE = UNICODE +UPPER = MAIÚSCULAS +VALUE = VALOR + +## +## Funções da Web (Web Functions) +## +ENCODEURL = CODIFICAÇÃOURL +FILTERXML = FILTRARXML +WEBSERVICE = SERVIÇOWEB + +## +## Funções de compatibilidade (Compatibility Functions) +## +BETADIST = DISTBETA +BETAINV = BETA.ACUM.INV +BINOMDIST = DISTRBINOM +CEILING = ARRED.EXCESSO +CHIDIST = DIST.CHI +CHIINV = INV.CHI +CHITEST = TESTE.CHI +CONCATENATE = CONCATENAR +CONFIDENCE = INT.CONFIANÇA +COVAR = COVAR +CRITBINOM = CRIT.BINOM +EXPONDIST = DISTEXPON +FDIST = DISTF +FINV = INVF +FLOOR = ARRED.DEFEITO +FORECAST = PREVISÃO +FTEST = TESTEF +GAMMADIST = DISTGAMA +GAMMAINV = INVGAMA +HYPGEOMDIST = DIST.HIPERGEOM +LOGINV = INVLOG +LOGNORMDIST = DIST.NORMALLOG +MODE = MODA +NEGBINOMDIST = DIST.BIN.NEG +NORMDIST = DIST.NORM +NORMINV = INV.NORM +NORMSDIST = DIST.NORMP +NORMSINV = INV.NORMP +PERCENTILE = PERCENTIL +PERCENTRANK = ORDEM.PERCENTUAL +POISSON = POISSON +QUARTILE = QUARTIL +RANK = ORDEM +STDEV = DESVPAD +STDEVP = DESVPADP +TDIST = DISTT +TINV = INVT +TTEST = TESTET +VAR = VAR +VARP = VARP +WEIBULL = WEIBULL +ZTEST = TESTEZ diff --git a/src/PhpSpreadsheet/Calculation/locale/ru/config b/src/PhpSpreadsheet/Calculation/locale/ru/config index 9ee9e6cc..2a5a0db8 100644 --- a/src/PhpSpreadsheet/Calculation/locale/ru/config +++ b/src/PhpSpreadsheet/Calculation/locale/ru/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## +## русский язык (Russian) +## +############################################################ -ArgumentSeparator = ; - +ArgumentSeparator = ; ## -## (For future use) +## Error Codes ## -currencySymbol = р - - -## -## Excel Error Codes (For future use) - -## -NULL = #ПУСТО! -DIV0 = #ДЕЛ/0! -VALUE = #ЗНАЧ! -REF = #ССЫЛ! -NAME = #ИМЯ? -NUM = #ЧИСЛО! -NA = #Н/Д +NULL = #ПУСТО! +DIV0 = #ДЕЛ/0! +VALUE = #ЗНАЧ! +REF = #ССЫЛКА! +NAME = #ИМЯ? +NUM = #ЧИСЛО! +NA = #Н/Д diff --git a/src/PhpSpreadsheet/Calculation/locale/ru/functions b/src/PhpSpreadsheet/Calculation/locale/ru/functions index 3597dbf8..7f9ce783 100644 --- a/src/PhpSpreadsheet/Calculation/locale/ru/functions +++ b/src/PhpSpreadsheet/Calculation/locale/ru/functions @@ -1,416 +1,536 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from information provided by web-junior (http://www.web-junior.net/) +## PhpSpreadsheet - function name translations ## +## русский язык (Russian) ## +############################################################ ## -## Add-in and Automation functions Функции надстроек и автоматизации +## Функции кубов (Cube Functions) ## -GETPIVOTDATA = ПОЛУЧИТЬ.ДАННЫЕ.СВОДНОЙ.ТАБЛИЦЫ ## Возвращает данные, хранящиеся в отчете сводной таблицы. - +CUBEKPIMEMBER = КУБЭЛЕМЕНТКИП +CUBEMEMBER = КУБЭЛЕМЕНТ +CUBEMEMBERPROPERTY = КУБСВОЙСТВОЭЛЕМЕНТА +CUBERANKEDMEMBER = КУБПОРЭЛЕМЕНТ +CUBESET = КУБМНОЖ +CUBESETCOUNT = КУБЧИСЛОЭЛМНОЖ +CUBEVALUE = КУБЗНАЧЕНИЕ ## -## Cube functions Функции Куб +## Функции для работы с базами данных (Database Functions) ## -CUBEKPIMEMBER = КУБЭЛЕМЕНТКИП ## Возвращает свойство ключевого индикатора производительности «(КИП)» и отображает имя «КИП» в ячейке. «КИП» представляет собой количественную величину, такую как ежемесячная валовая прибыль или ежеквартальная текучесть кадров, используемой для контроля эффективности работы организации. -CUBEMEMBER = КУБЭЛЕМЕНТ ## Возвращает элемент или кортеж из куба. Используется для проверки существования элемента или кортежа в кубе. -CUBEMEMBERPROPERTY = КУБСВОЙСТВОЭЛЕМЕНТА ## Возвращает значение свойства элемента из куба. Используется для проверки существования имени элемента в кубе и возвращает указанное свойство для этого элемента. -CUBERANKEDMEMBER = КУБПОРЭЛЕМЕНТ ## Возвращает n-ый или ранжированный элемент в множество. Используется для возвращения одного или нескольких элементов в множество, например, лучшего продавца или 10 лучших студентов. -CUBESET = КУБМНОЖ ## Определяет вычислительное множество элементов или кортежей, отправляя на сервер выражение, которое создает множество, а затем возвращает его в Microsoft Office Excel. -CUBESETCOUNT = КУБЧИСЛОЭЛМНОЖ ## Возвращает число элементов множества. -CUBEVALUE = КУБЗНАЧЕНИЕ ## Возвращает обобщенное значение из куба. - +DAVERAGE = ДСРЗНАЧ +DCOUNT = БСЧЁТ +DCOUNTA = БСЧЁТА +DGET = БИЗВЛЕЧЬ +DMAX = ДМАКС +DMIN = ДМИН +DPRODUCT = БДПРОИЗВЕД +DSTDEV = ДСТАНДОТКЛ +DSTDEVP = ДСТАНДОТКЛП +DSUM = БДСУММ +DVAR = БДДИСП +DVARP = БДДИСПП ## -## Database functions Функции для работы с базами данных +## Функции даты и времени (Date & Time Functions) ## -DAVERAGE = ДСРЗНАЧ ## Возвращает среднее значение выбранных записей базы данных. -DCOUNT = БСЧЁТ ## Подсчитывает количество числовых ячеек в базе данных. -DCOUNTA = БСЧЁТА ## Подсчитывает количество непустых ячеек в базе данных. -DGET = БИЗВЛЕЧЬ ## Извлекает из базы данных одну запись, удовлетворяющую заданному условию. -DMAX = ДМАКС ## Возвращает максимальное значение среди выделенных записей базы данных. -DMIN = ДМИН ## Возвращает минимальное значение среди выделенных записей базы данных. -DPRODUCT = БДПРОИЗВЕД ## Перемножает значения определенного поля в записях базы данных, удовлетворяющих условию. -DSTDEV = ДСТАНДОТКЛ ## Оценивает стандартное отклонение по выборке для выделенных записей базы данных. -DSTDEVP = ДСТАНДОТКЛП ## Вычисляет стандартное отклонение по генеральной совокупности для выделенных записей базы данных -DSUM = БДСУММ ## Суммирует числа в поле для записей базы данных, удовлетворяющих условию. -DVAR = БДДИСП ## Оценивает дисперсию по выборке из выделенных записей базы данных -DVARP = БДДИСПП ## Вычисляет дисперсию по генеральной совокупности для выделенных записей базы данных - +DATE = ДАТА +DATEDIF = РАЗНДАТ +DATESTRING = СТРОКАДАННЫХ +DATEVALUE = ДАТАЗНАЧ +DAY = ДЕНЬ +DAYS = ДНИ +DAYS360 = ДНЕЙ360 +EDATE = ДАТАМЕС +EOMONTH = КОНМЕСЯЦА +HOUR = ЧАС +ISOWEEKNUM = НОМНЕДЕЛИ.ISO +MINUTE = МИНУТЫ +MONTH = МЕСЯЦ +NETWORKDAYS = ЧИСТРАБДНИ +NETWORKDAYS.INTL = ЧИСТРАБДНИ.МЕЖД +NOW = ТДАТА +SECOND = СЕКУНДЫ +THAIDAYOFWEEK = ТАЙДЕНЬНЕД +THAIMONTHOFYEAR = ТАЙМЕСЯЦ +THAIYEAR = ТАЙГОД +TIME = ВРЕМЯ +TIMEVALUE = ВРЕМЗНАЧ +TODAY = СЕГОДНЯ +WEEKDAY = ДЕНЬНЕД +WEEKNUM = НОМНЕДЕЛИ +WORKDAY = РАБДЕНЬ +WORKDAY.INTL = РАБДЕНЬ.МЕЖД +YEAR = ГОД +YEARFRAC = ДОЛЯГОДА ## -## Date and time functions Функции даты и времени +## Инженерные функции (Engineering Functions) ## -DATE = ДАТА ## Возвращает заданную дату в числовом формате. -DATEVALUE = ДАТАЗНАЧ ## Преобразует дату из текстового формата в числовой формат. -DAY = ДЕНЬ ## Преобразует дату в числовом формате в день месяца. -DAYS360 = ДНЕЙ360 ## Вычисляет количество дней между двумя датами на основе 360-дневного года. -EDATE = ДАТАМЕС ## Возвращает дату в числовом формате, отстоящую на заданное число месяцев вперед или назад от начальной даты. -EOMONTH = КОНМЕСЯЦА ## Возвращает дату в числовом формате для последнего дня месяца, отстоящего вперед или назад на заданное число месяцев. -HOUR = ЧАС ## Преобразует дату в числовом формате в часы. -MINUTE = МИНУТЫ ## Преобразует дату в числовом формате в минуты. -MONTH = МЕСЯЦ ## Преобразует дату в числовом формате в месяцы. -NETWORKDAYS = ЧИСТРАБДНИ ## Возвращает количество рабочих дней между двумя датами. -NOW = ТДАТА ## Возвращает текущую дату и время в числовом формате. -SECOND = СЕКУНДЫ ## Преобразует дату в числовом формате в секунды. -TIME = ВРЕМЯ ## Возвращает заданное время в числовом формате. -TIMEVALUE = ВРЕМЗНАЧ ## Преобразует время из текстового формата в числовой формат. -TODAY = СЕГОДНЯ ## Возвращает текущую дату в числовом формате. -WEEKDAY = ДЕНЬНЕД ## Преобразует дату в числовом формате в день недели. -WEEKNUM = НОМНЕДЕЛИ ## Преобразует числовое представление в число, которое указывает, на какую неделю года приходится указанная дата. -WORKDAY = РАБДЕНЬ ## Возвращает дату в числовом формате, отстоящую вперед или назад на заданное количество рабочих дней. -YEAR = ГОД ## Преобразует дату в числовом формате в год. -YEARFRAC = ДОЛЯГОДА ## Возвращает долю года, которую составляет количество дней между начальной и конечной датами. - +BESSELI = БЕССЕЛЬ.I +BESSELJ = БЕССЕЛЬ.J +BESSELK = БЕССЕЛЬ.K +BESSELY = БЕССЕЛЬ.Y +BIN2DEC = ДВ.В.ДЕС +BIN2HEX = ДВ.В.ШЕСТН +BIN2OCT = ДВ.В.ВОСЬМ +BITAND = БИТ.И +BITLSHIFT = БИТ.СДВИГЛ +BITOR = БИТ.ИЛИ +BITRSHIFT = БИТ.СДВИГП +BITXOR = БИТ.ИСКЛИЛИ +COMPLEX = КОМПЛЕКСН +CONVERT = ПРЕОБР +DEC2BIN = ДЕС.В.ДВ +DEC2HEX = ДЕС.В.ШЕСТН +DEC2OCT = ДЕС.В.ВОСЬМ +DELTA = ДЕЛЬТА +ERF = ФОШ +ERF.PRECISE = ФОШ.ТОЧН +ERFC = ДФОШ +ERFC.PRECISE = ДФОШ.ТОЧН +GESTEP = ПОРОГ +HEX2BIN = ШЕСТН.В.ДВ +HEX2DEC = ШЕСТН.В.ДЕС +HEX2OCT = ШЕСТН.В.ВОСЬМ +IMABS = МНИМ.ABS +IMAGINARY = МНИМ.ЧАСТЬ +IMARGUMENT = МНИМ.АРГУМЕНТ +IMCONJUGATE = МНИМ.СОПРЯЖ +IMCOS = МНИМ.COS +IMCOSH = МНИМ.COSH +IMCOT = МНИМ.COT +IMCSC = МНИМ.CSC +IMCSCH = МНИМ.CSCH +IMDIV = МНИМ.ДЕЛ +IMEXP = МНИМ.EXP +IMLN = МНИМ.LN +IMLOG10 = МНИМ.LOG10 +IMLOG2 = МНИМ.LOG2 +IMPOWER = МНИМ.СТЕПЕНЬ +IMPRODUCT = МНИМ.ПРОИЗВЕД +IMREAL = МНИМ.ВЕЩ +IMSEC = МНИМ.SEC +IMSECH = МНИМ.SECH +IMSIN = МНИМ.SIN +IMSINH = МНИМ.SINH +IMSQRT = МНИМ.КОРЕНЬ +IMSUB = МНИМ.РАЗН +IMSUM = МНИМ.СУММ +IMTAN = МНИМ.TAN +OCT2BIN = ВОСЬМ.В.ДВ +OCT2DEC = ВОСЬМ.В.ДЕС +OCT2HEX = ВОСЬМ.В.ШЕСТН ## -## Engineering functions Инженерные функции +## Финансовые функции (Financial Functions) ## -BESSELI = БЕССЕЛЬ.I ## Возвращает модифицированную функцию Бесселя In(x). -BESSELJ = БЕССЕЛЬ.J ## Возвращает функцию Бесселя Jn(x). -BESSELK = БЕССЕЛЬ.K ## Возвращает модифицированную функцию Бесселя Kn(x). -BESSELY = БЕССЕЛЬ.Y ## Возвращает функцию Бесселя Yn(x). -BIN2DEC = ДВ.В.ДЕС ## Преобразует двоичное число в десятичное. -BIN2HEX = ДВ.В.ШЕСТН ## Преобразует двоичное число в шестнадцатеричное. -BIN2OCT = ДВ.В.ВОСЬМ ## Преобразует двоичное число в восьмеричное. -COMPLEX = КОМПЛЕКСН ## Преобразует коэффициенты при вещественной и мнимой частях комплексного числа в комплексное число. -CONVERT = ПРЕОБР ## Преобразует число из одной системы единиц измерения в другую. -DEC2BIN = ДЕС.В.ДВ ## Преобразует десятичное число в двоичное. -DEC2HEX = ДЕС.В.ШЕСТН ## Преобразует десятичное число в шестнадцатеричное. -DEC2OCT = ДЕС.В.ВОСЬМ ## Преобразует десятичное число в восьмеричное. -DELTA = ДЕЛЬТА ## Проверяет равенство двух значений. -ERF = ФОШ ## Возвращает функцию ошибки. -ERFC = ДФОШ ## Возвращает дополнительную функцию ошибки. -GESTEP = ПОРОГ ## Проверяет, не превышает ли данное число порогового значения. -HEX2BIN = ШЕСТН.В.ДВ ## Преобразует шестнадцатеричное число в двоичное. -HEX2DEC = ШЕСТН.В.ДЕС ## Преобразует шестнадцатеричное число в десятичное. -HEX2OCT = ШЕСТН.В.ВОСЬМ ## Преобразует шестнадцатеричное число в восьмеричное. -IMABS = МНИМ.ABS ## Возвращает абсолютную величину (модуль) комплексного числа. -IMAGINARY = МНИМ.ЧАСТЬ ## Возвращает коэффициент при мнимой части комплексного числа. -IMARGUMENT = МНИМ.АРГУМЕНТ ## Возвращает значение аргумента комплексного числа (тета) — угол, выраженный в радианах. -IMCONJUGATE = МНИМ.СОПРЯЖ ## Возвращает комплексно-сопряженное комплексное число. -IMCOS = МНИМ.COS ## Возвращает косинус комплексного числа. -IMDIV = МНИМ.ДЕЛ ## Возвращает частное от деления двух комплексных чисел. -IMEXP = МНИМ.EXP ## Возвращает экспоненту комплексного числа. -IMLN = МНИМ.LN ## Возвращает натуральный логарифм комплексного числа. -IMLOG10 = МНИМ.LOG10 ## Возвращает обычный (десятичный) логарифм комплексного числа. -IMLOG2 = МНИМ.LOG2 ## Возвращает двоичный логарифм комплексного числа. -IMPOWER = МНИМ.СТЕПЕНЬ ## Возвращает комплексное число, возведенное в целую степень. -IMPRODUCT = МНИМ.ПРОИЗВЕД ## Возвращает произведение от 2 до 29 комплексных чисел. -IMREAL = МНИМ.ВЕЩ ## Возвращает коэффициент при вещественной части комплексного числа. -IMSIN = МНИМ.SIN ## Возвращает синус комплексного числа. -IMSQRT = МНИМ.КОРЕНЬ ## Возвращает значение квадратного корня из комплексного числа. -IMSUB = МНИМ.РАЗН ## Возвращает разность двух комплексных чисел. -IMSUM = МНИМ.СУММ ## Возвращает сумму комплексных чисел. -OCT2BIN = ВОСЬМ.В.ДВ ## Преобразует восьмеричное число в двоичное. -OCT2DEC = ВОСЬМ.В.ДЕС ## Преобразует восьмеричное число в десятичное. -OCT2HEX = ВОСЬМ.В.ШЕСТН ## Преобразует восьмеричное число в шестнадцатеричное. - +ACCRINT = НАКОПДОХОД +ACCRINTM = НАКОПДОХОДПОГАШ +AMORDEGRC = АМОРУМ +AMORLINC = АМОРУВ +COUPDAYBS = ДНЕЙКУПОНДО +COUPDAYS = ДНЕЙКУПОН +COUPDAYSNC = ДНЕЙКУПОНПОСЛЕ +COUPNCD = ДАТАКУПОНПОСЛЕ +COUPNUM = ЧИСЛКУПОН +COUPPCD = ДАТАКУПОНДО +CUMIPMT = ОБЩПЛАТ +CUMPRINC = ОБЩДОХОД +DB = ФУО +DDB = ДДОБ +DISC = СКИДКА +DOLLARDE = РУБЛЬ.ДЕС +DOLLARFR = РУБЛЬ.ДРОБЬ +DURATION = ДЛИТ +EFFECT = ЭФФЕКТ +FV = БС +FVSCHEDULE = БЗРАСПИС +INTRATE = ИНОРМА +IPMT = ПРПЛТ +IRR = ВСД +ISPMT = ПРОЦПЛАТ +MDURATION = МДЛИТ +MIRR = МВСД +NOMINAL = НОМИНАЛ +NPER = КПЕР +NPV = ЧПС +ODDFPRICE = ЦЕНАПЕРВНЕРЕГ +ODDFYIELD = ДОХОДПЕРВНЕРЕГ +ODDLPRICE = ЦЕНАПОСЛНЕРЕГ +ODDLYIELD = ДОХОДПОСЛНЕРЕГ +PDURATION = ПДЛИТ +PMT = ПЛТ +PPMT = ОСПЛТ +PRICE = ЦЕНА +PRICEDISC = ЦЕНАСКИДКА +PRICEMAT = ЦЕНАПОГАШ +PV = ПС +RATE = СТАВКА +RECEIVED = ПОЛУЧЕНО +RRI = ЭКВ.СТАВКА +SLN = АПЛ +SYD = АСЧ +TBILLEQ = РАВНОКЧЕК +TBILLPRICE = ЦЕНАКЧЕК +TBILLYIELD = ДОХОДКЧЕК +VDB = ПУО +XIRR = ЧИСТВНДОХ +XNPV = ЧИСТНЗ +YIELD = ДОХОД +YIELDDISC = ДОХОДСКИДКА +YIELDMAT = ДОХОДПОГАШ ## -## Financial functions Финансовые функции +## Информационные функции (Information Functions) ## -ACCRINT = НАКОПДОХОД ## Возвращает накопленный процент по ценным бумагам с периодической выплатой процентов. -ACCRINTM = НАКОПДОХОДПОГАШ ## Возвращает накопленный процент по ценным бумагам, проценты по которым выплачиваются в срок погашения. -AMORDEGRC = АМОРУМ ## Возвращает величину амортизации для каждого периода, используя коэффициент амортизации. -AMORLINC = АМОРУВ ## Возвращает величину амортизации для каждого периода. -COUPDAYBS = ДНЕЙКУПОНДО ## Возвращает количество дней от начала действия купона до даты соглашения. -COUPDAYS = ДНЕЙКУПОН ## Возвращает число дней в периоде купона, содержащем дату соглашения. -COUPDAYSNC = ДНЕЙКУПОНПОСЛЕ ## Возвращает число дней от даты соглашения до срока следующего купона. -COUPNCD = ДАТАКУПОНПОСЛЕ ## Возвращает следующую дату купона после даты соглашения. -COUPNUM = ЧИСЛКУПОН ## Возвращает количество купонов, которые могут быть оплачены между датой соглашения и сроком вступления в силу. -COUPPCD = ДАТАКУПОНДО ## Возвращает предыдущую дату купона перед датой соглашения. -CUMIPMT = ОБЩПЛАТ ## Возвращает общую выплату, произведенную между двумя периодическими выплатами. -CUMPRINC = ОБЩДОХОД ## Возвращает общую выплату по займу между двумя периодами. -DB = ФУО ## Возвращает величину амортизации актива для заданного периода, рассчитанную методом фиксированного уменьшения остатка. -DDB = ДДОБ ## Возвращает величину амортизации актива за данный период, используя метод двойного уменьшения остатка или иной явно указанный метод. -DISC = СКИДКА ## Возвращает норму скидки для ценных бумаг. -DOLLARDE = РУБЛЬ.ДЕС ## Преобразует цену в рублях, выраженную в виде дроби, в цену в рублях, выраженную десятичным числом. -DOLLARFR = РУБЛЬ.ДРОБЬ ## Преобразует цену в рублях, выраженную десятичным числом, в цену в рублях, выраженную в виде дроби. -DURATION = ДЛИТ ## Возвращает ежегодную продолжительность действия ценных бумаг с периодическими выплатами по процентам. -EFFECT = ЭФФЕКТ ## Возвращает действующие ежегодные процентные ставки. -FV = БС ## Возвращает будущую стоимость инвестиции. -FVSCHEDULE = БЗРАСПИС ## Возвращает будущую стоимость первоначальной основной суммы после начисления ряда сложных процентов. -INTRATE = ИНОРМА ## Возвращает процентную ставку для полностью инвестированных ценных бумаг. -IPMT = ПРПЛТ ## Возвращает величину выплаты прибыли на вложения за данный период. -IRR = ВСД ## Возвращает внутреннюю ставку доходности для ряда потоков денежных средств. -ISPMT = ПРОЦПЛАТ ## Вычисляет выплаты за указанный период инвестиции. -MDURATION = МДЛИТ ## Возвращает модифицированную длительность Маколея для ценных бумаг с предполагаемой номинальной стоимостью 100 рублей. -MIRR = МВСД ## Возвращает внутреннюю ставку доходности, при которой положительные и отрицательные денежные потоки имеют разные значения ставки. -NOMINAL = НОМИНАЛ ## Возвращает номинальную годовую процентную ставку. -NPER = КПЕР ## Возвращает общее количество периодов выплаты для данного вклада. -NPV = ЧПС ## Возвращает чистую приведенную стоимость инвестиции, основанной на серии периодических денежных потоков и ставке дисконтирования. -ODDFPRICE = ЦЕНАПЕРВНЕРЕГ ## Возвращает цену за 100 рублей нарицательной стоимости ценных бумаг с нерегулярным первым периодом. -ODDFYIELD = ДОХОДПЕРВНЕРЕГ ## Возвращает доход по ценным бумагам с нерегулярным первым периодом. -ODDLPRICE = ЦЕНАПОСЛНЕРЕГ ## Возвращает цену за 100 рублей нарицательной стоимости ценных бумаг с нерегулярным последним периодом. -ODDLYIELD = ДОХОДПОСЛНЕРЕГ ## Возвращает доход по ценным бумагам с нерегулярным последним периодом. -PMT = ПЛТ ## Возвращает величину выплаты за один период аннуитета. -PPMT = ОСПЛТ ## Возвращает величину выплат в погашение основной суммы по инвестиции за заданный период. -PRICE = ЦЕНА ## Возвращает цену за 100 рублей нарицательной стоимости ценных бумаг, по которым производится периодическая выплата процентов. -PRICEDISC = ЦЕНАСКИДКА ## Возвращает цену за 100 рублей номинальной стоимости ценных бумаг, на которые сделана скидка. -PRICEMAT = ЦЕНАПОГАШ ## Возвращает цену за 100 рублей номинальной стоимости ценных бумаг, проценты по которым выплачиваются в срок погашения. -PV = ПС ## Возвращает приведенную (к текущему моменту) стоимость инвестиции. -RATE = СТАВКА ## Возвращает процентную ставку по аннуитету за один период. -RECEIVED = ПОЛУЧЕНО ## Возвращает сумму, полученную к сроку погашения полностью обеспеченных ценных бумаг. -SLN = АПЛ ## Возвращает величину линейной амортизации актива за один период. -SYD = АСЧ ## Возвращает величину амортизации актива за данный период, рассчитанную методом суммы годовых чисел. -TBILLEQ = РАВНОКЧЕК ## Возвращает эквивалентный облигации доход по казначейскому чеку. -TBILLPRICE = ЦЕНАКЧЕК ## Возвращает цену за 100 рублей нарицательной стоимости для казначейского чека. -TBILLYIELD = ДОХОДКЧЕК ## Возвращает доход по казначейскому чеку. -VDB = ПУО ## Возвращает величину амортизации актива для указанного или частичного периода при использовании метода сокращающегося баланса. -XIRR = ЧИСТВНДОХ ## Возвращает внутреннюю ставку доходности для графика денежных потоков, которые не обязательно носят периодический характер. -XNPV = ЧИСТНЗ ## Возвращает чистую приведенную стоимость для денежных потоков, которые не обязательно являются периодическими. -YIELD = ДОХОД ## Возвращает доход от ценных бумаг, по которым производятся периодические выплаты процентов. -YIELDDISC = ДОХОДСКИДКА ## Возвращает годовой доход по ценным бумагам, на которые сделана скидка (пример — казначейские чеки). -YIELDMAT = ДОХОДПОГАШ ## Возвращает годовой доход от ценных бумаг, проценты по которым выплачиваются в срок погашения. - +CELL = ЯЧЕЙКА +ERROR.TYPE = ТИП.ОШИБКИ +INFO = ИНФОРМ +ISBLANK = ЕПУСТО +ISERR = ЕОШ +ISERROR = ЕОШИБКА +ISEVEN = ЕЧЁТН +ISFORMULA = ЕФОРМУЛА +ISLOGICAL = ЕЛОГИЧ +ISNA = ЕНД +ISNONTEXT = ЕНЕТЕКСТ +ISNUMBER = ЕЧИСЛО +ISODD = ЕНЕЧЁТ +ISREF = ЕССЫЛКА +ISTEXT = ЕТЕКСТ +N = Ч +NA = НД +SHEET = ЛИСТ +SHEETS = ЛИСТЫ +TYPE = ТИП ## -## Information functions Информационные функции +## Логические функции (Logical Functions) ## -CELL = ЯЧЕЙКА ## Возвращает информацию о формате, расположении или содержимом ячейки. -ERROR.TYPE = ТИП.ОШИБКИ ## Возвращает числовой код, соответствующий типу ошибки. -INFO = ИНФОРМ ## Возвращает информацию о текущей операционной среде. -ISBLANK = ЕПУСТО ## Возвращает значение ИСТИНА, если аргумент является ссылкой на пустую ячейку. -ISERR = ЕОШ ## Возвращает значение ИСТИНА, если аргумент ссылается на любое значение ошибки, кроме #Н/Д. -ISERROR = ЕОШИБКА ## Возвращает значение ИСТИНА, если аргумент ссылается на любое значение ошибки. -ISEVEN = ЕЧЁТН ## Возвращает значение ИСТИНА, если значение аргумента является четным числом. -ISLOGICAL = ЕЛОГИЧ ## Возвращает значение ИСТИНА, если аргумент ссылается на логическое значение. -ISNA = ЕНД ## Возвращает значение ИСТИНА, если аргумент ссылается на значение ошибки #Н/Д. -ISNONTEXT = ЕНЕТЕКСТ ## Возвращает значение ИСТИНА, если значение аргумента не является текстом. -ISNUMBER = ЕЧИСЛО ## Возвращает значение ИСТИНА, если аргумент ссылается на число. -ISODD = ЕНЕЧЁТ ## Возвращает значение ИСТИНА, если значение аргумента является нечетным числом. -ISREF = ЕССЫЛКА ## Возвращает значение ИСТИНА, если значение аргумента является ссылкой. -ISTEXT = ЕТЕКСТ ## Возвращает значение ИСТИНА, если значение аргумента является текстом. -N = Ч ## Возвращает значение, преобразованное в число. -NA = НД ## Возвращает значение ошибки #Н/Д. -TYPE = ТИП ## Возвращает число, обозначающее тип данных значения. - +AND = И +FALSE = ЛОЖЬ +IF = ЕСЛИ +IFERROR = ЕСЛИОШИБКА +IFNA = ЕСНД +IFS = УСЛОВИЯ +NOT = НЕ +OR = ИЛИ +SWITCH = ПЕРЕКЛЮЧ +TRUE = ИСТИНА +XOR = ИСКЛИЛИ ## -## Logical functions Логические функции +## Функции ссылки и поиска (Lookup & Reference Functions) ## -AND = И ## Renvoie VRAI si tous ses arguments sont VRAI. -FALSE = ЛОЖЬ ## Возвращает логическое значение ЛОЖЬ. -IF = ЕСЛИ ## Выполняет проверку условия. -IFERROR = ЕСЛИОШИБКА ## Возвращает введённое значение, если вычисление по формуле вызывает ошибку; в противном случае функция возвращает результат вычисления. -NOT = НЕ ## Меняет логическое значение своего аргумента на противоположное. -OR = ИЛИ ## Возвращает значение ИСТИНА, если хотя бы один аргумент имеет значение ИСТИНА. -TRUE = ИСТИНА ## Возвращает логическое значение ИСТИНА. - +ADDRESS = АДРЕС +AREAS = ОБЛАСТИ +CHOOSE = ВЫБОР +COLUMN = СТОЛБЕЦ +COLUMNS = ЧИСЛСТОЛБ +FORMULATEXT = Ф.ТЕКСТ +GETPIVOTDATA = ПОЛУЧИТЬ.ДАННЫЕ.СВОДНОЙ.ТАБЛИЦЫ +HLOOKUP = ГПР +HYPERLINK = ГИПЕРССЫЛКА +INDEX = ИНДЕКС +INDIRECT = ДВССЫЛ +LOOKUP = ПРОСМОТР +MATCH = ПОИСКПОЗ +OFFSET = СМЕЩ +ROW = СТРОКА +ROWS = ЧСТРОК +RTD = ДРВ +TRANSPOSE = ТРАНСП +VLOOKUP = ВПР ## -## Lookup and reference functions Функции ссылки и поиска +## Математические и тригонометрические функции (Math & Trig Functions) ## -ADDRESS = АДРЕС ## Возвращает ссылку на отдельную ячейку листа в виде текста. -AREAS = ОБЛАСТИ ## Возвращает количество областей в ссылке. -CHOOSE = ВЫБОР ## Выбирает значение из списка значений по индексу. -COLUMN = СТОЛБЕЦ ## Возвращает номер столбца, на который указывает ссылка. -COLUMNS = ЧИСЛСТОЛБ ## Возвращает количество столбцов в ссылке. -HLOOKUP = ГПР ## Ищет в первой строке массива и возвращает значение отмеченной ячейки -HYPERLINK = ГИПЕРССЫЛКА ## Создает ссылку, открывающую документ, который находится на сервере сети, в интрасети или в Интернете. -INDEX = ИНДЕКС ## Использует индекс для выбора значения из ссылки или массива. -INDIRECT = ДВССЫЛ ## Возвращает ссылку, заданную текстовым значением. -LOOKUP = ПРОСМОТР ## Ищет значения в векторе или массиве. -MATCH = ПОИСКПОЗ ## Ищет значения в ссылке или массиве. -OFFSET = СМЕЩ ## Возвращает смещение ссылки относительно заданной ссылки. -ROW = СТРОКА ## Возвращает номер строки, определяемой ссылкой. -ROWS = ЧСТРОК ## Возвращает количество строк в ссылке. -RTD = ДРВ ## Извлекает данные реального времени из программ, поддерживающих автоматизацию COM (Программирование объектов. Стандартное средство для работы с объектами некоторого приложения из другого приложения или средства разработки. Программирование объектов (ранее называемое программированием OLE) является функцией модели COM (Component Object Model, модель компонентных объектов).). -TRANSPOSE = ТРАНСП ## Возвращает транспонированный массив. -VLOOKUP = ВПР ## Ищет значение в первом столбце массива и возвращает значение из ячейки в найденной строке и указанном столбце. - +ABS = ABS +ACOS = ACOS +ACOSH = ACOSH +ACOT = ACOT +ACOTH = ACOTH +AGGREGATE = АГРЕГАТ +ARABIC = АРАБСКОЕ +ASIN = ASIN +ASINH = ASINH +ATAN = ATAN +ATAN2 = ATAN2 +ATANH = ATANH +BASE = ОСНОВАНИЕ +CEILING.MATH = ОКРВВЕРХ.МАТ +CEILING.PRECISE = ОКРВВЕРХ.ТОЧН +COMBIN = ЧИСЛКОМБ +COMBINA = ЧИСЛКОМБА +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = ДЕС +DEGREES = ГРАДУСЫ +ECMA.CEILING = ECMA.ОКРВВЕРХ +EVEN = ЧЁТН +EXP = EXP +FACT = ФАКТР +FACTDOUBLE = ДВФАКТР +FLOOR.MATH = ОКРВНИЗ.МАТ +FLOOR.PRECISE = ОКРВНИЗ.ТОЧН +GCD = НОД +INT = ЦЕЛОЕ +ISO.CEILING = ISO.ОКРВВЕРХ +LCM = НОК +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = МОПРЕД +MINVERSE = МОБР +MMULT = МУМНОЖ +MOD = ОСТАТ +MROUND = ОКРУГЛТ +MULTINOMIAL = МУЛЬТИНОМ +MUNIT = МЕДИН +ODD = НЕЧЁТ +PI = ПИ +POWER = СТЕПЕНЬ +PRODUCT = ПРОИЗВЕД +QUOTIENT = ЧАСТНОЕ +RADIANS = РАДИАНЫ +RAND = СЛЧИС +RANDBETWEEN = СЛУЧМЕЖДУ +ROMAN = РИМСКОЕ +ROUND = ОКРУГЛ +ROUNDBAHTDOWN = ОКРУГЛБАТВНИЗ +ROUNDBAHTUP = ОКРУГЛБАТВВЕРХ +ROUNDDOWN = ОКРУГЛВНИЗ +ROUNDUP = ОКРУГЛВВЕРХ +SEC = SEC +SECH = SECH +SERIESSUM = РЯД.СУММ +SIGN = ЗНАК +SIN = SIN +SINH = SINH +SQRT = КОРЕНЬ +SQRTPI = КОРЕНЬПИ +SUBTOTAL = ПРОМЕЖУТОЧНЫЕ.ИТОГИ +SUM = СУММ +SUMIF = СУММЕСЛИ +SUMIFS = СУММЕСЛИМН +SUMPRODUCT = СУММПРОИЗВ +SUMSQ = СУММКВ +SUMX2MY2 = СУММРАЗНКВ +SUMX2PY2 = СУММСУММКВ +SUMXMY2 = СУММКВРАЗН +TAN = TAN +TANH = TANH +TRUNC = ОТБР ## -## Math and trigonometry functions Математические и тригонометрические функции +## Статистические функции (Statistical Functions) ## -ABS = ABS ## Возвращает модуль (абсолютную величину) числа. -ACOS = ACOS ## Возвращает арккосинус числа. -ACOSH = ACOSH ## Возвращает гиперболический арккосинус числа. -ASIN = ASIN ## Возвращает арксинус числа. -ASINH = ASINH ## Возвращает гиперболический арксинус числа. -ATAN = ATAN ## Возвращает арктангенс числа. -ATAN2 = ATAN2 ## Возвращает арктангенс для заданных координат x и y. -ATANH = ATANH ## Возвращает гиперболический арктангенс числа. -CEILING = ОКРВВЕРХ ## Округляет число до ближайшего целого или до ближайшего кратного указанному значению. -COMBIN = ЧИСЛКОМБ ## Возвращает количество комбинаций для заданного числа объектов. -COS = COS ## Возвращает косинус числа. -COSH = COSH ## Возвращает гиперболический косинус числа. -DEGREES = ГРАДУСЫ ## Преобразует радианы в градусы. -EVEN = ЧЁТН ## Округляет число до ближайшего четного целого. -EXP = EXP ## Возвращает число e, возведенное в указанную степень. -FACT = ФАКТР ## Возвращает факториал числа. -FACTDOUBLE = ДВФАКТР ## Возвращает двойной факториал числа. -FLOOR = ОКРВНИЗ ## Округляет число до ближайшего меньшего по модулю значения. -GCD = НОД ## Возвращает наибольший общий делитель. -INT = ЦЕЛОЕ ## Округляет число до ближайшего меньшего целого. -LCM = НОК ## Возвращает наименьшее общее кратное. -LN = LN ## Возвращает натуральный логарифм числа. -LOG = LOG ## Возвращает логарифм числа по заданному основанию. -LOG10 = LOG10 ## Возвращает десятичный логарифм числа. -MDETERM = МОПРЕД ## Возвращает определитель матрицы массива. -MINVERSE = МОБР ## Возвращает обратную матрицу массива. -MMULT = МУМНОЖ ## Возвращает произведение матриц двух массивов. -MOD = ОСТАТ ## Возвращает остаток от деления. -MROUND = ОКРУГЛТ ## Возвращает число, округленное с требуемой точностью. -MULTINOMIAL = МУЛЬТИНОМ ## Возвращает мультиномиальный коэффициент множества чисел. -ODD = НЕЧЁТ ## Округляет число до ближайшего нечетного целого. -PI = ПИ ## Возвращает число пи. -POWER = СТЕПЕНЬ ## Возвращает результат возведения числа в степень. -PRODUCT = ПРОИЗВЕД ## Возвращает произведение аргументов. -QUOTIENT = ЧАСТНОЕ ## Возвращает целую часть частного при делении. -RADIANS = РАДИАНЫ ## Преобразует градусы в радианы. -RAND = СЛЧИС ## Возвращает случайное число в интервале от 0 до 1. -RANDBETWEEN = СЛУЧМЕЖДУ ## Возвращает случайное число в интервале между двумя заданными числами. -ROMAN = РИМСКОЕ ## Преобразует арабские цифры в римские в виде текста. -ROUND = ОКРУГЛ ## Округляет число до указанного количества десятичных разрядов. -ROUNDDOWN = ОКРУГЛВНИЗ ## Округляет число до ближайшего меньшего по модулю значения. -ROUNDUP = ОКРУГЛВВЕРХ ## Округляет число до ближайшего большего по модулю значения. -SERIESSUM = РЯД.СУММ ## Возвращает сумму степенного ряда, вычисленную по формуле. -SIGN = ЗНАК ## Возвращает знак числа. -SIN = SIN ## Возвращает синус заданного угла. -SINH = SINH ## Возвращает гиперболический синус числа. -SQRT = КОРЕНЬ ## Возвращает положительное значение квадратного корня. -SQRTPI = КОРЕНЬПИ ## Возвращает квадратный корень из значения выражения (число * ПИ). -SUBTOTAL = ПРОМЕЖУТОЧНЫЕ.ИТОГИ ## Возвращает промежуточный итог в списке или базе данных. -SUM = СУММ ## Суммирует аргументы. -SUMIF = СУММЕСЛИ ## Суммирует ячейки, удовлетворяющие заданному условию. -SUMIFS = СУММЕСЛИМН ## Суммирует диапазон ячеек, удовлетворяющих нескольким условиям. -SUMPRODUCT = СУММПРОИЗВ ## Возвращает сумму произведений соответствующих элементов массивов. -SUMSQ = СУММКВ ## Возвращает сумму квадратов аргументов. -SUMX2MY2 = СУММРАЗНКВ ## Возвращает сумму разностей квадратов соответствующих значений в двух массивах. -SUMX2PY2 = СУММСУММКВ ## Возвращает сумму сумм квадратов соответствующих элементов двух массивов. -SUMXMY2 = СУММКВРАЗН ## Возвращает сумму квадратов разностей соответствующих значений в двух массивах. -TAN = TAN ## Возвращает тангенс числа. -TANH = TANH ## Возвращает гиперболический тангенс числа. -TRUNC = ОТБР ## Отбрасывает дробную часть числа. - +AVEDEV = СРОТКЛ +AVERAGE = СРЗНАЧ +AVERAGEA = СРЗНАЧА +AVERAGEIF = СРЗНАЧЕСЛИ +AVERAGEIFS = СРЗНАЧЕСЛИМН +BETA.DIST = БЕТА.РАСП +BETA.INV = БЕТА.ОБР +BINOM.DIST = БИНОМ.РАСП +BINOM.DIST.RANGE = БИНОМ.РАСП.ДИАП +BINOM.INV = БИНОМ.ОБР +CHISQ.DIST = ХИ2.РАСП +CHISQ.DIST.RT = ХИ2.РАСП.ПХ +CHISQ.INV = ХИ2.ОБР +CHISQ.INV.RT = ХИ2.ОБР.ПХ +CHISQ.TEST = ХИ2.ТЕСТ +CONFIDENCE.NORM = ДОВЕРИТ.НОРМ +CONFIDENCE.T = ДОВЕРИТ.СТЬЮДЕНТ +CORREL = КОРРЕЛ +COUNT = СЧЁТ +COUNTA = СЧЁТЗ +COUNTBLANK = СЧИТАТЬПУСТОТЫ +COUNTIF = СЧЁТЕСЛИ +COUNTIFS = СЧЁТЕСЛИМН +COVARIANCE.P = КОВАРИАЦИЯ.Г +COVARIANCE.S = КОВАРИАЦИЯ.В +DEVSQ = КВАДРОТКЛ +EXPON.DIST = ЭКСП.РАСП +F.DIST = F.РАСП +F.DIST.RT = F.РАСП.ПХ +F.INV = F.ОБР +F.INV.RT = F.ОБР.ПХ +F.TEST = F.ТЕСТ +FISHER = ФИШЕР +FISHERINV = ФИШЕРОБР +FORECAST.ETS = ПРЕДСКАЗ.ETS +FORECAST.ETS.CONFINT = ПРЕДСКАЗ.ЕTS.ДОВИНТЕРВАЛ +FORECAST.ETS.SEASONALITY = ПРЕДСКАЗ.ETS.СЕЗОННОСТЬ +FORECAST.ETS.STAT = ПРЕДСКАЗ.ETS.СТАТ +FORECAST.LINEAR = ПРЕДСКАЗ.ЛИНЕЙН +FREQUENCY = ЧАСТОТА +GAMMA = ГАММА +GAMMA.DIST = ГАММА.РАСП +GAMMA.INV = ГАММА.ОБР +GAMMALN = ГАММАНЛОГ +GAMMALN.PRECISE = ГАММАНЛОГ.ТОЧН +GAUSS = ГАУСС +GEOMEAN = СРГЕОМ +GROWTH = РОСТ +HARMEAN = СРГАРМ +HYPGEOM.DIST = ГИПЕРГЕОМ.РАСП +INTERCEPT = ОТРЕЗОК +KURT = ЭКСЦЕСС +LARGE = НАИБОЛЬШИЙ +LINEST = ЛИНЕЙН +LOGEST = ЛГРФПРИБЛ +LOGNORM.DIST = ЛОГНОРМ.РАСП +LOGNORM.INV = ЛОГНОРМ.ОБР +MAX = МАКС +MAXA = МАКСА +MAXIFS = МАКСЕСЛИ +MEDIAN = МЕДИАНА +MIN = МИН +MINA = МИНА +MINIFS = МИНЕСЛИ +MODE.MULT = МОДА.НСК +MODE.SNGL = МОДА.ОДН +NEGBINOM.DIST = ОТРБИНОМ.РАСП +NORM.DIST = НОРМ.РАСП +NORM.INV = НОРМ.ОБР +NORM.S.DIST = НОРМ.СТ.РАСП +NORM.S.INV = НОРМ.СТ.ОБР +PEARSON = PEARSON +PERCENTILE.EXC = ПРОЦЕНТИЛЬ.ИСКЛ +PERCENTILE.INC = ПРОЦЕНТИЛЬ.ВКЛ +PERCENTRANK.EXC = ПРОЦЕНТРАНГ.ИСКЛ +PERCENTRANK.INC = ПРОЦЕНТРАНГ.ВКЛ +PERMUT = ПЕРЕСТ +PERMUTATIONA = ПЕРЕСТА +PHI = ФИ +POISSON.DIST = ПУАССОН.РАСП +PROB = ВЕРОЯТНОСТЬ +QUARTILE.EXC = КВАРТИЛЬ.ИСКЛ +QUARTILE.INC = КВАРТИЛЬ.ВКЛ +RANK.AVG = РАНГ.СР +RANK.EQ = РАНГ.РВ +RSQ = КВПИРСОН +SKEW = СКОС +SKEW.P = СКОС.Г +SLOPE = НАКЛОН +SMALL = НАИМЕНЬШИЙ +STANDARDIZE = НОРМАЛИЗАЦИЯ +STDEV.P = СТАНДОТКЛОН.Г +STDEV.S = СТАНДОТКЛОН.В +STDEVA = СТАНДОТКЛОНА +STDEVPA = СТАНДОТКЛОНПА +STEYX = СТОШYX +T.DIST = СТЬЮДЕНТ.РАСП +T.DIST.2T = СТЬЮДЕНТ.РАСП.2Х +T.DIST.RT = СТЬЮДЕНТ.РАСП.ПХ +T.INV = СТЬЮДЕНТ.ОБР +T.INV.2T = СТЬЮДЕНТ.ОБР.2Х +T.TEST = СТЬЮДЕНТ.ТЕСТ +TREND = ТЕНДЕНЦИЯ +TRIMMEAN = УРЕЗСРЕДНЕЕ +VAR.P = ДИСП.Г +VAR.S = ДИСП.В +VARA = ДИСПА +VARPA = ДИСПРА +WEIBULL.DIST = ВЕЙБУЛЛ.РАСП +Z.TEST = Z.ТЕСТ ## -## Statistical functions Статистические функции +## Текстовые функции (Text Functions) ## -AVEDEV = СРОТКЛ ## Возвращает среднее арифметическое абсолютных значений отклонений точек данных от среднего. -AVERAGE = СРЗНАЧ ## Возвращает среднее арифметическое аргументов. -AVERAGEA = СРЗНАЧА ## Возвращает среднее арифметическое аргументов, включая числа, текст и логические значения. -AVERAGEIF = СРЗНАЧЕСЛИ ## Возвращает среднее значение (среднее арифметическое) всех ячеек в диапазоне, которые удовлетворяют данному условию. -AVERAGEIFS = СРЗНАЧЕСЛИМН ## Возвращает среднее значение (среднее арифметическое) всех ячеек, которые удовлетворяют нескольким условиям. -BETADIST = БЕТАРАСП ## Возвращает интегральную функцию бета-распределения. -BETAINV = БЕТАОБР ## Возвращает обратную интегральную функцию указанного бета-распределения. -BINOMDIST = БИНОМРАСП ## Возвращает отдельное значение биномиального распределения. -CHIDIST = ХИ2РАСП ## Возвращает одностороннюю вероятность распределения хи-квадрат. -CHIINV = ХИ2ОБР ## Возвращает обратное значение односторонней вероятности распределения хи-квадрат. -CHITEST = ХИ2ТЕСТ ## Возвращает тест на независимость. -CONFIDENCE = ДОВЕРИТ ## Возвращает доверительный интервал для среднего значения по генеральной совокупности. -CORREL = КОРРЕЛ ## Возвращает коэффициент корреляции между двумя множествами данных. -COUNT = СЧЁТ ## Подсчитывает количество чисел в списке аргументов. -COUNTA = СЧЁТЗ ## Подсчитывает количество значений в списке аргументов. -COUNTBLANK = СЧИТАТЬПУСТОТЫ ## Подсчитывает количество пустых ячеек в диапазоне -COUNTIF = СЧЁТЕСЛИ ## Подсчитывает количество ячеек в диапазоне, удовлетворяющих заданному условию -COUNTIFS = СЧЁТЕСЛИМН ## Подсчитывает количество ячеек внутри диапазона, удовлетворяющих нескольким условиям. -COVAR = КОВАР ## Возвращает ковариацию, среднее произведений парных отклонений -CRITBINOM = КРИТБИНОМ ## Возвращает наименьшее значение, для которого интегральное биномиальное распределение меньше или равно заданному критерию. -DEVSQ = КВАДРОТКЛ ## Возвращает сумму квадратов отклонений. -EXPONDIST = ЭКСПРАСП ## Возвращает экспоненциальное распределение. -FDIST = FРАСП ## Возвращает F-распределение вероятности. -FINV = FРАСПОБР ## Возвращает обратное значение для F-распределения вероятности. -FISHER = ФИШЕР ## Возвращает преобразование Фишера. -FISHERINV = ФИШЕРОБР ## Возвращает обратное преобразование Фишера. -FORECAST = ПРЕДСКАЗ ## Возвращает значение линейного тренда. -FREQUENCY = ЧАСТОТА ## Возвращает распределение частот в виде вертикального массива. -FTEST = ФТЕСТ ## Возвращает результат F-теста. -GAMMADIST = ГАММАРАСП ## Возвращает гамма-распределение. -GAMMAINV = ГАММАОБР ## Возвращает обратное гамма-распределение. -GAMMALN = ГАММАНЛОГ ## Возвращает натуральный логарифм гамма функции, Γ(x). -GEOMEAN = СРГЕОМ ## Возвращает среднее геометрическое. -GROWTH = РОСТ ## Возвращает значения в соответствии с экспоненциальным трендом. -HARMEAN = СРГАРМ ## Возвращает среднее гармоническое. -HYPGEOMDIST = ГИПЕРГЕОМЕТ ## Возвращает гипергеометрическое распределение. -INTERCEPT = ОТРЕЗОК ## Возвращает отрезок, отсекаемый на оси линией линейной регрессии. -KURT = ЭКСЦЕСС ## Возвращает эксцесс множества данных. -LARGE = НАИБОЛЬШИЙ ## Возвращает k-ое наибольшее значение в множестве данных. -LINEST = ЛИНЕЙН ## Возвращает параметры линейного тренда. -LOGEST = ЛГРФПРИБЛ ## Возвращает параметры экспоненциального тренда. -LOGINV = ЛОГНОРМОБР ## Возвращает обратное логарифмическое нормальное распределение. -LOGNORMDIST = ЛОГНОРМРАСП ## Возвращает интегральное логарифмическое нормальное распределение. -MAX = МАКС ## Возвращает наибольшее значение в списке аргументов. -MAXA = МАКСА ## Возвращает наибольшее значение в списке аргументов, включая числа, текст и логические значения. -MEDIAN = МЕДИАНА ## Возвращает медиану заданных чисел. -MIN = МИН ## Возвращает наименьшее значение в списке аргументов. -MINA = МИНА ## Возвращает наименьшее значение в списке аргументов, включая числа, текст и логические значения. -MODE = МОДА ## Возвращает значение моды множества данных. -NEGBINOMDIST = ОТРБИНОМРАСП ## Возвращает отрицательное биномиальное распределение. -NORMDIST = НОРМРАСП ## Возвращает нормальную функцию распределения. -NORMINV = НОРМОБР ## Возвращает обратное нормальное распределение. -NORMSDIST = НОРМСТРАСП ## Возвращает стандартное нормальное интегральное распределение. -NORMSINV = НОРМСТОБР ## Возвращает обратное значение стандартного нормального распределения. -PEARSON = ПИРСОН ## Возвращает коэффициент корреляции Пирсона. -PERCENTILE = ПЕРСЕНТИЛЬ ## Возвращает k-ую персентиль для значений диапазона. -PERCENTRANK = ПРОЦЕНТРАНГ ## Возвращает процентную норму значения в множестве данных. -PERMUT = ПЕРЕСТ ## Возвращает количество перестановок для заданного числа объектов. -POISSON = ПУАССОН ## Возвращает распределение Пуассона. -PROB = ВЕРОЯТНОСТЬ ## Возвращает вероятность того, что значение из диапазона находится внутри заданных пределов. -QUARTILE = КВАРТИЛЬ ## Возвращает квартиль множества данных. -RANK = РАНГ ## Возвращает ранг числа в списке чисел. -RSQ = КВПИРСОН ## Возвращает квадрат коэффициента корреляции Пирсона. -SKEW = СКОС ## Возвращает асимметрию распределения. -SLOPE = НАКЛОН ## Возвращает наклон линии линейной регрессии. -SMALL = НАИМЕНЬШИЙ ## Возвращает k-ое наименьшее значение в множестве данных. -STANDARDIZE = НОРМАЛИЗАЦИЯ ## Возвращает нормализованное значение. -STDEV = СТАНДОТКЛОН ## Оценивает стандартное отклонение по выборке. -STDEVA = СТАНДОТКЛОНА ## Оценивает стандартное отклонение по выборке, включая числа, текст и логические значения. -STDEVP = СТАНДОТКЛОНП ## Вычисляет стандартное отклонение по генеральной совокупности. -STDEVPA = СТАНДОТКЛОНПА ## Вычисляет стандартное отклонение по генеральной совокупности, включая числа, текст и логические значения. -STEYX = СТОШYX ## Возвращает стандартную ошибку предсказанных значений y для каждого значения x в регрессии. -TDIST = СТЬЮДРАСП ## Возвращает t-распределение Стьюдента. -TINV = СТЬЮДРАСПОБР ## Возвращает обратное t-распределение Стьюдента. -TREND = ТЕНДЕНЦИЯ ## Возвращает значения в соответствии с линейным трендом. -TRIMMEAN = УРЕЗСРЕДНЕЕ ## Возвращает среднее внутренности множества данных. -TTEST = ТТЕСТ ## Возвращает вероятность, соответствующую критерию Стьюдента. -VAR = ДИСП ## Оценивает дисперсию по выборке. -VARA = ДИСПА ## Оценивает дисперсию по выборке, включая числа, текст и логические значения. -VARP = ДИСПР ## Вычисляет дисперсию для генеральной совокупности. -VARPA = ДИСПРА ## Вычисляет дисперсию для генеральной совокупности, включая числа, текст и логические значения. -WEIBULL = ВЕЙБУЛЛ ## Возвращает распределение Вейбулла. -ZTEST = ZТЕСТ ## Возвращает двустороннее P-значение z-теста. - +BAHTTEXT = БАТТЕКСТ +CHAR = СИМВОЛ +CLEAN = ПЕЧСИМВ +CODE = КОДСИМВ +CONCAT = СЦЕП +DOLLAR = РУБЛЬ +EXACT = СОВПАД +FIND = НАЙТИ +FIXED = ФИКСИРОВАННЫЙ +ISTHAIDIGIT = TAYRAKAMIYSA +LEFT = ЛЕВСИМВ +LEN = ДЛСТР +LOWER = СТРОЧН +MID = ПСТР +NUMBERSTRING = СТРОКАЧИСЕЛ +NUMBERVALUE = ЧЗНАЧ +PROPER = ПРОПНАЧ +REPLACE = ЗАМЕНИТЬ +REPT = ПОВТОР +RIGHT = ПРАВСИМВ +SEARCH = ПОИСК +SUBSTITUTE = ПОДСТАВИТЬ +T = Т +TEXT = ТЕКСТ +TEXTJOIN = ОБЪЕДИНИТЬ +THAIDIGIT = ТАЙЦИФРА +THAINUMSOUND = ТАЙЧИСЛОВЗВУК +THAINUMSTRING = ТАЙЧИСЛОВСТРОКУ +THAISTRINGLENGTH = ТАЙДЛИНАСТРОКИ +TRIM = СЖПРОБЕЛЫ +UNICHAR = ЮНИСИМВ +UNICODE = UNICODE +UPPER = ПРОПИСН +VALUE = ЗНАЧЕН ## -## Text functions Текстовые функции +## Веб-функции (Web Functions) ## -ASC = ASC ## Для языков с двухбайтовыми наборами знаков (например, катакана) преобразует полноширинные (двухбайтовые) знаки в полуширинные (однобайтовые). -BAHTTEXT = БАТТЕКСТ ## Преобразует число в текст, используя денежный формат ß (БАТ). -CHAR = СИМВОЛ ## Возвращает знак с заданным кодом. -CLEAN = ПЕЧСИМВ ## Удаляет все непечатаемые знаки из текста. -CODE = КОДСИМВ ## Возвращает числовой код первого знака в текстовой строке. -CONCATENATE = СЦЕПИТЬ ## Объединяет несколько текстовых элементов в один. -DOLLAR = РУБЛЬ ## Преобразует число в текст, используя денежный формат. -EXACT = СОВПАД ## Проверяет идентичность двух текстовых значений. -FIND = НАЙТИ ## Ищет вхождения одного текстового значения в другом (с учетом регистра). -FINDB = НАЙТИБ ## Ищет вхождения одного текстового значения в другом (с учетом регистра). -FIXED = ФИКСИРОВАННЫЙ ## Форматирует число и преобразует его в текст с заданным числом десятичных знаков. -JIS = JIS ## Для языков с двухбайтовыми наборами знаков (например, катакана) преобразует полуширинные (однобайтовые) знаки в текстовой строке в полноширинные (двухбайтовые). -LEFT = ЛЕВСИМВ ## Возвращает крайние слева знаки текстового значения. -LEFTB = ЛЕВБ ## Возвращает крайние слева знаки текстового значения. -LEN = ДЛСТР ## Возвращает количество знаков в текстовой строке. -LENB = ДЛИНБ ## Возвращает количество знаков в текстовой строке. -LOWER = СТРОЧН ## Преобразует все буквы текста в строчные. -MID = ПСТР ## Возвращает заданное число знаков из строки текста, начиная с указанной позиции. -MIDB = ПСТРБ ## Возвращает заданное число знаков из строки текста, начиная с указанной позиции. -PHONETIC = PHONETIC ## Извлекает фонетические (фуригана) знаки из текстовой строки. -PROPER = ПРОПНАЧ ## Преобразует первую букву в каждом слове текста в прописную. -REPLACE = ЗАМЕНИТЬ ## Заменяет знаки в тексте. -REPLACEB = ЗАМЕНИТЬБ ## Заменяет знаки в тексте. -REPT = ПОВТОР ## Повторяет текст заданное число раз. -RIGHT = ПРАВСИМВ ## Возвращает крайние справа знаки текстовой строки. -RIGHTB = ПРАВБ ## Возвращает крайние справа знаки текстовой строки. -SEARCH = ПОИСК ## Ищет вхождения одного текстового значения в другом (без учета регистра). -SEARCHB = ПОИСКБ ## Ищет вхождения одного текстового значения в другом (без учета регистра). -SUBSTITUTE = ПОДСТАВИТЬ ## Заменяет в текстовой строке старый текст новым. -T = Т ## Преобразует аргументы в текст. -TEXT = ТЕКСТ ## Форматирует число и преобразует его в текст. -TRIM = СЖПРОБЕЛЫ ## Удаляет из текста пробелы. -UPPER = ПРОПИСН ## Преобразует все буквы текста в прописные. -VALUE = ЗНАЧЕН ## Преобразует текстовый аргумент в число. +ENCODEURL = КОДИР.URL +FILTERXML = ФИЛЬТР.XML +WEBSERVICE = ВЕБСЛУЖБА + +## +## Функции совместимости (Compatibility Functions) +## +BETADIST = БЕТАРАСП +BETAINV = БЕТАОБР +BINOMDIST = БИНОМРАСП +CEILING = ОКРВВЕРХ +CHIDIST = ХИ2РАСП +CHIINV = ХИ2ОБР +CHITEST = ХИ2ТЕСТ +CONCATENATE = СЦЕПИТЬ +CONFIDENCE = ДОВЕРИТ +COVAR = КОВАР +CRITBINOM = КРИТБИНОМ +EXPONDIST = ЭКСПРАСП +FDIST = FРАСП +FINV = FРАСПОБР +FLOOR = ОКРВНИЗ +FORECAST = ПРЕДСКАЗ +FTEST = ФТЕСТ +GAMMADIST = ГАММАРАСП +GAMMAINV = ГАММАОБР +HYPGEOMDIST = ГИПЕРГЕОМЕТ +LOGINV = ЛОГНОРМОБР +LOGNORMDIST = ЛОГНОРМРАСП +MODE = МОДА +NEGBINOMDIST = ОТРБИНОМРАСП +NORMDIST = НОРМРАСП +NORMINV = НОРМОБР +NORMSDIST = НОРМСТРАСП +NORMSINV = НОРМСТОБР +PERCENTILE = ПЕРСЕНТИЛЬ +PERCENTRANK = ПРОЦЕНТРАНГ +POISSON = ПУАССОН +QUARTILE = КВАРТИЛЬ +RANK = РАНГ +STDEV = СТАНДОТКЛОН +STDEVP = СТАНДОТКЛОНП +TDIST = СТЬЮДРАСП +TINV = СТЬЮДРАСПОБР +TTEST = ТТЕСТ +VAR = ДИСП +VARP = ДИСПР +WEIBULL = ВЕЙБУЛЛ +ZTEST = ZТЕСТ diff --git a/src/PhpSpreadsheet/Calculation/locale/sv/config b/src/PhpSpreadsheet/Calculation/locale/sv/config index bf72cc4f..c7440f71 100644 --- a/src/PhpSpreadsheet/Calculation/locale/sv/config +++ b/src/PhpSpreadsheet/Calculation/locale/sv/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## +## Svenska (Swedish) +## +############################################################ -ArgumentSeparator = ; - +ArgumentSeparator = ; ## -## (For future use) +## Error Codes ## -currencySymbol = kr - - -## -## Excel Error Codes (For future use) - -## -NULL = #Skärning! -DIV0 = #Division/0! -VALUE = #Värdefel! -REF = #Referens! -NAME = #Namn? -NUM = #Ogiltigt! -NA = #Saknas! +NULL = #SKÄRNING! +DIV0 = #DIVISION/0! +VALUE = #VÄRDEFEL! +REF = #REFERENS! +NAME = #NAMN? +NUM = #OGILTIGT! +NA = #SAKNAS! diff --git a/src/PhpSpreadsheet/Calculation/locale/sv/functions b/src/PhpSpreadsheet/Calculation/locale/sv/functions index 73b2deb5..2531b4c1 100644 --- a/src/PhpSpreadsheet/Calculation/locale/sv/functions +++ b/src/PhpSpreadsheet/Calculation/locale/sv/functions @@ -1,408 +1,532 @@ +############################################################ ## -## Add-in and Automation functions Tilläggs- och automatiseringsfunktioner +## PhpSpreadsheet - function name translations ## -GETPIVOTDATA = HÄMTA.PIVOTDATA ## Returnerar data som lagrats i en pivottabellrapport +## Svenska (Swedish) +## +############################################################ ## -## Cube functions Kubfunktioner +## Kubfunktioner (Cube Functions) ## -CUBEKPIMEMBER = KUBKPIMEDLEM ## Returnerar namn, egenskap och mått för en KPI och visar namnet och egenskapen i cellen. En KPI, eller prestandaindikator, är ett kvantifierbart mått, t.ex. månatlig bruttovinst eller personalomsättning per kvartal, som används för att analysera ett företags resultat. -CUBEMEMBER = KUBMEDLEM ## Returnerar en medlem eller ett par i en kubhierarki. Används för att verifiera att medlemmen eller paret finns i kuben. -CUBEMEMBERPROPERTY = KUBMEDLEMSEGENSKAP ## Returnerar värdet för en medlemsegenskap i kuben. Används för att verifiera att ett medlemsnamn finns i kuben, samt för att returnera den angivna egenskapen för medlemmen. -CUBERANKEDMEMBER = KUBRANGORDNADMEDLEM ## Returnerar den n:te, eller rangordnade, medlemmen i en uppsättning. Används för att returnera ett eller flera element i en uppsättning, till exempelvis den bästa försäljaren eller de tio bästa eleverna. -CUBESET = KUBINSTÄLLNING ## Definierar en beräknad uppsättning medlemmar eller par genom att skicka ett bestämt uttryck till kuben på servern, som skapar uppsättningen och sedan returnerar den till Microsoft Office Excel. -CUBESETCOUNT = KUBINSTÄLLNINGANTAL ## Returnerar antalet objekt i en uppsättning. -CUBEVALUE = KUBVÄRDE ## Returnerar ett mängdvärde från en kub. - +CUBEKPIMEMBER = KUBKPIMEDLEM +CUBEMEMBER = KUBMEDLEM +CUBEMEMBERPROPERTY = KUBMEDLEMSEGENSKAP +CUBERANKEDMEMBER = KUBRANGORDNADMEDLEM +CUBESET = KUBUPPSÄTTNING +CUBESETCOUNT = KUBUPPSÄTTNINGANTAL +CUBEVALUE = KUBVÄRDE ## -## Database functions Databasfunktioner +## Databasfunktioner (Database Functions) ## -DAVERAGE = DMEDEL ## Returnerar medelvärdet av databasposterna -DCOUNT = DANTAL ## Räknar antalet celler som innehåller tal i en databas -DCOUNTA = DANTALV ## Räknar ifyllda celler i en databas -DGET = DHÄMTA ## Hämtar en enstaka post från en databas som uppfyller de angivna villkoren -DMAX = DMAX ## Returnerar det största värdet från databasposterna -DMIN = DMIN ## Returnerar det minsta värdet från databasposterna -DPRODUCT = DPRODUKT ## Multiplicerar värdena i ett visst fält i poster som uppfyller villkoret -DSTDEV = DSTDAV ## Uppskattar standardavvikelsen baserat på ett urval av databasposterna -DSTDEVP = DSTDAVP ## Beräknar standardavvikelsen utifrån hela populationen av valda databasposter -DSUM = DSUMMA ## Summerar talen i kolumnfält i databasposter som uppfyller villkoret -DVAR = DVARIANS ## Uppskattar variansen baserat på ett urval av databasposterna -DVARP = DVARIANSP ## Beräknar variansen utifrån hela populationen av valda databasposter - +DAVERAGE = DMEDEL +DCOUNT = DANTAL +DCOUNTA = DANTALV +DGET = DHÄMTA +DMAX = DMAX +DMIN = DMIN +DPRODUCT = DPRODUKT +DSTDEV = DSTDAV +DSTDEVP = DSTDAVP +DSUM = DSUMMA +DVAR = DVARIANS +DVARP = DVARIANSP ## -## Date and time functions Tid- och datumfunktioner +## Tid- och datumfunktioner (Date & Time Functions) ## -DATE = DATUM ## Returnerar ett serienummer för ett visst datum -DATEVALUE = DATUMVÄRDE ## Konverterar ett datum i textformat till ett serienummer -DAY = DAG ## Konverterar ett serienummer till dag i månaden -DAYS360 = DAGAR360 ## Beräknar antalet dagar mellan två datum baserat på ett 360-dagarsår -EDATE = EDATUM ## Returnerar serienumret för ett datum som infaller ett visst antal månader före eller efter startdatumet -EOMONTH = SLUTMÅNAD ## Returnerar serienumret för sista dagen i månaden ett visst antal månader tidigare eller senare -HOUR = TIMME ## Konverterar ett serienummer till en timme -MINUTE = MINUT ## Konverterar ett serienummer till en minut -MONTH = MÅNAD ## Konverterar ett serienummer till en månad -NETWORKDAYS = NETTOARBETSDAGAR ## Returnerar antalet hela arbetsdagar mellan två datum -NOW = NU ## Returnerar serienumret för dagens datum och aktuell tid -SECOND = SEKUND ## Konverterar ett serienummer till en sekund -TIME = KLOCKSLAG ## Returnerar serienumret för en viss tid -TIMEVALUE = TIDVÄRDE ## Konverterar en tid i textformat till ett serienummer -TODAY = IDAG ## Returnerar serienumret för dagens datum -WEEKDAY = VECKODAG ## Konverterar ett serienummer till en dag i veckan -WEEKNUM = VECKONR ## Konverterar ett serienummer till ett veckonummer -WORKDAY = ARBETSDAGAR ## Returnerar serienumret för ett datum ett visst antal arbetsdagar tidigare eller senare -YEAR = ÅR ## Konverterar ett serienummer till ett år -YEARFRAC = ÅRDEL ## Returnerar en del av ett år som representerar antalet hela dagar mellan start- och slutdatum - +DATE = DATUM +DATEVALUE = DATUMVÄRDE +DAY = DAG +DAYS = DAGAR +DAYS360 = DAGAR360 +EDATE = EDATUM +EOMONTH = SLUTMÅNAD +HOUR = TIMME +ISOWEEKNUM = ISOVECKONR +MINUTE = MINUT +MONTH = MÅNAD +NETWORKDAYS = NETTOARBETSDAGAR +NETWORKDAYS.INTL = NETTOARBETSDAGAR.INT +NOW = NU +SECOND = SEKUND +THAIDAYOFWEEK = THAIVECKODAG +THAIMONTHOFYEAR = THAIMÅNAD +THAIYEAR = THAIÅR +TIME = KLOCKSLAG +TIMEVALUE = TIDVÄRDE +TODAY = IDAG +WEEKDAY = VECKODAG +WEEKNUM = VECKONR +WORKDAY = ARBETSDAGAR +WORKDAY.INTL = ARBETSDAGAR.INT +YEAR = ÅR +YEARFRAC = ÅRDEL ## -## Engineering functions Tekniska funktioner +## Tekniska funktioner (Engineering Functions) ## -BESSELI = BESSELI ## Returnerar den modifierade Bessel-funktionen In(x) -BESSELJ = BESSELJ ## Returnerar Bessel-funktionen Jn(x) -BESSELK = BESSELK ## Returnerar den modifierade Bessel-funktionen Kn(x) -BESSELY = BESSELY ## Returnerar Bessel-funktionen Yn(x) -BIN2DEC = BIN.TILL.DEC ## Omvandlar ett binärt tal till decimalt -BIN2HEX = BIN.TILL.HEX ## Omvandlar ett binärt tal till hexadecimalt -BIN2OCT = BIN.TILL.OKT ## Omvandlar ett binärt tal till oktalt -COMPLEX = KOMPLEX ## Omvandlar reella och imaginära koefficienter till ett komplext tal -CONVERT = KONVERTERA ## Omvandlar ett tal från ett måttsystem till ett annat -DEC2BIN = DEC.TILL.BIN ## Omvandlar ett decimalt tal till binärt -DEC2HEX = DEC.TILL.HEX ## Omvandlar ett decimalt tal till hexadecimalt -DEC2OCT = DEC.TILL.OKT ## Omvandlar ett decimalt tal till oktalt -DELTA = DELTA ## Testar om två värden är lika -ERF = FELF ## Returnerar felfunktionen -ERFC = FELFK ## Returnerar den komplementära felfunktionen -GESTEP = SLSTEG ## Testar om ett tal är större än ett tröskelvärde -HEX2BIN = HEX.TILL.BIN ## Omvandlar ett hexadecimalt tal till binärt -HEX2DEC = HEX.TILL.DEC ## Omvandlar ett hexadecimalt tal till decimalt -HEX2OCT = HEX.TILL.OKT ## Omvandlar ett hexadecimalt tal till oktalt -IMABS = IMABS ## Returnerar absolutvärdet (modulus) för ett komplext tal -IMAGINARY = IMAGINÄR ## Returnerar den imaginära koefficienten för ett komplext tal -IMARGUMENT = IMARGUMENT ## Returnerar det komplexa talets argument, en vinkel uttryckt i radianer -IMCONJUGATE = IMKONJUGAT ## Returnerar det komplexa talets konjugat -IMCOS = IMCOS ## Returnerar cosinus för ett komplext tal -IMDIV = IMDIV ## Returnerar kvoten för två komplexa tal -IMEXP = IMEUPPHÖJT ## Returnerar exponenten för ett komplext tal -IMLN = IMLN ## Returnerar den naturliga logaritmen för ett komplext tal -IMLOG10 = IMLOG10 ## Returnerar 10-logaritmen för ett komplext tal -IMLOG2 = IMLOG2 ## Returnerar 2-logaritmen för ett komplext tal -IMPOWER = IMUPPHÖJT ## Returnerar ett komplext tal upphöjt till en exponent -IMPRODUCT = IMPRODUKT ## Returnerar produkten av komplexa tal -IMREAL = IMREAL ## Returnerar den reella koefficienten för ett komplext tal -IMSIN = IMSIN ## Returnerar sinus för ett komplext tal -IMSQRT = IMROT ## Returnerar kvadratroten av ett komplext tal -IMSUB = IMDIFF ## Returnerar differensen mellan två komplexa tal -IMSUM = IMSUM ## Returnerar summan av komplexa tal -OCT2BIN = OKT.TILL.BIN ## Omvandlar ett oktalt tal till binärt -OCT2DEC = OKT.TILL.DEC ## Omvandlar ett oktalt tal till decimalt -OCT2HEX = OKT.TILL.HEX ## Omvandlar ett oktalt tal till hexadecimalt - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BIN.TILL.DEC +BIN2HEX = BIN.TILL.HEX +BIN2OCT = BIN.TILL.OKT +BITAND = BITOCH +BITLSHIFT = BITVSKIFT +BITOR = BITELLER +BITRSHIFT = BITHSKIFT +BITXOR = BITXELLER +COMPLEX = KOMPLEX +CONVERT = KONVERTERA +DEC2BIN = DEC.TILL.BIN +DEC2HEX = DEC.TILL.HEX +DEC2OCT = DEC.TILL.OKT +DELTA = DELTA +ERF = FELF +ERF.PRECISE = FELF.EXAKT +ERFC = FELFK +ERFC.PRECISE = FELFK.EXAKT +GESTEP = SLSTEG +HEX2BIN = HEX.TILL.BIN +HEX2DEC = HEX.TILL.DEC +HEX2OCT = HEX.TILL.OKT +IMABS = IMABS +IMAGINARY = IMAGINÄR +IMARGUMENT = IMARGUMENT +IMCONJUGATE = IMKONJUGAT +IMCOS = IMCOS +IMCOSH = IMCOSH +IMCOT = IMCOT +IMCSC = IMCSC +IMCSCH = IMCSCH +IMDIV = IMDIV +IMEXP = IMEUPPHÖJT +IMLN = IMLN +IMLOG10 = IMLOG10 +IMLOG2 = IMLOG2 +IMPOWER = IMUPPHÖJT +IMPRODUCT = IMPRODUKT +IMREAL = IMREAL +IMSEC = IMSEK +IMSECH = IMSEKH +IMSIN = IMSIN +IMSINH = IMSINH +IMSQRT = IMROT +IMSUB = IMDIFF +IMSUM = IMSUM +IMTAN = IMTAN +OCT2BIN = OKT.TILL.BIN +OCT2DEC = OKT.TILL.DEC +OCT2HEX = OKT.TILL.HEX ## -## Financial functions Finansiella funktioner +## Finansiella funktioner (Financial Functions) ## -ACCRINT = UPPLRÄNTA ## Returnerar den upplupna räntan för värdepapper med periodisk ränta -ACCRINTM = UPPLOBLRÄNTA ## Returnerar den upplupna räntan för ett värdepapper som ger avkastning på förfallodagen -AMORDEGRC = AMORDEGRC ## Returnerar avskrivningen för varje redovisningsperiod med hjälp av en avskrivningskoefficient -AMORLINC = AMORLINC ## Returnerar avskrivningen för varje redovisningsperiod -COUPDAYBS = KUPDAGBB ## Returnerar antal dagar från början av kupongperioden till likviddagen -COUPDAYS = KUPDAGARS ## Returnerar antalet dagar i kupongperioden som innehåller betalningsdatumet -COUPDAYSNC = KUPDAGNK ## Returnerar antalet dagar från betalningsdatumet till nästa kupongdatum -COUPNCD = KUPNKD ## Returnerar nästa kupongdatum efter likviddagen -COUPNUM = KUPANT ## Returnerar kuponger som förfaller till betalning mellan likviddagen och förfallodagen -COUPPCD = KUPFKD ## Returnerar föregående kupongdatum före likviddagen -CUMIPMT = KUMRÄNTA ## Returnerar den ackumulerade räntan som betalats mellan två perioder -CUMPRINC = KUMPRIS ## Returnerar det ackumulerade kapitalbeloppet som betalats på ett lån mellan två perioder -DB = DB ## Returnerar avskrivningen för en tillgång under en angiven tid enligt metoden för fast degressiv avskrivning -DDB = DEGAVSKR ## Returnerar en tillgångs värdeminskning under en viss period med hjälp av dubbel degressiv avskrivning eller någon annan metod som du anger -DISC = DISK ## Returnerar diskonteringsräntan för ett värdepapper -DOLLARDE = DECTAL ## Omvandlar ett pris uttryckt som ett bråk till ett decimaltal -DOLLARFR = BRÅK ## Omvandlar ett pris i kronor uttryckt som ett decimaltal till ett bråk -DURATION = LÖPTID ## Returnerar den årliga löptiden för en säkerhet med periodiska räntebetalningar -EFFECT = EFFRÄNTA ## Returnerar den årliga effektiva räntesatsen -FV = SLUTVÄRDE ## Returnerar det framtida värdet på en investering -FVSCHEDULE = FÖRRÄNTNING ## Returnerar det framtida värdet av ett begynnelsekapital beräknat på olika räntenivåer -INTRATE = ÅRSRÄNTA ## Returnerar räntesatsen för ett betalt värdepapper -IPMT = RBETALNING ## Returnerar räntedelen av en betalning för en given period -IRR = IR ## Returnerar internräntan för en serie betalningar -ISPMT = RALÅN ## Beräknar räntan som har betalats under en specifik betalningsperiod -MDURATION = MLÖPTID ## Returnerar den modifierade Macauley-löptiden för ett värdepapper med det antagna nominella värdet 100 kr -MIRR = MODIR ## Returnerar internräntan där positiva och negativa betalningar finansieras med olika räntor -NOMINAL = NOMRÄNTA ## Returnerar den årliga nominella räntesatsen -NPER = PERIODER ## Returnerar antalet perioder för en investering -NPV = NETNUVÄRDE ## Returnerar nuvärdet av en serie periodiska betalningar vid en given diskonteringsränta -ODDFPRICE = UDDAFPRIS ## Returnerar priset per 100 kr nominellt värde för ett värdepapper med en udda första period -ODDFYIELD = UDDAFAVKASTNING ## Returnerar avkastningen för en säkerhet med en udda första period -ODDLPRICE = UDDASPRIS ## Returnerar priset per 100 kr nominellt värde för ett värdepapper med en udda sista period -ODDLYIELD = UDDASAVKASTNING ## Returnerar avkastningen för en säkerhet med en udda sista period -PMT = BETALNING ## Returnerar den periodiska betalningen för en annuitet -PPMT = AMORT ## Returnerar amorteringsdelen av en annuitetsbetalning för en given period -PRICE = PRIS ## Returnerar priset per 100 kr nominellt värde för ett värdepapper som ger periodisk ränta -PRICEDISC = PRISDISK ## Returnerar priset per 100 kr nominellt värde för ett diskonterat värdepapper -PRICEMAT = PRISFÖRF ## Returnerar priset per 100 kr nominellt värde för ett värdepapper som ger ränta på förfallodagen -PV = PV ## Returnerar nuvärdet av en serie lika stora periodiska betalningar -RATE = RÄNTA ## Returnerar räntesatsen per period i en annuitet -RECEIVED = BELOPP ## Returnerar beloppet som utdelas på förfallodagen för ett betalat värdepapper -SLN = LINAVSKR ## Returnerar den linjära avskrivningen för en tillgång under en period -SYD = ÅRSAVSKR ## Returnerar den årliga avskrivningssumman för en tillgång under en angiven period -TBILLEQ = SSVXEKV ## Returnerar avkastningen motsvarande en obligation för en statsskuldväxel -TBILLPRICE = SSVXPRIS ## Returnerar priset per 100 kr nominellt värde för en statsskuldväxel -TBILLYIELD = SSVXRÄNTA ## Returnerar avkastningen för en statsskuldväxel -VDB = VDEGRAVSKR ## Returnerar avskrivningen för en tillgång under en angiven period (med degressiv avskrivning) -XIRR = XIRR ## Returnerar internräntan för en serie betalningar som inte nödvändigtvis är periodiska -XNPV = XNUVÄRDE ## Returnerar det nuvarande nettovärdet för en serie betalningar som inte nödvändigtvis är periodiska -YIELD = NOMAVK ## Returnerar avkastningen för ett värdepapper som ger periodisk ränta -YIELDDISC = NOMAVKDISK ## Returnerar den årliga avkastningen för diskonterade värdepapper, exempelvis en statsskuldväxel -YIELDMAT = NOMAVKFÖRF ## Returnerar den årliga avkastningen för ett värdepapper som ger ränta på förfallodagen - +ACCRINT = UPPLRÄNTA +ACCRINTM = UPPLOBLRÄNTA +AMORDEGRC = AMORDEGRC +AMORLINC = AMORLINC +COUPDAYBS = KUPDAGBB +COUPDAYS = KUPDAGB +COUPDAYSNC = KUPDAGNK +COUPNCD = KUPNKD +COUPNUM = KUPANT +COUPPCD = KUPFKD +CUMIPMT = KUMRÄNTA +CUMPRINC = KUMPRIS +DB = DB +DDB = DEGAVSKR +DISC = DISK +DOLLARDE = DECTAL +DOLLARFR = BRÅK +DURATION = LÖPTID +EFFECT = EFFRÄNTA +FV = SLUTVÄRDE +FVSCHEDULE = FÖRRÄNTNING +INTRATE = ÅRSRÄNTA +IPMT = RBETALNING +IRR = IR +ISPMT = RALÅN +MDURATION = MLÖPTID +MIRR = MODIR +NOMINAL = NOMRÄNTA +NPER = PERIODER +NPV = NETNUVÄRDE +ODDFPRICE = UDDAFPRIS +ODDFYIELD = UDDAFAVKASTNING +ODDLPRICE = UDDASPRIS +ODDLYIELD = UDDASAVKASTNING +PDURATION = PLÖPTID +PMT = BETALNING +PPMT = AMORT +PRICE = PRIS +PRICEDISC = PRISDISK +PRICEMAT = PRISFÖRF +PV = NUVÄRDE +RATE = RÄNTA +RECEIVED = BELOPP +RRI = AVKPÅINVEST +SLN = LINAVSKR +SYD = ÅRSAVSKR +TBILLEQ = SSVXEKV +TBILLPRICE = SSVXPRIS +TBILLYIELD = SSVXRÄNTA +VDB = VDEGRAVSKR +XIRR = XIRR +XNPV = XNUVÄRDE +YIELD = NOMAVK +YIELDDISC = NOMAVKDISK +YIELDMAT = NOMAVKFÖRF ## -## Information functions Informationsfunktioner +## Informationsfunktioner (Information Functions) ## -CELL = CELL ## Returnerar information om formatering, plats och innehåll i en cell -ERROR.TYPE = FEL.TYP ## Returnerar ett tal som motsvarar ett felvärde -INFO = INFO ## Returnerar information om operativsystemet -ISBLANK = ÄRREF ## Returnerar SANT om värdet är tomt -ISERR = Ä ## Returnerar SANT om värdet är ett felvärde annat än #SAKNAS! -ISERROR = ÄRFEL ## Returnerar SANT om värdet är ett felvärde -ISEVEN = ÄRJÄMN ## Returnerar SANT om talet är jämnt -ISLOGICAL = ÄREJTEXT ## Returnerar SANT om värdet är ett logiskt värde -ISNA = ÄRLOGISK ## Returnerar SANT om värdet är felvärdet #SAKNAS! -ISNONTEXT = ÄRSAKNAD ## Returnerar SANT om värdet inte är text -ISNUMBER = ÄRTAL ## Returnerar SANT om värdet är ett tal -ISODD = ÄRUDDA ## Returnerar SANT om talet är udda -ISREF = ÄRTOM ## Returnerar SANT om värdet är en referens -ISTEXT = ÄRTEXT ## Returnerar SANT om värdet är text -N = N ## Returnerar ett värde omvandlat till ett tal -NA = SAKNAS ## Returnerar felvärdet #SAKNAS! -TYPE = VÄRDETYP ## Returnerar ett tal som anger värdets datatyp - +CELL = CELL +ERROR.TYPE = FEL.TYP +INFO = INFO +ISBLANK = ÄRTOM +ISERR = ÄRF +ISERROR = ÄRFEL +ISEVEN = ÄRJÄMN +ISFORMULA = ÄRFORMEL +ISLOGICAL = ÄRLOGISK +ISNA = ÄRSAKNAD +ISNONTEXT = ÄREJTEXT +ISNUMBER = ÄRTAL +ISODD = ÄRUDDA +ISREF = ÄRREF +ISTEXT = ÄRTEXT +N = N +NA = SAKNAS +SHEET = BLAD +SHEETS = ANTALBLAD +TYPE = VÄRDETYP ## -## Logical functions Logiska funktioner +## Logiska funktioner (Logical Functions) ## -AND = OCH ## Returnerar SANT om alla argument är sanna -FALSE = FALSKT ## Returnerar det logiska värdet FALSKT -IF = OM ## Anger vilket logiskt test som ska utföras -IFERROR = OMFEL ## Returnerar ett värde som du anger om en formel utvärderar till ett fel; annars returneras resultatet av formeln -NOT = ICKE ## Inverterar logiken för argumenten -OR = ELLER ## Returnerar SANT om något argument är SANT -TRUE = SANT ## Returnerar det logiska värdet SANT - +AND = OCH +FALSE = FALSKT +IF = OM +IFERROR = OMFEL +IFNA = OMSAKNAS +IFS = IFS +NOT = ICKE +OR = ELLER +SWITCH = VÄXLA +TRUE = SANT +XOR = XELLER ## -## Lookup and reference functions Sök- och referensfunktioner +## Sök- och referensfunktioner (Lookup & Reference Functions) ## -ADDRESS = ADRESS ## Returnerar en referens som text till en enstaka cell i ett kalkylblad -AREAS = OMRÅDEN ## Returnerar antalet områden i en referens -CHOOSE = VÄLJ ## Väljer ett värde i en lista över värden -COLUMN = KOLUMN ## Returnerar kolumnnumret för en referens -COLUMNS = KOLUMNER ## Returnerar antalet kolumner i en referens -HLOOKUP = LETAKOLUMN ## Söker i den översta raden i en matris och returnerar värdet för angiven cell -HYPERLINK = HYPERLÄNK ## Skapar en genväg eller ett hopp till ett dokument i nätverket, i ett intranät eller på Internet -INDEX = INDEX ## Använder ett index för ett välja ett värde i en referens eller matris -INDIRECT = INDIREKT ## Returnerar en referens som anges av ett textvärde -LOOKUP = LETAUPP ## Letar upp värden i en vektor eller matris -MATCH = PASSA ## Letar upp värden i en referens eller matris -OFFSET = FÖRSKJUTNING ## Returnerar en referens förskjuten i förhållande till en given referens -ROW = RAD ## Returnerar radnumret för en referens -ROWS = RADER ## Returnerar antalet rader i en referens -RTD = RTD ## Hämtar realtidsdata från ett program som stöder COM-automation (Automation: Ett sätt att arbeta med ett programs objekt från ett annat program eller utvecklingsverktyg. Detta kallades tidigare för OLE Automation, och är en branschstandard och ingår i Component Object Model (COM).) -TRANSPOSE = TRANSPONERA ## Transponerar en matris -VLOOKUP = LETARAD ## Letar i den första kolumnen i en matris och flyttar över raden för att returnera värdet för en cell - +ADDRESS = ADRESS +AREAS = OMRÅDEN +CHOOSE = VÄLJ +COLUMN = KOLUMN +COLUMNS = KOLUMNER +FORMULATEXT = FORMELTEXT +GETPIVOTDATA = HÄMTA.PIVOTDATA +HLOOKUP = LETAKOLUMN +HYPERLINK = HYPERLÄNK +INDEX = INDEX +INDIRECT = INDIREKT +LOOKUP = LETAUPP +MATCH = PASSA +OFFSET = FÖRSKJUTNING +ROW = RAD +ROWS = RADER +RTD = RTD +TRANSPOSE = TRANSPONERA +VLOOKUP = LETARAD ## -## Math and trigonometry functions Matematiska och trigonometriska funktioner +## Matematiska och trigonometriska funktioner (Math & Trig Functions) ## -ABS = ABS ## Returnerar absolutvärdet av ett tal -ACOS = ARCCOS ## Returnerar arcus cosinus för ett tal -ACOSH = ARCCOSH ## Returnerar inverterad hyperbolisk cosinus för ett tal -ASIN = ARCSIN ## Returnerar arcus cosinus för ett tal -ASINH = ARCSINH ## Returnerar hyperbolisk arcus sinus för ett tal -ATAN = ARCTAN ## Returnerar arcus tangens för ett tal -ATAN2 = ARCTAN2 ## Returnerar arcus tangens för en x- och en y- koordinat -ATANH = ARCTANH ## Returnerar hyperbolisk arcus tangens för ett tal -CEILING = RUNDA.UPP ## Avrundar ett tal till närmaste heltal eller närmaste signifikanta multipel -COMBIN = KOMBIN ## Returnerar antalet kombinationer för ett givet antal objekt -COS = COS ## Returnerar cosinus för ett tal -COSH = COSH ## Returnerar hyperboliskt cosinus för ett tal -DEGREES = GRADER ## Omvandlar radianer till grader -EVEN = JÄMN ## Avrundar ett tal uppåt till närmaste heltal -EXP = EXP ## Returnerar e upphöjt till ett givet tal -FACT = FAKULTET ## Returnerar fakulteten för ett tal -FACTDOUBLE = DUBBELFAKULTET ## Returnerar dubbelfakulteten för ett tal -FLOOR = RUNDA.NED ## Avrundar ett tal nedåt mot noll -GCD = SGD ## Returnerar den största gemensamma nämnaren -INT = HELTAL ## Avrundar ett tal nedåt till närmaste heltal -LCM = MGM ## Returnerar den minsta gemensamma multipeln -LN = LN ## Returnerar den naturliga logaritmen för ett tal -LOG = LOG ## Returnerar logaritmen för ett tal för en given bas -LOG10 = LOG10 ## Returnerar 10-logaritmen för ett tal -MDETERM = MDETERM ## Returnerar matrisen som är avgörandet av en matris -MINVERSE = MINVERT ## Returnerar matrisinversen av en matris -MMULT = MMULT ## Returnerar matrisprodukten av två matriser -MOD = REST ## Returnerar resten vid en division -MROUND = MAVRUNDA ## Returnerar ett tal avrundat till en given multipel -MULTINOMIAL = MULTINOMIAL ## Returnerar multinomialen för en uppsättning tal -ODD = UDDA ## Avrundar ett tal uppåt till närmaste udda heltal -PI = PI ## Returnerar värdet pi -POWER = UPPHÖJT.TILL ## Returnerar resultatet av ett tal upphöjt till en exponent -PRODUCT = PRODUKT ## Multiplicerar argumenten -QUOTIENT = KVOT ## Returnerar heltalsdelen av en division -RADIANS = RADIANER ## Omvandlar grader till radianer -RAND = SLUMP ## Returnerar ett slumptal mellan 0 och 1 -RANDBETWEEN = SLUMP.MELLAN ## Returnerar ett slumptal mellan de tal som du anger -ROMAN = ROMERSK ## Omvandlar vanliga (arabiska) siffror till romerska som text -ROUND = AVRUNDA ## Avrundar ett tal till ett angivet antal siffror -ROUNDDOWN = AVRUNDA.NEDÅT ## Avrundar ett tal nedåt mot noll -ROUNDUP = AVRUNDA.UPPÅT ## Avrundar ett tal uppåt, från noll -SERIESSUM = SERIESUMMA ## Returnerar summan av en potensserie baserat på formeln -SIGN = TECKEN ## Returnerar tecknet för ett tal -SIN = SIN ## Returnerar sinus för en given vinkel -SINH = SINH ## Returnerar hyperbolisk sinus för ett tal -SQRT = ROT ## Returnerar den positiva kvadratroten -SQRTPI = ROTPI ## Returnerar kvadratroten för (tal * pi) -SUBTOTAL = DELSUMMA ## Returnerar en delsumma i en lista eller databas -SUM = SUMMA ## Summerar argumenten -SUMIF = SUMMA.OM ## Summerar celler enligt ett angivet villkor -SUMIFS = SUMMA.OMF ## Lägger till cellerna i ett område som uppfyller flera kriterier -SUMPRODUCT = PRODUKTSUMMA ## Returnerar summan av produkterna i motsvarande matriskomponenter -SUMSQ = KVADRATSUMMA ## Returnerar summan av argumentens kvadrater -SUMX2MY2 = SUMMAX2MY2 ## Returnerar summan av differensen mellan kvadraterna för motsvarande värden i två matriser -SUMX2PY2 = SUMMAX2PY2 ## Returnerar summan av summan av kvadraterna av motsvarande värden i två matriser -SUMXMY2 = SUMMAXMY2 ## Returnerar summan av kvadraten av skillnaden mellan motsvarande värden i två matriser -TAN = TAN ## Returnerar tangens för ett tal -TANH = TANH ## Returnerar hyperbolisk tangens för ett tal -TRUNC = AVKORTA ## Avkortar ett tal till ett heltal - +ABS = ABS +ACOS = ARCCOS +ACOSH = ARCCOSH +ACOT = ARCCOT +ACOTH = ARCCOTH +AGGREGATE = MÄNGD +ARABIC = ARABISKA +ASIN = ARCSIN +ASINH = ARCSINH +ATAN = ARCTAN +ATAN2 = ARCTAN2 +ATANH = ARCTANH +BASE = BAS +CEILING.MATH = RUNDA.UPP.MATEMATISKT +CEILING.PRECISE = RUNDA.UPP.EXAKT +COMBIN = KOMBIN +COMBINA = KOMBINA +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = DECIMAL +DEGREES = GRADER +ECMA.CEILING = ECMA.RUNDA.UPP +EVEN = JÄMN +EXP = EXP +FACT = FAKULTET +FACTDOUBLE = DUBBELFAKULTET +FLOOR.MATH = RUNDA.NER.MATEMATISKT +FLOOR.PRECISE = RUNDA.NER.EXAKT +GCD = SGD +INT = HELTAL +ISO.CEILING = ISO.RUNDA.UPP +LCM = MGM +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = MDETERM +MINVERSE = MINVERT +MMULT = MMULT +MOD = REST +MROUND = MAVRUNDA +MULTINOMIAL = MULTINOMIAL +MUNIT = MENHET +ODD = UDDA +PI = PI +POWER = UPPHÖJT.TILL +PRODUCT = PRODUKT +QUOTIENT = KVOT +RADIANS = RADIANER +RAND = SLUMP +RANDBETWEEN = SLUMP.MELLAN +ROMAN = ROMERSK +ROUND = AVRUNDA +ROUNDBAHTDOWN = AVRUNDABAHTNEDÅT +ROUNDBAHTUP = AVRUNDABAHTUPPÅT +ROUNDDOWN = AVRUNDA.NEDÅT +ROUNDUP = AVRUNDA.UPPÅT +SEC = SEK +SECH = SEKH +SERIESSUM = SERIESUMMA +SIGN = TECKEN +SIN = SIN +SINH = SINH +SQRT = ROT +SQRTPI = ROTPI +SUBTOTAL = DELSUMMA +SUM = SUMMA +SUMIF = SUMMA.OM +SUMIFS = SUMMA.OMF +SUMPRODUCT = PRODUKTSUMMA +SUMSQ = KVADRATSUMMA +SUMX2MY2 = SUMMAX2MY2 +SUMX2PY2 = SUMMAX2PY2 +SUMXMY2 = SUMMAXMY2 +TAN = TAN +TANH = TANH +TRUNC = AVKORTA ## -## Statistical functions Statistiska funktioner +## Statistiska funktioner (Statistical Functions) ## -AVEDEV = MEDELAVV ## Returnerar medelvärdet för datapunkters absoluta avvikelse från deras medelvärde -AVERAGE = MEDEL ## Returnerar medelvärdet av argumenten -AVERAGEA = AVERAGEA ## Returnerar medelvärdet av argumenten, inklusive tal, text och logiska värden -AVERAGEIF = MEDELOM ## Returnerar medelvärdet (aritmetiskt medelvärde) för alla celler i ett område som uppfyller ett givet kriterium -AVERAGEIFS = MEDELOMF ## Returnerar medelvärdet (det aritmetiska medelvärdet) för alla celler som uppfyller flera villkor. -BETADIST = BETAFÖRD ## Returnerar den kumulativa betafördelningsfunktionen -BETAINV = BETAINV ## Returnerar inversen till den kumulativa fördelningsfunktionen för en viss betafördelning -BINOMDIST = BINOMFÖRD ## Returnerar den individuella binomialfördelningen -CHIDIST = CHI2FÖRD ## Returnerar den ensidiga sannolikheten av c2-fördelningen -CHIINV = CHI2INV ## Returnerar inversen av chi2-fördelningen -CHITEST = CHI2TEST ## Returnerar oberoendetesten -CONFIDENCE = KONFIDENS ## Returnerar konfidensintervallet för en populations medelvärde -CORREL = KORREL ## Returnerar korrelationskoefficienten mellan två datamängder -COUNT = ANTAL ## Räknar hur många tal som finns bland argumenten -COUNTA = ANTALV ## Räknar hur många värden som finns bland argumenten -COUNTBLANK = ANTAL.TOMMA ## Räknar antalet tomma celler i ett område -COUNTIF = ANTAL.OM ## Räknar antalet celler i ett område som uppfyller angivna villkor. -COUNTIFS = ANTAL.OMF ## Räknar antalet celler i ett område som uppfyller flera villkor. -COVAR = KOVAR ## Returnerar kovariansen, d.v.s. medelvärdet av produkterna för parade avvikelser -CRITBINOM = KRITBINOM ## Returnerar det minsta värdet för vilket den kumulativa binomialfördelningen är mindre än eller lika med ett villkorsvärde -DEVSQ = KVADAVV ## Returnerar summan av kvadrater på avvikelser -EXPONDIST = EXPONFÖRD ## Returnerar exponentialfördelningen -FDIST = FFÖRD ## Returnerar F-sannolikhetsfördelningen -FINV = FINV ## Returnerar inversen till F-sannolikhetsfördelningen -FISHER = FISHER ## Returnerar Fisher-transformationen -FISHERINV = FISHERINV ## Returnerar inversen till Fisher-transformationen -FORECAST = PREDIKTION ## Returnerar ett värde längs en linjär trendlinje -FREQUENCY = FREKVENS ## Returnerar en frekvensfördelning som en lodrät matris -FTEST = FTEST ## Returnerar resultatet av en F-test -GAMMADIST = GAMMAFÖRD ## Returnerar gammafördelningen -GAMMAINV = GAMMAINV ## Returnerar inversen till den kumulativa gammafördelningen -GAMMALN = GAMMALN ## Returnerar den naturliga logaritmen för gammafunktionen, G(x) -GEOMEAN = GEOMEDEL ## Returnerar det geometriska medelvärdet -GROWTH = EXPTREND ## Returnerar värden längs en exponentiell trend -HARMEAN = HARMMEDEL ## Returnerar det harmoniska medelvärdet -HYPGEOMDIST = HYPGEOMFÖRD ## Returnerar den hypergeometriska fördelningen -INTERCEPT = SKÄRNINGSPUNKT ## Returnerar skärningspunkten för en linjär regressionslinje -KURT = TOPPIGHET ## Returnerar toppigheten av en mängd data -LARGE = STÖRSTA ## Returnerar det n:te största värdet i en mängd data -LINEST = REGR ## Returnerar parametrar till en linjär trendlinje -LOGEST = EXPREGR ## Returnerar parametrarna i en exponentiell trend -LOGINV = LOGINV ## Returnerar inversen till den lognormala fördelningen -LOGNORMDIST = LOGNORMFÖRD ## Returnerar den kumulativa lognormala fördelningen -MAX = MAX ## Returnerar det största värdet i en lista av argument -MAXA = MAXA ## Returnerar det största värdet i en lista av argument, inklusive tal, text och logiska värden -MEDIAN = MEDIAN ## Returnerar medianen för angivna tal -MIN = MIN ## Returnerar det minsta värdet i en lista med argument -MINA = MINA ## Returnerar det minsta värdet i en lista över argument, inklusive tal, text och logiska värden -MODE = TYPVÄRDE ## Returnerar det vanligaste värdet i en datamängd -NEGBINOMDIST = NEGBINOMFÖRD ## Returnerar den negativa binomialfördelningen -NORMDIST = NORMFÖRD ## Returnerar den kumulativa normalfördelningen -NORMINV = NORMINV ## Returnerar inversen till den kumulativa normalfördelningen -NORMSDIST = NORMSFÖRD ## Returnerar den kumulativa standardnormalfördelningen -NORMSINV = NORMSINV ## Returnerar inversen till den kumulativa standardnormalfördelningen -PEARSON = PEARSON ## Returnerar korrelationskoefficienten till Pearsons momentprodukt -PERCENTILE = PERCENTIL ## Returnerar den n:te percentilen av värden i ett område -PERCENTRANK = PROCENTRANG ## Returnerar procentrangen för ett värde i en datamängd -PERMUT = PERMUT ## Returnerar antal permutationer för ett givet antal objekt -POISSON = POISSON ## Returnerar Poisson-fördelningen -PROB = SANNOLIKHET ## Returnerar sannolikheten att värden i ett område ligger mellan två gränser -QUARTILE = KVARTIL ## Returnerar kvartilen av en mängd data -RANK = RANG ## Returnerar rangordningen för ett tal i en lista med tal -RSQ = RKV ## Returnerar kvadraten av Pearsons produktmomentkorrelationskoefficient -SKEW = SNEDHET ## Returnerar snedheten för en fördelning -SLOPE = LUTNING ## Returnerar lutningen på en linjär regressionslinje -SMALL = MINSTA ## Returnerar det n:te minsta värdet i en mängd data -STANDARDIZE = STANDARDISERA ## Returnerar ett normaliserat värde -STDEV = STDAV ## Uppskattar standardavvikelsen baserat på ett urval -STDEVA = STDEVA ## Uppskattar standardavvikelsen baserat på ett urval, inklusive tal, text och logiska värden -STDEVP = STDAVP ## Beräknar standardavvikelsen baserat på hela populationen -STDEVPA = STDEVPA ## Beräknar standardavvikelsen baserat på hela populationen, inklusive tal, text och logiska värden -STEYX = STDFELYX ## Returnerar standardfelet för ett förutspått y-värde för varje x-värde i regressionen -TDIST = TFÖRD ## Returnerar Students t-fördelning -TINV = TINV ## Returnerar inversen till Students t-fördelning -TREND = TREND ## Returnerar värden längs en linjär trend -TRIMMEAN = TRIMMEDEL ## Returnerar medelvärdet av mittpunkterna i en datamängd -TTEST = TTEST ## Returnerar sannolikheten beräknad ur Students t-test -VAR = VARIANS ## Uppskattar variansen baserat på ett urval -VARA = VARA ## Uppskattar variansen baserat på ett urval, inklusive tal, text och logiska värden -VARP = VARIANSP ## Beräknar variansen baserat på hela populationen -VARPA = VARPA ## Beräknar variansen baserat på hela populationen, inklusive tal, text och logiska värden -WEIBULL = WEIBULL ## Returnerar Weibull-fördelningen -ZTEST = ZTEST ## Returnerar det ensidiga sannolikhetsvärdet av ett z-test - +AVEDEV = MEDELAVV +AVERAGE = MEDEL +AVERAGEA = AVERAGEA +AVERAGEIF = MEDEL.OM +AVERAGEIFS = MEDEL.OMF +BETA.DIST = BETA.FÖRD +BETA.INV = BETA.INV +BINOM.DIST = BINOM.FÖRD +BINOM.DIST.RANGE = BINOM.FÖRD.INTERVALL +BINOM.INV = BINOM.INV +CHISQ.DIST = CHI2.FÖRD +CHISQ.DIST.RT = CHI2.FÖRD.RT +CHISQ.INV = CHI2.INV +CHISQ.INV.RT = CHI2.INV.RT +CHISQ.TEST = CHI2.TEST +CONFIDENCE.NORM = KONFIDENS.NORM +CONFIDENCE.T = KONFIDENS.T +CORREL = KORREL +COUNT = ANTAL +COUNTA = ANTALV +COUNTBLANK = ANTAL.TOMMA +COUNTIF = ANTAL.OM +COUNTIFS = ANTAL.OMF +COVARIANCE.P = KOVARIANS.P +COVARIANCE.S = KOVARIANS.S +DEVSQ = KVADAVV +EXPON.DIST = EXPON.FÖRD +F.DIST = F.FÖRD +F.DIST.RT = F.FÖRD.RT +F.INV = F.INV +F.INV.RT = F.INV.RT +F.TEST = F.TEST +FISHER = FISHER +FISHERINV = FISHERINV +FORECAST.ETS = PROGNOS.ETS +FORECAST.ETS.CONFINT = PROGNOS.ETS.KONFINT +FORECAST.ETS.SEASONALITY = PROGNOS.ETS.SÄSONGSBEROENDE +FORECAST.ETS.STAT = PROGNOS.ETS.STAT +FORECAST.LINEAR = PROGNOS.LINJÄR +FREQUENCY = FREKVENS +GAMMA = GAMMA +GAMMA.DIST = GAMMA.FÖRD +GAMMA.INV = GAMMA.INV +GAMMALN = GAMMALN +GAMMALN.PRECISE = GAMMALN.EXAKT +GAUSS = GAUSS +GEOMEAN = GEOMEDEL +GROWTH = EXPTREND +HARMEAN = HARMMEDEL +HYPGEOM.DIST = HYPGEOM.FÖRD +INTERCEPT = SKÄRNINGSPUNKT +KURT = TOPPIGHET +LARGE = STÖRSTA +LINEST = REGR +LOGEST = EXPREGR +LOGNORM.DIST = LOGNORM.FÖRD +LOGNORM.INV = LOGNORM.INV +MAX = MAX +MAXA = MAXA +MAXIFS = MAXIFS +MEDIAN = MEDIAN +MIN = MIN +MINA = MINA +MINIFS = MINIFS +MODE.MULT = TYPVÄRDE.FLERA +MODE.SNGL = TYPVÄRDE.ETT +NEGBINOM.DIST = NEGBINOM.FÖRD +NORM.DIST = NORM.FÖRD +NORM.INV = NORM.INV +NORM.S.DIST = NORM.S.FÖRD +NORM.S.INV = NORM.S.INV +PEARSON = PEARSON +PERCENTILE.EXC = PERCENTIL.EXK +PERCENTILE.INC = PERCENTIL.INK +PERCENTRANK.EXC = PROCENTRANG.EXK +PERCENTRANK.INC = PROCENTRANG.INK +PERMUT = PERMUT +PERMUTATIONA = PERMUTATIONA +PHI = PHI +POISSON.DIST = POISSON.FÖRD +PROB = SANNOLIKHET +QUARTILE.EXC = KVARTIL.EXK +QUARTILE.INC = KVARTIL.INK +RANK.AVG = RANG.MED +RANK.EQ = RANG.EKV +RSQ = RKV +SKEW = SNEDHET +SKEW.P = SNEDHET.P +SLOPE = LUTNING +SMALL = MINSTA +STANDARDIZE = STANDARDISERA +STDEV.P = STDAV.P +STDEV.S = STDAV.S +STDEVA = STDEVA +STDEVPA = STDEVPA +STEYX = STDFELYX +T.DIST = T.FÖRD +T.DIST.2T = T.FÖRD.2T +T.DIST.RT = T.FÖRD.RT +T.INV = T.INV +T.INV.2T = T.INV.2T +T.TEST = T.TEST +TREND = TREND +TRIMMEAN = TRIMMEDEL +VAR.P = VARIANS.P +VAR.S = VARIANS.S +VARA = VARA +VARPA = VARPA +WEIBULL.DIST = WEIBULL.FÖRD +Z.TEST = Z.TEST ## -## Text functions Textfunktioner +## Textfunktioner (Text Functions) ## -ASC = ASC ## Ändrar helbredds (dubbel byte) engelska bokstäver eller katakana inom en teckensträng till tecken med halvt breddsteg (enkel byte) -BAHTTEXT = BAHTTEXT ## Omvandlar ett tal till text med valutaformatet ß (baht) -CHAR = TECKENKOD ## Returnerar tecknet som anges av kod -CLEAN = STÄDA ## Tar bort alla icke utskrivbara tecken i en text -CODE = KOD ## Returnerar en numerisk kod för det första tecknet i en textsträng -CONCATENATE = SAMMANFOGA ## Sammanfogar flera textdelar till en textsträng -DOLLAR = VALUTA ## Omvandlar ett tal till text med valutaformat -EXACT = EXAKT ## Kontrollerar om två textvärden är identiska -FIND = HITTA ## Hittar en text i en annan (skiljer på gemener och versaler) -FINDB = HITTAB ## Hittar en text i en annan (skiljer på gemener och versaler) -FIXED = FASTTAL ## Formaterar ett tal som text med ett fast antal decimaler -JIS = JIS ## Ändrar halvbredds (enkel byte) engelska bokstäver eller katakana inom en teckensträng till tecken med helt breddsteg (dubbel byte) -LEFT = VÄNSTER ## Returnerar tecken längst till vänster i en sträng -LEFTB = VÄNSTERB ## Returnerar tecken längst till vänster i en sträng -LEN = LÄNGD ## Returnerar antalet tecken i en textsträng -LENB = LÄNGDB ## Returnerar antalet tecken i en textsträng -LOWER = GEMENER ## Omvandlar text till gemener -MID = EXTEXT ## Returnerar angivet antal tecken från en text med början vid den position som du anger -MIDB = EXTEXTB ## Returnerar angivet antal tecken från en text med början vid den position som du anger -PHONETIC = PHONETIC ## Returnerar de fonetiska (furigana) tecknen i en textsträng -PROPER = INITIAL ## Ändrar första bokstaven i varje ord i ett textvärde till versal -REPLACE = ERSÄTT ## Ersätter tecken i text -REPLACEB = ERSÄTTB ## Ersätter tecken i text -REPT = REP ## Upprepar en text ett bestämt antal gånger -RIGHT = HÖGER ## Returnerar tecken längst till höger i en sträng -RIGHTB = HÖGERB ## Returnerar tecken längst till höger i en sträng -SEARCH = SÖK ## Hittar ett textvärde i ett annat (skiljer inte på gemener och versaler) -SEARCHB = SÖKB ## Hittar ett textvärde i ett annat (skiljer inte på gemener och versaler) -SUBSTITUTE = BYT.UT ## Ersätter gammal text med ny text i en textsträng -T = T ## Omvandlar argumenten till text -TEXT = TEXT ## Formaterar ett tal och omvandlar det till text -TRIM = RENSA ## Tar bort blanksteg från text -UPPER = VERSALER ## Omvandlar text till versaler -VALUE = TEXTNUM ## Omvandlar ett textargument till ett tal +BAHTTEXT = BAHTTEXT +CHAR = TECKENKOD +CLEAN = STÄDA +CODE = KOD +CONCAT = SAMMAN +DOLLAR = VALUTA +EXACT = EXAKT +FIND = HITTA +FIXED = FASTTAL +LEFT = VÄNSTER +LEN = LÄNGD +LOWER = GEMENER +MID = EXTEXT +NUMBERVALUE = TALVÄRDE +PROPER = INITIAL +REPLACE = ERSÄTT +REPT = REP +RIGHT = HÖGER +SEARCH = SÖK +SUBSTITUTE = BYT.UT +T = T +TEXT = TEXT +TEXTJOIN = TEXTJOIN +THAIDIGIT = THAISIFFRA +THAINUMSOUND = THAITALLJUD +THAINUMSTRING = THAITALSTRÄNG +THAISTRINGLENGTH = THAISTRÄNGLÄNGD +TRIM = RENSA +UNICHAR = UNITECKENKOD +UNICODE = UNICODE +UPPER = VERSALER +VALUE = TEXTNUM + +## +## Webbfunktioner (Web Functions) +## +ENCODEURL = KODAWEBBADRESS +FILTERXML = FILTRERAXML +WEBSERVICE = WEBBTJÄNST + +## +## Kompatibilitetsfunktioner (Compatibility Functions) +## +BETADIST = BETAFÖRD +BETAINV = BETAINV +BINOMDIST = BINOMFÖRD +CEILING = RUNDA.UPP +CHIDIST = CHI2FÖRD +CHIINV = CHI2INV +CHITEST = CHI2TEST +CONCATENATE = SAMMANFOGA +CONFIDENCE = KONFIDENS +COVAR = KOVAR +CRITBINOM = KRITBINOM +EXPONDIST = EXPONFÖRD +FDIST = FFÖRD +FINV = FINV +FLOOR = RUNDA.NER +FORECAST = PREDIKTION +FTEST = FTEST +GAMMADIST = GAMMAFÖRD +GAMMAINV = GAMMAINV +HYPGEOMDIST = HYPGEOMFÖRD +LOGINV = LOGINV +LOGNORMDIST = LOGNORMFÖRD +MODE = TYPVÄRDE +NEGBINOMDIST = NEGBINOMFÖRD +NORMDIST = NORMFÖRD +NORMINV = NORMINV +NORMSDIST = NORMSFÖRD +NORMSINV = NORMSINV +PERCENTILE = PERCENTIL +PERCENTRANK = PROCENTRANG +POISSON = POISSON +QUARTILE = KVARTIL +RANK = RANG +STDEV = STDAV +STDEVP = STDAVP +TDIST = TFÖRD +TINV = TINV +TTEST = TTEST +VAR = VARIANS +VARP = VARIANSP +WEIBULL = WEIBULL +ZTEST = ZTEST diff --git a/src/PhpSpreadsheet/Calculation/locale/tr/config b/src/PhpSpreadsheet/Calculation/locale/tr/config index 266e000f..63d22fd0 100644 --- a/src/PhpSpreadsheet/Calculation/locale/tr/config +++ b/src/PhpSpreadsheet/Calculation/locale/tr/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## +## Türkçe (Turkish) +## +############################################################ -ArgumentSeparator = ; - +ArgumentSeparator = ; ## -## (For future use) +## Error Codes ## -currencySymbol = YTL - - -## -## Excel Error Codes (For future use) - -## -NULL = #BOŞ! -DIV0 = #SAYI/0! -VALUE = #DEĞER! -REF = #BAŞV! -NAME = #AD? -NUM = #SAYI! -NA = #YOK +NULL = #BOŞ! +DIV0 = #SAYI/0! +VALUE = #DEĞER! +REF = #BAŞV! +NAME = #AD? +NUM = #SAYI! +NA = #YOK diff --git a/src/PhpSpreadsheet/Calculation/locale/tr/functions b/src/PhpSpreadsheet/Calculation/locale/tr/functions index f03563a7..f872274f 100644 --- a/src/PhpSpreadsheet/Calculation/locale/tr/functions +++ b/src/PhpSpreadsheet/Calculation/locale/tr/functions @@ -1,416 +1,537 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Türkçe (Turkish) ## +############################################################ ## -## Add-in and Automation functions Eklenti ve Otomasyon fonksiyonları +## Küp işlevleri (Cube Functions) ## -GETPIVOTDATA = ÖZETVERİAL ## Bir Özet Tablo raporunda saklanan verileri verir. - +CUBEKPIMEMBER = KÜPKPIÜYESİ +CUBEMEMBER = KÜPÜYESİ +CUBEMEMBERPROPERTY = KÜPÜYEÖZELLİĞİ +CUBERANKEDMEMBER = DERECELİKÜPÜYESİ +CUBESET = KÜPKÜMESİ +CUBESETCOUNT = KÜPKÜMESAYISI +CUBEVALUE = KÜPDEĞERİ ## -## Cube functions Küp işlevleri +## Veritabanı işlevleri (Database Functions) ## -CUBEKPIMEMBER = KÜPKPIÜYE ## Kilit performans göstergesi (KPI-Key Performance Indicator) adını, özelliğini ve ölçüsünü verir ve hücredeki ad ve özelliği gösterir. KPI, bir kurumun performansını izlemek için kullanılan aylık brüt kâr ya da üç aylık çalışan giriş çıkışları gibi ölçülebilen bir birimdir. -CUBEMEMBER = KÜPÜYE ## Bir küp hiyerarşisinde bir üyeyi veya kaydı verir. Üye veya kaydın küpte varolduğunu doğrulamak için kullanılır. -CUBEMEMBERPROPERTY = KÜPÜYEÖZELLİĞİ ## Bir küpte bir üyenin özelliğinin değerini verir. Küp içinde üye adının varlığını doğrulamak ve bu üyenin belli özelliklerini getirmek için kullanılır. -CUBERANKEDMEMBER = KÜPÜYESIRASI ## Bir küme içindeki üyenin derecesini veya kaçıncı olduğunu verir. En iyi satış elemanı, veya en iyi on öğrenci gibi bir kümedeki bir veya daha fazla öğeyi getirmek için kullanılır. -CUBESET = KÜPKÜME ## Kümeyi oluşturan ve ardından bu kümeyi Microsoft Office Excel'e getiren sunucudaki küpe küme ifadelerini göndererek hesaplanan üye veya kayıt kümesini tanımlar. -CUBESETCOUNT = KÜPKÜMESAY ## Bir kümedeki öğelerin sayısını getirir. -CUBEVALUE = KÜPDEĞER ## Bir küpten toplam değeri getirir. - +DAVERAGE = VSEÇORT +DCOUNT = VSEÇSAY +DCOUNTA = VSEÇSAYDOLU +DGET = VAL +DMAX = VSEÇMAK +DMIN = VSEÇMİN +DPRODUCT = VSEÇÇARP +DSTDEV = VSEÇSTDSAPMA +DSTDEVP = VSEÇSTDSAPMAS +DSUM = VSEÇTOPLA +DVAR = VSEÇVAR +DVARP = VSEÇVARS ## -## Database functions Veritabanı işlevleri +## Tarih ve saat işlevleri (Date & Time Functions) ## -DAVERAGE = VSEÇORT ## Seçili veritabanı girdilerinin ortalamasını verir. -DCOUNT = VSEÇSAY ## Veritabanında sayı içeren hücre sayısını hesaplar. -DCOUNTA = VSEÇSAYDOLU ## Veritabanındaki boş olmayan hücreleri sayar. -DGET = VAL ## Veritabanından, belirtilen ölçütlerle eşleşen tek bir rapor çıkarır. -DMAX = VSEÇMAK ## Seçili veritabanı girişlerinin en yüksek değerini verir. -DMIN = VSEÇMİN ## Seçili veritabanı girişlerinin en düşük değerini verir. -DPRODUCT = VSEÇÇARP ## Kayıtların belli bir alanında bulunan, bir veritabanındaki ölçütlerle eşleşen değerleri çarpar. -DSTDEV = VSEÇSTDSAPMA ## Seçili veritabanı girişlerinden oluşan bir örneğe dayanarak, standart sapmayı tahmin eder. -DSTDEVP = VSEÇSTDSAPMAS ## Standart sapmayı, seçili veritabanı girişlerinin tüm popülasyonunu esas alarak hesaplar. -DSUM = VSEÇTOPLA ## Kayıtların alan sütununda bulunan, ölçütle eşleşen sayıları toplar. -DVAR = VSEÇVAR ## Seçili veritabanı girişlerinden oluşan bir örneği esas alarak farkı tahmin eder. -DVARP = VSEÇVARS ## Seçili veritabanı girişlerinin tüm popülasyonunu esas alarak farkı hesaplar. - +DATE = TARİH +DATEDIF = ETARİHLİ +DATESTRING = TARİHDİZİ +DATEVALUE = TARİHSAYISI +DAY = GÜN +DAYS = GÜNSAY +DAYS360 = GÜN360 +EDATE = SERİTARİH +EOMONTH = SERİAY +HOUR = SAAT +ISOWEEKNUM = ISOHAFTASAY +MINUTE = DAKİKA +MONTH = AY +NETWORKDAYS = TAMİŞGÜNÜ +NETWORKDAYS.INTL = TAMİŞGÜNÜ.ULUSL +NOW = ŞİMDİ +SECOND = SANİYE +THAIDAYOFWEEK = TAYHAFTANINGÜNÜ +THAIMONTHOFYEAR = TAYYILINAYI +THAIYEAR = TAYYILI +TIME = ZAMAN +TIMEVALUE = ZAMANSAYISI +TODAY = BUGÜN +WEEKDAY = HAFTANINGÜNÜ +WEEKNUM = HAFTASAY +WORKDAY = İŞGÜNÜ +WORKDAY.INTL = İŞGÜNÜ.ULUSL +YEAR = YIL +YEARFRAC = YILORAN ## -## Date and time functions Tarih ve saat işlevleri +## Mühendislik işlevleri (Engineering Functions) ## -DATE = TARİH ## Belirli bir tarihin seri numarasını verir. -DATEVALUE = TARİHSAYISI ## Metin biçimindeki bir tarihi seri numarasına dönüştürür. -DAY = GÜN ## Seri numarasını, ayın bir gününe dönüştürür. -DAYS360 = GÜN360 ## İki tarih arasındaki gün sayısını, 360 günlük yılı esas alarak hesaplar. -EDATE = SERİTARİH ## Başlangıç tarihinden itibaren, belirtilen ay sayısından önce veya sonraki tarihin seri numarasını verir. -EOMONTH = SERİAY ## Belirtilen sayıda ay önce veya sonraki ayın son gününün seri numarasını verir. -HOUR = SAAT ## Bir seri numarasını saate dönüştürür. -MINUTE = DAKİKA ## Bir seri numarasını dakikaya dönüştürür. -MONTH = AY ## Bir seri numarasını aya dönüştürür. -NETWORKDAYS = TAMİŞGÜNÜ ## İki tarih arasındaki tam çalışma günlerinin sayısını verir. -NOW = ŞİMDİ ## Geçerli tarihin ve saatin seri numarasını verir. -SECOND = SANİYE ## Bir seri numarasını saniyeye dönüştürür. -TIME = ZAMAN ## Belirli bir zamanın seri numarasını verir. -TIMEVALUE = ZAMANSAYISI ## Metin biçimindeki zamanı seri numarasına dönüştürür. -TODAY = BUGÜN ## Bugünün tarihini seri numarasına dönüştürür. -WEEKDAY = HAFTANINGÜNÜ ## Bir seri numarasını, haftanın gününe dönüştürür. -WEEKNUM = HAFTASAY ## Dizisel değerini, haftanın yıl içinde bulunduğu konumu sayısal olarak gösteren sayıya dönüştürür. -WORKDAY = İŞGÜNÜ ## Belirtilen sayıda çalışma günü öncesinin ya da sonrasının tarihinin seri numarasını verir. -YEAR = YIL ## Bir seri numarasını yıla dönüştürür. -YEARFRAC = YILORAN ## Başlangıç_tarihi ve bitiş_tarihi arasındaki tam günleri gösteren yıl kesrini verir. - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BIN2DEC +BIN2HEX = BIN2HEX +BIN2OCT = BIN2OCT +BITAND = BİTVE +BITLSHIFT = BİTSOLAKAYDIR +BITOR = BİTVEYA +BITRSHIFT = BİTSAĞAKAYDIR +BITXOR = BİTÖZELVEYA +COMPLEX = KARMAŞIK +CONVERT = ÇEVİR +DEC2BIN = DEC2BIN +DEC2HEX = DEC2HEX +DEC2OCT = DEC2OCT +DELTA = DELTA +ERF = HATAİŞLEV +ERF.PRECISE = HATAİŞLEV.DUYARLI +ERFC = TÜMHATAİŞLEV +ERFC.PRECISE = TÜMHATAİŞLEV.DUYARLI +GESTEP = BESINIR +HEX2BIN = HEX2BIN +HEX2DEC = HEX2DEC +HEX2OCT = HEX2OCT +IMABS = SANMUTLAK +IMAGINARY = SANAL +IMARGUMENT = SANBAĞ_DEĞİŞKEN +IMCONJUGATE = SANEŞLENEK +IMCOS = SANCOS +IMCOSH = SANCOSH +IMCOT = SANCOT +IMCSC = SANCSC +IMCSCH = SANCSCH +IMDIV = SANBÖL +IMEXP = SANÜS +IMLN = SANLN +IMLOG10 = SANLOG10 +IMLOG2 = SANLOG2 +IMPOWER = SANKUVVET +IMPRODUCT = SANÇARP +IMREAL = SANGERÇEK +IMSEC = SANSEC +IMSECH = SANSECH +IMSIN = SANSIN +IMSINH = SANSINH +IMSQRT = SANKAREKÖK +IMSUB = SANTOPLA +IMSUM = SANÇIKAR +IMTAN = SANTAN +OCT2BIN = OCT2BIN +OCT2DEC = OCT2DEC +OCT2HEX = OCT2HEX ## -## Engineering functions Mühendislik işlevleri +## Finansal işlevler (Financial Functions) ## -BESSELI = BESSELI ## Değiştirilmiş Bessel fonksiyonu In(x)'i verir. -BESSELJ = BESSELJ ## Bessel fonksiyonu Jn(x)'i verir. -BESSELK = BESSELK ## Değiştirilmiş Bessel fonksiyonu Kn(x)'i verir. -BESSELY = BESSELY ## Bessel fonksiyonu Yn(x)'i verir. -BIN2DEC = BIN2DEC ## İkili bir sayıyı, ondalık sayıya dönüştürür. -BIN2HEX = BIN2HEX ## İkili bir sayıyı, onaltılıya dönüştürür. -BIN2OCT = BIN2OCT ## İkili bir sayıyı, sekizliye dönüştürür. -COMPLEX = KARMAŞIK ## Gerçek ve sanal katsayıları, karmaşık sayıya dönüştürür. -CONVERT = ÇEVİR ## Bir sayıyı, bir ölçüm sisteminden bir başka ölçüm sistemine dönüştürür. -DEC2BIN = DEC2BIN ## Ondalık bir sayıyı, ikiliye dönüştürür. -DEC2HEX = DEC2HEX ## Ondalık bir sayıyı, onaltılıya dönüştürür. -DEC2OCT = DEC2OCT ## Ondalık bir sayıyı sekizliğe dönüştürür. -DELTA = DELTA ## İki değerin eşit olup olmadığını sınar. -ERF = HATAİŞLEV ## Hata işlevini verir. -ERFC = TÜMHATAİŞLEV ## Tümleyici hata işlevini verir. -GESTEP = BESINIR ## Bir sayının eşik değerinden büyük olup olmadığını sınar. -HEX2BIN = HEX2BIN ## Onaltılı bir sayıyı ikiliye dönüştürür. -HEX2DEC = HEX2DEC ## Onaltılı bir sayıyı ondalığa dönüştürür. -HEX2OCT = HEX2OCT ## Onaltılı bir sayıyı sekizliğe dönüştürür. -IMABS = SANMUTLAK ## Karmaşık bir sayının mutlak değerini (modül) verir. -IMAGINARY = SANAL ## Karmaşık bir sayının sanal katsayısını verir. -IMARGUMENT = SANBAĞ_DEĞİŞKEN ## Radyanlarla belirtilen bir açı olan teta bağımsız değişkenini verir. -IMCONJUGATE = SANEŞLENEK ## Karmaşık bir sayının karmaşık eşleniğini verir. -IMCOS = SANCOS ## Karmaşık bir sayının kosinüsünü verir. -IMDIV = SANBÖL ## İki karmaşık sayının bölümünü verir. -IMEXP = SANÜS ## Karmaşık bir sayının üssünü verir. -IMLN = SANLN ## Karmaşık bir sayının doğal logaritmasını verir. -IMLOG10 = SANLOG10 ## Karmaşık bir sayının, 10 tabanında logaritmasını verir. -IMLOG2 = SANLOG2 ## Karmaşık bir sayının 2 tabanında logaritmasını verir. -IMPOWER = SANÜSSÜ ## Karmaşık bir sayıyı, bir tamsayı üssüne yükseltilmiş olarak verir. -IMPRODUCT = SANÇARP ## Karmaşık sayıların çarpımını verir. -IMREAL = SANGERÇEK ## Karmaşık bir sayının, gerçek katsayısını verir. -IMSIN = SANSIN ## Karmaşık bir sayının sinüsünü verir. -IMSQRT = SANKAREKÖK ## Karmaşık bir sayının karekökünü verir. -IMSUB = SANÇIKAR ## İki karmaşık sayının farkını verir. -IMSUM = SANTOPLA ## Karmaşık sayıların toplamını verir. -OCT2BIN = OCT2BIN ## Sekizli bir sayıyı ikiliye dönüştürür. -OCT2DEC = OCT2DEC ## Sekizli bir sayıyı ondalığa dönüştürür. -OCT2HEX = OCT2HEX ## Sekizli bir sayıyı onaltılıya dönüştürür. - +ACCRINT = GERÇEKFAİZ +ACCRINTM = GERÇEKFAİZV +AMORDEGRC = AMORDEGRC +AMORLINC = AMORLINC +COUPDAYBS = KUPONGÜNBD +COUPDAYS = KUPONGÜN +COUPDAYSNC = KUPONGÜNDSK +COUPNCD = KUPONGÜNSKT +COUPNUM = KUPONSAYI +COUPPCD = KUPONGÜNÖKT +CUMIPMT = TOPÖDENENFAİZ +CUMPRINC = TOPANAPARA +DB = AZALANBAKİYE +DDB = ÇİFTAZALANBAKİYE +DISC = İNDİRİM +DOLLARDE = LİRAON +DOLLARFR = LİRAKES +DURATION = SÜRE +EFFECT = ETKİN +FV = GD +FVSCHEDULE = GDPROGRAM +INTRATE = FAİZORANI +IPMT = FAİZTUTARI +IRR = İÇ_VERİM_ORANI +ISPMT = ISPMT +MDURATION = MSÜRE +MIRR = D_İÇ_VERİM_ORANI +NOMINAL = NOMİNAL +NPER = TAKSİT_SAYISI +NPV = NBD +ODDFPRICE = TEKYDEĞER +ODDFYIELD = TEKYÖDEME +ODDLPRICE = TEKSDEĞER +ODDLYIELD = TEKSÖDEME +PDURATION = PSÜRE +PMT = DEVRESEL_ÖDEME +PPMT = ANA_PARA_ÖDEMESİ +PRICE = DEĞER +PRICEDISC = DEĞERİND +PRICEMAT = DEĞERVADE +PV = BD +RATE = FAİZ_ORANI +RECEIVED = GETİRİ +RRI = GERÇEKLEŞENYATIRIMGETİRİSİ +SLN = DA +SYD = YAT +TBILLEQ = HTAHEŞ +TBILLPRICE = HTAHDEĞER +TBILLYIELD = HTAHÖDEME +VDB = DAB +XIRR = AİÇVERİMORANI +XNPV = ANBD +YIELD = ÖDEME +YIELDDISC = ÖDEMEİND +YIELDMAT = ÖDEMEVADE ## -## Financial functions Finansal fonksiyonlar +## Bilgi işlevleri (Information Functions) ## -ACCRINT = GERÇEKFAİZ ## Dönemsel faiz ödeyen hisse senedine ilişkin tahakkuk eden faizi getirir. -ACCRINTM = GERÇEKFAİZV ## Vadesinde ödeme yapan bir tahvilin tahakkuk etmiş faizini verir. -AMORDEGRC = AMORDEGRC ## Yıpranma katsayısı kullanarak her hesap döneminin değer kaybını verir. -AMORLINC = AMORLINC ## Her hesap dönemi içindeki yıpranmayı verir. -COUPDAYBS = KUPONGÜNBD ## Kupon süresinin başlangıcından alış tarihine kadar olan süredeki gün sayısını verir. -COUPDAYS = KUPONGÜN ## Kupon süresindeki, gün sayısını, alış tarihini de içermek üzere, verir. -COUPDAYSNC = KUPONGÜNDSK ## Alış tarihinden bir sonraki kupon tarihine kadar olan gün sayısını verir. -COUPNCD = KUPONGÜNSKT ## Alış tarihinden bir sonraki kupon tarihini verir. -COUPNUM = KUPONSAYI ## Alış tarihiyle vade tarihi arasında ödenecek kuponların sayısını verir. -COUPPCD = KUPONGÜNÖKT ## Alış tarihinden bir önceki kupon tarihini verir. -CUMIPMT = AİÇVERİMORANI ## İki dönem arasında ödenen kümülatif faizi verir. -CUMPRINC = ANA_PARA_ÖDEMESİ ## İki dönem arasında bir borç üzerine ödenen birikimli temeli verir. -DB = AZALANBAKİYE ## Bir malın belirtilen bir süre içindeki yıpranmasını, sabit azalan bakiye yöntemini kullanarak verir. -DDB = ÇİFTAZALANBAKİYE ## Bir malın belirtilen bir süre içindeki yıpranmasını, çift azalan bakiye yöntemi ya da sizin belirttiğiniz başka bir yöntemi kullanarak verir. -DISC = İNDİRİM ## Bir tahvilin indirim oranını verir. -DOLLARDE = LİRAON ## Kesir olarak tanımlanmış lira fiyatını, ondalık sayı olarak tanımlanmış lira fiyatına dönüştürür. -DOLLARFR = LİRAKES ## Ondalık sayı olarak tanımlanmış lira fiyatını, kesir olarak tanımlanmış lira fiyatına dönüştürür. -DURATION = SÜRE ## Belli aralıklarla faiz ödemesi yapan bir tahvilin yıllık süresini verir. -EFFECT = ETKİN ## Efektif yıllık faiz oranını verir. -FV = ANBD ## Bir yatırımın gelecekteki değerini verir. -FVSCHEDULE = GDPROGRAM ## Bir seri birleşik faiz oranı uyguladıktan sonra, bir başlangıçtaki anaparanın gelecekteki değerini verir. -INTRATE = FAİZORANI ## Tam olarak yatırım yapılmış bir tahvilin faiz oranını verir. -IPMT = FAİZTUTARI ## Bir yatırımın verilen bir süre için faiz ödemesini verir. -IRR = İÇ_VERİM_ORANI ## Bir para akışı serisi için, iç verim oranını verir. -ISPMT = ISPMT ## Yatırımın belirli bir dönemi boyunca ödenen faizi hesaplar. -MDURATION = MSÜRE ## Varsayılan par değeri 10.000.000 lira olan bir tahvil için Macauley değiştirilmiş süreyi verir. -MIRR = D_İÇ_VERİM_ORANI ## Pozitif ve negatif para akışlarının farklı oranlarda finanse edildiği durumlarda, iç verim oranını verir. -NOMINAL = NOMİNAL ## Yıllık nominal faiz oranını verir. -NPER = DÖNEM_SAYISI ## Bir yatırımın dönem sayısını verir. -NPV = NBD ## Bir yatırımın bugünkü net değerini, bir dönemsel para akışları serisine ve bir indirim oranına bağlı olarak verir. -ODDFPRICE = TEKYDEĞER ## Tek bir ilk dönemi olan bir tahvilin değerini, her 100.000.000 lirada bir verir. -ODDFYIELD = TEKYÖDEME ## Tek bir ilk dönemi olan bir tahvilin ödemesini verir. -ODDLPRICE = TEKSDEĞER ## Tek bir son dönemi olan bir tahvilin fiyatını her 10.000.000 lirada bir verir. -ODDLYIELD = TEKSÖDEME ## Tek bir son dönemi olan bir tahvilin ödemesini verir. -PMT = DEVRESEL_ÖDEME ## Bir yıllık dönemsel ödemeyi verir. -PPMT = ANA_PARA_ÖDEMESİ ## Verilen bir süre için, bir yatırımın anaparasına dayanan ödemeyi verir. -PRICE = DEĞER ## Dönemsel faiz ödeyen bir tahvilin fiyatını 10.000.00 liralık değer başına verir. -PRICEDISC = DEĞERİND ## İndirimli bir tahvilin fiyatını 10.000.000 liralık nominal değer başına verir. -PRICEMAT = DEĞERVADE ## Faizini vade sonunda ödeyen bir tahvilin fiyatını 10.000.000 nominal değer başına verir. -PV = BD ## Bir yatırımın bugünkü değerini verir. -RATE = FAİZ_ORANI ## Bir yıllık dönem başına düşen faiz oranını verir. -RECEIVED = GETİRİ ## Tam olarak yatırılmış bir tahvilin vadesinin bitiminde alınan miktarı verir. -SLN = DA ## Bir malın bir dönem içindeki doğrusal yıpranmasını verir. -SYD = YAT ## Bir malın belirli bir dönem için olan amortismanını verir. -TBILLEQ = HTAHEŞ ## Bir Hazine bonosunun bono eşdeğeri ödemesini verir. -TBILLPRICE = HTAHDEĞER ## Bir Hazine bonosunun değerini, 10.000.000 liralık nominal değer başına verir. -TBILLYIELD = HTAHÖDEME ## Bir Hazine bonosunun ödemesini verir. -VDB = DAB ## Bir malın amortismanını, belirlenmiş ya da kısmi bir dönem için, bir azalan bakiye yöntemi kullanarak verir. -XIRR = AİÇVERİMORANI ## Dönemsel olması gerekmeyen bir para akışları programı için, iç verim oranını verir. -XNPV = ANBD ## Dönemsel olması gerekmeyen bir para akışları programı için, bugünkü net değeri verir. -YIELD = ÖDEME ## Belirli aralıklarla faiz ödeyen bir tahvilin ödemesini verir. -YIELDDISC = ÖDEMEİND ## İndirimli bir tahvilin yıllık ödemesini verir; örneğin, bir Hazine bonosunun. -YIELDMAT = ÖDEMEVADE ## Vadesinin bitiminde faiz ödeyen bir tahvilin yıllık ödemesini verir. - +CELL = HÜCRE +ERROR.TYPE = HATA.TİPİ +INFO = BİLGİ +ISBLANK = EBOŞSA +ISERR = EHATA +ISERROR = EHATALIYSA +ISEVEN = ÇİFTMİ +ISFORMULA = EFORMÜLSE +ISLOGICAL = EMANTIKSALSA +ISNA = EYOKSA +ISNONTEXT = EMETİNDEĞİLSE +ISNUMBER = ESAYIYSA +ISODD = TEKMİ +ISREF = EREFSE +ISTEXT = EMETİNSE +N = S +NA = YOKSAY +SHEET = SAYFA +SHEETS = SAYFALAR +TYPE = TÜR ## -## Information functions Bilgi fonksiyonları +## Mantıksal işlevler (Logical Functions) ## -CELL = HÜCRE ## Bir hücrenin biçimlendirmesi, konumu ya da içeriği hakkında bilgi verir. -ERROR.TYPE = HATA.TİPİ ## Bir hata türüne ilişkin sayıları verir. -INFO = BİLGİ ## Geçerli işletim ortamı hakkında bilgi verir. -ISBLANK = EBOŞSA ## Değer boşsa, DOĞRU verir. -ISERR = EHATA ## Değer, #YOK dışındaki bir hata değeriyse, DOĞRU verir. -ISERROR = EHATALIYSA ## Değer, herhangi bir hata değeriyse, DOĞRU verir. -ISEVEN = ÇİFTTİR ## Sayı çiftse, DOĞRU verir. -ISLOGICAL = EMANTIKSALSA ## Değer, mantıksal bir değerse, DOĞRU verir. -ISNA = EYOKSA ## Değer, #YOK hata değeriyse, DOĞRU verir. -ISNONTEXT = EMETİNDEĞİLSE ## Değer, metin değilse, DOĞRU verir. -ISNUMBER = ESAYIYSA ## Değer, bir sayıysa, DOĞRU verir. -ISODD = TEKTİR ## Sayı tekse, DOĞRU verir. -ISREF = EREFSE ## Değer bir başvuruysa, DOĞRU verir. -ISTEXT = EMETİNSE ## Değer bir metinse DOĞRU verir. -N = N ## Sayıya dönüştürülmüş bir değer verir. -NA = YOKSAY ## #YOK hata değerini verir. -TYPE = TİP ## Bir değerin veri türünü belirten bir sayı verir. - +AND = VE +FALSE = YANLIŞ +IF = EĞER +IFERROR = EĞERHATA +IFNA = EĞERYOKSA +IFS = ÇOKEĞER +NOT = DEĞİL +OR = YADA +SWITCH = İLKEŞLEŞEN +TRUE = DOĞRU +XOR = ÖZELVEYA ## -## Logical functions Mantıksal fonksiyonlar +## Arama ve başvuru işlevleri (Lookup & Reference Functions) ## -AND = VE ## Bütün bağımsız değişkenleri DOĞRU ise, DOĞRU verir. -FALSE = YANLIŞ ## YANLIŞ mantıksal değerini verir. -IF = EĞER ## Gerçekleştirilecek bir mantıksal sınama belirtir. -IFERROR = EĞERHATA ## Formül hatalıysa belirttiğiniz değeri verir; bunun dışındaki durumlarda formülün sonucunu verir. -NOT = DEĞİL ## Bağımsız değişkeninin mantığını tersine çevirir. -OR = YADA ## Bağımsız değişkenlerden herhangi birisi DOĞRU ise, DOĞRU verir. -TRUE = DOĞRU ## DOĞRU mantıksal değerini verir. - +ADDRESS = ADRES +AREAS = ALANSAY +CHOOSE = ELEMAN +COLUMN = SÜTUN +COLUMNS = SÜTUNSAY +FORMULATEXT = FORMÜLMETNİ +GETPIVOTDATA = ÖZETVERİAL +HLOOKUP = YATAYARA +HYPERLINK = KÖPRÜ +INDEX = İNDİS +INDIRECT = DOLAYLI +LOOKUP = ARA +MATCH = KAÇINCI +OFFSET = KAYDIR +ROW = SATIR +ROWS = SATIRSAY +RTD = GZV +TRANSPOSE = DEVRİK_DÖNÜŞÜM +VLOOKUP = DÜŞEYARA ## -## Lookup and reference functions Arama ve Başvuru fonksiyonları +## Matematik ve trigonometri işlevleri (Math & Trig Functions) ## -ADDRESS = ADRES ## Bir başvuruyu, çalışma sayfasındaki tek bir hücreye metin olarak verir. -AREAS = ALANSAY ## Renvoie le nombre de zones dans une référence. -CHOOSE = ELEMAN ## Değerler listesinden bir değer seçer. -COLUMN = SÜTUN ## Bir başvurunun sütun sayısını verir. -COLUMNS = SÜTUNSAY ## Bir başvurudaki sütunların sayısını verir. -HLOOKUP = YATAYARA ## Bir dizinin en üst satırına bakar ve belirtilen hücrenin değerini verir. -HYPERLINK = KÖPRÜ ## Bir ağ sunucusunda, bir intranette ya da Internet'te depolanan bir belgeyi açan bir kısayol ya da atlama oluşturur. -INDEX = İNDİS ## Başvurudan veya diziden bir değer seçmek için, bir dizin kullanır. -INDIRECT = DOLAYLI ## Metin değeriyle belirtilen bir başvuru verir. -LOOKUP = ARA ## Bir vektördeki veya dizideki değerleri arar. -MATCH = KAÇINCI ## Bir başvurudaki veya dizideki değerleri arar. -OFFSET = KAYDIR ## Verilen bir başvurudan, bir başvuru kaydırmayı verir. -ROW = SATIR ## Bir başvurunun satır sayısını verir. -ROWS = SATIRSAY ## Bir başvurudaki satırların sayısını verir. -RTD = RTD ## COM otomasyonunu destekleyen programdan gerçek zaman verileri alır. -TRANSPOSE = DEVRİK_DÖNÜŞÜM ## Bir dizinin devrik dönüşümünü verir. -VLOOKUP = DÜŞEYARA ## Bir dizinin ilk sütununa bakar ve bir hücrenin değerini vermek için satır boyunca hareket eder. - +ABS = MUTLAK +ACOS = ACOS +ACOSH = ACOSH +ACOT = ACOT +ACOTH = ACOTH +AGGREGATE = TOPLAMA +ARABIC = ARAP +ASIN = ASİN +ASINH = ASİNH +ATAN = ATAN +ATAN2 = ATAN2 +ATANH = ATANH +BASE = TABAN +CEILING.MATH = TAVANAYUVARLA.MATEMATİK +CEILING.PRECISE = TAVANAYUVARLA.DUYARLI +COMBIN = KOMBİNASYON +COMBINA = KOMBİNASYONA +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = ONDALIK +DEGREES = DERECE +ECMA.CEILING = ECMA.TAVAN +EVEN = ÇİFT +EXP = ÜS +FACT = ÇARPINIM +FACTDOUBLE = ÇİFTFAKTÖR +FLOOR.MATH = TABANAYUVARLA.MATEMATİK +FLOOR.PRECISE = TABANAYUVARLA.DUYARLI +GCD = OBEB +INT = TAMSAYI +ISO.CEILING = ISO.TAVAN +LCM = OKEK +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = DETERMİNANT +MINVERSE = DİZEY_TERS +MMULT = DÇARP +MOD = MOD +MROUND = KYUVARLA +MULTINOMIAL = ÇOKTERİMLİ +MUNIT = BİRİMMATRİS +ODD = TEK +PI = Pİ +POWER = KUVVET +PRODUCT = ÇARPIM +QUOTIENT = BÖLÜM +RADIANS = RADYAN +RAND = S_SAYI_ÜRET +RANDBETWEEN = RASTGELEARADA +ROMAN = ROMEN +ROUND = YUVARLA +ROUNDBAHTDOWN = BAHTAŞAĞIYUVARLA +ROUNDBAHTUP = BAHTYUKARIYUVARLA +ROUNDDOWN = AŞAĞIYUVARLA +ROUNDUP = YUKARIYUVARLA +SEC = SEC +SECH = SECH +SERIESSUM = SERİTOPLA +SIGN = İŞARET +SIN = SİN +SINH = SİNH +SQRT = KAREKÖK +SQRTPI = KAREKÖKPİ +SUBTOTAL = ALTTOPLAM +SUM = TOPLA +SUMIF = ETOPLA +SUMIFS = ÇOKETOPLA +SUMPRODUCT = TOPLA.ÇARPIM +SUMSQ = TOPKARE +SUMX2MY2 = TOPX2EY2 +SUMX2PY2 = TOPX2AY2 +SUMXMY2 = TOPXEY2 +TAN = TAN +TANH = TANH +TRUNC = NSAT ## -## Math and trigonometry functions Matematik ve trigonometri fonksiyonları +## İstatistik işlevleri (Statistical Functions) ## -ABS = MUTLAK ## Bir sayının mutlak değerini verir. -ACOS = ACOS ## Bir sayının ark kosinüsünü verir. -ACOSH = ACOSH ## Bir sayının ters hiperbolik kosinüsünü verir. -ASIN = ASİN ## Bir sayının ark sinüsünü verir. -ASINH = ASİNH ## Bir sayının ters hiperbolik sinüsünü verir. -ATAN = ATAN ## Bir sayının ark tanjantını verir. -ATAN2 = ATAN2 ## Ark tanjantı, x- ve y- koordinatlarından verir. -ATANH = ATANH ## Bir sayının ters hiperbolik tanjantını verir. -CEILING = TAVANAYUVARLA ## Bir sayıyı, en yakın tamsayıya ya da en yakın katına yuvarlar. -COMBIN = KOMBİNASYON ## Verilen sayıda öğenin kombinasyon sayısını verir. -COS = COS ## Bir sayının kosinüsünü verir. -COSH = COSH ## Bir sayının hiperbolik kosinüsünü verir. -DEGREES = DERECE ## Radyanları dereceye dönüştürür. -EVEN = ÇİFT ## Bir sayıyı, en yakın daha büyük çift tamsayıya yuvarlar. -EXP = ÜS ## e'yi, verilen bir sayının üssüne yükseltilmiş olarak verir. -FACT = ÇARPINIM ## Bir sayının faktörünü verir. -FACTDOUBLE = ÇİFTFAKTÖR ## Bir sayının çift çarpınımını verir. -FLOOR = TABANAYUVARLA ## Bir sayıyı, daha küçük sayıya, sıfıra yakınsayarak yuvarlar. -GCD = OBEB ## En büyük ortak böleni verir. -INT = TAMSAYI ## Bir sayıyı aşağıya doğru en yakın tamsayıya yuvarlar. -LCM = OKEK ## En küçük ortak katı verir. -LN = LN ## Bir sayının doğal logaritmasını verir. -LOG = LOG ## Bir sayının, belirtilen bir tabandaki logaritmasını verir. -LOG10 = LOG10 ## Bir sayının 10 tabanında logaritmasını verir. -MDETERM = DETERMİNANT ## Bir dizinin dizey determinantını verir. -MINVERSE = DİZEY_TERS ## Bir dizinin dizey tersini verir. -MMULT = DÇARP ## İki dizinin dizey çarpımını verir. -MOD = MODÜLO ## Bölmeden kalanı verir. -MROUND = KYUVARLA ## İstenen kata yuvarlanmış bir sayı verir. -MULTINOMIAL = ÇOKTERİMLİ ## Bir sayılar kümesinin çok terimlisini verir. -ODD = TEK ## Bir sayıyı en yakın daha büyük tek sayıya yuvarlar. -PI = Pİ ## Pi değerini verir. -POWER = KUVVET ## Bir üsse yükseltilmiş sayının sonucunu verir. -PRODUCT = ÇARPIM ## Bağımsız değişkenlerini çarpar. -QUOTIENT = BÖLÜM ## Bir bölme işleminin tamsayı kısmını verir. -RADIANS = RADYAN ## Dereceleri radyanlara dönüştürür. -RAND = S_SAYI_ÜRET ## 0 ile 1 arasında rastgele bir sayı verir. -RANDBETWEEN = RASTGELEARALIK ## Belirttiğiniz sayılar arasında rastgele bir sayı verir. -ROMAN = ROMEN ## Bir normal rakamı, metin olarak, romen rakamına çevirir. -ROUND = YUVARLA ## Bir sayıyı, belirtilen basamak sayısına yuvarlar. -ROUNDDOWN = AŞAĞIYUVARLA ## Bir sayıyı, daha küçük sayıya, sıfıra yakınsayarak yuvarlar. -ROUNDUP = YUKARIYUVARLA ## Bir sayıyı daha büyük sayıya, sıfırdan ıraksayarak yuvarlar. -SERIESSUM = SERİTOPLA ## Bir üs serisinin toplamını, formüle bağlı olarak verir. -SIGN = İŞARET ## Bir sayının işaretini verir. -SIN = SİN ## Verilen bir açının sinüsünü verir. -SINH = SİNH ## Bir sayının hiperbolik sinüsünü verir. -SQRT = KAREKÖK ## Pozitif bir karekök verir. -SQRTPI = KAREKÖKPİ ## (* Pi sayısının) kare kökünü verir. -SUBTOTAL = ALTTOPLAM ## Bir listedeki ya da veritabanındaki bir alt toplamı verir. -SUM = TOPLA ## Bağımsız değişkenlerini toplar. -SUMIF = ETOPLA ## Verilen ölçütle belirlenen hücreleri toplar. -SUMIFS = SUMIFS ## Bir aralıktaki, birden fazla ölçüte uyan hücreleri ekler. -SUMPRODUCT = TOPLA.ÇARPIM ## İlişkili dizi bileşenlerinin çarpımlarının toplamını verir. -SUMSQ = TOPKARE ## Bağımsız değişkenlerin karelerinin toplamını verir. -SUMX2MY2 = TOPX2EY2 ## İki dizideki ilişkili değerlerin farkının toplamını verir. -SUMX2PY2 = TOPX2AY2 ## İki dizideki ilişkili değerlerin karelerinin toplamının toplamını verir. -SUMXMY2 = TOPXEY2 ## İki dizideki ilişkili değerlerin farklarının karelerinin toplamını verir. -TAN = TAN ## Bir sayının tanjantını verir. -TANH = TANH ## Bir sayının hiperbolik tanjantını verir. -TRUNC = NSAT ## Bir sayının, tamsayı durumuna gelecek şekilde, fazlalıklarını atar. - +AVEDEV = ORTSAP +AVERAGE = ORTALAMA +AVERAGEA = ORTALAMAA +AVERAGEIF = EĞERORTALAMA +AVERAGEIFS = ÇOKEĞERORTALAMA +BETA.DIST = BETA.DAĞ +BETA.INV = BETA.TERS +BINOM.DIST = BİNOM.DAĞ +BINOM.DIST.RANGE = BİNOM.DAĞ.ARALIK +BINOM.INV = BİNOM.TERS +CHISQ.DIST = KİKARE.DAĞ +CHISQ.DIST.RT = KİKARE.DAĞ.SAĞK +CHISQ.INV = KİKARE.TERS +CHISQ.INV.RT = KİKARE.TERS.SAĞK +CHISQ.TEST = KİKARE.TEST +CONFIDENCE.NORM = GÜVENİLİRLİK.NORM +CONFIDENCE.T = GÜVENİLİRLİK.T +CORREL = KORELASYON +COUNT = BAĞ_DEĞ_SAY +COUNTA = BAĞ_DEĞ_DOLU_SAY +COUNTBLANK = BOŞLUKSAY +COUNTIF = EĞERSAY +COUNTIFS = ÇOKEĞERSAY +COVARIANCE.P = KOVARYANS.P +COVARIANCE.S = KOVARYANS.S +DEVSQ = SAPKARE +EXPON.DIST = ÜSTEL.DAĞ +F.DIST = F.DAĞ +F.DIST.RT = F.DAĞ.SAĞK +F.INV = F.TERS +F.INV.RT = F.TERS.SAĞK +F.TEST = F.TEST +FISHER = FISHER +FISHERINV = FISHERTERS +FORECAST.ETS = TAHMİN.ETS +FORECAST.ETS.CONFINT = TAHMİN.ETS.GVNARAL +FORECAST.ETS.SEASONALITY = TAHMİN.ETS.MEVSİMSELLİK +FORECAST.ETS.STAT = TAHMİN.ETS.İSTAT +FORECAST.LINEAR = TAHMİN.DOĞRUSAL +FREQUENCY = SIKLIK +GAMMA = GAMA +GAMMA.DIST = GAMA.DAĞ +GAMMA.INV = GAMA.TERS +GAMMALN = GAMALN +GAMMALN.PRECISE = GAMALN.DUYARLI +GAUSS = GAUSS +GEOMEAN = GEOORT +GROWTH = BÜYÜME +HARMEAN = HARORT +HYPGEOM.DIST = HİPERGEOM.DAĞ +INTERCEPT = KESMENOKTASI +KURT = BASIKLIK +LARGE = BÜYÜK +LINEST = DOT +LOGEST = LOT +LOGNORM.DIST = LOGNORM.DAĞ +LOGNORM.INV = LOGNORM.TERS +MAX = MAK +MAXA = MAKA +MAXIFS = ÇOKEĞERMAK +MEDIAN = ORTANCA +MIN = MİN +MINA = MİNA +MINIFS = ÇOKEĞERMİN +MODE.MULT = ENÇOK_OLAN.ÇOK +MODE.SNGL = ENÇOK_OLAN.TEK +NEGBINOM.DIST = NEGBİNOM.DAĞ +NORM.DIST = NORM.DAĞ +NORM.INV = NORM.TERS +NORM.S.DIST = NORM.S.DAĞ +NORM.S.INV = NORM.S.TERS +PEARSON = PEARSON +PERCENTILE.EXC = YÜZDEBİRLİK.HRC +PERCENTILE.INC = YÜZDEBİRLİK.DHL +PERCENTRANK.EXC = YÜZDERANK.HRC +PERCENTRANK.INC = YÜZDERANK.DHL +PERMUT = PERMÜTASYON +PERMUTATIONA = PERMÜTASYONA +PHI = PHI +POISSON.DIST = POISSON.DAĞ +PROB = OLASILIK +QUARTILE.EXC = DÖRTTEBİRLİK.HRC +QUARTILE.INC = DÖRTTEBİRLİK.DHL +RANK.AVG = RANK.ORT +RANK.EQ = RANK.EŞİT +RSQ = RKARE +SKEW = ÇARPIKLIK +SKEW.P = ÇARPIKLIK.P +SLOPE = EĞİM +SMALL = KÜÇÜK +STANDARDIZE = STANDARTLAŞTIRMA +STDEV.P = STDSAPMA.P +STDEV.S = STDSAPMA.S +STDEVA = STDSAPMAA +STDEVPA = STDSAPMASA +STEYX = STHYX +T.DIST = T.DAĞ +T.DIST.2T = T.DAĞ.2K +T.DIST.RT = T.DAĞ.SAĞK +T.INV = T.TERS +T.INV.2T = T.TERS.2K +T.TEST = T.TEST +TREND = EĞİLİM +TRIMMEAN = KIRPORTALAMA +VAR.P = VAR.P +VAR.S = VAR.S +VARA = VARA +VARPA = VARSA +WEIBULL.DIST = WEIBULL.DAĞ +Z.TEST = Z.TEST ## -## Statistical functions İstatistiksel fonksiyonlar +## Metin işlevleri (Text Functions) ## -AVEDEV = ORTSAP ## Veri noktalarının ortalamalarından mutlak sapmalarının ortalamasını verir. -AVERAGE = ORTALAMA ## Bağımsız değişkenlerinin ortalamasını verir. -AVERAGEA = ORTALAMAA ## Bağımsız değişkenlerinin, sayılar, metin ve mantıksal değerleri içermek üzere ortalamasını verir. -AVERAGEIF = EĞERORTALAMA ## Verili ölçütü karşılayan bir aralıktaki bütün hücrelerin ortalamasını (aritmetik ortalama) hesaplar. -AVERAGEIFS = EĞERLERORTALAMA ## Birden çok ölçüte uyan tüm hücrelerin ortalamasını (aritmetik ortalama) hesaplar. -BETADIST = BETADAĞ ## Beta birikimli dağılım fonksiyonunu verir. -BETAINV = BETATERS ## Belirli bir beta dağılımı için birikimli dağılım fonksiyonunun tersini verir. -BINOMDIST = BİNOMDAĞ ## Tek terimli binom dağılımı olasılığını verir. -CHIDIST = KİKAREDAĞ ## Kikare dağılımın tek kuyruklu olasılığını verir. -CHIINV = KİKARETERS ## Kikare dağılımın kuyruklu olasılığının tersini verir. -CHITEST = KİKARETEST ## Bağımsızlık sınamalarını verir. -CONFIDENCE = GÜVENİRLİK ## Bir popülasyon ortalaması için güvenirlik aralığını verir. -CORREL = KORELASYON ## İki veri kümesi arasındaki bağlantı katsayısını verir. -COUNT = BAĞ_DEĞ_SAY ## Bağımsız değişkenler listesinde kaç tane sayı bulunduğunu sayar. -COUNTA = BAĞ_DEĞ_DOLU_SAY ## Bağımsız değişkenler listesinde kaç tane değer bulunduğunu sayar. -COUNTBLANK = BOŞLUKSAY ## Aralıktaki boş hücre sayısını hesaplar. -COUNTIF = EĞERSAY ## Verilen ölçütlere uyan bir aralık içindeki hücreleri sayar. -COUNTIFS = ÇOKEĞERSAY ## Birden çok ölçüte uyan bir aralık içindeki hücreleri sayar. -COVAR = KOVARYANS ## Eşleştirilmiş sapmaların ortalaması olan kovaryansı verir. -CRITBINOM = KRİTİKBİNOM ## Birikimli binom dağılımının bir ölçüt değerinden küçük veya ölçüt değerine eşit olduğu en küçük değeri verir. -DEVSQ = SAPKARE ## Sapmaların karelerinin toplamını verir. -EXPONDIST = ÜSTELDAĞ ## Üstel dağılımı verir. -FDIST = FDAĞ ## F olasılık dağılımını verir. -FINV = FTERS ## F olasılık dağılımının tersini verir. -FISHER = FISHER ## Fisher dönüşümünü verir. -FISHERINV = FISHERTERS ## Fisher dönüşümünün tersini verir. -FORECAST = TAHMİN ## Bir doğrusal eğilim boyunca bir değer verir. -FREQUENCY = SIKLIK ## Bir sıklık dağılımını, dikey bir dizi olarak verir. -FTEST = FTEST ## Bir F-test'in sonucunu verir. -GAMMADIST = GAMADAĞ ## Gama dağılımını verir. -GAMMAINV = GAMATERS ## Gama kümülatif dağılımının tersini verir. -GAMMALN = GAMALN ## Gama fonksiyonunun (?(x)) doğal logaritmasını verir. -GEOMEAN = GEOORT ## Geometrik ortayı verir. -GROWTH = BÜYÜME ## Üstel bir eğilim boyunca değerler verir. -HARMEAN = HARORT ## Harmonik ortayı verir. -HYPGEOMDIST = HİPERGEOMDAĞ ## Hipergeometrik dağılımı verir. -INTERCEPT = KESMENOKTASI ## Doğrusal çakıştırma çizgisinin kesişme noktasını verir. -KURT = BASIKLIK ## Bir veri kümesinin basıklığını verir. -LARGE = BÜYÜK ## Bir veri kümesinde k. en büyük değeri verir. -LINEST = DOT ## Doğrusal bir eğilimin parametrelerini verir. -LOGEST = LOT ## Üstel bir eğilimin parametrelerini verir. -LOGINV = LOGTERS ## Bir lognormal dağılımının tersini verir. -LOGNORMDIST = LOGNORMDAĞ ## Birikimli lognormal dağılımını verir. -MAX = MAK ## Bir bağımsız değişkenler listesindeki en büyük değeri verir. -MAXA = MAKA ## Bir bağımsız değişkenler listesindeki, sayılar, metin ve mantıksal değerleri içermek üzere, en büyük değeri verir. -MEDIAN = ORTANCA ## Belirtilen sayıların orta değerini verir. -MIN = MİN ## Bir bağımsız değişkenler listesindeki en küçük değeri verir. -MINA = MİNA ## Bir bağımsız değişkenler listesindeki, sayılar, metin ve mantıksal değerleri de içermek üzere, en küçük değeri verir. -MODE = ENÇOK_OLAN ## Bir veri kümesindeki en sık rastlanan değeri verir. -NEGBINOMDIST = NEGBİNOMDAĞ ## Negatif binom dağılımını verir. -NORMDIST = NORMDAĞ ## Normal birikimli dağılımı verir. -NORMINV = NORMTERS ## Normal kümülatif dağılımın tersini verir. -NORMSDIST = NORMSDAĞ ## Standart normal birikimli dağılımı verir. -NORMSINV = NORMSTERS ## Standart normal birikimli dağılımın tersini verir. -PEARSON = PEARSON ## Pearson çarpım moment korelasyon katsayısını verir. -PERCENTILE = YÜZDEBİRLİK ## Bir aralık içerisinde bulunan değerlerin k. frekans toplamını verir. -PERCENTRANK = YÜZDERANK ## Bir veri kümesindeki bir değerin yüzde mertebesini verir. -PERMUT = PERMÜTASYON ## Verilen sayıda nesne için permütasyon sayısını verir. -POISSON = POISSON ## Poisson dağılımını verir. -PROB = OLASILIK ## Bir aralıktaki değerlerin iki sınır arasında olması olasılığını verir. -QUARTILE = DÖRTTEBİRLİK ## Bir veri kümesinin dörtte birliğini verir. -RANK = RANK ## Bir sayılar listesinde bir sayının mertebesini verir. -RSQ = RKARE ## Pearson çarpım moment korelasyon katsayısının karesini verir. -SKEW = ÇARPIKLIK ## Bir dağılımın çarpıklığını verir. -SLOPE = EĞİM ## Doğrusal çakışma çizgisinin eğimini verir. -SMALL = KÜÇÜK ## Bir veri kümesinde k. en küçük değeri verir. -STANDARDIZE = STANDARTLAŞTIRMA ## Normalleştirilmiş bir değer verir. -STDEV = STDSAPMA ## Bir örneğe dayanarak standart sapmayı tahmin eder. -STDEVA = STDSAPMAA ## Standart sapmayı, sayılar, metin ve mantıksal değerleri içermek üzere, bir örneğe bağlı olarak tahmin eder. -STDEVP = STDSAPMAS ## Standart sapmayı, tüm popülasyona bağlı olarak hesaplar. -STDEVPA = STDSAPMASA ## Standart sapmayı, sayılar, metin ve mantıksal değerleri içermek üzere, tüm popülasyona bağlı olarak hesaplar. -STEYX = STHYX ## Regresyondaki her x için tahmini y değerinin standart hatasını verir. -TDIST = TDAĞ ## T-dağılımını verir. -TINV = TTERS ## T-dağılımının tersini verir. -TREND = EĞİLİM ## Doğrusal bir eğilim boyunca değerler verir. -TRIMMEAN = KIRPORTALAMA ## Bir veri kümesinin içinin ortalamasını verir. -TTEST = TTEST ## T-test'le ilişkilendirilmiş olasılığı verir. -VAR = VAR ## Varyansı, bir örneğe bağlı olarak tahmin eder. -VARA = VARA ## Varyansı, sayılar, metin ve mantıksal değerleri içermek üzere, bir örneğe bağlı olarak tahmin eder. -VARP = VARS ## Varyansı, tüm popülasyona dayanarak hesaplar. -VARPA = VARSA ## Varyansı, sayılar, metin ve mantıksal değerleri içermek üzere, tüm popülasyona bağlı olarak hesaplar. -WEIBULL = WEIBULL ## Weibull dağılımını hesaplar. -ZTEST = ZTEST ## Z-testinin tek kuyruklu olasılık değerini hesaplar. - +BAHTTEXT = BAHTMETİN +CHAR = DAMGA +CLEAN = TEMİZ +CODE = KOD +CONCAT = ARALIKBİRLEŞTİR +DOLLAR = LİRA +EXACT = ÖZDEŞ +FIND = BUL +FIXED = SAYIDÜZENLE +ISTHAIDIGIT = TAYRAKAMIYSA +LEFT = SOLDAN +LEN = UZUNLUK +LOWER = KÜÇÜKHARF +MID = PARÇAAL +NUMBERSTRING = SAYIDİZİ +NUMBERVALUE = SAYIDEĞERİ +PHONETIC = SES +PROPER = YAZIM.DÜZENİ +REPLACE = DEĞİŞTİR +REPT = YİNELE +RIGHT = SAĞDAN +SEARCH = MBUL +SUBSTITUTE = YERİNEKOY +T = M +TEXT = METNEÇEVİR +TEXTJOIN = METİNBİRLEŞTİR +THAIDIGIT = TAYRAKAM +THAINUMSOUND = TAYSAYISES +THAINUMSTRING = TAYSAYIDİZE +THAISTRINGLENGTH = TAYDİZEUZUNLUĞU +TRIM = KIRP +UNICHAR = UNICODEKARAKTERİ +UNICODE = UNICODE +UPPER = BÜYÜKHARF +VALUE = SAYIYAÇEVİR ## -## Text functions Metin fonksiyonları +## Metin işlevleri (Web Functions) ## -ASC = ASC ## Bir karakter dizesindeki çift enli (iki bayt) İngilizce harfleri veya katakanayı yarım enli (tek bayt) karakterlerle değiştirir. -BAHTTEXT = BAHTTEXT ## Sayıyı, ß (baht) para birimi biçimini kullanarak metne dönüştürür. -CHAR = DAMGA ## Kod sayısıyla belirtilen karakteri verir. -CLEAN = TEMİZ ## Metindeki bütün yazdırılamaz karakterleri kaldırır. -CODE = KOD ## Bir metin dizesindeki ilk karakter için sayısal bir kod verir. -CONCATENATE = BİRLEŞTİR ## Pek çok metin öğesini bir metin öğesi olarak birleştirir. -DOLLAR = LİRA ## Bir sayıyı YTL (yeni Türk lirası) para birimi biçimini kullanarak metne dönüştürür. -EXACT = ÖZDEŞ ## İki metin değerinin özdeş olup olmadığını anlamak için, değerleri denetler. -FIND = BUL ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlıdır). -FINDB = BULB ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlıdır). -FIXED = SAYIDÜZENLE ## Bir sayıyı, sabit sayıda ondalıkla, metin olarak biçimlendirir. -JIS = JIS ## Bir karakter dizesindeki tek enli (tek bayt) İngilizce harfleri veya katakanayı çift enli (iki bayt) karakterlerle değiştirir. -LEFT = SOL ## Bir metin değerinden en soldaki karakterleri verir. -LEFTB = SOLB ## Bir metin değerinden en soldaki karakterleri verir. -LEN = UZUNLUK ## Bir metin dizesindeki karakter sayısını verir. -LENB = UZUNLUKB ## Bir metin dizesindeki karakter sayısını verir. -LOWER = KÜÇÜKHARF ## Metni küçük harfe çevirir. -MID = ORTA ## Bir metin dizesinden belirli sayıda karakteri, belirttiğiniz konumdan başlamak üzere verir. -MIDB = ORTAB ## Bir metin dizesinden belirli sayıda karakteri, belirttiğiniz konumdan başlamak üzere verir. -PHONETIC = SES ## Metin dizesinden ses (furigana) karakterlerini ayıklar. -PROPER = YAZIM.DÜZENİ ## Bir metin değerinin her bir sözcüğünün ilk harfini büyük harfe çevirir. -REPLACE = DEĞİŞTİR ## Metnin içindeki karakterleri değiştirir. -REPLACEB = DEĞİŞTİRB ## Metnin içindeki karakterleri değiştirir. -REPT = YİNELE ## Metni belirtilen sayıda yineler. -RIGHT = SAĞ ## Bir metin değerinden en sağdaki karakterleri verir. -RIGHTB = SAĞB ## Bir metin değerinden en sağdaki karakterleri verir. -SEARCH = BUL ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlı değildir). -SEARCHB = BULB ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlı değildir). -SUBSTITUTE = YERİNEKOY ## Bir metin dizesinde, eski metnin yerine yeni metin koyar. -T = M ## Bağımsız değerlerini metne dönüştürür. -TEXT = METNEÇEVİR ## Bir sayıyı biçimlendirir ve metne dönüştürür. -TRIM = KIRP ## Metindeki boşlukları kaldırır. -UPPER = BÜYÜKHARF ## Metni büyük harfe çevirir. -VALUE = SAYIYAÇEVİR ## Bir metin bağımsız değişkenini sayıya dönüştürür. +ENCODEURL = URLKODLA +FILTERXML = XMLFİLTRELE +WEBSERVICE = WEBHİZMETİ + +## +## Uyumluluk işlevleri (Compatibility Functions) +## +BETADIST = BETADAĞ +BETAINV = BETATERS +BINOMDIST = BİNOMDAĞ +CEILING = TAVANAYUVARLA +CHIDIST = KİKAREDAĞ +CHIINV = KİKARETERS +CHITEST = KİKARETEST +CONCATENATE = BİRLEŞTİR +CONFIDENCE = GÜVENİRLİK +COVAR = KOVARYANS +CRITBINOM = KRİTİKBİNOM +EXPONDIST = ÜSTELDAĞ +FDIST = FDAĞ +FINV = FTERS +FLOOR = TABANAYUVARLA +FORECAST = TAHMİN +FTEST = FTEST +GAMMADIST = GAMADAĞ +GAMMAINV = GAMATERS +HYPGEOMDIST = HİPERGEOMDAĞ +LOGINV = LOGTERS +LOGNORMDIST = LOGNORMDAĞ +MODE = ENÇOK_OLAN +NEGBINOMDIST = NEGBİNOMDAĞ +NORMDIST = NORMDAĞ +NORMINV = NORMTERS +NORMSDIST = NORMSDAĞ +NORMSINV = NORMSTERS +PERCENTILE = YÜZDEBİRLİK +PERCENTRANK = YÜZDERANK +POISSON = POISSON +QUARTILE = DÖRTTEBİRLİK +RANK = RANK +STDEV = STDSAPMA +STDEVP = STDSAPMAS +TDIST = TDAĞ +TINV = TTERS +TTEST = TTEST +VAR = VAR +VARP = VARS +WEIBULL = WEIBULL +ZTEST = ZTEST diff --git a/src/PhpSpreadsheet/Cell/AddressHelper.php b/src/PhpSpreadsheet/Cell/AddressHelper.php index 04fa3b8c..499d248c 100644 --- a/src/PhpSpreadsheet/Cell/AddressHelper.php +++ b/src/PhpSpreadsheet/Cell/AddressHelper.php @@ -6,6 +6,8 @@ use PhpOffice\PhpSpreadsheet\Exception; class AddressHelper { + public const R1C1_COORDINATE_REGEX = '/(R((?:\[-?\d*\])|(?:\d*))?)(C((?:\[-?\d*\])|(?:\d*))?)/i'; + /** * Converts an R1C1 format cell address to an A1 format cell address. */ @@ -27,7 +29,7 @@ class AddressHelper } // Bracketed R references are relative to the current row if ($rowReference[0] === '[') { - $rowReference = $currentRowNumber + trim($rowReference, '[]'); + $rowReference = $currentRowNumber + (int) trim($rowReference, '[]'); } $columnReference = $cellReference[4]; // Empty C reference is the current column @@ -36,7 +38,7 @@ class AddressHelper } // Bracketed C references are relative to the current column if (is_string($columnReference) && $columnReference[0] === '[') { - $columnReference = $currentColumnNumber + trim($columnReference, '[]'); + $columnReference = $currentColumnNumber + (int) trim($columnReference, '[]'); } if ($columnReference <= 0 || $rowReference <= 0) { @@ -47,8 +49,24 @@ class AddressHelper return $A1CellReference; } + protected static function convertSpreadsheetMLFormula(string $formula): string + { + $formula = substr($formula, 3); + $temp = explode('"', $formula); + $key = false; + foreach ($temp as &$value) { + // Only replace in alternate array entries (i.e. non-quoted blocks) + if ($key = !$key) { + $value = str_replace(['[.', ':.', ']'], ['', ':', ''], $value); + } + } + unset($value); + + return implode('"', $temp); + } + /** - * Converts a formula that uses R1C1 format cell address to an A1 format cell address. + * Converts a formula that uses R1C1/SpreadsheetXML format cell address to an A1 format cell address. */ public static function convertFormulaToA1( string $formula, @@ -56,41 +74,33 @@ class AddressHelper int $currentColumnNumber = 1 ): string { if (substr($formula, 0, 3) == 'of:') { - $formula = substr($formula, 3); - $temp = explode('"', $formula); - $key = false; - foreach ($temp as &$value) { - // Only replace in alternate array entries (i.e. non-quoted blocks) - if ($key = !$key) { - $value = str_replace(['[.', '.', ']'], '', $value); - } - } - } else { - // Convert R1C1 style references to A1 style references (but only when not quoted) - $temp = explode('"', $formula); - $key = false; - foreach ($temp as &$value) { - // Only replace in alternate array entries (i.e. non-quoted blocks) - if ($key = !$key) { - preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/', $value, $cellReferences, PREG_SET_ORDER + PREG_OFFSET_CAPTURE); - // Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way - // through the formula from left to right. Reversing means that we work right to left.through - // the formula - $cellReferences = array_reverse($cellReferences); - // Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent, - // then modify the formula to use that new reference - foreach ($cellReferences as $cellReference) { - $A1CellReference = self::convertToA1($cellReference[0][0], $currentRowNumber, $currentColumnNumber); - $value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0])); - } + // We have an old-style SpreadsheetML Formula + return self::convertSpreadsheetMLFormula($formula); + } + + // Convert R1C1 style references to A1 style references (but only when not quoted) + $temp = explode('"', $formula); + $key = false; + foreach ($temp as &$value) { + // Only replace in alternate array entries (i.e. non-quoted blocks) + if ($key = !$key) { + preg_match_all(self::R1C1_COORDINATE_REGEX, $value, $cellReferences, PREG_SET_ORDER + PREG_OFFSET_CAPTURE); + // Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way + // through the formula from left to right. Reversing means that we work right to left.through + // the formula + $cellReferences = array_reverse($cellReferences); + // Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent, + // then modify the formula to use that new reference + foreach ($cellReferences as $cellReference) { + $A1CellReference = self::convertToA1($cellReference[0][0], $currentRowNumber, $currentColumnNumber); + $value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0])); } } } unset($value); - // Then rebuild the formula string - $formula = implode('"', $temp); - return $formula; + // Then rebuild the formula string + return implode('"', $temp); } /** @@ -102,14 +112,23 @@ class AddressHelper ?int $currentRowNumber = null, ?int $currentColumnNumber = null ): string { - $validityCheck = preg_match('/^\$?([A-Z]{1,3})\$?(\d{1,7})$/i', $address, $cellReference); + $validityCheck = preg_match(Coordinate::A1_COORDINATE_REGEX, $address, $cellReference); if ($validityCheck === 0) { throw new Exception('Invalid A1-format Cell Reference'); } - $columnId = Coordinate::columnIndexFromString($cellReference[1]); - $rowId = (int) $cellReference[2]; + $columnId = Coordinate::columnIndexFromString($cellReference['col_ref']); + if ($cellReference['absolute_col'] === '$') { + // Column must be absolute address + $currentColumnNumber = null; + } + + $rowId = (int) $cellReference['row_ref']; + if ($cellReference['absolute_row'] === '$') { + // Row must be absolute address + $currentRowNumber = null; + } if ($currentRowNumber !== null) { if ($rowId === $currentRowNumber) { diff --git a/src/PhpSpreadsheet/Cell/AdvancedValueBinder.php b/src/PhpSpreadsheet/Cell/AdvancedValueBinder.php index cf638d05..025a687b 100644 --- a/src/PhpSpreadsheet/Cell/AdvancedValueBinder.php +++ b/src/PhpSpreadsheet/Cell/AdvancedValueBinder.php @@ -20,8 +20,10 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder */ public function bindValue(Cell $cell, $value = null) { - // sanitize UTF-8 strings - if (is_string($value)) { + if ($value === null) { + return parent::bindValue($cell, $value); + } elseif (is_string($value)) { + // sanitize UTF-8 strings $value = StringHelper::sanitizeUTF8($value); } @@ -41,50 +43,16 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder return true; } - // Check for number in scientific format - if (preg_match('/^' . Calculation::CALCULATION_REGEXP_NUMBER . '$/', $value)) { - $cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC); - - return true; - } - - // Check for fraction + // Check for fractions if (preg_match('/^([+-]?)\s*(\d+)\s?\/\s*(\d+)$/', $value, $matches)) { - // Convert value to number - $value = $matches[2] / $matches[3]; - if ($matches[1] == '-') { - $value = 0 - $value; - } - $cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC); - // Set style - $cell->getWorksheet()->getStyle($cell->getCoordinate()) - ->getNumberFormat()->setFormatCode('??/??'); - - return true; + return $this->setProperFraction($matches, $cell); } elseif (preg_match('/^([+-]?)(\d*) +(\d*)\s?\/\s*(\d*)$/', $value, $matches)) { - // Convert value to number - $value = $matches[2] + ($matches[3] / $matches[4]); - if ($matches[1] == '-') { - $value = 0 - $value; - } - $cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC); - // Set style - $cell->getWorksheet()->getStyle($cell->getCoordinate()) - ->getNumberFormat()->setFormatCode('# ??/??'); - - return true; + return $this->setImproperFraction($matches, $cell); } // Check for percentage if (preg_match('/^\-?\d*\.?\d*\s?\%$/', $value)) { - // Convert value to number - $value = (float) str_replace('%', '', $value) / 100; - $cell->setValueExplicit($value, DataType::TYPE_NUMERIC); - // Set style - $cell->getWorksheet()->getStyle($cell->getCoordinate()) - ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_PERCENTAGE_00); - - return true; + return $this->setPercentage($value, $cell); } // Check for currency @@ -115,29 +83,12 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder // Check for time without seconds e.g. '9:45', '09:45' if (preg_match('/^(\d|[0-1]\d|2[0-3]):[0-5]\d$/', $value)) { - // Convert value to number - [$h, $m] = explode(':', $value); - $days = $h / 24 + $m / 1440; - $cell->setValueExplicit($days, DataType::TYPE_NUMERIC); - // Set style - $cell->getWorksheet()->getStyle($cell->getCoordinate()) - ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_TIME3); - - return true; + return $this->setTimeHoursMinutes($value, $cell); } // Check for time with seconds '9:45:59', '09:45:59' if (preg_match('/^(\d|[0-1]\d|2[0-3]):[0-5]\d:[0-5]\d$/', $value)) { - // Convert value to number - [$h, $m, $s] = explode(':', $value); - $days = $h / 24 + $m / 1440 + $s / 86400; - // Convert value to number - $cell->setValueExplicit($days, DataType::TYPE_NUMERIC); - // Set style - $cell->getWorksheet()->getStyle($cell->getCoordinate()) - ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_TIME4); - - return true; + return $this->setTimeHoursMinutesSeconds($value, $cell); } // Check for datetime, e.g. '2008-12-31', '2008-12-31 15:59', '2008-12-31 15:59:10' @@ -158,7 +109,6 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder // Check for newline character "\n" if (strpos($value, "\n") !== false) { - $value = StringHelper::sanitizeUTF8($value); $cell->setValueExplicit($value, DataType::TYPE_STRING); // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) @@ -171,4 +121,85 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder // Not bound yet? Use parent... return parent::bindValue($cell, $value); } + + protected function setImproperFraction(array $matches, Cell $cell): bool + { + // Convert value to number + $value = $matches[2] + ($matches[3] / $matches[4]); + if ($matches[1] === '-') { + $value = 0 - $value; + } + $cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC); + + // Build the number format mask based on the size of the matched values + $dividend = str_repeat('?', strlen($matches[3])); + $divisor = str_repeat('?', strlen($matches[4])); + $fractionMask = "# {$dividend}/{$divisor}"; + // Set style + $cell->getWorksheet()->getStyle($cell->getCoordinate()) + ->getNumberFormat()->setFormatCode($fractionMask); + + return true; + } + + protected function setProperFraction(array $matches, Cell $cell): bool + { + // Convert value to number + $value = $matches[2] / $matches[3]; + if ($matches[1] === '-') { + $value = 0 - $value; + } + $cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC); + + // Build the number format mask based on the size of the matched values + $dividend = str_repeat('?', strlen($matches[2])); + $divisor = str_repeat('?', strlen($matches[3])); + $fractionMask = "{$dividend}/{$divisor}"; + // Set style + $cell->getWorksheet()->getStyle($cell->getCoordinate()) + ->getNumberFormat()->setFormatCode($fractionMask); + + return true; + } + + protected function setPercentage(string $value, Cell $cell): bool + { + // Convert value to number + $value = ((float) str_replace('%', '', $value)) / 100; + $cell->setValueExplicit($value, DataType::TYPE_NUMERIC); + + // Set style + $cell->getWorksheet()->getStyle($cell->getCoordinate()) + ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_PERCENTAGE_00); + + return true; + } + + protected function setTimeHoursMinutes(string $value, Cell $cell): bool + { + // Convert value to number + [$hours, $minutes] = explode(':', $value); + $days = ($hours / 24) + ($minutes / 1440); + $cell->setValueExplicit($days, DataType::TYPE_NUMERIC); + + // Set style + $cell->getWorksheet()->getStyle($cell->getCoordinate()) + ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_TIME3); + + return true; + } + + protected function setTimeHoursMinutesSeconds(string $value, Cell $cell): bool + { + // Convert value to number + [$hours, $minutes, $seconds] = explode(':', $value); + $days = ($hours / 24) + ($minutes / 1440) + ($seconds / 86400); + $cell->setValueExplicit($days, DataType::TYPE_NUMERIC); + + // Set style + $cell->getWorksheet()->getStyle($cell->getCoordinate()) + ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_TIME4); + + return true; + } } diff --git a/src/PhpSpreadsheet/Cell/Cell.php b/src/PhpSpreadsheet/Cell/Cell.php index 05ad5cb8..56604f1e 100644 --- a/src/PhpSpreadsheet/Cell/Cell.php +++ b/src/PhpSpreadsheet/Cell/Cell.php @@ -78,6 +78,7 @@ class Cell public function detach(): void { + // @phpstan-ignore-next-line $this->parent = null; } @@ -252,9 +253,11 @@ class Cell if ($this->dataType == DataType::TYPE_FORMULA) { try { $index = $this->getWorksheet()->getParent()->getActiveSheetIndex(); + $selected = $this->getWorksheet()->getSelectedCells(); $result = Calculation::getInstance( $this->getWorksheet()->getParent() )->calculateCellValue($this, $resetLog); + $this->getWorksheet()->setSelectedCells($selected); $this->getWorksheet()->getParent()->setActiveSheetIndex($index); // We don't yet handle array returns if (is_array($result)) { @@ -265,7 +268,7 @@ class Cell } catch (Exception $ex) { if (($ex->getMessage() === 'Unable to access External Workbook') && ($this->calculatedValue !== null)) { return $this->calculatedValue; // Fallback for calculations referencing external files. - } elseif (strpos($ex->getMessage(), 'undefined name') !== false) { + } elseif (preg_match('/[Uu]ndefined (name|offset: 2|array key 2)/', $ex->getMessage()) === 1) { return \PhpOffice\PhpSpreadsheet\Calculation\Functions::NAME(); } diff --git a/src/PhpSpreadsheet/Cell/Coordinate.php b/src/PhpSpreadsheet/Cell/Coordinate.php index d2bc6e0a..33b0c214 100644 --- a/src/PhpSpreadsheet/Cell/Coordinate.php +++ b/src/PhpSpreadsheet/Cell/Coordinate.php @@ -13,6 +13,8 @@ use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; */ abstract class Coordinate { + public const A1_COORDINATE_REGEX = '/^(?\$?)(?[A-Z]{1,3})(?\$?)(?\d{1,7})$/i'; + /** * Default range variable constant. * @@ -25,12 +27,12 @@ abstract class Coordinate * * @param string $cellAddress eg: 'A1' * - * @return string[] Array containing column and row (indexes 0 and 1) + * @return array{0: string, 1: string} Array containing column and row (indexes 0 and 1) */ public static function coordinateFromString($cellAddress) { - if (preg_match('/^([$]?[A-Z]{1,3})([$]?\\d{1,7})$/', $cellAddress, $matches)) { - return [$matches[1], $matches[2]]; + if (preg_match(self::A1_COORDINATE_REGEX, $cellAddress, $matches)) { + return [$matches['absolute_col'] . $matches['col_ref'], $matches['absolute_row'] . $matches['row_ref']]; } elseif (self::coordinateIsRange($cellAddress)) { throw new Exception('Cell coordinate string can not be a range of cells'); } elseif ($cellAddress == '') { @@ -40,6 +42,23 @@ abstract class Coordinate throw new Exception('Invalid cell coordinate ' . $cellAddress); } + /** + * Get indexes from a string coordinates. + * + * @param string $coordinates eg: 'A1', '$B$12' + * + * @return array{0: int, 1: int} Array containing column index and row index (indexes 0 and 1) + */ + public static function indexesFromString(string $coordinates): array + { + [$col, $row] = self::coordinateFromString($coordinates); + + return [ + self::columnIndexFromString(ltrim($col, '$')), + (int) ltrim($row, '$'), + ]; + } + /** * Checks if a Cell Address represents a range of cells. * @@ -339,7 +358,8 @@ abstract class Coordinate private static function processRangeSetOperators(array $operators, array $cells): array { - for ($offset = 0; $offset < count($operators); ++$offset) { + $operatorCount = count($operators); + for ($offset = 0; $offset < $operatorCount; ++$offset) { $operator = $operators[$offset]; if ($operator !== ' ') { continue; @@ -350,6 +370,7 @@ abstract class Coordinate $operators = array_values($operators); $cells = array_values($cells); --$offset; + --$operatorCount; } return $cells; diff --git a/src/PhpSpreadsheet/Cell/DataValidation.php b/src/PhpSpreadsheet/Cell/DataValidation.php index f4a712e0..79d70a98 100644 --- a/src/PhpSpreadsheet/Cell/DataValidation.php +++ b/src/PhpSpreadsheet/Cell/DataValidation.php @@ -212,13 +212,13 @@ class DataValidation /** * Set Error style. * - * @param string $errorStye see self::STYLE_* + * @param string $errorStyle see self::STYLE_* * * @return $this */ - public function setErrorStyle($errorStye) + public function setErrorStyle($errorStyle) { - $this->errorStyle = $errorStye; + $this->errorStyle = $errorStyle; return $this; } @@ -478,4 +478,19 @@ class DataValidation } } } + + /** @var ?string */ + private $sqref; + + public function getSqref(): ?string + { + return $this->sqref; + } + + public function setSqref(?string $str): self + { + $this->sqref = $str; + + return $this; + } } diff --git a/src/PhpSpreadsheet/Cell/DefaultValueBinder.php b/src/PhpSpreadsheet/Cell/DefaultValueBinder.php index 693446e6..4f2cdf78 100644 --- a/src/PhpSpreadsheet/Cell/DefaultValueBinder.php +++ b/src/PhpSpreadsheet/Cell/DefaultValueBinder.php @@ -26,6 +26,7 @@ class DefaultValueBinder implements IValueBinder if ($value instanceof DateTimeInterface) { $value = $value->format('Y-m-d H:i:s'); } elseif (!($value instanceof RichText)) { + // Attempt to cast any unexpected objects to string $value = (string) $value; } } @@ -40,39 +41,39 @@ class DefaultValueBinder implements IValueBinder /** * DataType for value. * - * @param mixed $pValue + * @param mixed $value * * @return string */ - public static function dataTypeForValue($pValue) + public static function dataTypeForValue($value) { // Match the value against a few data types - if ($pValue === null) { + if ($value === null) { return DataType::TYPE_NULL; - } elseif (is_float($pValue) || is_int($pValue)) { + } elseif (is_float($value) || is_int($value)) { return DataType::TYPE_NUMERIC; - } elseif (is_bool($pValue)) { + } elseif (is_bool($value)) { return DataType::TYPE_BOOL; - } elseif ($pValue === '') { + } elseif ($value === '') { return DataType::TYPE_STRING; - } elseif ($pValue instanceof RichText) { + } elseif ($value instanceof RichText) { return DataType::TYPE_INLINE; - } elseif (is_string($pValue) && $pValue[0] === '=' && strlen($pValue) > 1) { + } elseif (is_string($value) && strlen($value) > 1 && $value[0] === '=') { return DataType::TYPE_FORMULA; - } elseif (preg_match('/^[\+\-]?(\d+\\.?\d*|\d*\\.?\d+)([Ee][\-\+]?[0-2]?\d{1,3})?$/', $pValue)) { - $tValue = ltrim($pValue, '+-'); - if (is_string($pValue) && $tValue[0] === '0' && strlen($tValue) > 1 && $tValue[1] !== '.') { + } elseif (preg_match('/^[\+\-]?(\d+\\.?\d*|\d*\\.?\d+)([Ee][\-\+]?[0-2]?\d{1,3})?$/', $value)) { + $tValue = ltrim($value, '+-'); + if (is_string($value) && strlen($tValue) > 1 && $tValue[0] === '0' && $tValue[1] !== '.') { return DataType::TYPE_STRING; - } elseif ((strpos($pValue, '.') === false) && ($pValue > PHP_INT_MAX)) { + } elseif ((strpos($value, '.') === false) && ($value > PHP_INT_MAX)) { return DataType::TYPE_STRING; - } elseif (!is_numeric($pValue)) { + } elseif (!is_numeric($value)) { return DataType::TYPE_STRING; } return DataType::TYPE_NUMERIC; - } elseif (is_string($pValue)) { + } elseif (is_string($value)) { $errorCodes = DataType::getErrorCodes(); - if (isset($errorCodes[$pValue])) { + if (isset($errorCodes[$value])) { return DataType::TYPE_ERROR; } } diff --git a/src/PhpSpreadsheet/Cell/StringValueBinder.php b/src/PhpSpreadsheet/Cell/StringValueBinder.php index 346d0253..5b6e3db1 100644 --- a/src/PhpSpreadsheet/Cell/StringValueBinder.php +++ b/src/PhpSpreadsheet/Cell/StringValueBinder.php @@ -2,28 +2,118 @@ namespace PhpOffice\PhpSpreadsheet\Cell; +use DateTimeInterface; +use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class StringValueBinder implements IValueBinder { + /** + * @var bool + */ + protected $convertNull = true; + + /** + * @var bool + */ + protected $convertBoolean = true; + + /** + * @var bool + */ + protected $convertNumeric = true; + + /** + * @var bool + */ + protected $convertFormula = true; + + public function setNullConversion(bool $suppressConversion = false): self + { + $this->convertNull = $suppressConversion; + + return $this; + } + + public function setBooleanConversion(bool $suppressConversion = false): self + { + $this->convertBoolean = $suppressConversion; + + return $this; + } + + public function setNumericConversion(bool $suppressConversion = false): self + { + $this->convertNumeric = $suppressConversion; + + return $this; + } + + public function setFormulaConversion(bool $suppressConversion = false): self + { + $this->convertFormula = $suppressConversion; + + return $this; + } + + public function setConversionForAllValueTypes(bool $suppressConversion = false): self + { + $this->convertNull = $suppressConversion; + $this->convertBoolean = $suppressConversion; + $this->convertNumeric = $suppressConversion; + $this->convertFormula = $suppressConversion; + + return $this; + } + /** * Bind value to a cell. * * @param Cell $cell Cell to bind value to * @param mixed $value Value to bind in cell - * - * @return bool */ public function bindValue(Cell $cell, $value) { + if (is_object($value)) { + return $this->bindObjectValue($cell, $value); + } + // sanitize UTF-8 strings if (is_string($value)) { $value = StringHelper::sanitizeUTF8($value); } + if ($value === null && $this->convertNull === false) { + $cell->setValueExplicit($value, DataType::TYPE_NULL); + } elseif (is_bool($value) && $this->convertBoolean === false) { + $cell->setValueExplicit($value, DataType::TYPE_BOOL); + } elseif ((is_int($value) || is_float($value)) && $this->convertNumeric === false) { + $cell->setValueExplicit($value, DataType::TYPE_NUMERIC); + } elseif (is_string($value) && strlen($value) > 1 && $value[0] === '=' && $this->convertFormula === false) { + $cell->setValueExplicit($value, DataType::TYPE_FORMULA); + } else { + if (is_string($value) && strlen($value) > 1 && $value[0] === '=') { + $cell->getStyle()->setQuotePrefix(true); + } + $cell->setValueExplicit((string) $value, DataType::TYPE_STRING); + } + + return true; + } + + protected function bindObjectValue(Cell $cell, object $value): bool + { + // Handle any objects that might be injected + if ($value instanceof DateTimeInterface) { + $value = $value->format('Y-m-d H:i:s'); + } elseif ($value instanceof RichText) { + $cell->setValueExplicit($value, DataType::TYPE_INLINE); + + return true; + } + $cell->setValueExplicit((string) $value, DataType::TYPE_STRING); - // Done! return true; } } diff --git a/src/PhpSpreadsheet/Chart/Axis.php b/src/PhpSpreadsheet/Chart/Axis.php index 5f235c3d..eeed326d 100644 --- a/src/PhpSpreadsheet/Chart/Axis.php +++ b/src/PhpSpreadsheet/Chart/Axis.php @@ -13,7 +13,7 @@ class Axis extends Properties /** * Axis Number. * - * @var array of mixed + * @var mixed[] */ private $axisNumber = [ 'format' => self::FORMAT_CODE_GENERAL, @@ -23,7 +23,7 @@ class Axis extends Properties /** * Axis Options. * - * @var array of mixed + * @var mixed[] */ private $axisOptions = [ 'minimum' => null, @@ -41,7 +41,7 @@ class Axis extends Properties /** * Fill Properties. * - * @var array of mixed + * @var mixed[] */ private $fillProperties = [ 'type' => self::EXCEL_COLOR_TYPE_ARGB, @@ -52,7 +52,7 @@ class Axis extends Properties /** * Line Properties. * - * @var array of mixed + * @var mixed[] */ private $lineProperties = [ 'type' => self::EXCEL_COLOR_TYPE_ARGB, @@ -63,7 +63,7 @@ class Axis extends Properties /** * Line Style Properties. * - * @var array of mixed + * @var mixed[] */ private $lineStyleProperties = [ 'width' => '9525', @@ -86,7 +86,7 @@ class Axis extends Properties /** * Shadow Properties. * - * @var array of mixed + * @var mixed[] */ private $shadowProperties = [ 'presets' => self::SHADOW_PRESETS_NOSHADOW, @@ -111,7 +111,7 @@ class Axis extends Properties /** * Glow Properties. * - * @var array of mixed + * @var mixed[] */ private $glowProperties = [ 'size' => null, @@ -125,7 +125,7 @@ class Axis extends Properties /** * Soft Edge Properties. * - * @var array of mixed + * @var mixed[] */ private $softEdges = [ 'size' => null, @@ -135,10 +135,8 @@ class Axis extends Properties * Get Series Data Type. * * @param mixed $format_code - * - * @return string */ - public function setAxisNumberProperties($format_code) + public function setAxisNumberProperties($format_code): void { $this->axisNumber['format'] = (string) $format_code; $this->axisNumber['source_linked'] = 0; @@ -340,9 +338,9 @@ class Axis extends Properties { $this->setShadowPresetsProperties((int) $shadowPresets) ->setShadowColor( - $colorValue === null ? $this->shadowProperties['color']['value'] : $colorValue, - $colorAlpha === null ? $this->shadowProperties['color']['alpha'] : $colorAlpha, - $colorType === null ? $this->shadowProperties['color']['type'] : $colorType + $colorValue ?? $this->shadowProperties['color']['value'], + $colorAlpha ?? (int) $this->shadowProperties['color']['alpha'], + $colorType ?? $this->shadowProperties['color']['type'] ) ->setShadowBlur($blur) ->setShadowAngle($angle) @@ -367,7 +365,7 @@ class Axis extends Properties /** * Set Shadow Properties from Mapped Values. * - * @param mixed &$reference + * @param mixed $reference * * @return $this */ @@ -482,9 +480,9 @@ class Axis extends Properties { $this->setGlowSize($size) ->setGlowColor( - $colorValue === null ? $this->glowProperties['color']['value'] : $colorValue, - $colorAlpha === null ? (int) $this->glowProperties['color']['alpha'] : $colorAlpha, - $colorType === null ? $this->glowProperties['color']['type'] : $colorType + $colorValue ?? $this->glowProperties['color']['value'], + $colorAlpha ?? (int) $this->glowProperties['color']['alpha'], + $colorType ?? $this->glowProperties['color']['type'] ); } diff --git a/src/PhpSpreadsheet/Chart/Chart.php b/src/PhpSpreadsheet/Chart/Chart.php index b6093c45..106e44c6 100644 --- a/src/PhpSpreadsheet/Chart/Chart.php +++ b/src/PhpSpreadsheet/Chart/Chart.php @@ -424,7 +424,7 @@ class Chart /** * Get the top left position of the chart. * - * @return array an associative array containing the cell address, X-Offset and Y-Offset from the top left of that cell + * @return array{cell: string, xOffset: int, yOffset: int} an associative array containing the cell address, X-Offset and Y-Offset from the top left of that cell */ public function getTopLeftPosition() { diff --git a/src/PhpSpreadsheet/Chart/DataSeries.php b/src/PhpSpreadsheet/Chart/DataSeries.php index 3a44b335..067d30e5 100644 --- a/src/PhpSpreadsheet/Chart/DataSeries.php +++ b/src/PhpSpreadsheet/Chart/DataSeries.php @@ -75,21 +75,21 @@ class DataSeries /** * Order of plots in Series. * - * @var array of integer + * @var int[] */ private $plotOrder = []; /** * Plot Label. * - * @var array of DataSeriesValues + * @var DataSeriesValues[] */ private $plotLabel = []; /** * Plot Category. * - * @var array of DataSeriesValues + * @var DataSeriesValues[] */ private $plotCategory = []; @@ -103,7 +103,7 @@ class DataSeries /** * Plot Values. * - * @var array of DataSeriesValues + * @var DataSeriesValues[] */ private $plotValues = []; @@ -231,7 +231,7 @@ class DataSeries /** * Get Plot Labels. * - * @return array of DataSeriesValues + * @return DataSeriesValues[] */ public function getPlotLabels() { @@ -243,7 +243,7 @@ class DataSeries * * @param mixed $index * - * @return DataSeriesValues + * @return DataSeriesValues|false */ public function getPlotLabelByIndex($index) { @@ -260,7 +260,7 @@ class DataSeries /** * Get Plot Categories. * - * @return array of DataSeriesValues + * @return DataSeriesValues[] */ public function getPlotCategories() { @@ -272,7 +272,7 @@ class DataSeries * * @param mixed $index * - * @return DataSeriesValues + * @return DataSeriesValues|false */ public function getPlotCategoryByIndex($index) { @@ -313,7 +313,7 @@ class DataSeries /** * Get Plot Values. * - * @return array of DataSeriesValues + * @return DataSeriesValues[] */ public function getPlotValues() { @@ -325,7 +325,7 @@ class DataSeries * * @param mixed $index * - * @return DataSeriesValues + * @return DataSeriesValues|false */ public function getPlotValuesByIndex($index) { diff --git a/src/PhpSpreadsheet/Chart/DataSeriesValues.php b/src/PhpSpreadsheet/Chart/DataSeriesValues.php index c1bd973a..88063336 100644 --- a/src/PhpSpreadsheet/Chart/DataSeriesValues.php +++ b/src/PhpSpreadsheet/Chart/DataSeriesValues.php @@ -55,7 +55,7 @@ class DataSeriesValues /** * Data Values. * - * @var array of mixed + * @var mixed[] */ private $dataValues = []; @@ -313,7 +313,7 @@ class DataSeriesValues /** * Get Series Data Values. * - * @return array of mixed + * @return mixed[] */ public function getDataValues() { diff --git a/src/PhpSpreadsheet/Chart/GridLines.php b/src/PhpSpreadsheet/Chart/GridLines.php index fb789d76..84af3ada 100644 --- a/src/PhpSpreadsheet/Chart/GridLines.php +++ b/src/PhpSpreadsheet/Chart/GridLines.php @@ -291,9 +291,9 @@ class GridLines extends Properties $this->activateObject() ->setShadowPresetsProperties((int) $presets) ->setShadowColor( - $colorValue === null ? $this->shadowProperties['color']['value'] : $colorValue, - $colorAlpha === null ? $this->shadowProperties['color']['alpha'] : $this->getTrueAlpha($colorAlpha), - $colorType === null ? $this->shadowProperties['color']['type'] : $colorType + $colorValue ?? $this->shadowProperties['color']['value'], + $colorAlpha === null ? (int) $this->shadowProperties['color']['alpha'] : $this->getTrueAlpha($colorAlpha), + $colorType ?? $this->shadowProperties['color']['type'] ) ->setShadowBlur((float) $blur) ->setShadowAngle($angle) @@ -318,7 +318,7 @@ class GridLines extends Properties /** * Set Shadow Properties Values. * - * @param mixed &$reference + * @param mixed $reference * * @return $this */ diff --git a/src/PhpSpreadsheet/Chart/Legend.php b/src/PhpSpreadsheet/Chart/Legend.php index fc0ed140..2f003cd8 100644 --- a/src/PhpSpreadsheet/Chart/Legend.php +++ b/src/PhpSpreadsheet/Chart/Legend.php @@ -131,18 +131,10 @@ class Legend * Set allow overlay of other elements? * * @param bool $overlay - * - * @return bool */ - public function setOverlay($overlay) + public function setOverlay($overlay): void { - if (!is_bool($overlay)) { - return false; - } - $this->overlay = $overlay; - - return true; } /** diff --git a/src/PhpSpreadsheet/Chart/PlotArea.php b/src/PhpSpreadsheet/Chart/PlotArea.php index 954777cf..ecb7b6c9 100644 --- a/src/PhpSpreadsheet/Chart/PlotArea.php +++ b/src/PhpSpreadsheet/Chart/PlotArea.php @@ -43,10 +43,8 @@ class PlotArea /** * Get Number of Plot Groups. - * - * @return array of DataSeries */ - public function getPlotGroupCount() + public function getPlotGroupCount(): int { return count($this->plotSeries); } @@ -69,7 +67,7 @@ class PlotArea /** * Get Plot Series. * - * @return array of DataSeries + * @return DataSeries[] */ public function getPlotGroup() { diff --git a/src/PhpSpreadsheet/Chart/Renderer/JpGraph.php b/src/PhpSpreadsheet/Chart/Renderer/JpGraph.php index 02fbfed7..0ab70870 100644 --- a/src/PhpSpreadsheet/Chart/Renderer/JpGraph.php +++ b/src/PhpSpreadsheet/Chart/Renderer/JpGraph.php @@ -301,6 +301,8 @@ class JpGraph implements IRenderer $seriesPlots = []; if ($grouping == 'percentStacked') { $sumValues = $this->percentageSumCalculation($groupID, $seriesCount); + } else { + $sumValues = []; } // Loop through each data series in turn @@ -376,6 +378,8 @@ class JpGraph implements IRenderer $seriesPlots = []; if ($grouping == 'percentStacked') { $sumValues = $this->percentageSumCalculation($groupID, $seriesCount); + } else { + $sumValues = []; } // Loop through each data series in turn diff --git a/src/PhpSpreadsheet/Chart/Title.php b/src/PhpSpreadsheet/Chart/Title.php index af9fa088..090c4f3f 100644 --- a/src/PhpSpreadsheet/Chart/Title.php +++ b/src/PhpSpreadsheet/Chart/Title.php @@ -2,14 +2,16 @@ namespace PhpOffice\PhpSpreadsheet\Chart; +use PhpOffice\PhpSpreadsheet\RichText\RichText; + class Title { /** * Title Caption. * - * @var string + * @var array|RichText|string */ - private $caption; + private $caption = ''; /** * Title Layout. @@ -21,9 +23,9 @@ class Title /** * Create a new Title. * - * @param null|mixed $caption + * @param array|RichText|string $caption */ - public function __construct($caption = null, ?Layout $layout = null) + public function __construct($caption = '', ?Layout $layout = null) { $this->caption = $caption; $this->layout = $layout; @@ -32,17 +34,40 @@ class Title /** * Get caption. * - * @return string + * @return array|RichText|string */ public function getCaption() { return $this->caption; } + public function getCaptionText(): string + { + $caption = $this->caption; + if (is_string($caption)) { + return $caption; + } + if ($caption instanceof RichText) { + return $caption->getPlainText(); + } + $retVal = ''; + foreach ($caption as $textx) { + /** @var RichText|string */ + $text = $textx; + if ($text instanceof RichText) { + $retVal .= $text->getPlainText(); + } else { + $retVal .= $text; + } + } + + return $retVal; + } + /** * Set caption. * - * @param string $caption + * @param array|RichText|string $caption * * @return $this */ diff --git a/src/PhpSpreadsheet/Collection/Cells.php b/src/PhpSpreadsheet/Collection/Cells.php index aedff5d9..3bbf76fc 100644 --- a/src/PhpSpreadsheet/Collection/Cells.php +++ b/src/PhpSpreadsheet/Collection/Cells.php @@ -12,28 +12,28 @@ use Psr\SimpleCache\CacheInterface; class Cells { /** - * @var \Psr\SimpleCache\CacheInterface + * @var CacheInterface */ private $cache; /** * Parent worksheet. * - * @var Worksheet + * @var null|Worksheet */ private $parent; /** * The currently active Cell. * - * @var Cell + * @var null|Cell */ private $currentCell; /** * Coordinate of the currently active Cell. * - * @var string + * @var null|string */ private $currentCoordinate; @@ -405,7 +405,7 @@ class Cells * @param string $cellCoordinate Coordinate of the cell to update * @param Cell $cell Cell to update * - * @return \PhpOffice\PhpSpreadsheet\Cell\Cell + * @return Cell */ public function add($cellCoordinate, Cell $cell) { @@ -426,7 +426,7 @@ class Cells * * @param string $cellCoordinate Coordinate of the cell * - * @return null|\PhpOffice\PhpSpreadsheet\Cell\Cell Cell that was found, or null if not found + * @return null|Cell Cell that was found, or null if not found */ public function get($cellCoordinate) { diff --git a/src/PhpSpreadsheet/DefinedName.php b/src/PhpSpreadsheet/DefinedName.php index 74ee0551..3b874b43 100644 --- a/src/PhpSpreadsheet/DefinedName.php +++ b/src/PhpSpreadsheet/DefinedName.php @@ -241,9 +241,18 @@ abstract class DefinedName /** * Resolve a named range to a regular cell range or formula. */ - public static function resolveName(string $definedName, Worksheet $worksheet): ?self + public static function resolveName(string $definedName, Worksheet $worksheet, string $sheetName = ''): ?self { - return $worksheet->getParent()->getDefinedName($definedName, $worksheet); + if ($sheetName === '') { + $worksheet2 = $worksheet; + } else { + $worksheet2 = $worksheet->getParent()->getSheetByName($sheetName); + if ($worksheet2 === null) { + return null; + } + } + + return $worksheet->getParent()->getDefinedName($definedName, $worksheet2); } /** diff --git a/src/PhpSpreadsheet/Document/Properties.php b/src/PhpSpreadsheet/Document/Properties.php index 2538fe39..3be5a67a 100644 --- a/src/PhpSpreadsheet/Document/Properties.php +++ b/src/PhpSpreadsheet/Document/Properties.php @@ -2,15 +2,26 @@ namespace PhpOffice\PhpSpreadsheet\Document; +use DateTime; +use PhpOffice\PhpSpreadsheet\Shared\IntOrFloat; + class Properties { /** constants */ - const PROPERTY_TYPE_BOOLEAN = 'b'; - const PROPERTY_TYPE_INTEGER = 'i'; - const PROPERTY_TYPE_FLOAT = 'f'; - const PROPERTY_TYPE_DATE = 'd'; - const PROPERTY_TYPE_STRING = 's'; - const PROPERTY_TYPE_UNKNOWN = 'u'; + public const PROPERTY_TYPE_BOOLEAN = 'b'; + public const PROPERTY_TYPE_INTEGER = 'i'; + public const PROPERTY_TYPE_FLOAT = 'f'; + public const PROPERTY_TYPE_DATE = 'd'; + public const PROPERTY_TYPE_STRING = 's'; + public const PROPERTY_TYPE_UNKNOWN = 'u'; + + private const VALID_PROPERTY_TYPE_LIST = [ + self::PROPERTY_TYPE_BOOLEAN, + self::PROPERTY_TYPE_INTEGER, + self::PROPERTY_TYPE_FLOAT, + self::PROPERTY_TYPE_DATE, + self::PROPERTY_TYPE_STRING, + ]; /** * Creator. @@ -29,14 +40,14 @@ class Properties /** * Created. * - * @var int + * @var float|int */ private $created; /** * Modified. * - * @var int + * @var float|int */ private $modified; @@ -87,12 +98,12 @@ class Properties * * @var string */ - private $company = 'Microsoft Corporation'; + private $company = ''; /** * Custom Properties. * - * @var array + * @var array{value: mixed, type: string}[] */ private $customProperties = []; @@ -103,16 +114,14 @@ class Properties { // Initialise values $this->lastModifiedBy = $this->creator; - $this->created = time(); - $this->modified = time(); + $this->created = self::intOrFloatTimestamp(null); + $this->modified = self::intOrFloatTimestamp(null); } /** * Get Creator. - * - * @return string */ - public function getCreator() + public function getCreator(): string { return $this->creator; } @@ -120,11 +129,9 @@ class Properties /** * Set Creator. * - * @param string $creator - * * @return $this */ - public function setCreator($creator) + public function setCreator(string $creator): self { $this->creator = $creator; @@ -133,10 +140,8 @@ class Properties /** * Get Last Modified By. - * - * @return string */ - public function getLastModifiedBy() + public function getLastModifiedBy(): string { return $this->lastModifiedBy; } @@ -144,52 +149,58 @@ class Properties /** * Set Last Modified By. * - * @param string $modifiedBy - * * @return $this */ - public function setLastModifiedBy($modifiedBy) + public function setLastModifiedBy(string $modifiedBy): self { $this->lastModifiedBy = $modifiedBy; return $this; } + /** + * @param null|float|int|string $timestamp + * + * @return float|int + */ + private static function intOrFloatTimestamp($timestamp) + { + if ($timestamp === null) { + $timestamp = (float) (new DateTime())->format('U'); + } elseif (is_string($timestamp)) { + if (is_numeric($timestamp)) { + $timestamp = (float) $timestamp; + } else { + $timestamp = preg_replace('/[.][0-9]*$/', '', $timestamp) ?? ''; + $timestamp = preg_replace('/^(\\d{4})- (\\d)/', '$1-0$2', $timestamp) ?? ''; + $timestamp = preg_replace('/^(\\d{4}-\\d{2})- (\\d)/', '$1-0$2', $timestamp) ?? ''; + $timestamp = (float) (new DateTime($timestamp))->format('U'); + } + } + + return IntOrFloat::evaluate($timestamp); + } + /** * Get Created. * - * @return int + * @return float|int */ public function getCreated() { return $this->created; } - private function asTimeStamp($timestamp) - { - if ($timestamp === null) { - return time(); - } elseif (is_string($timestamp)) { - if (is_numeric($timestamp)) { - return (int) $timestamp; - } - - return strtotime($timestamp); - } - - return $timestamp; - } - /** * Set Created. * - * @param int|string $timestamp + * @param null|float|int|string $timestamp * * @return $this */ - public function setCreated($timestamp) + public function setCreated($timestamp): self { - $this->created = $this->asTimeStamp($timestamp); + $this->created = self::intOrFloatTimestamp($timestamp); return $this; } @@ -197,7 +208,7 @@ class Properties /** * Get Modified. * - * @return int + * @return float|int */ public function getModified() { @@ -207,23 +218,21 @@ class Properties /** * Set Modified. * - * @param int|string $timestamp + * @param null|float|int|string $timestamp * * @return $this */ - public function setModified($timestamp) + public function setModified($timestamp): self { - $this->modified = $this->asTimeStamp($timestamp); + $this->modified = self::intOrFloatTimestamp($timestamp); return $this; } /** * Get Title. - * - * @return string */ - public function getTitle() + public function getTitle(): string { return $this->title; } @@ -231,11 +240,9 @@ class Properties /** * Set Title. * - * @param string $title - * * @return $this */ - public function setTitle($title) + public function setTitle(string $title): self { $this->title = $title; @@ -244,10 +251,8 @@ class Properties /** * Get Description. - * - * @return string */ - public function getDescription() + public function getDescription(): string { return $this->description; } @@ -255,11 +260,9 @@ class Properties /** * Set Description. * - * @param string $description - * * @return $this */ - public function setDescription($description) + public function setDescription(string $description): self { $this->description = $description; @@ -268,10 +271,8 @@ class Properties /** * Get Subject. - * - * @return string */ - public function getSubject() + public function getSubject(): string { return $this->subject; } @@ -279,11 +280,9 @@ class Properties /** * Set Subject. * - * @param string $subject - * * @return $this */ - public function setSubject($subject) + public function setSubject(string $subject): self { $this->subject = $subject; @@ -292,10 +291,8 @@ class Properties /** * Get Keywords. - * - * @return string */ - public function getKeywords() + public function getKeywords(): string { return $this->keywords; } @@ -303,11 +300,9 @@ class Properties /** * Set Keywords. * - * @param string $keywords - * * @return $this */ - public function setKeywords($keywords) + public function setKeywords(string $keywords): self { $this->keywords = $keywords; @@ -316,10 +311,8 @@ class Properties /** * Get Category. - * - * @return string */ - public function getCategory() + public function getCategory(): string { return $this->category; } @@ -327,11 +320,9 @@ class Properties /** * Set Category. * - * @param string $category - * * @return $this */ - public function setCategory($category) + public function setCategory(string $category): self { $this->category = $category; @@ -340,10 +331,8 @@ class Properties /** * Get Company. - * - * @return string */ - public function getCompany() + public function getCompany(): string { return $this->company; } @@ -351,11 +340,9 @@ class Properties /** * Set Company. * - * @param string $company - * * @return $this */ - public function setCompany($company) + public function setCompany(string $company): self { $this->company = $company; @@ -364,10 +351,8 @@ class Properties /** * Get Manager. - * - * @return string */ - public function getManager() + public function getManager(): string { return $this->manager; } @@ -375,11 +360,9 @@ class Properties /** * Set Manager. * - * @param string $manager - * * @return $this */ - public function setManager($manager) + public function setManager(string $manager): self { $this->manager = $manager; @@ -389,33 +372,27 @@ class Properties /** * Get a List of Custom Property Names. * - * @return array + * @return string[] */ - public function getCustomProperties() + public function getCustomProperties(): array { return array_keys($this->customProperties); } /** * Check if a Custom Property is defined. - * - * @param string $propertyName - * - * @return bool */ - public function isCustomPropertySet($propertyName) + public function isCustomPropertySet(string $propertyName): bool { - return isset($this->customProperties[$propertyName]); + return array_key_exists($propertyName, $this->customProperties); } /** * Get a Custom Property Value. * - * @param string $propertyName - * * @return mixed */ - public function getCustomPropertyValue($propertyName) + public function getCustomPropertyValue(string $propertyName) { if (isset($this->customProperties[$propertyName])) { return $this->customProperties[$propertyName]['value']; @@ -427,23 +404,34 @@ class Properties /** * Get a Custom Property Type. * - * @param string $propertyName - * - * @return mixed + * @return null|string */ - public function getCustomPropertyType($propertyName) + public function getCustomPropertyType(string $propertyName) { - if (isset($this->customProperties[$propertyName])) { - return $this->customProperties[$propertyName]['type']; + return $this->customProperties[$propertyName]['type'] ?? null; + } + + /** + * @param mixed $propertyValue + */ + private function identifyPropertyType($propertyValue): string + { + if (is_float($propertyValue)) { + return self::PROPERTY_TYPE_FLOAT; + } + if (is_int($propertyValue)) { + return self::PROPERTY_TYPE_INTEGER; + } + if (is_bool($propertyValue)) { + return self::PROPERTY_TYPE_BOOLEAN; } - return null; + return self::PROPERTY_TYPE_STRING; } /** * Set a Custom Property. * - * @param string $propertyName * @param mixed $propertyValue * @param string $propertyType * 'i' : Integer @@ -454,178 +442,96 @@ class Properties * * @return $this */ - public function setCustomProperty($propertyName, $propertyValue = '', $propertyType = null) + public function setCustomProperty(string $propertyName, $propertyValue = '', $propertyType = null): self { - if ( - ($propertyType === null) || (!in_array($propertyType, [self::PROPERTY_TYPE_INTEGER, - self::PROPERTY_TYPE_FLOAT, - self::PROPERTY_TYPE_STRING, - self::PROPERTY_TYPE_DATE, - self::PROPERTY_TYPE_BOOLEAN, - ])) - ) { - if ($propertyValue === null) { - $propertyType = self::PROPERTY_TYPE_STRING; - } elseif (is_float($propertyValue)) { - $propertyType = self::PROPERTY_TYPE_FLOAT; - } elseif (is_int($propertyValue)) { - $propertyType = self::PROPERTY_TYPE_INTEGER; - } elseif (is_bool($propertyValue)) { - $propertyType = self::PROPERTY_TYPE_BOOLEAN; - } else { - $propertyType = self::PROPERTY_TYPE_STRING; - } + if (($propertyType === null) || (!in_array($propertyType, self::VALID_PROPERTY_TYPE_LIST))) { + $propertyType = $this->identifyPropertyType($propertyValue); } - $this->customProperties[$propertyName] = [ - 'value' => $propertyValue, - 'type' => $propertyType, - ]; + if (!is_object($propertyValue)) { + $this->customProperties[$propertyName] = [ + 'value' => self::convertProperty($propertyValue, $propertyType), + 'type' => $propertyType, + ]; + } return $this; } + private const PROPERTY_TYPE_ARRAY = [ + 'i' => self::PROPERTY_TYPE_INTEGER, // Integer + 'i1' => self::PROPERTY_TYPE_INTEGER, // 1-Byte Signed Integer + 'i2' => self::PROPERTY_TYPE_INTEGER, // 2-Byte Signed Integer + 'i4' => self::PROPERTY_TYPE_INTEGER, // 4-Byte Signed Integer + 'i8' => self::PROPERTY_TYPE_INTEGER, // 8-Byte Signed Integer + 'int' => self::PROPERTY_TYPE_INTEGER, // Integer + 'ui1' => self::PROPERTY_TYPE_INTEGER, // 1-Byte Unsigned Integer + 'ui2' => self::PROPERTY_TYPE_INTEGER, // 2-Byte Unsigned Integer + 'ui4' => self::PROPERTY_TYPE_INTEGER, // 4-Byte Unsigned Integer + 'ui8' => self::PROPERTY_TYPE_INTEGER, // 8-Byte Unsigned Integer + 'uint' => self::PROPERTY_TYPE_INTEGER, // Unsigned Integer + 'f' => self::PROPERTY_TYPE_FLOAT, // Real Number + 'r4' => self::PROPERTY_TYPE_FLOAT, // 4-Byte Real Number + 'r8' => self::PROPERTY_TYPE_FLOAT, // 8-Byte Real Number + 'decimal' => self::PROPERTY_TYPE_FLOAT, // Decimal + 's' => self::PROPERTY_TYPE_STRING, // String + 'empty' => self::PROPERTY_TYPE_STRING, // Empty + 'null' => self::PROPERTY_TYPE_STRING, // Null + 'lpstr' => self::PROPERTY_TYPE_STRING, // LPSTR + 'lpwstr' => self::PROPERTY_TYPE_STRING, // LPWSTR + 'bstr' => self::PROPERTY_TYPE_STRING, // Basic String + 'd' => self::PROPERTY_TYPE_DATE, // Date and Time + 'date' => self::PROPERTY_TYPE_DATE, // Date and Time + 'filetime' => self::PROPERTY_TYPE_DATE, // File Time + 'b' => self::PROPERTY_TYPE_BOOLEAN, // Boolean + 'bool' => self::PROPERTY_TYPE_BOOLEAN, // Boolean + ]; + + private const SPECIAL_TYPES = [ + 'empty' => '', + 'null' => null, + ]; + /** - * Implement PHP __clone to create a deep clone, not just a shallow copy. + * Convert property to form desired by Excel. + * + * @param mixed $propertyValue + * + * @return mixed */ - public function __clone() + public static function convertProperty($propertyValue, string $propertyType) { - $vars = get_object_vars($this); - foreach ($vars as $key => $value) { - if (is_object($value)) { - $this->$key = clone $value; - } else { - $this->$key = $value; - } - } + return self::SPECIAL_TYPES[$propertyType] ?? self::convertProperty2($propertyValue, $propertyType); } - public static function convertProperty($propertyValue, $propertyType) + /** + * Convert property to form desired by Excel. + * + * @param mixed $propertyValue + * + * @return mixed + */ + private static function convertProperty2($propertyValue, string $type) { + $propertyType = self::convertPropertyType($type); switch ($propertyType) { - case 'empty': // Empty - return ''; + case self::PROPERTY_TYPE_INTEGER: + $intValue = (int) $propertyValue; - break; - case 'null': // Null - return null; - - break; - case 'i1': // 1-Byte Signed Integer - case 'i2': // 2-Byte Signed Integer - case 'i4': // 4-Byte Signed Integer - case 'i8': // 8-Byte Signed Integer - case 'int': // Integer - return (int) $propertyValue; - - break; - case 'ui1': // 1-Byte Unsigned Integer - case 'ui2': // 2-Byte Unsigned Integer - case 'ui4': // 4-Byte Unsigned Integer - case 'ui8': // 8-Byte Unsigned Integer - case 'uint': // Unsigned Integer - return abs((int) $propertyValue); - - break; - case 'r4': // 4-Byte Real Number - case 'r8': // 8-Byte Real Number - case 'decimal': // Decimal + return ($type[0] === 'u') ? abs($intValue) : $intValue; + case self::PROPERTY_TYPE_FLOAT: return (float) $propertyValue; - - break; - case 'lpstr': // LPSTR - case 'lpwstr': // LPWSTR - case 'bstr': // Basic String + case self::PROPERTY_TYPE_DATE: + return self::intOrFloatTimestamp($propertyValue); + case self::PROPERTY_TYPE_BOOLEAN: + return is_bool($propertyValue) ? $propertyValue : ($propertyValue === 'true'); + default: // includes string return $propertyValue; - - break; - case 'date': // Date and Time - case 'filetime': // File Time - return strtotime($propertyValue); - - break; - case 'bool': // Boolean - return $propertyValue == 'true'; - - break; - case 'cy': // Currency - case 'error': // Error Status Code - case 'vector': // Vector - case 'array': // Array - case 'blob': // Binary Blob - case 'oblob': // Binary Blob Object - case 'stream': // Binary Stream - case 'ostream': // Binary Stream Object - case 'storage': // Binary Storage - case 'ostorage': // Binary Storage Object - case 'vstream': // Binary Versioned Stream - case 'clsid': // Class ID - case 'cf': // Clipboard Data - return $propertyValue; - - break; } - - return $propertyValue; } - public static function convertPropertyType($propertyType) + public static function convertPropertyType(string $propertyType): string { - switch ($propertyType) { - case 'i1': // 1-Byte Signed Integer - case 'i2': // 2-Byte Signed Integer - case 'i4': // 4-Byte Signed Integer - case 'i8': // 8-Byte Signed Integer - case 'int': // Integer - case 'ui1': // 1-Byte Unsigned Integer - case 'ui2': // 2-Byte Unsigned Integer - case 'ui4': // 4-Byte Unsigned Integer - case 'ui8': // 8-Byte Unsigned Integer - case 'uint': // Unsigned Integer - return self::PROPERTY_TYPE_INTEGER; - - break; - case 'r4': // 4-Byte Real Number - case 'r8': // 8-Byte Real Number - case 'decimal': // Decimal - return self::PROPERTY_TYPE_FLOAT; - - break; - case 'empty': // Empty - case 'null': // Null - case 'lpstr': // LPSTR - case 'lpwstr': // LPWSTR - case 'bstr': // Basic String - return self::PROPERTY_TYPE_STRING; - - break; - case 'date': // Date and Time - case 'filetime': // File Time - return self::PROPERTY_TYPE_DATE; - - break; - case 'bool': // Boolean - return self::PROPERTY_TYPE_BOOLEAN; - - break; - case 'cy': // Currency - case 'error': // Error Status Code - case 'vector': // Vector - case 'array': // Array - case 'blob': // Binary Blob - case 'oblob': // Binary Blob Object - case 'stream': // Binary Stream - case 'ostream': // Binary Stream Object - case 'storage': // Binary Storage - case 'ostorage': // Binary Storage Object - case 'vstream': // Binary Versioned Stream - case 'clsid': // Class ID - case 'cf': // Clipboard Data - return self::PROPERTY_TYPE_UNKNOWN; - - break; - } - - return self::PROPERTY_TYPE_UNKNOWN; + return self::PROPERTY_TYPE_ARRAY[$propertyType] ?? self::PROPERTY_TYPE_UNKNOWN; } } diff --git a/src/PhpSpreadsheet/Document/Security.php b/src/PhpSpreadsheet/Document/Security.php index e13f5e72..279aed43 100644 --- a/src/PhpSpreadsheet/Document/Security.php +++ b/src/PhpSpreadsheet/Document/Security.php @@ -50,94 +50,57 @@ class Security /** * Is some sort of document security enabled? - * - * @return bool */ - public function isSecurityEnabled() + public function isSecurityEnabled(): bool { return $this->lockRevision || $this->lockStructure || $this->lockWindows; } - /** - * Get LockRevision. - * - * @return bool - */ - public function getLockRevision() + public function getLockRevision(): bool { return $this->lockRevision; } - /** - * Set LockRevision. - * - * @param bool $locked - * - * @return $this - */ - public function setLockRevision($locked) + public function setLockRevision(?bool $locked): self { - $this->lockRevision = $locked; + if ($locked !== null) { + $this->lockRevision = $locked; + } return $this; } - /** - * Get LockStructure. - * - * @return bool - */ - public function getLockStructure() + public function getLockStructure(): bool { return $this->lockStructure; } - /** - * Set LockStructure. - * - * @param bool $locked - * - * @return $this - */ - public function setLockStructure($locked) + public function setLockStructure(?bool $locked): self { - $this->lockStructure = $locked; + if ($locked !== null) { + $this->lockStructure = $locked; + } return $this; } - /** - * Get LockWindows. - * - * @return bool - */ - public function getLockWindows() + public function getLockWindows(): bool { return $this->lockWindows; } - /** - * Set LockWindows. - * - * @param bool $locked - * - * @return $this - */ - public function setLockWindows($locked) + public function setLockWindows(?bool $locked): self { - $this->lockWindows = $locked; + if ($locked !== null) { + $this->lockWindows = $locked; + } return $this; } - /** - * Get RevisionsPassword (hashed). - * - * @return string - */ - public function getRevisionsPassword() + public function getRevisionsPassword(): string { return $this->revisionsPassword; } @@ -150,22 +113,19 @@ class Security * * @return $this */ - public function setRevisionsPassword($password, $alreadyHashed = false) + public function setRevisionsPassword(?string $password, bool $alreadyHashed = false) { - if (!$alreadyHashed) { - $password = PasswordHasher::hashPassword($password); + if ($password !== null) { + if (!$alreadyHashed) { + $password = PasswordHasher::hashPassword($password); + } + $this->revisionsPassword = $password; } - $this->revisionsPassword = $password; return $this; } - /** - * Get WorkbookPassword (hashed). - * - * @return string - */ - public function getWorkbookPassword() + public function getWorkbookPassword(): string { return $this->workbookPassword; } @@ -178,28 +138,15 @@ class Security * * @return $this */ - public function setWorkbookPassword($password, $alreadyHashed = false) + public function setWorkbookPassword(?string $password, bool $alreadyHashed = false) { - if (!$alreadyHashed) { - $password = PasswordHasher::hashPassword($password); + if ($password !== null) { + if (!$alreadyHashed) { + $password = PasswordHasher::hashPassword($password); + } + $this->workbookPassword = $password; } - $this->workbookPassword = $password; return $this; } - - /** - * Implement PHP __clone to create a deep clone, not just a shallow copy. - */ - public function __clone() - { - $vars = get_object_vars($this); - foreach ($vars as $key => $value) { - if (is_object($value)) { - $this->$key = clone $value; - } else { - $this->$key = $value; - } - } - } } diff --git a/src/PhpSpreadsheet/HashTable.php b/src/PhpSpreadsheet/HashTable.php index f433e237..59209eed 100644 --- a/src/PhpSpreadsheet/HashTable.php +++ b/src/PhpSpreadsheet/HashTable.php @@ -2,12 +2,15 @@ namespace PhpOffice\PhpSpreadsheet; +/** + * @template T of IComparable + */ class HashTable { /** * HashTable elements. * - * @var array + * @var array */ protected $items = []; @@ -21,7 +24,7 @@ class HashTable /** * Create a new HashTable. * - * @param IComparable[] $source Optional source array to create HashTable from + * @param T[] $source Optional source array to create HashTable from */ public function __construct($source = null) { @@ -34,7 +37,7 @@ class HashTable /** * Add HashTable items from source. * - * @param IComparable[] $source Source array to create HashTable from + * @param T[] $source Source array to create HashTable from */ public function addFromSource(?array $source = null): void { @@ -51,7 +54,7 @@ class HashTable /** * Add HashTable item. * - * @param IComparable $source Item to add + * @param T $source Item to add */ public function add(IComparable $source): void { @@ -65,7 +68,7 @@ class HashTable /** * Remove HashTable item. * - * @param IComparable $source Item to remove + * @param T $source Item to remove */ public function remove(IComparable $source): void { @@ -109,7 +112,7 @@ class HashTable /** * Get index for hash code. * - * @return false|int|string Index (return should never be a string, but scrutinizer refuses to recognise that) + * @return false|int Index */ public function getIndexForHashCode(string $hashCode) { @@ -119,7 +122,7 @@ class HashTable /** * Get by index. * - * @return IComparable + * @return null|T */ public function getByIndex(int $index) { @@ -133,7 +136,7 @@ class HashTable /** * Get by hashcode. * - * @return IComparable + * @return null|T */ public function getByHashCode(string $hashCode) { @@ -147,7 +150,7 @@ class HashTable /** * HashTable to array. * - * @return IComparable[] + * @return T[] */ public function toArray() { @@ -161,8 +164,15 @@ class HashTable { $vars = get_object_vars($this); foreach ($vars as $key => $value) { - if (is_object($value)) { - $this->$key = clone $value; + // each member of this class is an array + if (is_array($value)) { + $array1 = $value; + foreach ($array1 as $key1 => $value1) { + if (is_object($value1)) { + $array1[$key1] = clone $value1; + } + } + $this->$key = $array1; } } } diff --git a/src/PhpSpreadsheet/Helper/Dimension.php b/src/PhpSpreadsheet/Helper/Dimension.php new file mode 100644 index 00000000..136ffd7f --- /dev/null +++ b/src/PhpSpreadsheet/Helper/Dimension.php @@ -0,0 +1,103 @@ + 96.0 / 2.54, + self::UOM_MILLIMETERS => 96.0 / 25.4, + self::UOM_INCHES => 96.0, + self::UOM_PIXELS => 1.0, + self::UOM_POINTS => 96.0 / 72, + self::UOM_PICA => 96.0 * 12 / 72, + ]; + + /** + * Based on a standard column width of 8.54 units in MS Excel. + */ + const RELATIVE_UNITS = [ + 'em' => 10.0 / 8.54, + 'ex' => 10.0 / 8.54, + 'ch' => 10.0 / 8.54, + 'rem' => 10.0 / 8.54, + 'vw' => 8.54, + 'vh' => 8.54, + 'vmin' => 8.54, + 'vmax' => 8.54, + '%' => 8.54 / 100, + ]; + + /** + * @var float|int If this is a width, then size is measured in pixels (if is set) + * or in Excel's default column width units if $unit is null. + * If this is a height, then size is measured in pixels () + * or in points () if $unit is null. + */ + protected $size; + + /** + * @var null|string + */ + protected $unit; + + public function __construct(string $dimension) + { + [$size, $unit] = sscanf($dimension, '%[1234567890.]%s'); + $unit = strtolower(trim($unit)); + + // If a UoM is specified, then convert the size to pixels for internal storage + if (isset(self::ABSOLUTE_UNITS[$unit])) { + $size *= self::ABSOLUTE_UNITS[$unit]; + $this->unit = self::UOM_PIXELS; + } elseif (isset(self::RELATIVE_UNITS[$unit])) { + $size *= self::RELATIVE_UNITS[$unit]; + $size = round($size, 4); + } + + $this->size = $size; + } + + public function width(): float + { + return (float) ($this->unit === null) + ? $this->size + : round(Drawing::pixelsToCellDimension((int) $this->size, new Font(false)), 4); + } + + public function height(): float + { + return (float) ($this->unit === null) + ? $this->size + : $this->toUnit(self::UOM_POINTS); + } + + public function toUnit(string $unitOfMeasure): float + { + $unitOfMeasure = strtolower($unitOfMeasure); + if (!array_key_exists($unitOfMeasure, self::ABSOLUTE_UNITS)) { + throw new Exception("{$unitOfMeasure} is not a vaid unit of measure"); + } + + $size = $this->size; + if ($this->unit === null) { + $size = Drawing::cellDimensionToPixels($size, new Font(false)); + } + + return $size / self::ABSOLUTE_UNITS[$unitOfMeasure]; + } +} diff --git a/src/PhpSpreadsheet/Helper/Html.php b/src/PhpSpreadsheet/Helper/Html.php index 908241d6..73a3308c 100644 --- a/src/PhpSpreadsheet/Helper/Html.php +++ b/src/PhpSpreadsheet/Helper/Html.php @@ -684,7 +684,7 @@ class Html $this->stringData = ''; } - protected function rgbToColour($rgbValue) + protected function rgbToColour(string $rgbValue): string { preg_match_all('/\d+/', $rgbValue, $values); foreach ($values[0] as &$value) { @@ -711,7 +711,7 @@ class Html } elseif (strpos(trim($attributeValue), '#') === 0) { $this->$attributeName = ltrim($attributeValue, '#'); } else { - $this->$attributeName = $this->colourNameLookup($attributeValue); + $this->$attributeName = static::colourNameLookup($attributeValue); } } else { $this->$attributeName = $attributeValue; diff --git a/src/PhpSpreadsheet/Helper/Sample.php b/src/PhpSpreadsheet/Helper/Sample.php index a91b195e..257a02a8 100644 --- a/src/PhpSpreadsheet/Helper/Sample.php +++ b/src/PhpSpreadsheet/Helper/Sample.php @@ -5,7 +5,6 @@ namespace PhpOffice\PhpSpreadsheet\Helper; use PhpOffice\PhpSpreadsheet\IOFactory; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\IWriter; -use PhpOffice\PhpSpreadsheet\Writer\Pdf; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use RecursiveRegexIterator; @@ -71,7 +70,7 @@ class Sample /** * Returns an array of all known samples. * - * @return string[] [$name => $path] + * @return string[][] [$name => $path] */ public function getSamples() { @@ -119,11 +118,6 @@ class Sample foreach ($writers as $writerType) { $path = $this->getFilename($filename, mb_strtolower($writerType)); $writer = IOFactory::createWriter($spreadsheet, $writerType); - if ($writer instanceof Pdf) { - // PDF writer needs temporary directory - $tempDir = $this->getTemporaryFolder(); - $writer->setTempDir($tempDir); - } $callStartTime = microtime(true); $writer->save($path); $this->logWrite($writer, $path, $callStartTime); @@ -132,6 +126,11 @@ class Sample $this->logEndingNotes(); } + protected function isDirOrMkdir(string $folder): bool + { + return \is_dir($folder) || \mkdir($folder); + } + /** * Returns the temporary directory and make sure it exists. * @@ -140,10 +139,8 @@ class Sample private function getTemporaryFolder() { $tempFolder = sys_get_temp_dir() . '/phpspreadsheet'; - if (!is_dir($tempFolder)) { - if (!mkdir($tempFolder) && !is_dir($tempFolder)) { - throw new RuntimeException(sprintf('Directory "%s" was not created', $tempFolder)); - } + if (!$this->isDirOrMkdir($tempFolder)) { + throw new RuntimeException(sprintf('Directory "%s" was not created', $tempFolder)); } return $tempFolder; diff --git a/src/PhpSpreadsheet/Helper/Size.php b/src/PhpSpreadsheet/Helper/Size.php index 80b6fbd7..12ba4ef7 100644 --- a/src/PhpSpreadsheet/Helper/Size.php +++ b/src/PhpSpreadsheet/Helper/Size.php @@ -6,10 +6,19 @@ class Size { const REGEXP_SIZE_VALIDATION = '/^(?P\d*\.?\d+)(?Ppt|px|em)?$/i'; + /** + * @var bool + */ protected $valid; + /** + * @var string + */ protected $size = ''; + /** + * @var string + */ protected $unit = ''; public function __construct(string $size) diff --git a/src/PhpSpreadsheet/IOFactory.php b/src/PhpSpreadsheet/IOFactory.php index 0fb0e89b..91613cb4 100644 --- a/src/PhpSpreadsheet/IOFactory.php +++ b/src/PhpSpreadsheet/IOFactory.php @@ -67,13 +67,15 @@ abstract class IOFactory } /** - * Loads Spreadsheet from file using automatic IReader resolution. + * Loads Spreadsheet from file using automatic Reader\IReader resolution. + * + * @param string $filename The name of the spreadsheet file */ - public static function load(string $filename): Spreadsheet + public static function load(string $filename, int $flags = 0): Spreadsheet { $reader = self::createReaderForFile($filename); - return $reader->load($filename); + return $reader->load($filename, $flags); } /** @@ -102,7 +104,7 @@ abstract class IOFactory $reader = self::createReader($guessedReader); // Let's see if we are lucky - if (isset($reader) && $reader->canRead($filename)) { + if ($reader->canRead($filename)) { return $reader; } } diff --git a/src/PhpSpreadsheet/NamedFormula.php b/src/PhpSpreadsheet/NamedFormula.php index eeddbbcb..500151f0 100644 --- a/src/PhpSpreadsheet/NamedFormula.php +++ b/src/PhpSpreadsheet/NamedFormula.php @@ -17,7 +17,7 @@ class NamedFormula extends DefinedName ?Worksheet $scope = null ) { // Validate data - if (empty($formula)) { + if (!isset($formula)) { throw new Exception('You must specify a Formula value for a Named Formula'); } parent::__construct($name, $worksheet, $formula, $localOnly, $scope); diff --git a/src/PhpSpreadsheet/Reader/BaseReader.php b/src/PhpSpreadsheet/Reader/BaseReader.php index 9804b57b..2ad8e6b2 100644 --- a/src/PhpSpreadsheet/Reader/BaseReader.php +++ b/src/PhpSpreadsheet/Reader/BaseReader.php @@ -38,7 +38,7 @@ abstract class BaseReader implements IReader * Restrict which sheets should be loaded? * This property holds an array of worksheet names to be loaded. If null, then all worksheets will be loaded. * - * @var array of string + * @var null|string[] */ protected $loadSheetsOnly; @@ -137,6 +137,13 @@ abstract class BaseReader implements IReader return $this->securityScanner; } + protected function processFlags(int $flags): void + { + if (((bool) ($flags & self::LOAD_WITH_CHARTS)) === true) { + $this->setIncludeCharts(true); + } + } + /** * Open file for reading. * diff --git a/src/PhpSpreadsheet/Reader/Csv.php b/src/PhpSpreadsheet/Reader/Csv.php index 25a660c4..e0f2c451 100644 --- a/src/PhpSpreadsheet/Reader/Csv.php +++ b/src/PhpSpreadsheet/Reader/Csv.php @@ -2,13 +2,16 @@ namespace PhpOffice\PhpSpreadsheet\Reader; -use InvalidArgumentException; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Reader\Csv\Delimiter; +use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; class Csv extends BaseReader { + const DEFAULT_FALLBACK_ENCODING = 'CP1252'; + const GUESS_ENCODING = 'guess'; const UTF8_BOM = "\xEF\xBB\xBF"; const UTF8_BOM_LEN = 3; const UTF16BE_BOM = "\xfe\xff"; @@ -32,10 +35,17 @@ class Csv extends BaseReader private $inputEncoding = 'UTF-8'; /** - * Delimiter. + * Fallback encoding if guess strikes out. * * @var string */ + private $fallbackEncoding = self::DEFAULT_FALLBACK_ENCODING; + + /** + * Delimiter. + * + * @var ?string + */ private $delimiter; /** @@ -66,38 +76,65 @@ class Csv extends BaseReader */ private $escapeCharacter = '\\'; + /** + * Callback for setting defaults in construction. + * + * @var ?callable + */ + private static $constructorCallback; + /** * Create a new CSV Reader instance. */ public function __construct() { parent::__construct(); + $callback = self::$constructorCallback; + if ($callback !== null) { + $callback($this); + } } /** - * Set input encoding. + * Set a callback to change the defaults. * - * @param string $encoding Input encoding, eg: 'UTF-8' - * - * @return $this + * The callback must accept the Csv Reader object as the first parameter, + * and it should return void. */ - public function setInputEncoding($encoding) + public static function setConstructorCallback(?callable $callback): void + { + self::$constructorCallback = $callback; + } + + public static function getConstructorCallback(): ?callable + { + return self::$constructorCallback; + } + + public function setInputEncoding(string $encoding): self { $this->inputEncoding = $encoding; return $this; } - /** - * Get input encoding. - * - * @return string - */ - public function getInputEncoding() + public function getInputEncoding(): string { return $this->inputEncoding; } + public function setFallbackEncoding(string $pValue): self + { + $this->fallbackEncoding = $pValue; + + return $this; + } + + public function getFallbackEncoding(): string + { + return $this->fallbackEncoding; + } + /** * Move filepointer past any BOM marker. */ @@ -138,126 +175,30 @@ class Csv extends BaseReader return; } - $potentialDelimiters = [',', ';', "\t", '|', ':', ' ', '~']; - $counts = []; - foreach ($potentialDelimiters as $delimiter) { - $counts[$delimiter] = []; - } - - // Count how many times each of the potential delimiters appears in each line - $numberLines = 0; - while (($line = $this->getNextLine()) !== false && (++$numberLines < 1000)) { - $countLine = []; - for ($i = strlen($line) - 1; $i >= 0; --$i) { - $char = $line[$i]; - if (isset($counts[$char])) { - if (!isset($countLine[$char])) { - $countLine[$char] = 0; - } - ++$countLine[$char]; - } - } - foreach ($potentialDelimiters as $delimiter) { - $counts[$delimiter][] = $countLine[$delimiter] - ?? 0; - } - } + $inferenceEngine = new Delimiter($this->fileHandle, $this->escapeCharacter, $this->enclosure); // If number of lines is 0, nothing to infer : fall back to the default - if ($numberLines === 0) { - $this->delimiter = reset($potentialDelimiters); + if ($inferenceEngine->linesCounted() === 0) { + $this->delimiter = $inferenceEngine->getDefaultDelimiter(); $this->skipBOM(); return; } - // Calculate the mean square deviations for each delimiter (ignoring delimiters that haven't been found consistently) - $meanSquareDeviations = []; - $middleIdx = floor(($numberLines - 1) / 2); - - foreach ($potentialDelimiters as $delimiter) { - $series = $counts[$delimiter]; - sort($series); - - $median = ($numberLines % 2) - ? $series[$middleIdx] - : ($series[$middleIdx] + $series[$middleIdx + 1]) / 2; - - if ($median === 0) { - continue; - } - - $meanSquareDeviations[$delimiter] = array_reduce( - $series, - function ($sum, $value) use ($median) { - return $sum + ($value - $median) ** 2; - } - ) / count($series); - } - - // ... and pick the delimiter with the smallest mean square deviation (in case of ties, the order in potentialDelimiters is respected) - $min = INF; - foreach ($potentialDelimiters as $delimiter) { - if (!isset($meanSquareDeviations[$delimiter])) { - continue; - } - - if ($meanSquareDeviations[$delimiter] < $min) { - $min = $meanSquareDeviations[$delimiter]; - $this->delimiter = $delimiter; - } - } + $this->delimiter = $inferenceEngine->infer(); // If no delimiter could be detected, fall back to the default if ($this->delimiter === null) { - $this->delimiter = reset($potentialDelimiters); + $this->delimiter = $inferenceEngine->getDefaultDelimiter(); } $this->skipBOM(); } - /** - * Get the next full line from the file. - * - * @return false|string - */ - private function getNextLine() - { - $line = ''; - $enclosure = ($this->escapeCharacter === '' ? '' - : ('(?escapeCharacter, '/') . ')')) - . preg_quote($this->enclosure, '/'); - - do { - // Get the next line in the file - $newLine = fgets($this->fileHandle); - - // Return false if there is no next line - if ($newLine === false) { - return false; - } - - // Add the new line to the line passed in - $line = $line . $newLine; - - // Drop everything that is enclosed to avoid counting false positives in enclosures - $line = preg_replace('/(' . $enclosure . '.*' . $enclosure . ')/Us', '', $line); - - // See if we have any enclosures left in the line - // if we still have an enclosure then we need to read the next line as well - } while (preg_match('/(' . $enclosure . ')/', $line) > 0); - - return $line; - } - /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). - * - * @param string $filename - * - * @return array */ - public function listWorksheetInfo($filename) + public function listWorksheetInfo(string $filename): array { // Open file $this->openFileOrMemory($filename); @@ -276,9 +217,11 @@ class Csv extends BaseReader $worksheetInfo[0]['totalColumns'] = 0; // Loop through each line of the file in turn - while (($rowData = fgetcsv($fileHandle, 0, $this->delimiter, $this->enclosure, $this->escapeCharacter)) !== false) { + $rowData = fgetcsv($fileHandle, 0, $this->delimiter ?? '', $this->enclosure, $this->escapeCharacter); + while (is_array($rowData)) { ++$worksheetInfo[0]['totalRows']; $worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], count($rowData) - 1); + $rowData = fgetcsv($fileHandle, 0, $this->delimiter ?? '', $this->enclosure, $this->escapeCharacter); } $worksheetInfo[0]['lastColumnLetter'] = Coordinate::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex'] + 1); @@ -293,12 +236,12 @@ class Csv extends BaseReader /** * Loads Spreadsheet from file. * - * @param string $filename - * * @return Spreadsheet */ - public function load($filename) + public function load(string $filename, int $flags = 0) { + $this->processFlags($flags); + // Create new Spreadsheet $spreadsheet = new Spreadsheet(); @@ -306,35 +249,49 @@ class Csv extends BaseReader return $this->loadIntoExisting($filename, $spreadsheet); } - private function openFileOrMemory($filename): void + private function openFileOrMemory(string $filename): void { // Open file $fhandle = $this->canRead($filename); if (!$fhandle) { throw new Exception($filename . ' is an Invalid Spreadsheet file.'); } + if ($this->inputEncoding === self::GUESS_ENCODING) { + $this->inputEncoding = self::guessEncoding($filename, $this->fallbackEncoding); + } $this->openFile($filename); if ($this->inputEncoding !== 'UTF-8') { fclose($this->fileHandle); $entireFile = file_get_contents($filename); $this->fileHandle = fopen('php://memory', 'r+b'); - $data = StringHelper::convertEncoding($entireFile, 'UTF-8', $this->inputEncoding); - fwrite($this->fileHandle, $data); - $this->skipBOM(); + if ($this->fileHandle !== false && $entireFile !== false) { + $data = StringHelper::convertEncoding($entireFile, 'UTF-8', $this->inputEncoding); + fwrite($this->fileHandle, $data); + $this->skipBOM(); + } } } + private static function setAutoDetect(?string $value): ?string + { + $retVal = null; + if ($value !== null) { + $retVal2 = @ini_set('auto_detect_line_endings', $value); + if (is_string($retVal2)) { + $retVal = $retVal2; + } + } + + return $retVal; + } + /** * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. - * - * @param string $filename - * - * @return Spreadsheet */ - public function loadIntoExisting($filename, Spreadsheet $spreadsheet) + public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Spreadsheet { - $lineEnding = ini_get('auto_detect_line_endings'); - ini_set('auto_detect_line_endings', true); + // Deprecated in Php8.1 + $iniset = self::setAutoDetect('1'); // Open file $this->openFileOrMemory($filename); @@ -356,11 +313,13 @@ class Csv extends BaseReader $outRow = 0; // Loop through each line of the file in turn - while (($rowData = fgetcsv($fileHandle, 0, $this->delimiter, $this->enclosure, $this->escapeCharacter)) !== false) { + $rowData = fgetcsv($fileHandle, 0, $this->delimiter ?? '', $this->enclosure, $this->escapeCharacter); + while (is_array($rowData)) { $noOutputYet = true; $columnLetter = 'A'; foreach ($rowData as $rowDatum) { - if ($rowDatum != '' && $this->readFilter->readCell($columnLetter, $currentRow)) { + self::convertBoolean($rowDatum); + if ($rowDatum !== '' && $this->readFilter->readCell($columnLetter, $currentRow)) { if ($this->contiguous) { if ($noOutputYet) { $noOutputYet = false; @@ -374,60 +333,55 @@ class Csv extends BaseReader } ++$columnLetter; } + $rowData = fgetcsv($fileHandle, 0, $this->delimiter ?? '', $this->enclosure, $this->escapeCharacter); ++$currentRow; } // Close file fclose($fileHandle); - ini_set('auto_detect_line_endings', $lineEnding); + self::setAutoDetect($iniset); // Return return $spreadsheet; } /** - * Get delimiter. + * Convert string true/false to boolean, and null to null-string. * - * @return string + * @param mixed $rowDatum */ - public function getDelimiter() + private static function convertBoolean(&$rowDatum): void + { + if (is_string($rowDatum)) { + if (strcasecmp('true', $rowDatum) === 0) { + $rowDatum = true; + } elseif (strcasecmp('false', $rowDatum) === 0) { + $rowDatum = false; + } + } elseif ($rowDatum === null) { + $rowDatum = ''; + } + } + + public function getDelimiter(): ?string { return $this->delimiter; } - /** - * Set delimiter. - * - * @param string $delimiter Delimiter, eg: ',' - * - * @return $this - */ - public function setDelimiter($delimiter) + public function setDelimiter(?string $delimiter): self { $this->delimiter = $delimiter; return $this; } - /** - * Get enclosure. - * - * @return string - */ - public function getEnclosure() + public function getEnclosure(): string { return $this->enclosure; } - /** - * Set enclosure. - * - * @param string $enclosure Enclosure, defaults to " - * - * @return $this - */ - public function setEnclosure($enclosure) + public function setEnclosure(string $enclosure): self { if ($enclosure == '') { $enclosure = '"'; @@ -437,91 +391,64 @@ class Csv extends BaseReader return $this; } - /** - * Get sheet index. - * - * @return int - */ - public function getSheetIndex() + public function getSheetIndex(): int { return $this->sheetIndex; } - /** - * Set sheet index. - * - * @param int $indexValue Sheet index - * - * @return $this - */ - public function setSheetIndex($indexValue) + public function setSheetIndex(int $indexValue): self { $this->sheetIndex = $indexValue; return $this; } - /** - * Set Contiguous. - * - * @param bool $contiguous - * - * @return $this - */ - public function setContiguous($contiguous) + public function setContiguous(bool $contiguous): self { $this->contiguous = (bool) $contiguous; return $this; } - /** - * Get Contiguous. - * - * @return bool - */ - public function getContiguous() + public function getContiguous(): bool { return $this->contiguous; } - /** - * Set escape backslashes. - * - * @param string $escapeCharacter - * - * @return $this - */ - public function setEscapeCharacter($escapeCharacter) + public function setEscapeCharacter(string $escapeCharacter): self { $this->escapeCharacter = $escapeCharacter; return $this; } - /** - * Get escape backslashes. - * - * @return string - */ - public function getEscapeCharacter() + public function getEscapeCharacter(): string { return $this->escapeCharacter; } /** - * Can the current IReader read the file? + * Scrutinizer believes, incorrectly, that the specific pathinfo + * call in canRead can return something other than an array. + * Phpstan knows better. + * This function satisfies both. * - * @param string $filename - * - * @return bool + * @param mixed $extension */ - public function canRead($filename) + private static function extractStringLower($extension): string + { + return is_string($extension) ? strtolower($extension) : ''; + } + + /** + * Can the current IReader read the file? + */ + public function canRead(string $filename): bool { // Check if file exists try { $this->openFile($filename); - } catch (InvalidArgumentException $e) { + } catch (ReaderException $e) { return false; } @@ -594,7 +521,7 @@ class Csv extends BaseReader return $encoding; } - public static function guessEncoding(string $filename, string $dflt = 'CP1252'): string + public static function guessEncoding(string $filename, string $dflt = self::DEFAULT_FALLBACK_ENCODING): string { $encoding = self::guessEncodingBom($filename); if ($encoding === '') { diff --git a/src/PhpSpreadsheet/Reader/Csv/Delimiter.php b/src/PhpSpreadsheet/Reader/Csv/Delimiter.php new file mode 100644 index 00000000..fc298957 --- /dev/null +++ b/src/PhpSpreadsheet/Reader/Csv/Delimiter.php @@ -0,0 +1,151 @@ +fileHandle = $fileHandle; + $this->escapeCharacter = $escapeCharacter; + $this->enclosure = $enclosure; + + $this->countPotentialDelimiters(); + } + + public function getDefaultDelimiter(): string + { + return self::POTENTIAL_DELIMETERS[0]; + } + + public function linesCounted(): int + { + return $this->numberLines; + } + + protected function countPotentialDelimiters(): void + { + $this->counts = array_fill_keys(self::POTENTIAL_DELIMETERS, []); + $delimiterKeys = array_flip(self::POTENTIAL_DELIMETERS); + + // Count how many times each of the potential delimiters appears in each line + $this->numberLines = 0; + while (($line = $this->getNextLine()) !== false && (++$this->numberLines < 1000)) { + $this->countDelimiterValues($line, $delimiterKeys); + } + } + + protected function countDelimiterValues(string $line, array $delimiterKeys): void + { + $splitString = str_split($line, 1); + if (is_array($splitString)) { + $distribution = array_count_values($splitString); + $countLine = array_intersect_key($distribution, $delimiterKeys); + + foreach (self::POTENTIAL_DELIMETERS as $delimiter) { + $this->counts[$delimiter][] = $countLine[$delimiter] ?? 0; + } + } + } + + public function infer(): ?string + { + // Calculate the mean square deviations for each delimiter + // (ignoring delimiters that haven't been found consistently) + $meanSquareDeviations = []; + $middleIdx = floor(($this->numberLines - 1) / 2); + + foreach (self::POTENTIAL_DELIMETERS as $delimiter) { + $series = $this->counts[$delimiter]; + sort($series); + + $median = ($this->numberLines % 2) + ? $series[$middleIdx] + : ($series[$middleIdx] + $series[$middleIdx + 1]) / 2; + + if ($median === 0) { + continue; + } + + $meanSquareDeviations[$delimiter] = array_reduce( + $series, + function ($sum, $value) use ($median) { + return $sum + ($value - $median) ** 2; + } + ) / count($series); + } + + // ... and pick the delimiter with the smallest mean square deviation + // (in case of ties, the order in potentialDelimiters is respected) + $min = INF; + foreach (self::POTENTIAL_DELIMETERS as $delimiter) { + if (!isset($meanSquareDeviations[$delimiter])) { + continue; + } + + if ($meanSquareDeviations[$delimiter] < $min) { + $min = $meanSquareDeviations[$delimiter]; + $this->delimiter = $delimiter; + } + } + + return $this->delimiter; + } + + /** + * Get the next full line from the file. + * + * @return false|string + */ + public function getNextLine() + { + $line = ''; + $enclosure = ($this->escapeCharacter === '' ? '' + : ('(?escapeCharacter, '/') . ')')) + . preg_quote($this->enclosure, '/'); + + do { + // Get the next line in the file + $newLine = fgets($this->fileHandle); + + // Return false if there is no next line + if ($newLine === false) { + return false; + } + + // Add the new line to the line passed in + $line = $line . $newLine; + + // Drop everything that is enclosed to avoid counting false positives in enclosures + $line = preg_replace('/(' . $enclosure . '.*' . $enclosure . ')/Us', '', $line); + + // See if we have any enclosures left in the line + // if we still have an enclosure then we need to read the next line as well + } while (preg_match('/(' . $enclosure . ')/', $line ?? '') > 0); + + return $line ?? false; + } +} diff --git a/src/PhpSpreadsheet/Reader/Gnumeric.php b/src/PhpSpreadsheet/Reader/Gnumeric.php index 7f583663..673a8a07 100644 --- a/src/PhpSpreadsheet/Reader/Gnumeric.php +++ b/src/PhpSpreadsheet/Reader/Gnumeric.php @@ -6,25 +6,33 @@ use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Reader\Gnumeric\PageSetup; +use PhpOffice\PhpSpreadsheet\Reader\Gnumeric\Properties; +use PhpOffice\PhpSpreadsheet\Reader\Gnumeric\Styles; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; use PhpOffice\PhpSpreadsheet\ReferenceHelper; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Settings; -use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Spreadsheet; -use PhpOffice\PhpSpreadsheet\Style\Alignment; -use PhpOffice\PhpSpreadsheet\Style\Border; -use PhpOffice\PhpSpreadsheet\Style\Borders; -use PhpOffice\PhpSpreadsheet\Style\Fill; -use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; use XMLReader; class Gnumeric extends BaseReader { - private const UOM_CONVERSION_POINTS_TO_CENTIMETERS = 0.03527777778; + const NAMESPACE_GNM = 'http://www.gnumeric.org/v10.dtd'; // gmr in old sheets + + const NAMESPACE_XSI = 'http://www.w3.org/2001/XMLSchema-instance'; + + const NAMESPACE_OFFICE = 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'; + + const NAMESPACE_XLINK = 'http://www.w3.org/1999/xlink'; + + const NAMESPACE_DC = 'http://purl.org/dc/elements/1.1/'; + + const NAMESPACE_META = 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'; + + const NAMESPACE_OOO = 'http://openoffice.org/2004/office'; /** * Shared Expressions. @@ -40,15 +48,22 @@ class Gnumeric extends BaseReader */ private $spreadsheet; + /** @var ReferenceHelper */ private $referenceHelper; - /** - * Namespace shared across all functions. - * It is 'gnm', except for really old sheets which use 'gmr'. - * - * @var string - */ - private $gnm = 'gnm'; + /** @var array */ + public static $mappings = [ + 'dataType' => [ + '10' => DataType::TYPE_NULL, + '20' => DataType::TYPE_BOOL, + '30' => DataType::TYPE_NUMERIC, // Integer doesn't exist in Excel + '40' => DataType::TYPE_NUMERIC, // Float + '50' => DataType::TYPE_ERROR, + '60' => DataType::TYPE_STRING, + //'70': // Cell Range + //'80': // Array + ], + ]; /** * Create a new Gnumeric. @@ -62,30 +77,27 @@ class Gnumeric extends BaseReader /** * Can the current IReader read the file? - * - * @param string $filename - * - * @return bool */ - public function canRead($filename) + public function canRead(string $filename): bool { - File::assertFile($filename); - // Check if gzlib functions are available - $data = ''; - if (function_exists('gzread')) { + if (File::testFileNoThrow($filename) && function_exists('gzread')) { // Read signature data (first 3 bytes) $fh = fopen($filename, 'rb'); - $data = fread($fh, 2); - fclose($fh); + if ($fh !== false) { + $data = fread($fh, 2); + fclose($fh); + } } - return $data == chr(0x1F) . chr(0x8B); + return isset($data) && $data === chr(0x1F) . chr(0x8B); } - private static function matchXml(string $name, string $field): bool + private static function matchXml(XMLReader $xml, string $expectedLocalName): bool { - return 1 === preg_match("/^(gnm|gmr):$field$/", $name); + return $xml->namespaceURI === self::NAMESPACE_GNM + && $xml->localName === $expectedLocalName + && $xml->nodeType === XMLReader::ELEMENT; } /** @@ -105,10 +117,10 @@ class Gnumeric extends BaseReader $worksheetNames = []; while ($xml->read()) { - if (self::matchXml($xml->name, 'SheetName') && $xml->nodeType == XMLReader::ELEMENT) { + if (self::matchXml($xml, 'SheetName')) { $xml->read(); // Move onto the value node $worksheetNames[] = (string) $xml->value; - } elseif (self::matchXml($xml->name, 'Sheets')) { + } elseif (self::matchXml($xml, 'Sheets')) { // break out of the loop once we've got our sheet names rather than parse the entire file break; } @@ -134,7 +146,7 @@ class Gnumeric extends BaseReader $worksheetInfo = []; while ($xml->read()) { - if (self::matchXml($xml->name, 'Sheet') && $xml->nodeType == XMLReader::ELEMENT) { + if (self::matchXml($xml, 'Sheet')) { $tmpInfo = [ 'worksheetName' => '', 'lastColumnLetter' => 'A', @@ -144,20 +156,18 @@ class Gnumeric extends BaseReader ]; while ($xml->read()) { - if ($xml->nodeType == XMLReader::ELEMENT) { - if (self::matchXml($xml->name, 'Name')) { - $xml->read(); // Move onto the value node - $tmpInfo['worksheetName'] = (string) $xml->value; - } elseif (self::matchXml($xml->name, 'MaxCol')) { - $xml->read(); // Move onto the value node - $tmpInfo['lastColumnIndex'] = (int) $xml->value; - $tmpInfo['totalColumns'] = (int) $xml->value + 1; - } elseif (self::matchXml($xml->name, 'MaxRow')) { - $xml->read(); // Move onto the value node - $tmpInfo['totalRows'] = (int) $xml->value + 1; + if (self::matchXml($xml, 'Name')) { + $xml->read(); // Move onto the value node + $tmpInfo['worksheetName'] = (string) $xml->value; + } elseif (self::matchXml($xml, 'MaxCol')) { + $xml->read(); // Move onto the value node + $tmpInfo['lastColumnIndex'] = (int) $xml->value; + $tmpInfo['totalColumns'] = (int) $xml->value + 1; + } elseif (self::matchXml($xml, 'MaxRow')) { + $xml->read(); // Move onto the value node + $tmpInfo['totalRows'] = (int) $xml->value + 1; - break; - } + break; } } $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1); @@ -187,245 +197,43 @@ class Gnumeric extends BaseReader return $data; } - private static $mappings = [ - 'borderStyle' => [ - '0' => Border::BORDER_NONE, - '1' => Border::BORDER_THIN, - '2' => Border::BORDER_MEDIUM, - '3' => Border::BORDER_SLANTDASHDOT, - '4' => Border::BORDER_DASHED, - '5' => Border::BORDER_THICK, - '6' => Border::BORDER_DOUBLE, - '7' => Border::BORDER_DOTTED, - '8' => Border::BORDER_MEDIUMDASHED, - '9' => Border::BORDER_DASHDOT, - '10' => Border::BORDER_MEDIUMDASHDOT, - '11' => Border::BORDER_DASHDOTDOT, - '12' => Border::BORDER_MEDIUMDASHDOTDOT, - '13' => Border::BORDER_MEDIUMDASHDOTDOT, - ], - 'dataType' => [ - '10' => DataType::TYPE_NULL, - '20' => DataType::TYPE_BOOL, - '30' => DataType::TYPE_NUMERIC, // Integer doesn't exist in Excel - '40' => DataType::TYPE_NUMERIC, // Float - '50' => DataType::TYPE_ERROR, - '60' => DataType::TYPE_STRING, - //'70': // Cell Range - //'80': // Array - ], - 'fillType' => [ - '1' => Fill::FILL_SOLID, - '2' => Fill::FILL_PATTERN_DARKGRAY, - '3' => Fill::FILL_PATTERN_MEDIUMGRAY, - '4' => Fill::FILL_PATTERN_LIGHTGRAY, - '5' => Fill::FILL_PATTERN_GRAY125, - '6' => Fill::FILL_PATTERN_GRAY0625, - '7' => Fill::FILL_PATTERN_DARKHORIZONTAL, // horizontal stripe - '8' => Fill::FILL_PATTERN_DARKVERTICAL, // vertical stripe - '9' => Fill::FILL_PATTERN_DARKDOWN, // diagonal stripe - '10' => Fill::FILL_PATTERN_DARKUP, // reverse diagonal stripe - '11' => Fill::FILL_PATTERN_DARKGRID, // diagoanl crosshatch - '12' => Fill::FILL_PATTERN_DARKTRELLIS, // thick diagonal crosshatch - '13' => Fill::FILL_PATTERN_LIGHTHORIZONTAL, - '14' => Fill::FILL_PATTERN_LIGHTVERTICAL, - '15' => Fill::FILL_PATTERN_LIGHTUP, - '16' => Fill::FILL_PATTERN_LIGHTDOWN, - '17' => Fill::FILL_PATTERN_LIGHTGRID, // thin horizontal crosshatch - '18' => Fill::FILL_PATTERN_LIGHTTRELLIS, // thin diagonal crosshatch - ], - 'horizontal' => [ - '1' => Alignment::HORIZONTAL_GENERAL, - '2' => Alignment::HORIZONTAL_LEFT, - '4' => Alignment::HORIZONTAL_RIGHT, - '8' => Alignment::HORIZONTAL_CENTER, - '16' => Alignment::HORIZONTAL_CENTER_CONTINUOUS, - '32' => Alignment::HORIZONTAL_JUSTIFY, - '64' => Alignment::HORIZONTAL_CENTER_CONTINUOUS, - ], - 'underline' => [ - '1' => Font::UNDERLINE_SINGLE, - '2' => Font::UNDERLINE_DOUBLE, - '3' => Font::UNDERLINE_SINGLEACCOUNTING, - '4' => Font::UNDERLINE_DOUBLEACCOUNTING, - ], - 'vertical' => [ - '1' => Alignment::VERTICAL_TOP, - '2' => Alignment::VERTICAL_BOTTOM, - '4' => Alignment::VERTICAL_CENTER, - '8' => Alignment::VERTICAL_JUSTIFY, - ], - ]; - public static function gnumericMappings(): array { - return self::$mappings; - } - - private function docPropertiesOld(SimpleXMLElement $gnmXML): void - { - $docProps = $this->spreadsheet->getProperties(); - foreach ($gnmXML->Summary->Item as $summaryItem) { - $propertyName = $summaryItem->name; - $propertyValue = $summaryItem->{'val-string'}; - switch ($propertyName) { - case 'title': - $docProps->setTitle(trim($propertyValue)); - - break; - case 'comments': - $docProps->setDescription(trim($propertyValue)); - - break; - case 'keywords': - $docProps->setKeywords(trim($propertyValue)); - - break; - case 'category': - $docProps->setCategory(trim($propertyValue)); - - break; - case 'manager': - $docProps->setManager(trim($propertyValue)); - - break; - case 'author': - $docProps->setCreator(trim($propertyValue)); - $docProps->setLastModifiedBy(trim($propertyValue)); - - break; - case 'company': - $docProps->setCompany(trim($propertyValue)); - - break; - } - } - } - - private function docPropertiesDC(SimpleXMLElement $officePropertyDC): void - { - $docProps = $this->spreadsheet->getProperties(); - foreach ($officePropertyDC as $propertyName => $propertyValue) { - $propertyValue = trim((string) $propertyValue); - switch ($propertyName) { - case 'title': - $docProps->setTitle($propertyValue); - - break; - case 'subject': - $docProps->setSubject($propertyValue); - - break; - case 'creator': - $docProps->setCreator($propertyValue); - $docProps->setLastModifiedBy($propertyValue); - - break; - case 'date': - $creationDate = strtotime($propertyValue); - $docProps->setCreated($creationDate); - $docProps->setModified($creationDate); - - break; - case 'description': - $docProps->setDescription($propertyValue); - - break; - } - } - } - - private function docPropertiesMeta(SimpleXMLElement $officePropertyMeta, array $namespacesMeta): void - { - $docProps = $this->spreadsheet->getProperties(); - foreach ($officePropertyMeta as $propertyName => $propertyValue) { - $attributes = $propertyValue->attributes($namespacesMeta['meta']); - $propertyValue = trim((string) $propertyValue); - switch ($propertyName) { - case 'keyword': - $docProps->setKeywords($propertyValue); - - break; - case 'initial-creator': - $docProps->setCreator($propertyValue); - $docProps->setLastModifiedBy($propertyValue); - - break; - case 'creation-date': - $creationDate = strtotime($propertyValue); - $docProps->setCreated($creationDate); - $docProps->setModified($creationDate); - - break; - case 'user-defined': - [, $attrName] = explode(':', $attributes['name']); - switch ($attrName) { - case 'publisher': - $docProps->setCompany($propertyValue); - - break; - case 'category': - $docProps->setCategory($propertyValue); - - break; - case 'manager': - $docProps->setManager($propertyValue); - - break; - } - - break; - } - } - } - - private function docProperties(SimpleXMLElement $xml, SimpleXMLElement $gnmXML, array $namespacesMeta): void - { - if (isset($namespacesMeta['office'])) { - $officeXML = $xml->children($namespacesMeta['office']); - $officeDocXML = $officeXML->{'document-meta'}; - $officeDocMetaXML = $officeDocXML->meta; - - foreach ($officeDocMetaXML as $officePropertyData) { - $officePropertyDC = []; - if (isset($namespacesMeta['dc'])) { - $officePropertyDC = $officePropertyData->children($namespacesMeta['dc']); - } - $this->docPropertiesDC($officePropertyDC); - - $officePropertyMeta = []; - if (isset($namespacesMeta['meta'])) { - $officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']); - } - $this->docPropertiesMeta($officePropertyMeta, $namespacesMeta); - } - } elseif (isset($gnmXML->Summary)) { - $this->docPropertiesOld($gnmXML); - } + return array_merge(self::$mappings, Styles::$mappings); } private function processComments(SimpleXMLElement $sheet): void { if ((!$this->readDataOnly) && (isset($sheet->Objects))) { - foreach ($sheet->Objects->children($this->gnm, true) as $key => $comment) { + foreach ($sheet->Objects->children(self::NAMESPACE_GNM) as $key => $comment) { $commentAttributes = $comment->attributes(); // Only comment objects are handled at the moment - if ($commentAttributes->Text) { - $this->spreadsheet->getActiveSheet()->getComment((string) $commentAttributes->ObjectBound)->setAuthor((string) $commentAttributes->Author)->setText($this->parseRichText((string) $commentAttributes->Text)); + if ($commentAttributes && $commentAttributes->Text) { + $this->spreadsheet->getActiveSheet()->getComment((string) $commentAttributes->ObjectBound) + ->setAuthor((string) $commentAttributes->Author) + ->setText($this->parseRichText((string) $commentAttributes->Text)); } } } } + /** + * @param mixed $value + */ + private static function testSimpleXml($value): SimpleXMLElement + { + return ($value instanceof SimpleXMLElement) ? $value : new SimpleXMLElement(''); + } + /** * Loads Spreadsheet from file. * - * @param string $filename - * * @return Spreadsheet */ - public function load($filename) + public function load(string $filename, int $flags = 0) { + $this->processFlags($flags); + // Create new Spreadsheet $spreadsheet = new Spreadsheet(); $spreadsheet->removeSheetByIndex(0); @@ -445,17 +253,16 @@ class Gnumeric extends BaseReader $gFileData = $this->gzfileGetContents($pFilename); $xml2 = simplexml_load_string($this->securityScanner->scan($gFileData), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions()); - $xml = ($xml2 !== false) ? $xml2 : new SimpleXMLElement(''); - $namespacesMeta = $xml->getNamespaces(true); - $this->gnm = array_key_exists('gmr', $namespacesMeta) ? 'gmr' : 'gnm'; + $xml = self::testSimpleXml($xml2); - $gnmXML = $xml->children($namespacesMeta[$this->gnm]); - $this->docProperties($xml, $gnmXML, $namespacesMeta); + $gnmXML = $xml->children(self::NAMESPACE_GNM); + (new Properties($this->spreadsheet))->readProperties($xml, $gnmXML); $worksheetID = 0; - foreach ($gnmXML->Sheets->Sheet as $sheet) { + foreach ($gnmXML->Sheets->Sheet as $sheetOrNull) { + $sheet = self::testSimpleXml($sheetOrNull); $worksheetName = (string) $sheet->Name; - if ((isset($this->loadSheetsOnly)) && (!in_array($worksheetName, $this->loadSheetsOnly))) { + if (is_array($this->loadSheetsOnly) && !in_array($worksheetName, $this->loadSheetsOnly, true)) { continue; } @@ -470,13 +277,14 @@ class Gnumeric extends BaseReader $this->spreadsheet->getActiveSheet()->setTitle($worksheetName, false, false); if (!$this->readDataOnly) { - (new PageSetup($this->spreadsheet, $this->gnm)) + (new PageSetup($this->spreadsheet)) ->printInformation($sheet) ->sheetMargins($sheet); } - foreach ($sheet->Cells->Cell as $cell) { - $cellAttributes = $cell->attributes(); + foreach ($sheet->Cells->Cell as $cellOrNull) { + $cell = self::testSimpleXml($cellOrNull); + $cellAttributes = self::testSimpleXml($cell->attributes()); $row = (int) $cellAttributes->Row + 1; $column = (int) $cellAttributes->Col; @@ -523,90 +331,22 @@ class Gnumeric extends BaseReader if (array_key_exists($vtype, self::$mappings['dataType'])) { $type = self::$mappings['dataType'][$vtype]; } - if ($vtype == '20') { // Boolean + if ($vtype === '20') { // Boolean $cell = $cell == 'TRUE'; } } $this->spreadsheet->getActiveSheet()->getCell($column . $row)->setValueExplicit((string) $cell, $type); } - $this->processComments($sheet); - - foreach ($sheet->Styles->StyleRegion as $styleRegion) { - $styleAttributes = $styleRegion->attributes(); - if ( - ($styleAttributes['startRow'] <= $maxRow) && - ($styleAttributes['startCol'] <= $maxCol) - ) { - $startColumn = Coordinate::stringFromColumnIndex((int) $styleAttributes['startCol'] + 1); - $startRow = $styleAttributes['startRow'] + 1; - - $endColumn = ($styleAttributes['endCol'] > $maxCol) ? $maxCol : (int) $styleAttributes['endCol']; - $endColumn = Coordinate::stringFromColumnIndex($endColumn + 1); - - $endRow = 1 + (($styleAttributes['endRow'] > $maxRow) ? $maxRow : (int) $styleAttributes['endRow']); - $cellRange = $startColumn . $startRow . ':' . $endColumn . $endRow; - - $styleAttributes = $styleRegion->Style->attributes(); - - $styleArray = []; - // We still set the number format mask for date/time values, even if readDataOnly is true - $formatCode = (string) $styleAttributes['Format']; - if (Date::isDateTimeFormatCode($formatCode)) { - $styleArray['numberFormat']['formatCode'] = $formatCode; - } - if (!$this->readDataOnly) { - // If readDataOnly is false, we set all formatting information - $styleArray['numberFormat']['formatCode'] = $formatCode; - - self::addStyle2($styleArray, 'alignment', 'horizontal', $styleAttributes['HAlign']); - self::addStyle2($styleArray, 'alignment', 'vertical', $styleAttributes['VAlign']); - $styleArray['alignment']['wrapText'] = $styleAttributes['WrapText'] == '1'; - $styleArray['alignment']['textRotation'] = $this->calcRotation($styleAttributes); - $styleArray['alignment']['shrinkToFit'] = $styleAttributes['ShrinkToFit'] == '1'; - $styleArray['alignment']['indent'] = ((int) ($styleAttributes['Indent']) > 0) ? $styleAttributes['indent'] : 0; - - $this->addColors($styleArray, $styleAttributes); - - $fontAttributes = $styleRegion->Style->Font->attributes(); - $styleArray['font']['name'] = (string) $styleRegion->Style->Font; - $styleArray['font']['size'] = (int) ($fontAttributes['Unit']); - $styleArray['font']['bold'] = $fontAttributes['Bold'] == '1'; - $styleArray['font']['italic'] = $fontAttributes['Italic'] == '1'; - $styleArray['font']['strikethrough'] = $fontAttributes['StrikeThrough'] == '1'; - self::addStyle2($styleArray, 'font', 'underline', $fontAttributes['Underline']); - - switch ($fontAttributes['Script']) { - case '1': - $styleArray['font']['superscript'] = true; - - break; - case '-1': - $styleArray['font']['subscript'] = true; - - break; - } - - if (isset($styleRegion->Style->StyleBorder)) { - $srssb = $styleRegion->Style->StyleBorder; - $this->addBorderStyle($srssb, $styleArray, 'top'); - $this->addBorderStyle($srssb, $styleArray, 'bottom'); - $this->addBorderStyle($srssb, $styleArray, 'left'); - $this->addBorderStyle($srssb, $styleArray, 'right'); - $this->addBorderDiagonal($srssb, $styleArray); - } - if (isset($styleRegion->Style->HyperLink)) { - // TO DO - $hyperlink = $styleRegion->Style->HyperLink->attributes(); - } - } - $this->spreadsheet->getActiveSheet()->getStyle($cellRange)->applyFromArray($styleArray); - } + if ($sheet->Styles !== null) { + (new Styles($this->spreadsheet, $this->readDataOnly))->read($sheet, $maxRow, $maxCol); } + $this->processComments($sheet); $this->processColumnWidths($sheet, $maxCol); $this->processRowHeights($sheet, $maxRow); $this->processMergedCells($sheet); + $this->processAutofilter($sheet); ++$worksheetID; } @@ -617,126 +357,158 @@ class Gnumeric extends BaseReader return $this->spreadsheet; } - private function addBorderDiagonal(SimpleXMLElement $srssb, array &$styleArray): void - { - if (isset($srssb->Diagonal, $srssb->{'Rev-Diagonal'})) { - $styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->Diagonal->attributes()); - $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_BOTH; - } elseif (isset($srssb->Diagonal)) { - $styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->Diagonal->attributes()); - $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_UP; - } elseif (isset($srssb->{'Rev-Diagonal'})) { - $styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->{'Rev-Diagonal'}->attributes()); - $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_DOWN; - } - } - - private function addBorderStyle(SimpleXMLElement $srssb, array &$styleArray, string $direction): void - { - $ucDirection = ucfirst($direction); - if (isset($srssb->$ucDirection)) { - $styleArray['borders'][$direction] = self::parseBorderAttributes($srssb->$ucDirection->attributes()); - } - } - - private function processMergedCells(SimpleXMLElement $sheet): void + private function processMergedCells(?SimpleXMLElement $sheet): void { // Handle Merged Cells in this worksheet - if (isset($sheet->MergedRegions)) { + if ($sheet !== null && isset($sheet->MergedRegions)) { foreach ($sheet->MergedRegions->Merge as $mergeCells) { - if (strpos($mergeCells, ':') !== false) { + if (strpos((string) $mergeCells, ':') !== false) { $this->spreadsheet->getActiveSheet()->mergeCells($mergeCells); } } } } - private function processColumnLoop(int $c, int $maxCol, SimpleXMLElement $columnOverride, float $defaultWidth): int + private function processAutofilter(?SimpleXMLElement $sheet): void { - $columnAttributes = $columnOverride->attributes(); + if ($sheet !== null && isset($sheet->Filters)) { + foreach ($sheet->Filters->Filter as $autofilter) { + if ($autofilter !== null) { + $attributes = $autofilter->attributes(); + if (isset($attributes['Area'])) { + $this->spreadsheet->getActiveSheet()->setAutoFilter((string) $attributes['Area']); + } + } + } + } + } + + private function setColumnWidth(int $whichColumn, float $defaultWidth): void + { + $columnDimension = $this->spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($whichColumn + 1)); + if ($columnDimension !== null) { + $columnDimension->setWidth($defaultWidth); + } + } + + private function setColumnInvisible(int $whichColumn): void + { + $columnDimension = $this->spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($whichColumn + 1)); + if ($columnDimension !== null) { + $columnDimension->setVisible(false); + } + } + + private function processColumnLoop(int $whichColumn, int $maxCol, ?SimpleXMLElement $columnOverride, float $defaultWidth): int + { + $columnOverride = self::testSimpleXml($columnOverride); + $columnAttributes = self::testSimpleXml($columnOverride->attributes()); $column = $columnAttributes['No']; $columnWidth = ((float) $columnAttributes['Unit']) / 5.4; $hidden = (isset($columnAttributes['Hidden'])) && ((string) $columnAttributes['Hidden'] == '1'); - $columnCount = (isset($columnAttributes['Count'])) ? $columnAttributes['Count'] : 1; - while ($c < $column) { - $this->spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($c + 1))->setWidth($defaultWidth); - ++$c; + $columnCount = (int) ($columnAttributes['Count'] ?? 1); + while ($whichColumn < $column) { + $this->setColumnWidth($whichColumn, $defaultWidth); + ++$whichColumn; } - while (($c < ($column + $columnCount)) && ($c <= $maxCol)) { - $this->spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($c + 1))->setWidth($columnWidth); + while (($whichColumn < ($column + $columnCount)) && ($whichColumn <= $maxCol)) { + $this->setColumnWidth($whichColumn, $columnWidth); if ($hidden) { - $this->spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($c + 1))->setVisible(false); + $this->setColumnInvisible($whichColumn); } - ++$c; + ++$whichColumn; } - return $c; + return $whichColumn; } - private function processColumnWidths(SimpleXMLElement $sheet, int $maxCol): void + private function processColumnWidths(?SimpleXMLElement $sheet, int $maxCol): void { - if ((!$this->readDataOnly) && (isset($sheet->Cols))) { + if ((!$this->readDataOnly) && $sheet !== null && (isset($sheet->Cols))) { // Column Widths + $defaultWidth = 0; $columnAttributes = $sheet->Cols->attributes(); - $defaultWidth = $columnAttributes['DefaultSizePts'] / 5.4; - $c = 0; - foreach ($sheet->Cols->ColInfo as $columnOverride) { - $c = $this->processColumnLoop($c, $maxCol, $columnOverride, $defaultWidth); + if ($columnAttributes !== null) { + $defaultWidth = $columnAttributes['DefaultSizePts'] / 5.4; } - while ($c <= $maxCol) { - $this->spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($c + 1))->setWidth($defaultWidth); - ++$c; + $whichColumn = 0; + foreach ($sheet->Cols->ColInfo as $columnOverride) { + $whichColumn = $this->processColumnLoop($whichColumn, $maxCol, $columnOverride, $defaultWidth); + } + while ($whichColumn <= $maxCol) { + $this->setColumnWidth($whichColumn, $defaultWidth); + ++$whichColumn; } } } - private function processRowLoop(int $r, int $maxRow, SimpleXMLElement $rowOverride, float $defaultHeight): int + private function setRowHeight(int $whichRow, float $defaultHeight): void { - $rowAttributes = $rowOverride->attributes(); + $rowDimension = $this->spreadsheet->getActiveSheet()->getRowDimension($whichRow); + if ($rowDimension !== null) { + $rowDimension->setRowHeight($defaultHeight); + } + } + + private function setRowInvisible(int $whichRow): void + { + $rowDimension = $this->spreadsheet->getActiveSheet()->getRowDimension($whichRow); + if ($rowDimension !== null) { + $rowDimension->setVisible(false); + } + } + + private function processRowLoop(int $whichRow, int $maxRow, ?SimpleXMLElement $rowOverride, float $defaultHeight): int + { + $rowOverride = self::testSimpleXml($rowOverride); + $rowAttributes = self::testSimpleXml($rowOverride->attributes()); $row = $rowAttributes['No']; $rowHeight = (float) $rowAttributes['Unit']; $hidden = (isset($rowAttributes['Hidden'])) && ((string) $rowAttributes['Hidden'] == '1'); - $rowCount = (isset($rowAttributes['Count'])) ? $rowAttributes['Count'] : 1; - while ($r < $row) { - ++$r; - $this->spreadsheet->getActiveSheet()->getRowDimension($r)->setRowHeight($defaultHeight); + $rowCount = (int) ($rowAttributes['Count'] ?? 1); + while ($whichRow < $row) { + ++$whichRow; + $this->setRowHeight($whichRow, $defaultHeight); } - while (($r < ($row + $rowCount)) && ($r < $maxRow)) { - ++$r; - $this->spreadsheet->getActiveSheet()->getRowDimension($r)->setRowHeight($rowHeight); + while (($whichRow < ($row + $rowCount)) && ($whichRow < $maxRow)) { + ++$whichRow; + $this->setRowHeight($whichRow, $rowHeight); if ($hidden) { - $this->spreadsheet->getActiveSheet()->getRowDimension($r)->setVisible(false); + $this->setRowInvisible($whichRow); } } - return $r; + return $whichRow; } - private function processRowHeights(SimpleXMLElement $sheet, int $maxRow): void + private function processRowHeights(?SimpleXMLElement $sheet, int $maxRow): void { - if ((!$this->readDataOnly) && (isset($sheet->Rows))) { + if ((!$this->readDataOnly) && $sheet !== null && (isset($sheet->Rows))) { // Row Heights + $defaultHeight = 0; $rowAttributes = $sheet->Rows->attributes(); - $defaultHeight = (float) $rowAttributes['DefaultSizePts']; - $r = 0; + if ($rowAttributes !== null) { + $defaultHeight = (float) $rowAttributes['DefaultSizePts']; + } + $whichRow = 0; foreach ($sheet->Rows->RowInfo as $rowOverride) { - $r = $this->processRowLoop($r, $maxRow, $rowOverride, $defaultHeight); + $whichRow = $this->processRowLoop($whichRow, $maxRow, $rowOverride, $defaultHeight); } // never executed, I can't figure out any circumstances // under which it would be executed, and, even if // such exist, I'm not convinced this is needed. - //while ($r < $maxRow) { - // ++$r; - // $this->spreadsheet->getActiveSheet()->getRowDimension($r)->setRowHeight($defaultHeight); + //while ($whichRow < $maxRow) { + // ++$whichRow; + // $this->spreadsheet->getActiveSheet()->getRowDimension($whichRow)->setRowHeight($defaultHeight); //} } } - private function processDefinedNames(SimpleXMLElement $gnmXML): void + private function processDefinedNames(?SimpleXMLElement $gnmXML): void { // Loop through definedNames (global named ranges) - if (isset($gnmXML->Names)) { + if ($gnmXML !== null && isset($gnmXML->Names)) { foreach ($gnmXML->Names->Name as $definedName) { $name = (string) $definedName->name; $value = (string) $definedName->value; @@ -755,77 +527,11 @@ class Gnumeric extends BaseReader } } - private function calcRotation(SimpleXMLElement $styleAttributes): int - { - $rotation = (int) $styleAttributes->Rotation; - if ($rotation >= 270 && $rotation <= 360) { - $rotation -= 360; - } - $rotation = (abs($rotation) > 90) ? 0 : $rotation; - - return $rotation; - } - - private static function addStyle(array &$styleArray, string $key, string $value): void - { - if (array_key_exists($value, self::$mappings[$key])) { - $styleArray[$key] = self::$mappings[$key][$value]; - } - } - - private static function addStyle2(array &$styleArray, string $key1, string $key, string $value): void - { - if (array_key_exists($value, self::$mappings[$key])) { - $styleArray[$key1][$key] = self::$mappings[$key][$value]; - } - } - - private static function parseBorderAttributes($borderAttributes) - { - $styleArray = []; - if (isset($borderAttributes['Color'])) { - $styleArray['color']['rgb'] = self::parseGnumericColour($borderAttributes['Color']); - } - - self::addStyle($styleArray, 'borderStyle', $borderAttributes['Style']); - - return $styleArray; - } - - private function parseRichText($is) + private function parseRichText(string $is): RichText { $value = new RichText(); $value->createText($is); return $value; } - - private static function parseGnumericColour($gnmColour) - { - [$gnmR, $gnmG, $gnmB] = explode(':', $gnmColour); - $gnmR = substr(str_pad($gnmR, 4, '0', STR_PAD_RIGHT), 0, 2); - $gnmG = substr(str_pad($gnmG, 4, '0', STR_PAD_RIGHT), 0, 2); - $gnmB = substr(str_pad($gnmB, 4, '0', STR_PAD_RIGHT), 0, 2); - - return $gnmR . $gnmG . $gnmB; - } - - private function addColors(array &$styleArray, SimpleXMLElement $styleAttributes): void - { - $RGB = self::parseGnumericColour($styleAttributes['Fore']); - $styleArray['font']['color']['rgb'] = $RGB; - $RGB = self::parseGnumericColour($styleAttributes['Back']); - $shade = (string) $styleAttributes['Shade']; - if (($RGB != '000000') || ($shade != '0')) { - $RGB2 = self::parseGnumericColour($styleAttributes['PatternColor']); - if ($shade == '1') { - $styleArray['fill']['startColor']['rgb'] = $RGB; - $styleArray['fill']['endColor']['rgb'] = $RGB2; - } else { - $styleArray['fill']['endColor']['rgb'] = $RGB; - $styleArray['fill']['startColor']['rgb'] = $RGB2; - } - self::addStyle2($styleArray, 'fill', 'fillType', $shade); - } - } } diff --git a/src/PhpSpreadsheet/Reader/Gnumeric/PageSetup.php b/src/PhpSpreadsheet/Reader/Gnumeric/PageSetup.php index 0fe73005..5b501e0f 100644 --- a/src/PhpSpreadsheet/Reader/Gnumeric/PageSetup.php +++ b/src/PhpSpreadsheet/Reader/Gnumeric/PageSetup.php @@ -2,6 +2,7 @@ namespace PhpOffice\PhpSpreadsheet\Reader\Gnumeric; +use PhpOffice\PhpSpreadsheet\Reader\Gnumeric; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\PageMargins; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup as WorksheetPageSetup; @@ -14,21 +15,19 @@ class PageSetup */ private $spreadsheet; - /** - * @var string - */ - private $gnm; - - public function __construct(Spreadsheet $spreadsheet, string $gnm) + public function __construct(Spreadsheet $spreadsheet) { $this->spreadsheet = $spreadsheet; - $this->gnm = $gnm; } public function printInformation(SimpleXMLElement $sheet): self { if (isset($sheet->PrintInformation)) { $printInformation = $sheet->PrintInformation[0]; + if (!$printInformation) { + return $this; + } + $scale = (string) $printInformation->Scale->attributes()['percentage']; $pageOrder = (string) $printInformation->order; $orientation = (string) $printInformation->orientation; @@ -68,7 +67,7 @@ class PageSetup private function buildMarginSet(SimpleXMLElement $sheet, array $marginSet): array { - foreach ($sheet->PrintInformation->Margins->children($this->gnm, true) as $key => $margin) { + foreach ($sheet->PrintInformation->Margins->children(Gnumeric::NAMESPACE_GNM) as $key => $margin) { $marginAttributes = $margin->attributes(); $marginSize = ($marginAttributes['Points']) ?? 72; // Default is 72pt // Convert value in points to inches diff --git a/src/PhpSpreadsheet/Reader/Gnumeric/Properties.php b/src/PhpSpreadsheet/Reader/Gnumeric/Properties.php new file mode 100644 index 00000000..23d4067b --- /dev/null +++ b/src/PhpSpreadsheet/Reader/Gnumeric/Properties.php @@ -0,0 +1,164 @@ +spreadsheet = $spreadsheet; + } + + private function docPropertiesOld(SimpleXMLElement $gnmXML): void + { + $docProps = $this->spreadsheet->getProperties(); + foreach ($gnmXML->Summary->Item as $summaryItem) { + $propertyName = $summaryItem->name; + $propertyValue = $summaryItem->{'val-string'}; + switch ($propertyName) { + case 'title': + $docProps->setTitle(trim($propertyValue)); + + break; + case 'comments': + $docProps->setDescription(trim($propertyValue)); + + break; + case 'keywords': + $docProps->setKeywords(trim($propertyValue)); + + break; + case 'category': + $docProps->setCategory(trim($propertyValue)); + + break; + case 'manager': + $docProps->setManager(trim($propertyValue)); + + break; + case 'author': + $docProps->setCreator(trim($propertyValue)); + $docProps->setLastModifiedBy(trim($propertyValue)); + + break; + case 'company': + $docProps->setCompany(trim($propertyValue)); + + break; + } + } + } + + private function docPropertiesDC(SimpleXMLElement $officePropertyDC): void + { + $docProps = $this->spreadsheet->getProperties(); + foreach ($officePropertyDC as $propertyName => $propertyValue) { + $propertyValue = trim((string) $propertyValue); + switch ($propertyName) { + case 'title': + $docProps->setTitle($propertyValue); + + break; + case 'subject': + $docProps->setSubject($propertyValue); + + break; + case 'creator': + $docProps->setCreator($propertyValue); + $docProps->setLastModifiedBy($propertyValue); + + break; + case 'date': + $creationDate = $propertyValue; + $docProps->setModified($creationDate); + + break; + case 'description': + $docProps->setDescription($propertyValue); + + break; + } + } + } + + private function docPropertiesMeta(SimpleXMLElement $officePropertyMeta): void + { + $docProps = $this->spreadsheet->getProperties(); + foreach ($officePropertyMeta as $propertyName => $propertyValue) { + if ($propertyValue !== null) { + $attributes = $propertyValue->attributes(Gnumeric::NAMESPACE_META); + $propertyValue = trim((string) $propertyValue); + switch ($propertyName) { + case 'keyword': + $docProps->setKeywords($propertyValue); + + break; + case 'initial-creator': + $docProps->setCreator($propertyValue); + $docProps->setLastModifiedBy($propertyValue); + + break; + case 'creation-date': + $creationDate = $propertyValue; + $docProps->setCreated($creationDate); + + break; + case 'user-defined': + if ($attributes) { + [, $attrName] = explode(':', (string) $attributes['name']); + $this->userDefinedProperties($attrName, $propertyValue); + } + + break; + } + } + } + } + + private function userDefinedProperties(string $attrName, string $propertyValue): void + { + $docProps = $this->spreadsheet->getProperties(); + switch ($attrName) { + case 'publisher': + $docProps->setCompany($propertyValue); + + break; + case 'category': + $docProps->setCategory($propertyValue); + + break; + case 'manager': + $docProps->setManager($propertyValue); + + break; + } + } + + public function readProperties(SimpleXMLElement $xml, SimpleXMLElement $gnmXML): void + { + $officeXML = $xml->children(Gnumeric::NAMESPACE_OFFICE); + if (!empty($officeXML)) { + $officeDocXML = $officeXML->{'document-meta'}; + $officeDocMetaXML = $officeDocXML->meta; + + foreach ($officeDocMetaXML as $officePropertyData) { + $officePropertyDC = $officePropertyData->children(Gnumeric::NAMESPACE_DC); + $this->docPropertiesDC($officePropertyDC); + + $officePropertyMeta = $officePropertyData->children(Gnumeric::NAMESPACE_META); + $this->docPropertiesMeta($officePropertyMeta); + } + } elseif (isset($gnmXML->Summary)) { + $this->docPropertiesOld($gnmXML); + } + } +} diff --git a/src/PhpSpreadsheet/Reader/Gnumeric/Styles.php b/src/PhpSpreadsheet/Reader/Gnumeric/Styles.php new file mode 100644 index 00000000..e2e9d561 --- /dev/null +++ b/src/PhpSpreadsheet/Reader/Gnumeric/Styles.php @@ -0,0 +1,278 @@ + [ + '0' => Border::BORDER_NONE, + '1' => Border::BORDER_THIN, + '2' => Border::BORDER_MEDIUM, + '3' => Border::BORDER_SLANTDASHDOT, + '4' => Border::BORDER_DASHED, + '5' => Border::BORDER_THICK, + '6' => Border::BORDER_DOUBLE, + '7' => Border::BORDER_DOTTED, + '8' => Border::BORDER_MEDIUMDASHED, + '9' => Border::BORDER_DASHDOT, + '10' => Border::BORDER_MEDIUMDASHDOT, + '11' => Border::BORDER_DASHDOTDOT, + '12' => Border::BORDER_MEDIUMDASHDOTDOT, + '13' => Border::BORDER_MEDIUMDASHDOTDOT, + ], + 'fillType' => [ + '1' => Fill::FILL_SOLID, + '2' => Fill::FILL_PATTERN_DARKGRAY, + '3' => Fill::FILL_PATTERN_MEDIUMGRAY, + '4' => Fill::FILL_PATTERN_LIGHTGRAY, + '5' => Fill::FILL_PATTERN_GRAY125, + '6' => Fill::FILL_PATTERN_GRAY0625, + '7' => Fill::FILL_PATTERN_DARKHORIZONTAL, // horizontal stripe + '8' => Fill::FILL_PATTERN_DARKVERTICAL, // vertical stripe + '9' => Fill::FILL_PATTERN_DARKDOWN, // diagonal stripe + '10' => Fill::FILL_PATTERN_DARKUP, // reverse diagonal stripe + '11' => Fill::FILL_PATTERN_DARKGRID, // diagoanl crosshatch + '12' => Fill::FILL_PATTERN_DARKTRELLIS, // thick diagonal crosshatch + '13' => Fill::FILL_PATTERN_LIGHTHORIZONTAL, + '14' => Fill::FILL_PATTERN_LIGHTVERTICAL, + '15' => Fill::FILL_PATTERN_LIGHTUP, + '16' => Fill::FILL_PATTERN_LIGHTDOWN, + '17' => Fill::FILL_PATTERN_LIGHTGRID, // thin horizontal crosshatch + '18' => Fill::FILL_PATTERN_LIGHTTRELLIS, // thin diagonal crosshatch + ], + 'horizontal' => [ + '1' => Alignment::HORIZONTAL_GENERAL, + '2' => Alignment::HORIZONTAL_LEFT, + '4' => Alignment::HORIZONTAL_RIGHT, + '8' => Alignment::HORIZONTAL_CENTER, + '16' => Alignment::HORIZONTAL_CENTER_CONTINUOUS, + '32' => Alignment::HORIZONTAL_JUSTIFY, + '64' => Alignment::HORIZONTAL_CENTER_CONTINUOUS, + ], + 'underline' => [ + '1' => Font::UNDERLINE_SINGLE, + '2' => Font::UNDERLINE_DOUBLE, + '3' => Font::UNDERLINE_SINGLEACCOUNTING, + '4' => Font::UNDERLINE_DOUBLEACCOUNTING, + ], + 'vertical' => [ + '1' => Alignment::VERTICAL_TOP, + '2' => Alignment::VERTICAL_BOTTOM, + '4' => Alignment::VERTICAL_CENTER, + '8' => Alignment::VERTICAL_JUSTIFY, + ], + ]; + + public function __construct(Spreadsheet $spreadsheet, bool $readDataOnly) + { + $this->spreadsheet = $spreadsheet; + $this->readDataOnly = $readDataOnly; + } + + public function read(SimpleXMLElement $sheet, int $maxRow, int $maxCol): void + { + if ($sheet->Styles->StyleRegion !== null) { + $this->readStyles($sheet->Styles->StyleRegion, $maxRow, $maxCol); + } + } + + private function readStyles(SimpleXMLElement $styleRegion, int $maxRow, int $maxCol): void + { + foreach ($styleRegion as $style) { + $styleAttributes = $style->attributes(); + if ($styleAttributes !== null && ($styleAttributes['startRow'] <= $maxRow) && ($styleAttributes['startCol'] <= $maxCol)) { + $cellRange = $this->readStyleRange($styleAttributes, $maxCol, $maxRow); + + $styleAttributes = $style->Style->attributes(); + + $styleArray = []; + // We still set the number format mask for date/time values, even if readDataOnly is true + // so that we can identify whether a float is a float or a date value + $formatCode = $styleAttributes ? (string) $styleAttributes['Format'] : null; + if ($formatCode && Date::isDateTimeFormatCode($formatCode)) { + $styleArray['numberFormat']['formatCode'] = $formatCode; + } + if ($this->readDataOnly === false && $styleAttributes !== null) { + // If readDataOnly is false, we set all formatting information + $styleArray['numberFormat']['formatCode'] = $formatCode; + $styleArray = $this->readStyle($styleArray, $styleAttributes, $style); + } + $this->spreadsheet->getActiveSheet()->getStyle($cellRange)->applyFromArray($styleArray); + } + } + } + + private function addBorderDiagonal(SimpleXMLElement $srssb, array &$styleArray): void + { + if (isset($srssb->Diagonal, $srssb->{'Rev-Diagonal'})) { + $styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->Diagonal->attributes()); + $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_BOTH; + } elseif (isset($srssb->Diagonal)) { + $styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->Diagonal->attributes()); + $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_UP; + } elseif (isset($srssb->{'Rev-Diagonal'})) { + $styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->{'Rev-Diagonal'}->attributes()); + $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_DOWN; + } + } + + private function addBorderStyle(SimpleXMLElement $srssb, array &$styleArray, string $direction): void + { + $ucDirection = ucfirst($direction); + if (isset($srssb->$ucDirection)) { + $styleArray['borders'][$direction] = self::parseBorderAttributes($srssb->$ucDirection->attributes()); + } + } + + private function calcRotation(SimpleXMLElement $styleAttributes): int + { + $rotation = (int) $styleAttributes->Rotation; + if ($rotation >= 270 && $rotation <= 360) { + $rotation -= 360; + } + $rotation = (abs($rotation) > 90) ? 0 : $rotation; + + return $rotation; + } + + private static function addStyle(array &$styleArray, string $key, string $value): void + { + if (array_key_exists($value, self::$mappings[$key])) { + $styleArray[$key] = self::$mappings[$key][$value]; + } + } + + private static function addStyle2(array &$styleArray, string $key1, string $key, string $value): void + { + if (array_key_exists($value, self::$mappings[$key])) { + $styleArray[$key1][$key] = self::$mappings[$key][$value]; + } + } + + private static function parseBorderAttributes(?SimpleXMLElement $borderAttributes): array + { + $styleArray = []; + if ($borderAttributes !== null) { + if (isset($borderAttributes['Color'])) { + $styleArray['color']['rgb'] = self::parseGnumericColour($borderAttributes['Color']); + } + + self::addStyle($styleArray, 'borderStyle', (string) $borderAttributes['Style']); + } + + return $styleArray; + } + + private static function parseGnumericColour(string $gnmColour): string + { + [$gnmR, $gnmG, $gnmB] = explode(':', $gnmColour); + $gnmR = substr(str_pad($gnmR, 4, '0', STR_PAD_RIGHT), 0, 2); + $gnmG = substr(str_pad($gnmG, 4, '0', STR_PAD_RIGHT), 0, 2); + $gnmB = substr(str_pad($gnmB, 4, '0', STR_PAD_RIGHT), 0, 2); + + return $gnmR . $gnmG . $gnmB; + } + + private function addColors(array &$styleArray, SimpleXMLElement $styleAttributes): void + { + $RGB = self::parseGnumericColour((string) $styleAttributes['Fore']); + $styleArray['font']['color']['rgb'] = $RGB; + $RGB = self::parseGnumericColour((string) $styleAttributes['Back']); + $shade = (string) $styleAttributes['Shade']; + if (($RGB !== '000000') || ($shade !== '0')) { + $RGB2 = self::parseGnumericColour((string) $styleAttributes['PatternColor']); + if ($shade === '1') { + $styleArray['fill']['startColor']['rgb'] = $RGB; + $styleArray['fill']['endColor']['rgb'] = $RGB2; + } else { + $styleArray['fill']['endColor']['rgb'] = $RGB; + $styleArray['fill']['startColor']['rgb'] = $RGB2; + } + self::addStyle2($styleArray, 'fill', 'fillType', $shade); + } + } + + private function readStyleRange(SimpleXMLElement $styleAttributes, int $maxCol, int $maxRow): string + { + $startColumn = Coordinate::stringFromColumnIndex((int) $styleAttributes['startCol'] + 1); + $startRow = $styleAttributes['startRow'] + 1; + + $endColumn = ($styleAttributes['endCol'] > $maxCol) ? $maxCol : (int) $styleAttributes['endCol']; + $endColumn = Coordinate::stringFromColumnIndex($endColumn + 1); + + $endRow = 1 + (($styleAttributes['endRow'] > $maxRow) ? $maxRow : (int) $styleAttributes['endRow']); + $cellRange = $startColumn . $startRow . ':' . $endColumn . $endRow; + + return $cellRange; + } + + private function readStyle(array $styleArray, SimpleXMLElement $styleAttributes, SimpleXMLElement $style): array + { + self::addStyle2($styleArray, 'alignment', 'horizontal', (string) $styleAttributes['HAlign']); + self::addStyle2($styleArray, 'alignment', 'vertical', (string) $styleAttributes['VAlign']); + $styleArray['alignment']['wrapText'] = $styleAttributes['WrapText'] == '1'; + $styleArray['alignment']['textRotation'] = $this->calcRotation($styleAttributes); + $styleArray['alignment']['shrinkToFit'] = $styleAttributes['ShrinkToFit'] == '1'; + $styleArray['alignment']['indent'] = ((int) ($styleAttributes['Indent']) > 0) ? $styleAttributes['indent'] : 0; + + $this->addColors($styleArray, $styleAttributes); + + $fontAttributes = $style->Style->Font->attributes(); + if ($fontAttributes !== null) { + $styleArray['font']['name'] = (string) $style->Style->Font; + $styleArray['font']['size'] = (int) ($fontAttributes['Unit']); + $styleArray['font']['bold'] = $fontAttributes['Bold'] == '1'; + $styleArray['font']['italic'] = $fontAttributes['Italic'] == '1'; + $styleArray['font']['strikethrough'] = $fontAttributes['StrikeThrough'] == '1'; + self::addStyle2($styleArray, 'font', 'underline', (string) $fontAttributes['Underline']); + + switch ($fontAttributes['Script']) { + case '1': + $styleArray['font']['superscript'] = true; + + break; + case '-1': + $styleArray['font']['subscript'] = true; + + break; + } + } + + if (isset($style->Style->StyleBorder)) { + $srssb = $style->Style->StyleBorder; + $this->addBorderStyle($srssb, $styleArray, 'top'); + $this->addBorderStyle($srssb, $styleArray, 'bottom'); + $this->addBorderStyle($srssb, $styleArray, 'left'); + $this->addBorderStyle($srssb, $styleArray, 'right'); + $this->addBorderDiagonal($srssb, $styleArray); + } + if (isset($style->Style->HyperLink)) { + // TO DO + $hyperlink = $style->Style->HyperLink->attributes(); + } + + return $styleArray; + } +} diff --git a/src/PhpSpreadsheet/Reader/Html.php b/src/PhpSpreadsheet/Reader/Html.php index ed58fb51..ac763c92 100644 --- a/src/PhpSpreadsheet/Reader/Html.php +++ b/src/PhpSpreadsheet/Reader/Html.php @@ -7,6 +7,7 @@ use DOMElement; use DOMNode; use DOMText; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Helper\Dimension as CssDimension; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Border; @@ -122,6 +123,7 @@ class Html extends BaseReader ], // Italic ]; + /** @var array */ protected $rowspan = []; /** @@ -135,12 +137,8 @@ class Html extends BaseReader /** * Validate that the current file is an HTML file. - * - * @param string $filename - * - * @return bool */ - public function canRead($filename) + public function canRead(string $filename): bool { // Check if file exists try { @@ -159,19 +157,19 @@ class Html extends BaseReader return $startWithTag && $containsTags && $endsWithTag; } - private function readBeginning() + private function readBeginning(): string { fseek($this->fileHandle, 0); - return fread($this->fileHandle, self::TEST_SAMPLE_SIZE); + return (string) fread($this->fileHandle, self::TEST_SAMPLE_SIZE); } - private function readEnding() + private function readEnding(): string { $meta = stream_get_meta_data($this->fileHandle); $filename = $meta['uri']; - $size = filesize($filename); + $size = (int) filesize($filename); if ($size === 0) { return ''; } @@ -183,20 +181,20 @@ class Html extends BaseReader fseek($this->fileHandle, $size - $blockSize); - return fread($this->fileHandle, $blockSize); + return (string) fread($this->fileHandle, $blockSize); } - private static function startsWithTag($data) + private static function startsWithTag(string $data): bool { return '<' === substr(trim($data), 0, 1); } - private static function endsWithTag($data) + private static function endsWithTag(string $data): bool { return '>' === substr(trim($data), -1, 1); } - private static function containsTags($data) + private static function containsTags(string $data): bool { return strlen($data) !== strlen(strip_tags($data)); } @@ -204,12 +202,12 @@ class Html extends BaseReader /** * Loads Spreadsheet from file. * - * @param string $filename - * * @return Spreadsheet */ - public function load($filename) + public function load(string $filename, int $flags = 0) { + $this->processFlags($flags); + // Create new Spreadsheet $spreadsheet = new Spreadsheet(); @@ -220,13 +218,13 @@ class Html extends BaseReader /** * Set input encoding. * - * @deprecated no use is made of this property - * * @param string $pValue Input encoding, eg: 'ANSI' * * @return $this * * @codeCoverageIgnore + * + * @deprecated no use is made of this property */ public function setInputEncoding($pValue) { @@ -238,11 +236,11 @@ class Html extends BaseReader /** * Get input encoding. * - * @deprecated no use is made of this property - * * @return string * * @codeCoverageIgnore + * + * @deprecated no use is made of this property */ public function getInputEncoding() { @@ -250,13 +248,17 @@ class Html extends BaseReader } // Data Array used for testing only, should write to Spreadsheet object on completion of tests + + /** @var array */ protected $dataArray = []; + /** @var int */ protected $tableLevel = 0; + /** @var array */ protected $nestedColumn = ['A']; - protected function setTableStartColumn($column) + protected function setTableStartColumn(string $column): string { if ($this->tableLevel == 0) { $column = 'A'; @@ -267,18 +269,25 @@ class Html extends BaseReader return $this->nestedColumn[$this->tableLevel]; } - protected function getTableStartColumn() + protected function getTableStartColumn(): string { return $this->nestedColumn[$this->tableLevel]; } - protected function releaseTableStartColumn() + protected function releaseTableStartColumn(): string { --$this->tableLevel; return array_pop($this->nestedColumn); } + /** + * Flush cell. + * + * @param string $column + * @param int|string $row + * @param mixed $cellContent + */ protected function flushCell(Worksheet $sheet, $column, $row, &$cellContent): void { if (is_string($cellContent)) { @@ -301,7 +310,7 @@ class Html extends BaseReader private function processDomElementBody(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child): void { $attributeArray = []; - foreach ($child->attributes as $attribute) { + foreach (($child->attributes ?? []) as $attribute) { $attributeArray[$attribute->name] = $attribute->value; } @@ -320,24 +329,25 @@ class Html extends BaseReader { if ($child->nodeName === 'title') { $this->processDomElement($child, $sheet, $row, $column, $cellContent); - $sheet->setTitle($cellContent, true, false); + $sheet->setTitle($cellContent, true, true); $cellContent = ''; } else { $this->processDomElementSpanEtc($sheet, $row, $column, $cellContent, $child, $attributeArray); } } - private static $spanEtc = ['span', 'div', 'font', 'i', 'em', 'strong', 'b']; + private const SPAN_ETC = ['span', 'div', 'font', 'i', 'em', 'strong', 'b']; private function processDomElementSpanEtc(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { - if (in_array($child->nodeName, self::$spanEtc)) { + if (in_array((string) $child->nodeName, self::SPAN_ETC, true)) { if (isset($attributeArray['class']) && $attributeArray['class'] === 'comment') { $sheet->getComment($column . $row) ->getText() ->createTextRun($child->textContent); + } else { + $this->processDomElement($child, $sheet, $row, $column, $cellContent); } - $this->processDomElement($child, $sheet, $row, $column, $cellContent); if (isset($this->formats[$child->nodeName])) { $sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]); @@ -404,11 +414,11 @@ class Html extends BaseReader } } - private static $h1Etc = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ol', 'ul', 'p']; + private const H1_ETC = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ol', 'ul', 'p']; private function processDomElementH1Etc(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { - if (in_array($child->nodeName, self::$h1Etc)) { + if (in_array((string) $child->nodeName, self::H1_ETC, true)) { if ($this->tableLevel > 0) { // If we're inside a table, replace with a \n $cellContent .= $cellContent ? "\n" : ''; @@ -469,7 +479,7 @@ class Html extends BaseReader if ($child->nodeName === 'table') { $this->flushCell($sheet, $column, $row, $cellContent); $column = $this->setTableStartColumn($column); - if ($this->tableLevel > 1) { + if ($this->tableLevel > 1 && $row > 1) { --$row; } $this->processDomElement($child, $sheet, $row, $column, $cellContent); @@ -527,14 +537,14 @@ class Html extends BaseReader private function processDomElementWidth(Worksheet $sheet, string $column, array $attributeArray): void { if (isset($attributeArray['width'])) { - $sheet->getColumnDimension($column)->setWidth($attributeArray['width']); + $sheet->getColumnDimension($column)->setWidth((new CssDimension($attributeArray['width']))->width()); } } private function processDomElementHeight(Worksheet $sheet, int $row, array $attributeArray): void { if (isset($attributeArray['height'])) { - $sheet->getRowDimension($row)->setRowHeight($attributeArray['height']); + $sheet->getRowDimension($row)->setRowHeight((new CssDimension($attributeArray['height']))->height()); } } @@ -627,6 +637,16 @@ class Html extends BaseReader } } + /** + * Make sure mb_convert_encoding returns string. + * + * @param mixed $result + */ + private static function ensureString($result): string + { + return is_string($result) ? $result : ''; + } + /** * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. * @@ -645,12 +665,13 @@ class Html extends BaseReader $dom = new DOMDocument(); // Reload the HTML file into the DOM object try { - $loaded = $dom->loadHTML(mb_convert_encoding($this->securityScanner->scanFile($pFilename), 'HTML-ENTITIES', 'UTF-8')); + $convert = mb_convert_encoding($this->securityScanner->scanFile($pFilename), 'HTML-ENTITIES', 'UTF-8'); + $loaded = $dom->loadHTML(self::ensureString($convert)); } catch (Throwable $e) { $loaded = false; } if ($loaded === false) { - throw new Exception('Failed to load ' . $pFilename . ' as a DOM Document'); + throw new Exception('Failed to load ' . $pFilename . ' as a DOM Document', 0, $e ?? null); } return $this->loadDocument($dom, $spreadsheet); @@ -667,12 +688,13 @@ class Html extends BaseReader $dom = new DOMDocument(); // Reload the HTML file into the DOM object try { - $loaded = $dom->loadHTML(mb_convert_encoding($this->securityScanner->scan($content), 'HTML-ENTITIES', 'UTF-8')); + $convert = mb_convert_encoding($this->securityScanner->scan($content), 'HTML-ENTITIES', 'UTF-8'); + $loaded = $dom->loadHTML(self::ensureString($convert)); } catch (Throwable $e) { $loaded = false; } if ($loaded === false) { - throw new Exception('Failed to load content as a DOM Document'); + throw new Exception('Failed to load content as a DOM Document', 0, $e ?? null); } return $this->loadDocument($dom, $spreadsheet ?? new Spreadsheet()); @@ -773,6 +795,7 @@ class Html extends BaseReader $value = explode(':', $st); $styleName = isset($value[0]) ? trim($value[0]) : null; $styleValue = isset($value[1]) ? trim($value[1]) : null; + $styleValueString = (string) $styleValue; if (!$styleName) { continue; @@ -781,7 +804,7 @@ class Html extends BaseReader switch ($styleName) { case 'background': case 'background-color': - $styleColor = $this->getStyleColor($styleValue); + $styleColor = $this->getStyleColor($styleValueString); if (!$styleColor) { continue 2; @@ -791,7 +814,7 @@ class Html extends BaseReader break; case 'color': - $styleColor = $this->getStyleColor($styleValue); + $styleColor = $this->getStyleColor($styleValueString); if (!$styleColor) { continue 2; @@ -802,27 +825,27 @@ class Html extends BaseReader break; case 'border': - $this->setBorderStyle($cellStyle, $styleValue, 'allBorders'); + $this->setBorderStyle($cellStyle, $styleValueString, 'allBorders'); break; case 'border-top': - $this->setBorderStyle($cellStyle, $styleValue, 'top'); + $this->setBorderStyle($cellStyle, $styleValueString, 'top'); break; case 'border-bottom': - $this->setBorderStyle($cellStyle, $styleValue, 'bottom'); + $this->setBorderStyle($cellStyle, $styleValueString, 'bottom'); break; case 'border-left': - $this->setBorderStyle($cellStyle, $styleValue, 'left'); + $this->setBorderStyle($cellStyle, $styleValueString, 'left'); break; case 'border-right': - $this->setBorderStyle($cellStyle, $styleValue, 'right'); + $this->setBorderStyle($cellStyle, $styleValueString, 'right'); break; @@ -848,7 +871,7 @@ class Html extends BaseReader break; case 'font-family': - $cellStyle->getFont()->setName(str_replace('\'', '', $styleValue)); + $cellStyle->getFont()->setName(str_replace('\'', '', $styleValueString)); break; @@ -867,25 +890,25 @@ class Html extends BaseReader break; case 'text-align': - $cellStyle->getAlignment()->setHorizontal($styleValue); + $cellStyle->getAlignment()->setHorizontal($styleValueString); break; case 'vertical-align': - $cellStyle->getAlignment()->setVertical($styleValue); + $cellStyle->getAlignment()->setVertical($styleValueString); break; case 'width': $sheet->getColumnDimension($column)->setWidth( - str_replace('px', '', $styleValue) + (new CssDimension($styleValue ?? ''))->width() ); break; case 'height': $sheet->getRowDimension($row)->setRowHeight( - str_replace('px', '', $styleValue) + (new CssDimension($styleValue ?? ''))->height() ); break; @@ -899,7 +922,7 @@ class Html extends BaseReader case 'text-indent': $cellStyle->getAlignment()->setIndent( - (int) str_replace(['px'], '', $styleValue) + (int) str_replace(['px'], '', $styleValueString) ); break; @@ -910,17 +933,18 @@ class Html extends BaseReader /** * Check if has #, so we can get clean hex. * - * @param $value + * @param mixed $value * * @return null|string */ public function getStyleColor($value) { - if (strpos($value, '#') === 0) { + $value = (string) $value; + if (strpos($value ?? '', '#') === 0) { return substr($value, 1); } - return \PhpOffice\PhpSpreadsheet\Helper\Html::colourNameLookup((string) $value); + return \PhpOffice\PhpSpreadsheet\Helper\Html::colourNameLookup($value); } /** @@ -967,7 +991,7 @@ class Html extends BaseReader ); } - private static $borderMappings = [ + private const BORDER_MAPPINGS = [ 'dash-dot' => Border::BORDER_DASHDOT, 'dash-dot-dot' => Border::BORDER_DASHDOTDOT, 'dashed' => Border::BORDER_DASHED, @@ -986,7 +1010,7 @@ class Html extends BaseReader public static function getBorderMappings(): array { - return self::$borderMappings; + return self::BORDER_MAPPINGS; } /** @@ -998,7 +1022,7 @@ class Html extends BaseReader */ public function getBorderStyle($style) { - return (array_key_exists($style, self::$borderMappings)) ? self::$borderMappings[$style] : null; + return self::BORDER_MAPPINGS[$style] ?? null; } /** @@ -1011,7 +1035,15 @@ class Html extends BaseReader $borderStyle = Border::BORDER_NONE; $color = null; } else { - [, $borderStyle, $color] = explode(' ', $styleValue); + $borderArray = explode(' ', $styleValue); + $borderCount = count($borderArray); + if ($borderCount >= 3) { + $borderStyle = $borderArray[1]; + $color = $borderArray[2]; + } else { + $borderStyle = $borderArray[0]; + $color = $borderArray[1] ?? null; + } } $cellStyle->applyFromArray([ diff --git a/src/PhpSpreadsheet/Reader/IReader.php b/src/PhpSpreadsheet/Reader/IReader.php index bbbc1ec3..63059693 100644 --- a/src/PhpSpreadsheet/Reader/IReader.php +++ b/src/PhpSpreadsheet/Reader/IReader.php @@ -4,6 +4,8 @@ namespace PhpOffice\PhpSpreadsheet\Reader; interface IReader { + public const LOAD_WITH_CHARTS = 1; + /** * IReader constructor. */ @@ -11,12 +13,8 @@ interface IReader /** * Can the current IReader read the file? - * - * @param string $filename - * - * @return bool */ - public function canRead($filename); + public function canRead(string $filename): bool; /** * Read data only? @@ -32,11 +30,11 @@ interface IReader * Set to true, to advise the Reader only to read data values for cells, and to ignore any formatting information. * Set to false (the default) to advise the Reader to read both data and formatting for cells. * - * @param bool $readCellValuesOnly + * @param bool $pValue * * @return IReader */ - public function setReadDataOnly($readCellValuesOnly); + public function setReadDataOnly($pValue); /** * Read empty cells? @@ -52,11 +50,11 @@ interface IReader * Set to true (the default) to advise the Reader read data values for all cells, irrespective of value. * Set to false to advise the Reader to ignore cells containing a null value or an empty string. * - * @param bool $readEmptyCells + * @param bool $pValue * * @return IReader */ - public function setReadEmptyCells($readEmptyCells); + public function setReadEmptyCells($pValue); /** * Read charts in workbook? @@ -74,11 +72,11 @@ interface IReader * Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value. * Set to false (the default) to discard charts. * - * @param bool $includeCharts + * @param bool $pValue * * @return IReader */ - public function setIncludeCharts($includeCharts); + public function setIncludeCharts($pValue); /** * Get which sheets to load @@ -92,13 +90,13 @@ interface IReader /** * Set which sheets to load. * - * @param mixed $sheetList + * @param mixed $value * This should be either an array of worksheet names to be loaded, or a string containing a single worksheet name. * If NULL, then it tells the Reader to read all worksheets in the workbook * * @return IReader */ - public function setLoadSheetsOnly($sheetList); + public function setLoadSheetsOnly($value); /** * Set all sheets to load @@ -120,14 +118,12 @@ interface IReader * * @return IReader */ - public function setReadFilter(IReadFilter $readFilter); + public function setReadFilter(IReadFilter $pValue); /** * Loads PhpSpreadsheet from file. * - * @param string $filename - * * @return \PhpOffice\PhpSpreadsheet\Spreadsheet */ - public function load($filename); + public function load(string $filename, int $flags = 0); } diff --git a/src/PhpSpreadsheet/Reader/Ods.php b/src/PhpSpreadsheet/Reader/Ods.php index 668176d1..abf658e5 100644 --- a/src/PhpSpreadsheet/Reader/Ods.php +++ b/src/PhpSpreadsheet/Reader/Ods.php @@ -3,7 +3,6 @@ namespace PhpOffice\PhpSpreadsheet\Reader; use DateTime; -use DateTimeZone; use DOMAttr; use DOMDocument; use DOMElement; @@ -11,8 +10,8 @@ use DOMNode; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; -use PhpOffice\PhpSpreadsheet\DefinedName; -use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException; +use PhpOffice\PhpSpreadsheet\Reader\Ods\AutoFilter; +use PhpOffice\PhpSpreadsheet\Reader\Ods\DefinedNames; use PhpOffice\PhpSpreadsheet\Reader\Ods\PageSettings; use PhpOffice\PhpSpreadsheet\Reader\Ods\Properties as DocumentProperties; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; @@ -22,12 +21,14 @@ use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; -use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use Throwable; use XMLReader; use ZipArchive; class Ods extends BaseReader { + const INITIAL_FILE = 'content.xml'; + /** * Create a new Ods Reader instance. */ @@ -39,46 +40,42 @@ class Ods extends BaseReader /** * Can the current IReader read the file? - * - * @param string $filename - * - * @return bool */ - public function canRead($filename) + public function canRead(string $filename): bool { - File::assertFile($filename); - $mimeType = 'UNKNOWN'; // Load file - $zip = new ZipArchive(); - if ($zip->open($filename) === true) { - // check if it is an OOXML archive - $stat = $zip->statName('mimetype'); - if ($stat && ($stat['size'] <= 255)) { - $mimeType = $zip->getFromName($stat['name']); - } elseif ($zip->statName('META-INF/manifest.xml')) { - $xml = simplexml_load_string( + if (File::testFileNoThrow($filename)) { + $zip = new ZipArchive(); + if ($zip->open($filename) === true) { + // check if it is an OOXML archive + $stat = $zip->statName('mimetype'); + if ($stat && ($stat['size'] <= 255)) { + $mimeType = $zip->getFromName($stat['name']); + } elseif ($zip->statName('META-INF/manifest.xml')) { + $xml = simplexml_load_string( $this->securityScanner->scan($zip->getFromName('META-INF/manifest.xml')), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions() ); - $namespacesContent = $xml->getNamespaces(true); - if (isset($namespacesContent['manifest'])) { - $manifest = $xml->children($namespacesContent['manifest']); - foreach ($manifest as $manifestDataSet) { - $manifestAttributes = $manifestDataSet->attributes($namespacesContent['manifest']); - if ($manifestAttributes->{'full-path'} == '/') { - $mimeType = (string) $manifestAttributes->{'media-type'}; + $namespacesContent = $xml->getNamespaces(true); + if (isset($namespacesContent['manifest'])) { + $manifest = $xml->children($namespacesContent['manifest']); + foreach ($manifest as $manifestDataSet) { + $manifestAttributes = $manifestDataSet->attributes($namespacesContent['manifest']); + if ($manifestAttributes && $manifestAttributes->{'full-path'} == '/') { + $mimeType = (string) $manifestAttributes->{'media-type'}; - break; + break; + } } } } - } - $zip->close(); + $zip->close(); + } } return $mimeType === 'application/vnd.oasis.opendocument.spreadsheet'; @@ -93,18 +90,13 @@ class Ods extends BaseReader */ public function listWorksheetNames($pFilename) { - File::assertFile($pFilename); - - $zip = new ZipArchive(); - if ($zip->open($pFilename) !== true) { - throw new ReaderException('Could not open ' . $pFilename . ' for reading! Error opening file.'); - } + File::assertFile($pFilename, self::INITIAL_FILE); $worksheetNames = []; $xml = new XMLReader(); $xml->xml( - $this->securityScanner->scanFile('zip://' . realpath($pFilename) . '#content.xml'), + $this->securityScanner->scanFile('zip://' . realpath($pFilename) . '#' . self::INITIAL_FILE), null, Settings::getLibXmlLoaderOptions() ); @@ -145,18 +137,13 @@ class Ods extends BaseReader */ public function listWorksheetInfo($pFilename) { - File::assertFile($pFilename); + File::assertFile($pFilename, self::INITIAL_FILE); $worksheetInfo = []; - $zip = new ZipArchive(); - if ($zip->open($pFilename) !== true) { - throw new ReaderException('Could not open ' . $pFilename . ' for reading! Error opening file.'); - } - $xml = new XMLReader(); $xml->xml( - $this->securityScanner->scanFile('zip://' . realpath($pFilename) . '#content.xml'), + $this->securityScanner->scanFile('zip://' . realpath($pFilename) . '#' . self::INITIAL_FILE), null, Settings::getLibXmlLoaderOptions() ); @@ -231,12 +218,12 @@ class Ods extends BaseReader /** * Loads PhpSpreadsheet from file. * - * @param string $filename - * * @return Spreadsheet */ - public function load($filename) + public function load(string $filename, int $flags = 0) { + $this->processFlags($flags); + // Create new Spreadsheet $spreadsheet = new Spreadsheet(); @@ -253,15 +240,10 @@ class Ods extends BaseReader */ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) { - File::assertFile($pFilename); - - $timezoneObj = new DateTimeZone('Europe/London'); - $GMT = new DateTimeZone('UTC'); + File::assertFile($pFilename, self::INITIAL_FILE); $zip = new ZipArchive(); - if ($zip->open($pFilename) !== true) { - throw new Exception("Could not open {$pFilename} for reading! Error opening file."); - } + $zip->open($pFilename); // Meta @@ -292,7 +274,7 @@ class Ods extends BaseReader $dom = new DOMDocument('1.01', 'UTF-8'); $dom->loadXML( - $this->securityScanner->scan($zip->getFromName('content.xml')), + $this->securityScanner->scan($zip->getFromName(self::INITIAL_FILE)), Settings::getLibXmlLoaderOptions() ); @@ -303,8 +285,10 @@ class Ods extends BaseReader $pageSettings->readStyleCrossReferences($dom); - // Content + $autoFilterReader = new AutoFilter($spreadsheet, $tableNs); + $definedNameReader = new DefinedNames($spreadsheet, $tableNs); + // Content $spreadsheets = $dom->getElementsByTagNameNS($officeNs, 'body') ->item(0) ->getElementsByTagNameNS($officeNs, 'spreadsheet'); @@ -373,15 +357,14 @@ class Ods extends BaseReader break; case 'table-row': if ($childNode->hasAttributeNS($tableNs, 'number-rows-repeated')) { - $rowRepeats = $childNode->getAttributeNS($tableNs, 'number-rows-repeated'); + $rowRepeats = (int) $childNode->getAttributeNS($tableNs, 'number-rows-repeated'); } else { $rowRepeats = 1; } $columnID = 'A'; - foreach ($childNode->childNodes as $key => $cellData) { - // @var \DOMElement $cellData - + /** @var DOMElement $cellData */ + foreach ($childNode->childNodes as $cellData) { if ($this->getReadFilter() !== null) { if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) { ++$columnID; @@ -500,8 +483,7 @@ class Ods extends BaseReader $type = DataType::TYPE_NUMERIC; $value = $cellData->getAttributeNS($officeNs, 'date-value'); - $dateObj = new DateTime($value, $GMT); - $dateObj->setTimeZone($timezoneObj); + $dateObj = new DateTime($value); [$year, $month, $day, $hour, $minute, $second] = explode( ' ', $dateObj->format('Y m d H i s') @@ -532,7 +514,7 @@ class Ods extends BaseReader $dataValue = Date::PHPToExcel( strtotime( - '01-01-1970 ' . implode(':', sscanf($timeValue, 'PT%dH%dM%dS')) + '01-01-1970 ' . implode(':', sscanf($timeValue, 'PT%dH%dM%dS') ?? []) ) ); $formatting = NumberFormat::FORMAT_DATE_TIME4; @@ -642,14 +624,88 @@ class Ods extends BaseReader ++$worksheetID; } - $this->readDefinedRanges($spreadsheet, $workbookData, $tableNs); - $this->readDefinedExpressions($spreadsheet, $workbookData, $tableNs); + $autoFilterReader->read($workbookData); + $definedNameReader->read($workbookData); } $spreadsheet->setActiveSheetIndex(0); + + if ($zip->locateName('settings.xml') !== false) { + $this->processSettings($zip, $spreadsheet); + } + // Return return $spreadsheet; } + private function processSettings(ZipArchive $zip, Spreadsheet $spreadsheet): void + { + $dom = new DOMDocument('1.01', 'UTF-8'); + $dom->loadXML( + $this->securityScanner->scan($zip->getFromName('settings.xml')), + Settings::getLibXmlLoaderOptions() + ); + //$xlinkNs = $dom->lookupNamespaceUri('xlink'); + $configNs = $dom->lookupNamespaceUri('config'); + //$oooNs = $dom->lookupNamespaceUri('ooo'); + $officeNs = $dom->lookupNamespaceUri('office'); + $settings = $dom->getElementsByTagNameNS($officeNs, 'settings') + ->item(0); + $this->lookForActiveSheet($settings, $spreadsheet, $configNs); + $this->lookForSelectedCells($settings, $spreadsheet, $configNs); + } + + private function lookForActiveSheet(DOMElement $settings, Spreadsheet $spreadsheet, string $configNs): void + { + /** @var DOMElement $t */ + foreach ($settings->getElementsByTagNameNS($configNs, 'config-item') as $t) { + if ($t->getAttributeNs($configNs, 'name') === 'ActiveTable') { + try { + $spreadsheet->setActiveSheetIndexByName($t->nodeValue); + } catch (Throwable $e) { + // do nothing + } + + break; + } + } + } + + private function lookForSelectedCells(DOMElement $settings, Spreadsheet $spreadsheet, string $configNs): void + { + /** @var DOMElement $t */ + foreach ($settings->getElementsByTagNameNS($configNs, 'config-item-map-named') as $t) { + if ($t->getAttributeNs($configNs, 'name') === 'Tables') { + foreach ($t->getElementsByTagNameNS($configNs, 'config-item-map-entry') as $ws) { + $setRow = $setCol = ''; + $wsname = $ws->getAttributeNs($configNs, 'name'); + foreach ($ws->getElementsByTagNameNS($configNs, 'config-item') as $configItem) { + $attrName = $configItem->getAttributeNs($configNs, 'name'); + if ($attrName === 'CursorPositionX') { + $setCol = $configItem->nodeValue; + } + if ($attrName === 'CursorPositionY') { + $setRow = $configItem->nodeValue; + } + } + $this->setSelected($spreadsheet, $wsname, $setCol, $setRow); + } + + break; + } + } + } + + private function setSelected(Spreadsheet $spreadsheet, string $wsname, string $setCol, string $setRow): void + { + if (is_numeric($setCol) && is_numeric($setRow)) { + try { + $spreadsheet->getSheetByName($wsname)->setSelectedCellByColumnAndRow($setCol + 1, $setRow + 1); + } catch (Throwable $e) { + // do nothing + } + } + } + /** * Recursively scan element. * @@ -698,26 +754,6 @@ class Ods extends BaseReader return $value; } - private function convertToExcelAddressValue(string $openOfficeAddress): string - { - $excelAddress = $openOfficeAddress; - - // Cell range 3-d reference - // As we don't support 3-d ranges, we're just going to take a quick and dirty approach - // and assume that the second worksheet reference is the same as the first - $excelAddress = preg_replace('/\$?([^\.]+)\.([^\.]+):\$?([^\.]+)\.([^\.]+)/miu', '$1!$2:$4', $excelAddress); - // Cell range reference in another sheet - $excelAddress = preg_replace('/\$?([^\.]+)\.([^\.]+):\.([^\.]+)/miu', '$1!$2:$3', $excelAddress); - // Cell reference in another sheet - $excelAddress = preg_replace('/\$?([^\.]+)\.([^\.]+)/miu', '$1!$2', $excelAddress); - // Cell range reference - $excelAddress = preg_replace('/\.([^\.]+):\.([^\.]+)/miu', '$1:$2', $excelAddress); - // Simple cell reference - $excelAddress = preg_replace('/\.([^\.]+)/miu', '$1', $excelAddress); - - return $excelAddress; - } - private function convertToExcelFormulaValue(string $openOfficeFormula): string { $temp = explode('"', $openOfficeFormula); @@ -728,11 +764,13 @@ class Ods extends BaseReader // Cell range reference in another sheet $value = preg_replace('/\[\$?([^\.]+)\.([^\.]+):\.([^\.]+)\]/miu', '$1!$2:$3', $value); // Cell reference in another sheet - $value = preg_replace('/\[\$?([^\.]+)\.([^\.]+)\]/miu', '$1!$2', $value); + $value = preg_replace('/\[\$?([^\.]+)\.([^\.]+)\]/miu', '$1!$2', $value ?? ''); // Cell range reference - $value = preg_replace('/\[\.([^\.]+):\.([^\.]+)\]/miu', '$1:$2', $value); + $value = preg_replace('/\[\.([^\.]+):\.([^\.]+)\]/miu', '$1:$2', $value ?? ''); // Simple cell reference - $value = preg_replace('/\[\.([^\.]+)\]/miu', '$1', $value); + $value = preg_replace('/\[\.([^\.]+)\]/miu', '$1', $value ?? ''); + // Convert references to defined names/formulae + $value = str_replace('$$', '', $value ?? ''); $value = Calculation::translateSeparator(';', ',', $value, $inBraces); } @@ -743,53 +781,4 @@ class Ods extends BaseReader return $excelFormula; } - - /** - * Read any Named Ranges that are defined in this spreadsheet. - */ - private function readDefinedRanges(Spreadsheet $spreadsheet, DOMElement $workbookData, string $tableNs): void - { - $namedRanges = $workbookData->getElementsByTagNameNS($tableNs, 'named-range'); - foreach ($namedRanges as $definedNameElement) { - $definedName = $definedNameElement->getAttributeNS($tableNs, 'name'); - $baseAddress = $definedNameElement->getAttributeNS($tableNs, 'base-cell-address'); - $range = $definedNameElement->getAttributeNS($tableNs, 'cell-range-address'); - - $baseAddress = $this->convertToExcelAddressValue($baseAddress); - $range = $this->convertToExcelAddressValue($range); - - $this->addDefinedName($spreadsheet, $baseAddress, $definedName, $range); - } - } - - /** - * Read any Named Formulae that are defined in this spreadsheet. - */ - private function readDefinedExpressions(Spreadsheet $spreadsheet, DOMElement $workbookData, string $tableNs): void - { - $namedExpressions = $workbookData->getElementsByTagNameNS($tableNs, 'named-expression'); - foreach ($namedExpressions as $definedNameElement) { - $definedName = $definedNameElement->getAttributeNS($tableNs, 'name'); - $baseAddress = $definedNameElement->getAttributeNS($tableNs, 'base-cell-address'); - $expression = $definedNameElement->getAttributeNS($tableNs, 'expression'); - - $baseAddress = $this->convertToExcelAddressValue($baseAddress); - $expression = $this->convertToExcelFormulaValue($expression); - - $this->addDefinedName($spreadsheet, $baseAddress, $definedName, $expression); - } - } - - /** - * Assess scope and store the Defined Name. - */ - private function addDefinedName(Spreadsheet $spreadsheet, string $baseAddress, string $definedName, string $value): void - { - [$sheetReference] = Worksheet::extractSheetTitle($baseAddress, true); - $worksheet = $spreadsheet->getSheetByName($sheetReference); - // Worksheet might still be null if we're only loading selected sheets rather than the full spreadsheet - if ($worksheet !== null) { - $spreadsheet->addDefinedName(DefinedName::createInstance((string) $definedName, $worksheet, $value)); - } - } } diff --git a/src/PhpSpreadsheet/Reader/Ods/AutoFilter.php b/src/PhpSpreadsheet/Reader/Ods/AutoFilter.php new file mode 100644 index 00000000..bdc8b3ff --- /dev/null +++ b/src/PhpSpreadsheet/Reader/Ods/AutoFilter.php @@ -0,0 +1,45 @@ +readAutoFilters($workbookData); + } + + protected function readAutoFilters(DOMElement $workbookData): void + { + $databases = $workbookData->getElementsByTagNameNS($this->tableNs, 'database-ranges'); + + foreach ($databases as $autofilters) { + foreach ($autofilters->childNodes as $autofilter) { + $autofilterRange = $this->getAttributeValue($autofilter, 'target-range-address'); + if ($autofilterRange !== null) { + $baseAddress = $this->convertToExcelAddressValue($autofilterRange); + $this->spreadsheet->getActiveSheet()->setAutoFilter($baseAddress); + } + } + } + } + + protected function getAttributeValue(?DOMNode $node, string $attributeName): ?string + { + if ($node !== null && $node->attributes !== null) { + $attribute = $node->attributes->getNamedItemNS( + $this->tableNs, + $attributeName + ); + + if ($attribute !== null) { + return $attribute->nodeValue; + } + } + + return null; + } +} diff --git a/src/PhpSpreadsheet/Reader/Ods/BaseReader.php b/src/PhpSpreadsheet/Reader/Ods/BaseReader.php new file mode 100644 index 00000000..17e2d4d5 --- /dev/null +++ b/src/PhpSpreadsheet/Reader/Ods/BaseReader.php @@ -0,0 +1,77 @@ +spreadsheet = $spreadsheet; + $this->tableNs = $tableNs; + } + + abstract public function read(DOMElement $workbookData): void; + + protected function convertToExcelAddressValue(string $openOfficeAddress): string + { + $excelAddress = $openOfficeAddress; + + // Cell range 3-d reference + // As we don't support 3-d ranges, we're just going to take a quick and dirty approach + // and assume that the second worksheet reference is the same as the first + $excelAddress = preg_replace('/\$?([^\.]+)\.([^\.]+):\$?([^\.]+)\.([^\.]+)/miu', '$1!$2:$4', $excelAddress); + // Cell range reference in another sheet + $excelAddress = preg_replace('/\$?([^\.]+)\.([^\.]+):\.([^\.]+)/miu', '$1!$2:$3', $excelAddress ?? ''); + // Cell reference in another sheet + $excelAddress = preg_replace('/\$?([^\.]+)\.([^\.]+)/miu', '$1!$2', $excelAddress ?? ''); + // Cell range reference + $excelAddress = preg_replace('/\.([^\.]+):\.([^\.]+)/miu', '$1:$2', $excelAddress ?? ''); + // Simple cell reference + $excelAddress = preg_replace('/\.([^\.]+)/miu', '$1', $excelAddress ?? ''); + + return $excelAddress ?? ''; + } + + protected function convertToExcelFormulaValue(string $openOfficeFormula): string + { + $temp = explode('"', $openOfficeFormula); + $tKey = false; + foreach ($temp as &$value) { + // @var string $value + // Only replace in alternate array entries (i.e. non-quoted blocks) + if ($tKey = !$tKey) { + // Cell range reference in another sheet + $value = preg_replace('/\[\$?([^\.]+)\.([^\.]+):\.([^\.]+)\]/miu', '$1!$2:$3', $value); + // Cell reference in another sheet + $value = preg_replace('/\[\$?([^\.]+)\.([^\.]+)\]/miu', '$1!$2', $value ?? ''); + // Cell range reference + $value = preg_replace('/\[\.([^\.]+):\.([^\.]+)\]/miu', '$1:$2', $value ?? ''); + // Simple cell reference + $value = preg_replace('/\[\.([^\.]+)\]/miu', '$1', $value ?? ''); + // Convert references to defined names/formulae + $value = str_replace('$$', '', $value ?? ''); + + $value = Calculation::translateSeparator(';', ',', $value, $inBraces); + } + } + + // Then rebuild the formula string + $excelFormula = implode('"', $temp); + + return $excelFormula; + } +} diff --git a/src/PhpSpreadsheet/Reader/Ods/DefinedNames.php b/src/PhpSpreadsheet/Reader/Ods/DefinedNames.php new file mode 100644 index 00000000..6810a3c7 --- /dev/null +++ b/src/PhpSpreadsheet/Reader/Ods/DefinedNames.php @@ -0,0 +1,66 @@ +readDefinedRanges($workbookData); + $this->readDefinedExpressions($workbookData); + } + + /** + * Read any Named Ranges that are defined in this spreadsheet. + */ + protected function readDefinedRanges(DOMElement $workbookData): void + { + $namedRanges = $workbookData->getElementsByTagNameNS($this->tableNs, 'named-range'); + foreach ($namedRanges as $definedNameElement) { + $definedName = $definedNameElement->getAttributeNS($this->tableNs, 'name'); + $baseAddress = $definedNameElement->getAttributeNS($this->tableNs, 'base-cell-address'); + $range = $definedNameElement->getAttributeNS($this->tableNs, 'cell-range-address'); + + $baseAddress = $this->convertToExcelAddressValue($baseAddress); + $range = $this->convertToExcelAddressValue($range); + + $this->addDefinedName($baseAddress, $definedName, $range); + } + } + + /** + * Read any Named Formulae that are defined in this spreadsheet. + */ + protected function readDefinedExpressions(DOMElement $workbookData): void + { + $namedExpressions = $workbookData->getElementsByTagNameNS($this->tableNs, 'named-expression'); + foreach ($namedExpressions as $definedNameElement) { + $definedName = $definedNameElement->getAttributeNS($this->tableNs, 'name'); + $baseAddress = $definedNameElement->getAttributeNS($this->tableNs, 'base-cell-address'); + $expression = $definedNameElement->getAttributeNS($this->tableNs, 'expression'); + + $baseAddress = $this->convertToExcelAddressValue($baseAddress); + $expression = substr($expression, strpos($expression, ':=') + 1); + $expression = $this->convertToExcelFormulaValue($expression); + + $this->addDefinedName($baseAddress, $definedName, $expression); + } + } + + /** + * Assess scope and store the Defined Name. + */ + private function addDefinedName(string $baseAddress, string $definedName, string $value): void + { + [$sheetReference] = Worksheet::extractSheetTitle($baseAddress, true); + $worksheet = $this->spreadsheet->getSheetByName($sheetReference); + // Worksheet might still be null if we're only loading selected sheets rather than the full spreadsheet + if ($worksheet !== null) { + $this->spreadsheet->addDefinedName(DefinedName::createInstance((string) $definedName, $worksheet, $value)); + } + } +} diff --git a/src/PhpSpreadsheet/Reader/Ods/PageSettings.php b/src/PhpSpreadsheet/Reader/Ods/PageSettings.php index 77341aab..8d24fd0c 100644 --- a/src/PhpSpreadsheet/Reader/Ods/PageSettings.php +++ b/src/PhpSpreadsheet/Reader/Ods/PageSettings.php @@ -54,10 +54,10 @@ class PageSettings $marginBottom = $pageLayoutProperties->getAttributeNS($this->stylesFo, 'margin-bottom'); $header = $styleSet->getElementsByTagNameNS($this->stylesNs, 'header-style')[0]; $headerProperties = $header->getElementsByTagNameNS($this->stylesNs, 'header-footer-properties')[0]; - $marginHeader = $headerProperties->getAttributeNS($this->stylesFo, 'min-height'); + $marginHeader = isset($headerProperties) ? $headerProperties->getAttributeNS($this->stylesFo, 'min-height') : null; $footer = $styleSet->getElementsByTagNameNS($this->stylesNs, 'footer-style')[0]; $footerProperties = $footer->getElementsByTagNameNS($this->stylesNs, 'header-footer-properties')[0]; - $marginFooter = $footerProperties->getAttributeNS($this->stylesFo, 'min-height'); + $marginFooter = isset($footerProperties) ? $footerProperties->getAttributeNS($this->stylesFo, 'min-height') : null; $this->pageLayoutStyles[$styleName] = (object) [ 'orientation' => $styleOrientation ?: PageSetup::ORIENTATION_DEFAULT, diff --git a/src/PhpSpreadsheet/Reader/Ods/Properties.php b/src/PhpSpreadsheet/Reader/Ods/Properties.php index d0a45e6a..fc789367 100644 --- a/src/PhpSpreadsheet/Reader/Ods/Properties.php +++ b/src/PhpSpreadsheet/Reader/Ods/Properties.php @@ -26,7 +26,7 @@ class Properties $this->setCoreProperties($docProps, $officePropertiesDC); } - $officePropertyMeta = (object) []; + $officePropertyMeta = []; if (isset($namespacesMeta['dc'])) { $officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']); } @@ -55,9 +55,7 @@ class Properties break; case 'date': - $creationDate = strtotime($propertyValue); - $docProps->setCreated($creationDate); - $docProps->setModified($creationDate); + $docProps->setModified($propertyValue); break; case 'description': @@ -86,8 +84,7 @@ class Properties break; case 'creation-date': - $creationDate = strtotime($propertyValue); - $docProps->setCreated($creationDate); + $docProps->setCreated($propertyValue); break; case 'user-defined': diff --git a/src/PhpSpreadsheet/Reader/Security/XmlScanner.php b/src/PhpSpreadsheet/Reader/Security/XmlScanner.php index a65797c1..c9c3ecc0 100644 --- a/src/PhpSpreadsheet/Reader/Security/XmlScanner.php +++ b/src/PhpSpreadsheet/Reader/Security/XmlScanner.php @@ -18,6 +18,11 @@ class XmlScanner private static $libxmlDisableEntityLoaderValue; + /** + * @var bool + */ + private static $shutdownRegistered = false; + public function __construct($pattern = 'pattern = $pattern; @@ -25,7 +30,10 @@ class XmlScanner $this->disableEntityLoaderCheck(); // A fatal error will bypass the destructor, so we register a shutdown here - register_shutdown_function([__CLASS__, 'shutdown']); + if (!self::$shutdownRegistered) { + self::$shutdownRegistered = true; + register_shutdown_function([__CLASS__, 'shutdown']); + } } public static function getInstance(Reader\IReader $reader) diff --git a/src/PhpSpreadsheet/Reader/Slk.php b/src/PhpSpreadsheet/Reader/Slk.php index f1926d93..5e1525d6 100644 --- a/src/PhpSpreadsheet/Reader/Slk.php +++ b/src/PhpSpreadsheet/Reader/Slk.php @@ -2,7 +2,6 @@ namespace PhpOffice\PhpSpreadsheet\Reader; -use InvalidArgumentException; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException; @@ -65,21 +64,17 @@ class Slk extends BaseReader /** * Validate that the current file is a SYLK file. - * - * @param string $filename - * - * @return bool */ - public function canRead($filename) + public function canRead(string $filename): bool { try { $this->openFile($filename); - } catch (InvalidArgumentException $e) { + } catch (ReaderException $e) { return false; } // Read sample data (first 2 KB will do) - $data = fread($this->fileHandle, 2048); + $data = (string) fread($this->fileHandle, 2048); // Count delimiters in file $delimiterCount = substr_count($data, ';'); @@ -169,7 +164,7 @@ class Slk extends BaseReader foreach ($rowData as $rowDatum) { switch ($rowDatum[0]) { case 'X': - $columnIndex = substr($rowDatum, 1) - 1; + $columnIndex = (int) substr($rowDatum, 1) - 1; break; case 'Y': @@ -197,12 +192,12 @@ class Slk extends BaseReader /** * Loads PhpSpreadsheet from file. * - * @param string $filename - * * @return Spreadsheet */ - public function load($filename) + public function load(string $filename, int $flags = 0) { + $this->processFlags($flags); + // Create new Spreadsheet $spreadsheet = new Spreadsheet(); @@ -210,7 +205,7 @@ class Slk extends BaseReader return $this->loadIntoExisting($filename, $spreadsheet); } - private $colorArray = [ + private const COLOR_ARRAY = [ 'FF00FFFF', // 0 - cyan 'FF000000', // 1 - black 'FFFFFFFF', // 2 - white @@ -221,7 +216,7 @@ class Slk extends BaseReader 'FFFF00FF', // 7 - magenta ]; - private $fontStyleMappings = [ + private const FONT_STYLE_MAPPINGS = [ 'B' => 'bold', 'I' => 'italic', 'U' => 'underline', @@ -235,7 +230,8 @@ class Slk extends BaseReader $key = false; foreach ($temp as &$value) { // Only count/replace in alternate array entries - if ($key = !$key) { + $key = !$key; + if ($key) { preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/', $value, $cellReferences, PREG_SET_ORDER + PREG_OFFSET_CAPTURE); // Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way // through the formula from left to right. Reversing means that we work right to left.through @@ -251,7 +247,7 @@ class Slk extends BaseReader } // Bracketed R references are relative to the current row if ($rowReference[0] == '[') { - $rowReference = $row + trim($rowReference, '[]'); + $rowReference = (int) $row + (int) trim($rowReference, '[]'); } $columnReference = $cellReference[4][0]; // Empty C reference is the current column @@ -260,7 +256,7 @@ class Slk extends BaseReader } // Bracketed C references are relative to the current column if ($columnReference[0] == '[') { - $columnReference = $column + trim($columnReference, '[]'); + $columnReference = (int) $column + (int) trim($columnReference, '[]'); } $A1CellReference = Coordinate::stringFromColumnIndex($columnReference) . $rowReference; @@ -298,6 +294,15 @@ class Slk extends BaseReader case 'E': $this->processFormula($rowDatum, $hasCalculatedValue, $cellDataFormula, $row, $column); + break; + case 'A': + $comment = substr($rowDatum, 1); + $columnLetter = Coordinate::stringFromColumnIndex((int) $column); + $spreadsheet->getActiveSheet() + ->getComment("$columnLetter$row") + ->getText() + ->createText($comment); + break; } } @@ -357,9 +362,9 @@ class Slk extends BaseReader $this->addWidth($spreadsheet, $columnWidth, $startCol, $endCol); } - private $styleSettingsFont = ['D' => 'bold', 'I' => 'italic']; + private const STYLE_SETTINGS_FONT = ['D' => 'bold', 'I' => 'italic']; - private $styleSettingsBorder = [ + private const STYLE_SETTINGS_BORDER = [ 'B' => 'bottom', 'L' => 'left', 'R' => 'right', @@ -372,10 +377,10 @@ class Slk extends BaseReader $iMax = strlen($styleSettings); for ($i = 0; $i < $iMax; ++$i) { $char = $styleSettings[$i]; - if (array_key_exists($char, $this->styleSettingsFont)) { - $styleData['font'][$this->styleSettingsFont[$char]] = true; - } elseif (array_key_exists($char, $this->styleSettingsBorder)) { - $styleData['borders'][$this->styleSettingsBorder[$char]]['borderStyle'] = Border::BORDER_THIN; + if (array_key_exists($char, self::STYLE_SETTINGS_FONT)) { + $styleData['font'][self::STYLE_SETTINGS_FONT[$char]] = true; + } elseif (array_key_exists($char, self::STYLE_SETTINGS_BORDER)) { + $styleData['borders'][self::STYLE_SETTINGS_BORDER[$char]]['borderStyle'] = Border::BORDER_THIN; } elseif ($char == 'S') { $styleData['fill']['fillType'] = \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_PATTERN_GRAY125; } elseif ($char == 'M') { @@ -409,7 +414,7 @@ class Slk extends BaseReader private function addStyle(Spreadsheet &$spreadsheet, array $styleData, string $row, string $column): void { if ((!empty($styleData)) && $column > '' && $row > '') { - $columnLetter = Coordinate::stringFromColumnIndex($column); + $columnLetter = Coordinate::stringFromColumnIndex((int) $column); $spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($styleData); } } @@ -419,14 +424,14 @@ class Slk extends BaseReader if ($columnWidth > '') { if ($startCol == $endCol) { $startCol = Coordinate::stringFromColumnIndex((int) $startCol); - $spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth); + $spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth((float) $columnWidth); } else { - $startCol = Coordinate::stringFromColumnIndex($startCol); - $endCol = Coordinate::stringFromColumnIndex($endCol); + $startCol = Coordinate::stringFromColumnIndex((int) $startCol); + $endCol = Coordinate::stringFromColumnIndex((int) $endCol); $spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth((float) $columnWidth); do { - $spreadsheet->getActiveSheet()->getColumnDimension(++$startCol)->setWidth($columnWidth); - } while ($startCol != $endCol); + $spreadsheet->getActiveSheet()->getColumnDimension(++$startCol)->setWidth((float) $columnWidth); + } while ($startCol !== $endCol); } } } @@ -469,7 +474,7 @@ class Slk extends BaseReader { if (preg_match('/L([1-9]\\d*)/', $rowDatum, $matches)) { $fontColor = $matches[1] % 8; - $formatArray['font']['color']['argb'] = $this->colorArray[$fontColor]; + $formatArray['font']['color']['argb'] = self::COLOR_ARRAY[$fontColor]; } } @@ -478,8 +483,8 @@ class Slk extends BaseReader $styleSettings = substr($rowDatum, 1); $iMax = strlen($styleSettings); for ($i = 0; $i < $iMax; ++$i) { - if (array_key_exists($styleSettings[$i], $this->fontStyleMappings)) { - $formatArray['font'][$this->fontStyleMappings[$styleSettings[$i]]] = true; + if (array_key_exists($styleSettings[$i], self::FONT_STYLE_MAPPINGS)) { + $formatArray['font'][self::FONT_STYLE_MAPPINGS[$styleSettings[$i]]] = true; } } } diff --git a/src/PhpSpreadsheet/Reader/Xls.php b/src/PhpSpreadsheet/Reader/Xls.php index 97c36eff..a046626c 100644 --- a/src/PhpSpreadsheet/Reader/Xls.php +++ b/src/PhpSpreadsheet/Reader/Xls.php @@ -7,6 +7,7 @@ use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Cell\DataValidation; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\NamedRange; +use PhpOffice\PhpSpreadsheet\Reader\Xls\Style\CellFont; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared\CodePage; use PhpOffice\PhpSpreadsheet\Shared\Date; @@ -16,6 +17,7 @@ use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Shared\OLE; use PhpOffice\PhpSpreadsheet\Shared\OLERead; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; +use PhpOffice\PhpSpreadsheet\Shared\Xls as SharedXls; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Borders; @@ -224,7 +226,7 @@ class Xls extends BaseReader /** * Shared fonts. * - * @var array + * @var Font[] */ private $objFonts; @@ -374,7 +376,7 @@ class Xls extends BaseReader * * @var int */ - private $encryptionStartPos = false; + private $encryptionStartPos = 0; /** * The current RC4 decryption object. @@ -417,14 +419,12 @@ class Xls extends BaseReader /** * Can the current IReader read the file? - * - * @param string $filename - * - * @return bool */ - public function canRead($filename) + public function canRead(string $filename): bool { - File::assertFile($filename); + if (!File::testFileNoThrow($filename)) { + return false; + } try { // Use ParseXL for the hard work. @@ -621,12 +621,12 @@ class Xls extends BaseReader /** * Loads PhpSpreadsheet from file. * - * @param string $filename - * * @return Spreadsheet */ - public function load($filename) + public function load(string $filename, int $flags = 0) { + $this->processFlags($flags); + // Read the OLE file $this->loadOLE($filename); @@ -659,7 +659,7 @@ class Xls extends BaseReader $this->definedname = []; $this->sst = []; $this->drawingGroupData = ''; - $this->xfIndex = ''; + $this->xfIndex = 0; $this->mapCellXfIndex = []; $this->mapCellStyleXfIndex = []; @@ -801,9 +801,10 @@ class Xls extends BaseReader } // treat MSODRAWINGGROUP records, workbook-level Escher + $escherWorkbook = null; if (!$this->readDataOnly && $this->drawingGroupData) { - $escherWorkbook = new Escher(); - $reader = new Xls\Escher($escherWorkbook); + $escher = new Escher(); + $reader = new Xls\Escher($escher); $escherWorkbook = $reader->load($this->drawingGroupData); } @@ -1100,12 +1101,12 @@ class Xls extends BaseReader $endOffsetX = $spContainer->getEndOffsetX(); $endOffsetY = $spContainer->getEndOffsetY(); - $width = \PhpOffice\PhpSpreadsheet\Shared\Xls::getDistanceX($this->phpSheet, $startColumn, $startOffsetX, $endColumn, $endOffsetX); - $height = \PhpOffice\PhpSpreadsheet\Shared\Xls::getDistanceY($this->phpSheet, $startRow, $startOffsetY, $endRow, $endOffsetY); + $width = SharedXls::getDistanceX($this->phpSheet, $startColumn, $startOffsetX, $endColumn, $endOffsetX); + $height = SharedXls::getDistanceY($this->phpSheet, $startRow, $startOffsetY, $endRow, $endOffsetY); // calculate offsetX and offsetY of the shape - $offsetX = $startOffsetX * \PhpOffice\PhpSpreadsheet\Shared\Xls::sizeCol($this->phpSheet, $startColumn) / 1024; - $offsetY = $startOffsetY * \PhpOffice\PhpSpreadsheet\Shared\Xls::sizeRow($this->phpSheet, $startRow) / 256; + $offsetX = $startOffsetX * SharedXls::sizeCol($this->phpSheet, $startColumn) / 1024; + $offsetY = $startOffsetY * SharedXls::sizeRow($this->phpSheet, $startRow) / 256; switch ($obj['otObjType']) { case 0x19: @@ -1133,38 +1134,44 @@ class Xls extends BaseReader continue 2; } - $BSECollection = $escherWorkbook->getDggContainer()->getBstoreContainer()->getBSECollection(); - $BSE = $BSECollection[$BSEindex - 1]; - $blipType = $BSE->getBlipType(); + if ($escherWorkbook) { + $BSECollection = $escherWorkbook->getDggContainer()->getBstoreContainer()->getBSECollection(); + $BSE = $BSECollection[$BSEindex - 1]; + $blipType = $BSE->getBlipType(); - // need check because some blip types are not supported by Escher reader such as EMF - if ($blip = $BSE->getBlip()) { - $ih = imagecreatefromstring($blip->getData()); - $drawing = new MemoryDrawing(); - $drawing->setImageResource($ih); + // need check because some blip types are not supported by Escher reader such as EMF + if ($blip = $BSE->getBlip()) { + $ih = imagecreatefromstring($blip->getData()); + if ($ih !== false) { + $drawing = new MemoryDrawing(); + $drawing->setImageResource($ih); - // width, height, offsetX, offsetY - $drawing->setResizeProportional(false); - $drawing->setWidth($width); - $drawing->setHeight($height); - $drawing->setOffsetX($offsetX); - $drawing->setOffsetY($offsetY); + // width, height, offsetX, offsetY + $drawing->setResizeProportional(false); + $drawing->setWidth($width); + $drawing->setHeight($height); + $drawing->setOffsetX($offsetX); + $drawing->setOffsetY($offsetY); - switch ($blipType) { + switch ($blipType) { case BSE::BLIPTYPE_JPEG: $drawing->setRenderingFunction(MemoryDrawing::RENDERING_JPEG); $drawing->setMimeType(MemoryDrawing::MIMETYPE_JPEG); break; case BSE::BLIPTYPE_PNG: + imagealphablending($ih, false); + imagesavealpha($ih, true); $drawing->setRenderingFunction(MemoryDrawing::RENDERING_PNG); $drawing->setMimeType(MemoryDrawing::MIMETYPE_PNG); break; } - $drawing->setWorksheet($this->phpSheet); - $drawing->setCoordinates($spContainer->getStartCoordinates()); + $drawing->setWorksheet($this->phpSheet); + $drawing->setCoordinates($spContainer->getStartCoordinates()); + } + } } break; @@ -1293,7 +1300,7 @@ class Xls extends BaseReader // TODO Provide support for named values } } - $this->data = null; + $this->data = ''; return $this->spreadsheet; } @@ -1451,34 +1458,34 @@ class Xls extends BaseReader switch ($id) { case 0x01: // Code Page - $codePage = CodePage::numberToName($value); + $codePage = CodePage::numberToName((int) $value); break; case 0x02: // Title - $this->spreadsheet->getProperties()->setTitle($value); + $this->spreadsheet->getProperties()->setTitle("$value"); break; case 0x03: // Subject - $this->spreadsheet->getProperties()->setSubject($value); + $this->spreadsheet->getProperties()->setSubject("$value"); break; case 0x04: // Author (Creator) - $this->spreadsheet->getProperties()->setCreator($value); + $this->spreadsheet->getProperties()->setCreator("$value"); break; case 0x05: // Keywords - $this->spreadsheet->getProperties()->setKeywords($value); + $this->spreadsheet->getProperties()->setKeywords("$value"); break; case 0x06: // Comments (Description) - $this->spreadsheet->getProperties()->setDescription($value); + $this->spreadsheet->getProperties()->setDescription("$value"); break; case 0x07: // Template // Not supported by PhpSpreadsheet break; case 0x08: // Last Saved By (LastModifiedBy) - $this->spreadsheet->getProperties()->setLastModifiedBy($value); + $this->spreadsheet->getProperties()->setLastModifiedBy("$value"); break; case 0x09: // Revision @@ -1603,11 +1610,11 @@ class Xls extends BaseReader switch ($id) { case 0x01: // Code Page - $codePage = CodePage::numberToName($value); + $codePage = CodePage::numberToName((int) $value); break; case 0x02: // Category - $this->spreadsheet->getProperties()->setCategory($value); + $this->spreadsheet->getProperties()->setCategory("$value"); break; case 0x03: // Presentation Target @@ -1644,11 +1651,11 @@ class Xls extends BaseReader // Not supported by PhpSpreadsheet break; case 0x0E: // Manager - $this->spreadsheet->getProperties()->setManager($value); + $this->spreadsheet->getProperties()->setManager("$value"); break; case 0x0F: // Company - $this->spreadsheet->getProperties()->setCompany($value); + $this->spreadsheet->getProperties()->setCompany("$value"); break; case 0x10: // Links up-to-date @@ -1703,7 +1710,8 @@ class Xls extends BaseReader // max 2048 bytes will probably throw a wobbly. $row = self::getUInt2d($recordData, 0); $extension = true; - $cellAddress = array_pop(array_keys($this->phpSheet->getComments())); + $arrayKeys = array_keys($this->phpSheet->getComments()); + $cellAddress = array_pop($arrayKeys); } $cellAddress = str_replace('$', '', $cellAddress); @@ -2063,39 +2071,11 @@ class Xls extends BaseReader // offset: 8; size: 2; escapement type $escapement = self::getUInt2d($recordData, 8); - switch ($escapement) { - case 0x0001: - $objFont->setSuperscript(true); - - break; - case 0x0002: - $objFont->setSubscript(true); - - break; - } + CellFont::escapement($objFont, $escapement); // offset: 10; size: 1; underline type $underlineType = ord($recordData[10]); - switch ($underlineType) { - case 0x00: - break; // no underline - case 0x01: - $objFont->setUnderline(Font::UNDERLINE_SINGLE); - - break; - case 0x02: - $objFont->setUnderline(Font::UNDERLINE_DOUBLE); - - break; - case 0x21: - $objFont->setUnderline(Font::UNDERLINE_SINGLEACCOUNTING); - - break; - case 0x22: - $objFont->setUnderline(Font::UNDERLINE_DOUBLEACCOUNTING); - - break; - } + CellFont::underline($objFont, $underlineType); // offset: 11; size: 1; font family // offset: 12; size: 1; character set @@ -2145,6 +2125,10 @@ class Xls extends BaseReader } $formatString = $string['value']; + // Apache Open Office sets wrong case writing to xls - issue 2239 + if ($formatString === 'GENERAL') { + $formatString = NumberFormat::FORMAT_GENERAL; + } $this->formats[$indexCode] = $formatString; } } @@ -2194,7 +2178,7 @@ class Xls extends BaseReader $numberFormat = ['formatCode' => $code]; } else { // we set the general format code - $numberFormat = ['formatCode' => 'General']; + $numberFormat = ['formatCode' => NumberFormat::FORMAT_GENERAL]; } $objStyle->getNumberFormat()->setFormatCode($numberFormat['formatCode']); @@ -2215,68 +2199,15 @@ class Xls extends BaseReader // offset: 6; size: 1; Alignment and text break // bit 2-0, mask 0x07; horizontal alignment $horAlign = (0x07 & ord($recordData[6])) >> 0; - switch ($horAlign) { - case 0: - $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_GENERAL); + Xls\Style\CellAlignment::horizontal($objStyle->getAlignment(), $horAlign); - break; - case 1: - $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT); - - break; - case 2: - $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER); - - break; - case 3: - $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT); - - break; - case 4: - $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_FILL); - - break; - case 5: - $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_JUSTIFY); - - break; - case 6: - $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER_CONTINUOUS); - - break; - } // bit 3, mask 0x08; wrap text $wrapText = (0x08 & ord($recordData[6])) >> 3; - switch ($wrapText) { - case 0: - $objStyle->getAlignment()->setWrapText(false); + Xls\Style\CellAlignment::wrap($objStyle->getAlignment(), $wrapText); - break; - case 1: - $objStyle->getAlignment()->setWrapText(true); - - break; - } // bit 6-4, mask 0x70; vertical alignment $vertAlign = (0x70 & ord($recordData[6])) >> 4; - switch ($vertAlign) { - case 0: - $objStyle->getAlignment()->setVertical(Alignment::VERTICAL_TOP); - - break; - case 1: - $objStyle->getAlignment()->setVertical(Alignment::VERTICAL_CENTER); - - break; - case 2: - $objStyle->getAlignment()->setVertical(Alignment::VERTICAL_BOTTOM); - - break; - case 3: - $objStyle->getAlignment()->setVertical(Alignment::VERTICAL_JUSTIFY); - - break; - } + Xls\Style\CellAlignment::vertical($objStyle->getAlignment(), $vertAlign); if ($this->version == self::XLS_BIFF8) { // offset: 7; size: 1; XF_ROTATION: Text rotation angle @@ -2286,8 +2217,8 @@ class Xls extends BaseReader $rotation = $angle; } elseif ($angle <= 180) { $rotation = 90 - $angle; - } elseif ($angle == 255) { - $rotation = -165; + } elseif ($angle == Alignment::TEXTROTATION_STACK_EXCEL) { + $rotation = Alignment::TEXTROTATION_STACK_PHPSPREADSHEET; } $objStyle->getAlignment()->setTextRotation($rotation); @@ -2389,7 +2320,7 @@ class Xls extends BaseReader break; case 1: - $objStyle->getAlignment()->setTextRotation(-165); + $objStyle->getAlignment()->setTextRotation(Alignment::TEXTROTATION_STACK_PHPSPREADSHEET); break; case 2: @@ -2741,6 +2672,7 @@ class Xls extends BaseReader $sheetType = ord($recordData[5]); // offset: 6; size: var; sheet name + $rec_name = null; if ($this->version == self::XLS_BIFF8) { $string = self::readUnicodeStringShort(substr($recordData, 6)); $rec_name = $string['value']; @@ -3017,12 +2949,14 @@ class Xls extends BaseReader // bit: 3; mask: 0x03; 0 = ordinary; 1 = Rich-Text $hasRichText = (($optionFlags & 0x08) != 0); + $formattingRuns = 0; if ($hasRichText) { // number of Rich-Text formatting runs $formattingRuns = self::getUInt2d($recordData, $pos); $pos += 2; } + $extendedRunLength = 0; if ($hasAsian) { // size of Asian phonetic setting $extendedRunLength = self::getInt4d($recordData, $pos); @@ -3033,6 +2967,7 @@ class Xls extends BaseReader $len = ($isCompressed) ? $numChars : $numChars * 2; // look up limit position - Check it again to be sure that no error occurs when parsing SST structure + $limitpos = null; foreach ($spliceOffsets as $spliceOffset) { // it can happen that the string is empty, therefore we need // <= and not just < @@ -3626,7 +3561,7 @@ class Xls extends BaseReader $level = (0x0700 & self::getUInt2d($recordData, 8)) >> 8; // bit: 12; mask: 0x1000; 1 = collapsed - $isCollapsed = (0x1000 & self::getUInt2d($recordData, 8)) >> 12; + $isCollapsed = (bool) ((0x1000 & self::getUInt2d($recordData, 8)) >> 12); // offset: 10; size: 2; not used @@ -3696,7 +3631,7 @@ class Xls extends BaseReader $this->phpSheet->getRowDimension($r + 1)->setOutlineLevel($level); // bit: 4; mask: 0x00000010; 1 = outline group start or ends here... and is collapsed - $isCollapsed = (0x00000010 & self::getInt4d($recordData, 12)) >> 4; + $isCollapsed = (bool) ((0x00000010 & self::getInt4d($recordData, 12)) >> 4); $this->phpSheet->getRowDimension($r + 1)->setCollapsed($isCollapsed); // bit: 5; mask: 0x00000020; 1 = row is hidden @@ -3814,12 +3749,10 @@ class Xls extends BaseReader } else { $textRun = $richText->createTextRun($text); if (isset($fmtRuns[$i - 1])) { - if ($fmtRuns[$i - 1]['fontIndex'] < 4) { - $fontIndex = $fmtRuns[$i - 1]['fontIndex']; - } else { - // this has to do with that index 4 is omitted in all BIFF versions for some strange reason - // check the OpenOffice documentation of the FONT record - $fontIndex = $fmtRuns[$i - 1]['fontIndex'] - 1; + $fontIndex = $fmtRuns[$i - 1]['fontIndex']; + + if (array_key_exists($fontIndex, $this->objFonts) === false) { + $fontIndex = count($this->objFonts) - 1; } $textRun->setFont(clone $this->objFonts[$fontIndex]); } @@ -4384,6 +4317,8 @@ class Xls extends BaseReader // offset: 4; size: 2; index to first visible colum $firstVisibleColumn = self::getUInt2d($recordData, 4); + $zoomscaleInPageBreakPreview = 0; + $zoomscaleInNormalView = 0; if ($this->version === self::XLS_BIFF8) { // offset: 8; size: 2; not used // offset: 10; size: 2; cached magnification factor in page break preview (in percent); 0 = Default (60%) @@ -7181,6 +7116,7 @@ class Xls extends BaseReader { [$baseCol, $baseRow] = Coordinate::coordinateFromString($baseCell); $baseCol = Coordinate::columnIndexFromString($baseCol) - 1; + $baseRow = (int) $baseRow; // offset: 0; size: 2; index to row (0... 65535) (or offset (-32768... 32767)) $rowIndex = self::getUInt2d($cellAddressStructure, 0); @@ -7358,8 +7294,8 @@ class Xls extends BaseReader */ private function readBIFF8CellRangeAddressB($subData, $baseCell = 'A1') { - [$baseCol, $baseRow] = Coordinate::coordinateFromString($baseCell); - $baseCol = Coordinate::columnIndexFromString($baseCol) - 1; + [$baseCol, $baseRow] = Coordinate::indexesFromString($baseCell); + $baseCol = $baseCol - 1; // TODO: if cell range is just a single cell, should this funciton // not just return e.g. 'A1' and not 'A1:A1' ? @@ -7635,6 +7571,8 @@ class Xls extends BaseReader $size = 9; break; + default: + throw new PhpSpreadsheetException('Unsupported BIFF8 constant'); } return [ diff --git a/src/PhpSpreadsheet/Reader/Xls/Color.php b/src/PhpSpreadsheet/Reader/Xls/Color.php index c45f88c7..06c2d0b9 100644 --- a/src/PhpSpreadsheet/Reader/Xls/Color.php +++ b/src/PhpSpreadsheet/Reader/Xls/Color.php @@ -20,7 +20,7 @@ class Color if ($color <= 0x07 || $color >= 0x40) { // special built-in color return Color\BuiltIn::lookup($color); - } elseif (isset($palette, $palette[$color - 8])) { + } elseif (isset($palette[$color - 8])) { // palette color, color index 0x08 maps to pallete index 0 return $palette[$color - 8]; } diff --git a/src/PhpSpreadsheet/Reader/Xls/Escher.php b/src/PhpSpreadsheet/Reader/Xls/Escher.php index 306fc8f1..e9c95c88 100644 --- a/src/PhpSpreadsheet/Reader/Xls/Escher.php +++ b/src/PhpSpreadsheet/Reader/Xls/Escher.php @@ -71,6 +71,27 @@ class Escher $this->object = $object; } + private const WHICH_ROUTINE = [ + self::DGGCONTAINER => 'readDggContainer', + self::DGG => 'readDgg', + self::BSTORECONTAINER => 'readBstoreContainer', + self::BSE => 'readBSE', + self::BLIPJPEG => 'readBlipJPEG', + self::BLIPPNG => 'readBlipPNG', + self::OPT => 'readOPT', + self::TERTIARYOPT => 'readTertiaryOPT', + self::SPLITMENUCOLORS => 'readSplitMenuColors', + self::DGCONTAINER => 'readDgContainer', + self::DG => 'readDg', + self::SPGRCONTAINER => 'readSpgrContainer', + self::SPCONTAINER => 'readSpContainer', + self::SPGR => 'readSpgr', + self::SP => 'readSp', + self::CLIENTTEXTBOX => 'readClientTextbox', + self::CLIENTANCHOR => 'readClientAnchor', + self::CLIENTDATA => 'readClientData', + ]; + /** * Load Escher stream data. May be a partial Escher stream. * @@ -91,84 +112,9 @@ class Escher while ($this->pos < $this->dataSize) { // offset: 2; size: 2: Record Type $fbt = Xls::getUInt2d($this->data, $this->pos + 2); - - switch ($fbt) { - case self::DGGCONTAINER: - $this->readDggContainer(); - - break; - case self::DGG: - $this->readDgg(); - - break; - case self::BSTORECONTAINER: - $this->readBstoreContainer(); - - break; - case self::BSE: - $this->readBSE(); - - break; - case self::BLIPJPEG: - $this->readBlipJPEG(); - - break; - case self::BLIPPNG: - $this->readBlipPNG(); - - break; - case self::OPT: - $this->readOPT(); - - break; - case self::TERTIARYOPT: - $this->readTertiaryOPT(); - - break; - case self::SPLITMENUCOLORS: - $this->readSplitMenuColors(); - - break; - case self::DGCONTAINER: - $this->readDgContainer(); - - break; - case self::DG: - $this->readDg(); - - break; - case self::SPGRCONTAINER: - $this->readSpgrContainer(); - - break; - case self::SPCONTAINER: - $this->readSpContainer(); - - break; - case self::SPGR: - $this->readSpgr(); - - break; - case self::SP: - $this->readSp(); - - break; - case self::CLIENTTEXTBOX: - $this->readClientTextbox(); - - break; - case self::CLIENTANCHOR: - $this->readClientAnchor(); - - break; - case self::CLIENTDATA: - $this->readClientData(); - - break; - default: - $this->readDefault(); - - break; + $routine = self::WHICH_ROUTINE[$fbt] ?? 'readDefault'; + if (method_exists($this, $routine)) { + $this->$routine(); } } @@ -181,16 +127,16 @@ class Escher private function readDefault(): void { // offset 0; size: 2; recVer and recInstance - $verInstance = Xls::getUInt2d($this->data, $this->pos); + //$verInstance = Xls::getUInt2d($this->data, $this->pos); // offset: 2; size: 2: Record Type - $fbt = Xls::getUInt2d($this->data, $this->pos + 2); + //$fbt = Xls::getUInt2d($this->data, $this->pos + 2); // bit: 0-3; mask: 0x000F; recVer - $recVer = (0x000F & $verInstance) >> 0; + //$recVer = (0x000F & $verInstance) >> 0; $length = Xls::getInt4d($this->data, $this->pos + 4); - $recordData = substr($this->data, $this->pos + 8, $length); + //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; @@ -209,7 +155,7 @@ class Escher // record is a container, read contents $dggContainer = new DggContainer(); - $this->object->setDggContainer($dggContainer); + $this->applyAttribute('setDggContainer', $dggContainer); $reader = new self($dggContainer); $reader->load($recordData); } @@ -220,7 +166,7 @@ class Escher private function readDgg(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); - $recordData = substr($this->data, $this->pos + 8, $length); + //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; @@ -239,7 +185,7 @@ class Escher // record is a container, read contents $bstoreContainer = new BstoreContainer(); - $this->object->setBstoreContainer($bstoreContainer); + $this->applyAttribute('setBstoreContainer', $bstoreContainer); $reader = new self($bstoreContainer); $reader->load($recordData); } @@ -262,45 +208,45 @@ class Escher // add BSE to BstoreContainer $BSE = new BSE(); - $this->object->addBSE($BSE); + $this->applyAttribute('addBSE', $BSE); $BSE->setBLIPType($recInstance); // offset: 0; size: 1; btWin32 (MSOBLIPTYPE) - $btWin32 = ord($recordData[0]); + //$btWin32 = ord($recordData[0]); // offset: 1; size: 1; btWin32 (MSOBLIPTYPE) - $btMacOS = ord($recordData[1]); + //$btMacOS = ord($recordData[1]); // offset: 2; size: 16; MD4 digest - $rgbUid = substr($recordData, 2, 16); + //$rgbUid = substr($recordData, 2, 16); // offset: 18; size: 2; tag - $tag = Xls::getUInt2d($recordData, 18); + //$tag = Xls::getUInt2d($recordData, 18); // offset: 20; size: 4; size of BLIP in bytes - $size = Xls::getInt4d($recordData, 20); + //$size = Xls::getInt4d($recordData, 20); // offset: 24; size: 4; number of references to this BLIP - $cRef = Xls::getInt4d($recordData, 24); + //$cRef = Xls::getInt4d($recordData, 24); // offset: 28; size: 4; MSOFO file offset - $foDelay = Xls::getInt4d($recordData, 28); + //$foDelay = Xls::getInt4d($recordData, 28); // offset: 32; size: 1; unused1 - $unused1 = ord($recordData[32]); + //$unused1 = ord($recordData[32]); // offset: 33; size: 1; size of nameData in bytes (including null terminator) $cbName = ord($recordData[33]); // offset: 34; size: 1; unused2 - $unused2 = ord($recordData[34]); + //$unused2 = ord($recordData[34]); // offset: 35; size: 1; unused3 - $unused3 = ord($recordData[35]); + //$unused3 = ord($recordData[35]); // offset: 36; size: $cbName; nameData - $nameData = substr($recordData, 36, $cbName); + //$nameData = substr($recordData, 36, $cbName); // offset: 36 + $cbName, size: var; the BLIP data $blipData = substr($recordData, 36 + $cbName); @@ -329,17 +275,17 @@ class Escher $pos = 0; // offset: 0; size: 16; rgbUid1 (MD4 digest of) - $rgbUid1 = substr($recordData, 0, 16); + //$rgbUid1 = substr($recordData, 0, 16); $pos += 16; // offset: 16; size: 16; rgbUid2 (MD4 digest), only if $recInstance = 0x46B or 0x6E3 if (in_array($recInstance, [0x046B, 0x06E3])) { - $rgbUid2 = substr($recordData, 16, 16); + //$rgbUid2 = substr($recordData, 16, 16); $pos += 16; } // offset: var; size: 1; tag - $tag = ord($recordData[$pos]); + //$tag = ord($recordData[$pos]); ++$pos; // offset: var; size: var; the raw image data @@ -348,7 +294,7 @@ class Escher $blip = new Blip(); $blip->setData($data); - $this->object->setBlip($blip); + $this->applyAttribute('setBlip', $blip); } /** @@ -370,17 +316,17 @@ class Escher $pos = 0; // offset: 0; size: 16; rgbUid1 (MD4 digest of) - $rgbUid1 = substr($recordData, 0, 16); + //$rgbUid1 = substr($recordData, 0, 16); $pos += 16; // offset: 16; size: 16; rgbUid2 (MD4 digest), only if $recInstance = 0x46B or 0x6E3 if ($recInstance == 0x06E1) { - $rgbUid2 = substr($recordData, 16, 16); + //$rgbUid2 = substr($recordData, 16, 16); $pos += 16; } // offset: var; size: 1; tag - $tag = ord($recordData[$pos]); + //$tag = ord($recordData[$pos]); ++$pos; // offset: var; size: var; the raw image data @@ -389,7 +335,7 @@ class Escher $blip = new Blip(); $blip->setData($data); - $this->object->setBlip($blip); + $this->applyAttribute('setBlip', $blip); } /** @@ -419,10 +365,10 @@ class Escher // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance - $recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; + //$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); - $recordData = substr($this->data, $this->pos + 8, $length); + //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; @@ -434,7 +380,7 @@ class Escher private function readSplitMenuColors(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); - $recordData = substr($this->data, $this->pos + 8, $length); + //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; @@ -453,9 +399,9 @@ class Escher // record is a container, read contents $dgContainer = new DgContainer(); - $this->object->setDgContainer($dgContainer); + $this->applyAttribute('setDgContainer', $dgContainer); $reader = new self($dgContainer); - $escher = $reader->load($recordData); + $reader->load($recordData); } /** @@ -464,7 +410,7 @@ class Escher private function readDg(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); - $recordData = substr($this->data, $this->pos + 8, $length); + //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; @@ -489,13 +435,13 @@ class Escher if ($this->object instanceof DgContainer) { // DgContainer $this->object->setSpgrContainer($spgrContainer); - } else { + } elseif ($this->object instanceof SpgrContainer) { // SpgrContainer $this->object->addChild($spgrContainer); } $reader = new self($spgrContainer); - $escher = $reader->load($recordData); + $reader->load($recordData); } /** @@ -508,14 +454,14 @@ class Escher // add spContainer to spgrContainer $spContainer = new SpContainer(); - $this->object->addChild($spContainer); + $this->applyAttribute('addChild', $spContainer); // move stream pointer to next record $this->pos += 8 + $length; // record is a container, read contents $reader = new self($spContainer); - $escher = $reader->load($recordData); + $reader->load($recordData); } /** @@ -524,7 +470,7 @@ class Escher private function readSpgr(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); - $recordData = substr($this->data, $this->pos + 8, $length); + //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; @@ -538,10 +484,10 @@ class Escher // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance - $recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; + //$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); - $recordData = substr($this->data, $this->pos + 8, $length); + //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; @@ -555,10 +501,10 @@ class Escher // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance - $recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; + //$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); - $recordData = substr($this->data, $this->pos + 8, $length); + //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; @@ -599,23 +545,22 @@ class Escher // offset: 16; size: 2; bottom-right corner vertical offset in 1/256 of row height $endOffsetY = Xls::getUInt2d($recordData, 16); - // set the start coordinates - $this->object->setStartCoordinates(Coordinate::stringFromColumnIndex($c1 + 1) . ($r1 + 1)); + $this->applyAttribute('setStartCoordinates', Coordinate::stringFromColumnIndex($c1 + 1) . ($r1 + 1)); + $this->applyAttribute('setStartOffsetX', $startOffsetX); + $this->applyAttribute('setStartOffsetY', $startOffsetY); + $this->applyAttribute('setEndCoordinates', Coordinate::stringFromColumnIndex($c2 + 1) . ($r2 + 1)); + $this->applyAttribute('setEndOffsetX', $endOffsetX); + $this->applyAttribute('setEndOffsetY', $endOffsetY); + } - // set the start offsetX - $this->object->setStartOffsetX($startOffsetX); - - // set the start offsetY - $this->object->setStartOffsetY($startOffsetY); - - // set the end coordinates - $this->object->setEndCoordinates(Coordinate::stringFromColumnIndex($c2 + 1) . ($r2 + 1)); - - // set the end offsetX - $this->object->setEndOffsetX($endOffsetX); - - // set the end offsetY - $this->object->setEndOffsetY($endOffsetY); + /** + * @param mixed $value + */ + private function applyAttribute(string $name, $value): void + { + if (method_exists($this->object, $name)) { + $this->object->$name($value); + } } /** @@ -624,7 +569,7 @@ class Escher private function readClientData(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); - $recordData = substr($this->data, $this->pos + 8, $length); + //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; @@ -652,7 +597,7 @@ class Escher $opidOpid = (0x3FFF & $opid) >> 0; // bit: 14; mask 0x4000; 1 = value in op field is BLIP identifier - $opidFBid = (0x4000 & $opid) >> 14; + //$opidFBid = (0x4000 & $opid) >> 14; // bit: 15; mask 0x8000; 1 = this is a complex property, op field specifies size of complex data $opidFComplex = (0x8000 & $opid) >> 15; @@ -671,7 +616,9 @@ class Escher $value = $op; } - $this->object->setOPT($opidOpid, $value); + if (method_exists($this->object, 'setOPT')) { + $this->object->setOPT($opidOpid, $value); + } } } } diff --git a/src/PhpSpreadsheet/Reader/Xls/MD5.php b/src/PhpSpreadsheet/Reader/Xls/MD5.php index c0417ba6..3e15f641 100644 --- a/src/PhpSpreadsheet/Reader/Xls/MD5.php +++ b/src/PhpSpreadsheet/Reader/Xls/MD5.php @@ -5,12 +5,25 @@ namespace PhpOffice\PhpSpreadsheet\Reader\Xls; class MD5 { // Context + + /** + * @var int + */ private $a; + /** + * @var int + */ private $b; + /** + * @var int + */ private $c; + /** + * @var int + */ private $d; /** @@ -56,7 +69,7 @@ class MD5 * * @param string $data Data to add */ - public function add($data): void + public function add(string $data): void { $words = array_values(unpack('V16', $data)); @@ -148,34 +161,34 @@ class MD5 $this->d = ($this->d + $D) & 0xffffffff; } - private static function f($X, $Y, $Z) + private static function f(int $X, int $Y, int $Z) { return ($X & $Y) | ((~$X) & $Z); // X AND Y OR NOT X AND Z } - private static function g($X, $Y, $Z) + private static function g(int $X, int $Y, int $Z) { return ($X & $Z) | ($Y & (~$Z)); // X AND Z OR Y AND NOT Z } - private static function h($X, $Y, $Z) + private static function h(int $X, int $Y, int $Z) { return $X ^ $Y ^ $Z; // X XOR Y XOR Z } - private static function i($X, $Y, $Z) + private static function i(int $X, int $Y, int $Z) { return $Y ^ ($X | (~$Z)); // Y XOR (X OR NOT Z) } - private static function step($func, &$A, $B, $C, $D, $M, $s, $t): void + private static function step($func, int &$A, int $B, int $C, int $D, int $M, int $s, int $t): void { $A = ($A + call_user_func($func, $B, $C, $D) + $M + $t) & 0xffffffff; $A = self::rotate($A, $s); $A = ($B + $A) & 0xffffffff; } - private static function rotate($decimal, $bits) + private static function rotate(int $decimal, int $bits) { $binary = str_pad(decbin($decimal), 32, '0', STR_PAD_LEFT); diff --git a/src/PhpSpreadsheet/Reader/Xls/Style/Border.php b/src/PhpSpreadsheet/Reader/Xls/Style/Border.php index 91cbe36f..d832eb02 100644 --- a/src/PhpSpreadsheet/Reader/Xls/Style/Border.php +++ b/src/PhpSpreadsheet/Reader/Xls/Style/Border.php @@ -6,7 +6,10 @@ use PhpOffice\PhpSpreadsheet\Style\Border as StyleBorder; class Border { - protected static $map = [ + /** + * @var array + */ + protected static $borderStyleMap = [ 0x00 => StyleBorder::BORDER_NONE, 0x01 => StyleBorder::BORDER_THIN, 0x02 => StyleBorder::BORDER_MEDIUM, @@ -23,18 +26,10 @@ class Border 0x0D => StyleBorder::BORDER_SLANTDASHDOT, ]; - /** - * Map border style - * OpenOffice documentation: 2.5.11. - * - * @param int $index - * - * @return string - */ - public static function lookup($index) + public static function lookup(int $index): string { - if (isset(self::$map[$index])) { - return self::$map[$index]; + if (isset(self::$borderStyleMap[$index])) { + return self::$borderStyleMap[$index]; } return StyleBorder::BORDER_NONE; diff --git a/src/PhpSpreadsheet/Reader/Xls/Style/CellAlignment.php b/src/PhpSpreadsheet/Reader/Xls/Style/CellAlignment.php new file mode 100644 index 00000000..f03d47fa --- /dev/null +++ b/src/PhpSpreadsheet/Reader/Xls/Style/CellAlignment.php @@ -0,0 +1,50 @@ + + */ + protected static $horizontalAlignmentMap = [ + 0 => Alignment::HORIZONTAL_GENERAL, + 1 => Alignment::HORIZONTAL_LEFT, + 2 => Alignment::HORIZONTAL_CENTER, + 3 => Alignment::HORIZONTAL_RIGHT, + 4 => Alignment::HORIZONTAL_FILL, + 5 => Alignment::HORIZONTAL_JUSTIFY, + 6 => Alignment::HORIZONTAL_CENTER_CONTINUOUS, + ]; + + /** + * @var array + */ + protected static $verticalAlignmentMap = [ + 0 => Alignment::VERTICAL_TOP, + 1 => Alignment::VERTICAL_CENTER, + 2 => Alignment::VERTICAL_BOTTOM, + 3 => Alignment::VERTICAL_JUSTIFY, + ]; + + public static function horizontal(Alignment $alignment, int $horizontal): void + { + if (array_key_exists($horizontal, self::$horizontalAlignmentMap)) { + $alignment->setHorizontal(self::$horizontalAlignmentMap[$horizontal]); + } + } + + public static function vertical(Alignment $alignment, int $vertical): void + { + if (array_key_exists($vertical, self::$verticalAlignmentMap)) { + $alignment->setVertical(self::$verticalAlignmentMap[$vertical]); + } + } + + public static function wrap(Alignment $alignment, int $wrap): void + { + $alignment->setWrapText((bool) $wrap); + } +} diff --git a/src/PhpSpreadsheet/Reader/Xls/Style/CellFont.php b/src/PhpSpreadsheet/Reader/Xls/Style/CellFont.php new file mode 100644 index 00000000..e975be4d --- /dev/null +++ b/src/PhpSpreadsheet/Reader/Xls/Style/CellFont.php @@ -0,0 +1,39 @@ +setSuperscript(true); + + break; + case 0x0002: + $font->setSubscript(true); + + break; + } + } + + /** + * @var array + */ + protected static $underlineMap = [ + 0x01 => Font::UNDERLINE_SINGLE, + 0x02 => Font::UNDERLINE_DOUBLE, + 0x21 => Font::UNDERLINE_SINGLEACCOUNTING, + 0x22 => Font::UNDERLINE_DOUBLEACCOUNTING, + ]; + + public static function underline(Font $font, int $underline): void + { + if (array_key_exists($underline, self::$underlineMap)) { + $font->setUnderline(self::$underlineMap[$underline]); + } + } +} diff --git a/src/PhpSpreadsheet/Reader/Xls/Style/FillPattern.php b/src/PhpSpreadsheet/Reader/Xls/Style/FillPattern.php index 7b85c088..32ab5c85 100644 --- a/src/PhpSpreadsheet/Reader/Xls/Style/FillPattern.php +++ b/src/PhpSpreadsheet/Reader/Xls/Style/FillPattern.php @@ -6,7 +6,10 @@ use PhpOffice\PhpSpreadsheet\Style\Fill; class FillPattern { - protected static $map = [ + /** + * @var array + */ + protected static $fillPatternMap = [ 0x00 => Fill::FILL_NONE, 0x01 => Fill::FILL_SOLID, 0x02 => Fill::FILL_PATTERN_MEDIUMGRAY, @@ -38,8 +41,8 @@ class FillPattern */ public static function lookup($index) { - if (isset(self::$map[$index])) { - return self::$map[$index]; + if (isset(self::$fillPatternMap[$index])) { + return self::$fillPatternMap[$index]; } return Fill::FILL_NONE; diff --git a/src/PhpSpreadsheet/Reader/Xlsx.php b/src/PhpSpreadsheet/Reader/Xlsx.php index 21eccfe0..59403c64 100644 --- a/src/PhpSpreadsheet/Reader/Xlsx.php +++ b/src/PhpSpreadsheet/Reader/Xlsx.php @@ -3,6 +3,7 @@ namespace PhpOffice\PhpSpreadsheet\Reader; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Cell\Hyperlink; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; @@ -12,6 +13,7 @@ use PhpOffice\PhpSpreadsheet\Reader\Xlsx\ColumnAndRowAttributes; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\ConditionalStyles; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\DataValidations; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Hyperlinks; +use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\PageSetup; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Properties as PropertyReader; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\SheetViewOptions; @@ -26,11 +28,8 @@ use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Shared\Font; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; -use PhpOffice\PhpSpreadsheet\Style\Border; -use PhpOffice\PhpSpreadsheet\Style\Borders; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; -use PhpOffice\PhpSpreadsheet\Style\Protection; use PhpOffice\PhpSpreadsheet\Style\Style; use PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; @@ -42,6 +41,8 @@ use ZipArchive; class Xlsx extends BaseReader { + const INITIAL_FILE = '_rels/.rels'; + /** * ReferenceHelper instance. * @@ -54,7 +55,12 @@ class Xlsx extends BaseReader * * @var Xlsx\Theme */ - private static $theme = null; + private static $theme; + + /** + * @var ZipArchive + */ + private $zip; /** * Create a new Xlsx Reader instance. @@ -68,20 +74,18 @@ class Xlsx extends BaseReader /** * Can the current IReader read the file? - * - * @param string $filename - * - * @return bool */ - public function canRead($filename) + public function canRead(string $filename): bool { - File::assertFile($filename); + if (!File::testFileNoThrow($filename, self::INITIAL_FILE)) { + return false; + } $result = false; - $zip = new ZipArchive(); + $this->zip = $zip = new ZipArchive(); if ($zip->open($filename) === true) { - $workbookBasename = $this->getWorkbookBaseName($zip); + [$workbookBasename] = $this->getWorkbookBaseName(); $result = !empty($workbookBasename); $zip->close(); @@ -90,41 +94,102 @@ class Xlsx extends BaseReader return $result; } + /** + * @param mixed $value + */ + public static function testSimpleXml($value): SimpleXMLElement + { + return ($value instanceof SimpleXMLElement) ? $value : new SimpleXMLElement(''); + } + + public static function getAttributes(?SimpleXMLElement $value, string $ns = ''): SimpleXMLElement + { + return self::testSimpleXml($value === null ? $value : $value->attributes($ns)); + } + + // Phpstan thinks, correctly, that xpath can return false. + // Scrutinizer thinks it can't. + // Sigh. + private static function xpathNoFalse(SimpleXmlElement $sxml, string $path): array + { + return self::falseToArray($sxml->xpath($path)); + } + + /** + * @param mixed $value + */ + public static function falseToArray($value): array + { + return is_array($value) ? $value : []; + } + + private function loadZip(string $filename, string $ns = ''): SimpleXMLElement + { + $contents = $this->getFromZipArchive($this->zip, $filename); + $rels = simplexml_load_string( + $this->securityScanner->scan($contents), + 'SimpleXMLElement', + Settings::getLibXmlLoaderOptions(), + $ns + ); + + return self::testSimpleXml($rels); + } + + // This function is just to identify cases where I'm not sure + // why empty namespace is required. + private function loadZipNonamespace(string $filename, string $ns): SimpleXMLElement + { + $contents = $this->getFromZipArchive($this->zip, $filename); + $rels = simplexml_load_string( + $this->securityScanner->scan($contents), + 'SimpleXMLElement', + Settings::getLibXmlLoaderOptions(), + ($ns === '' ? $ns : '') + ); + + return self::testSimpleXml($rels); + } + + private const REL_TO_MAIN = [ + Namespaces::PURL_OFFICE_DOCUMENT => Namespaces::PURL_MAIN, + ]; + + private const REL_TO_DRAWING = [ + Namespaces::PURL_RELATIONSHIPS => Namespaces::PURL_DRAWING, + ]; + /** * Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object. * - * @param string $pFilename + * @param string $filename * * @return array */ - public function listWorksheetNames($pFilename) + public function listWorksheetNames($filename) { - File::assertFile($pFilename); + File::assertFile($filename, self::INITIAL_FILE); $worksheetNames = []; - $zip = new ZipArchive(); - $zip->open($pFilename); + $this->zip = $zip = new ZipArchive(); + $zip->open($filename); // The files we're looking at here are small enough that simpleXML is more efficient than XMLReader - //~ http://schemas.openxmlformats.org/package/2006/relationships"); - $rels = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, '_rels/.rels')) - ); - foreach ($rels->Relationship as $rel) { - switch ($rel['Type']) { - case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument': - //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main" - $xmlWorkbook = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, "{$rel['Target']}")) - ); + $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS); + foreach ($rels->Relationship as $relx) { + $rel = self::getAttributes($relx); + $relType = (string) $rel['Type']; + $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN; + if ($mainNS !== '') { + $xmlWorkbook = $this->loadZip((string) $rel['Target'], $mainNS); - if ($xmlWorkbook->sheets) { - foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { - // Check if sheet should be skipped - $worksheetNames[] = (string) $eleSheet['name']; - } + if ($xmlWorkbook->sheets) { + foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { + // Check if sheet should be skipped + $worksheetNames[] = (string) self::getAttributes($eleSheet)['name']; } + } } } @@ -136,72 +201,58 @@ class Xlsx extends BaseReader /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * - * @param string $pFilename + * @param string $filename * * @return array */ - public function listWorksheetInfo($pFilename) + public function listWorksheetInfo($filename) { - File::assertFile($pFilename); + File::assertFile($filename, self::INITIAL_FILE); $worksheetInfo = []; - $zip = new ZipArchive(); - $zip->open($pFilename); + $this->zip = $zip = new ZipArchive(); + $zip->open($filename); - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $rels = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, '_rels/.rels')), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - foreach ($rels->Relationship as $rel) { - if ($rel['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument') { - $dir = dirname($rel['Target']); - - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $relsWorkbook = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel['Target']) . '.rels') - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - $relsWorkbook->registerXPathNamespace('rel', 'http://schemas.openxmlformats.org/package/2006/relationships'); + $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS); + foreach ($rels->Relationship as $relx) { + $rel = self::getAttributes($relx); + $relType = (string) $rel['Type']; + $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN; + if ($mainNS !== '') { + $relTarget = (string) $rel['Target']; + $dir = dirname($relTarget); + $namespace = dirname($relType); + $relsWorkbook = $this->loadZip("$dir/_rels/" . basename($relTarget) . '.rels', ''); $worksheets = []; - foreach ($relsWorkbook->Relationship as $ele) { - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet') { + foreach ($relsWorkbook->Relationship as $elex) { + $ele = self::getAttributes($elex); + if ((string) $ele['Type'] === "$namespace/worksheet") { $worksheets[(string) $ele['Id']] = $ele['Target']; } } - //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main" - $xmlWorkbook = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, "{$rel['Target']}") - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $xmlWorkbook = $this->loadZip($relTarget, $mainNS); if ($xmlWorkbook->sheets) { - $dir = dirname($rel['Target']); + $dir = dirname($relTarget); /** @var SimpleXMLElement $eleSheet */ foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { $tmpInfo = [ - 'worksheetName' => (string) $eleSheet['name'], + 'worksheetName' => (string) self::getAttributes($eleSheet)['name'], 'lastColumnLetter' => 'A', 'lastColumnIndex' => 0, 'totalRows' => 0, 'totalColumns' => 0, ]; - $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')]; + $fileWorksheet = (string) $worksheets[(string) self::getArrayItem(self::getAttributes($eleSheet, $namespace), 'id')]; + $fileWorksheetPath = strpos($fileWorksheet, '/') === 0 ? substr($fileWorksheet, 1) : "$dir/$fileWorksheet"; $xml = new XMLReader(); $xml->xml( $this->securityScanner->scanFile( - 'zip://' . File::realpath($pFilename) . '#' . "$dir/$fileWorksheet" + 'zip://' . File::realpath($filename) . '#' . $fileWorksheetPath ), null, Settings::getLibXmlLoaderOptions() @@ -210,13 +261,14 @@ class Xlsx extends BaseReader $currCells = 0; while ($xml->read()) { - if ($xml->name == 'row' && $xml->nodeType == XMLReader::ELEMENT) { + if ($xml->localName == 'row' && $xml->nodeType == XMLReader::ELEMENT && $xml->namespaceURI === $mainNS) { $row = $xml->getAttribute('r'); $tmpInfo['totalRows'] = $row; $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); $currCells = 0; - } elseif ($xml->name == 'c' && $xml->nodeType == XMLReader::ELEMENT) { - ++$currCells; + } elseif ($xml->localName == 'c' && $xml->nodeType == XMLReader::ELEMENT && $xml->namespaceURI === $mainNS) { + $cell = $xml->getAttribute('r'); + $currCells = $cell ? max($currCells, Coordinate::indexesFromString($cell)[0]) : ($currCells + 1); } } $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); @@ -260,22 +312,23 @@ class Xlsx extends BaseReader private function castToFormula($c, $r, &$cellDataType, &$value, &$calculatedValue, &$sharedFormulas, $castBaseType): void { + $attr = $c->f->attributes(); $cellDataType = 'f'; $value = "={$c->f}"; $calculatedValue = self::$castBaseType($c); // Shared formula? - if (isset($c->f['t']) && strtolower((string) $c->f['t']) == 'shared') { - $instance = (string) $c->f['si']; + if (isset($attr['t']) && strtolower((string) $attr['t']) == 'shared') { + $instance = (string) $attr['si']; - if (!isset($sharedFormulas[(string) $c->f['si']])) { + if (!isset($sharedFormulas[(string) $attr['si']])) { $sharedFormulas[$instance] = ['master' => $r, 'formula' => $value]; } else { - $master = Coordinate::coordinateFromString($sharedFormulas[$instance]['master']); - $current = Coordinate::coordinateFromString($r); + $master = Coordinate::indexesFromString($sharedFormulas[$instance]['master']); + $current = Coordinate::indexesFromString($r); $difference = [0, 0]; - $difference[0] = Coordinate::columnIndexFromString($current[0]) - Coordinate::columnIndexFromString($master[0]); + $difference[0] = $current[0] - $master[0]; $difference[1] = $current[1] - $master[1]; $value = $this->referenceHelper->updateFormulaReferences($sharedFormulas[$instance]['formula'], 'A1', $difference[0], $difference[1]); @@ -283,6 +336,29 @@ class Xlsx extends BaseReader } } + /** + * @param string $fileName + */ + private function fileExistsInArchive(ZipArchive $archive, $fileName = ''): bool + { + // Root-relative paths + if (strpos($fileName, '//') !== false) { + $fileName = substr($fileName, strpos($fileName, '//') + 1); + } + $fileName = File::realpath($fileName); + + // Sadly, some 3rd party xlsx generators don't use consistent case for filenaming + // so we need to load case-insensitively from the zip file + + // Apache POI fixes + $contents = $archive->locateName($fileName, ZipArchive::FL_NOCASE); + if ($contents === false) { + $contents = $archive->locateName(substr($fileName, 1), ZipArchive::FL_NOCASE); + } + + return $contents !== false; + } + /** * @param string $fileName * @@ -310,126 +386,110 @@ class Xlsx extends BaseReader /** * Loads Spreadsheet from file. - * - * @param string $filename - * - * @return Spreadsheet */ - public function load($filename) + public function load(string $filename, int $flags = 0): Spreadsheet { - File::assertFile($filename); + File::assertFile($filename, self::INITIAL_FILE); + $this->processFlags($flags); // Initialisations $excel = new Spreadsheet(); $excel->removeSheetByIndex(0); - if (!$this->readDataOnly) { - $excel->removeCellStyleXfByIndex(0); // remove the default style - $excel->removeCellXfByIndex(0); // remove the default style - } + $addingFirstCellStyleXf = true; + $addingFirstCellXf = true; + $unparsedLoadedData = []; - $zip = new ZipArchive(); + $this->zip = $zip = new ZipArchive(); $zip->open($filename); // Read the theme first, because we need the colour scheme when reading the styles - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $workbookBasename = $this->getWorkbookBaseName($zip); - $wbRels = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, "xl/_rels/${workbookBasename}.rels")), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - foreach ($wbRels->Relationship as $rel) { + [$workbookBasename, $xmlNamespaceBase] = $this->getWorkbookBaseName(); + $wbRels = $this->loadZip("xl/_rels/${workbookBasename}.rels", Namespaces::RELATIONSHIPS); + foreach ($wbRels->Relationship as $relx) { + $rel = self::getAttributes($relx); + $relTarget = (string) $rel['Target']; switch ($rel['Type']) { - case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme': + case "$xmlNamespaceBase/theme": $themeOrderArray = ['lt1', 'dk1', 'lt2', 'dk2']; $themeOrderAdditional = count($themeOrderArray); + $drawingNS = self::REL_TO_DRAWING[$xmlNamespaceBase] ?? Namespaces::DRAWINGML; - $xmlTheme = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, "xl/{$rel['Target']}")), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - if (is_object($xmlTheme)) { - $xmlThemeName = $xmlTheme->attributes(); - $xmlTheme = $xmlTheme->children('http://schemas.openxmlformats.org/drawingml/2006/main'); - $themeName = (string) $xmlThemeName['name']; + $xmlTheme = $this->loadZip("xl/{$relTarget}", $drawingNS); + $xmlThemeName = self::getAttributes($xmlTheme); + $xmlTheme = $xmlTheme->children($drawingNS); + $themeName = (string) $xmlThemeName['name']; - $colourScheme = $xmlTheme->themeElements->clrScheme->attributes(); - $colourSchemeName = (string) $colourScheme['name']; - $colourScheme = $xmlTheme->themeElements->clrScheme->children('http://schemas.openxmlformats.org/drawingml/2006/main'); + $colourScheme = self::getAttributes($xmlTheme->themeElements->clrScheme); + $colourSchemeName = (string) $colourScheme['name']; + $colourScheme = $xmlTheme->themeElements->clrScheme->children($drawingNS); - $themeColours = []; - foreach ($colourScheme as $k => $xmlColour) { - $themePos = array_search($k, $themeOrderArray); - if ($themePos === false) { - $themePos = $themeOrderAdditional++; - } - if (isset($xmlColour->sysClr)) { - $xmlColourData = $xmlColour->sysClr->attributes(); - $themeColours[$themePos] = $xmlColourData['lastClr']; - } elseif (isset($xmlColour->srgbClr)) { - $xmlColourData = $xmlColour->srgbClr->attributes(); - $themeColours[$themePos] = $xmlColourData['val']; - } + $themeColours = []; + foreach ($colourScheme as $k => $xmlColour) { + $themePos = array_search($k, $themeOrderArray); + if ($themePos === false) { + $themePos = $themeOrderAdditional++; + } + if (isset($xmlColour->sysClr)) { + $xmlColourData = self::getAttributes($xmlColour->sysClr); + $themeColours[$themePos] = (string) $xmlColourData['lastClr']; + } elseif (isset($xmlColour->srgbClr)) { + $xmlColourData = self::getAttributes($xmlColour->srgbClr); + $themeColours[$themePos] = (string) $xmlColourData['val']; } - self::$theme = new Xlsx\Theme($themeName, $colourSchemeName, $themeColours); } + self::$theme = new Xlsx\Theme($themeName, $colourSchemeName, $themeColours); break; } } - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $rels = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, '_rels/.rels')), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS); $propertyReader = new PropertyReader($this->securityScanner, $excel->getProperties()); - foreach ($rels->Relationship as $rel) { - switch ($rel['Type']) { - case 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties': - $propertyReader->readCoreProperties($this->getFromZipArchive($zip, "{$rel['Target']}")); + foreach ($rels->Relationship as $relx) { + $rel = self::getAttributes($relx); + $relTarget = (string) $rel['Target']; + $relType = (string) $rel['Type']; + $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN; + switch ($relType) { + case Namespaces::CORE_PROPERTIES: + $propertyReader->readCoreProperties($this->getFromZipArchive($zip, $relTarget)); break; - case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties': - $propertyReader->readExtendedProperties($this->getFromZipArchive($zip, "{$rel['Target']}")); + case "$xmlNamespaceBase/extended-properties": + $propertyReader->readExtendedProperties($this->getFromZipArchive($zip, $relTarget)); break; - case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties': - $propertyReader->readCustomProperties($this->getFromZipArchive($zip, "{$rel['Target']}")); + case "$xmlNamespaceBase/custom-properties": + $propertyReader->readCustomProperties($this->getFromZipArchive($zip, $relTarget)); break; //Ribbon - case 'http://schemas.microsoft.com/office/2006/relationships/ui/extensibility': - $customUI = $rel['Target']; - if ($customUI !== null) { + case Namespaces::EXTENSIBILITY: + $customUI = $relTarget; + if ($customUI) { $this->readRibbon($excel, $customUI, $zip); } break; - case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument': - $dir = dirname($rel['Target']); - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $relsWorkbook = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel['Target']) . '.rels')), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - $relsWorkbook->registerXPathNamespace('rel', 'http://schemas.openxmlformats.org/package/2006/relationships'); + case "$xmlNamespaceBase/officeDocument": + $dir = dirname($relTarget); + + // Do not specify namespace in next stmt - do it in Xpath + $relsWorkbook = $this->loadZip("$dir/_rels/" . basename($relTarget) . '.rels', ''); + $relsWorkbook->registerXPathNamespace('rel', Namespaces::RELATIONSHIPS); $sharedStrings = []; - $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings']")); + $relType = "rel:Relationship[@Type='" + //. Namespaces::SHARED_STRINGS + . "$xmlNamespaceBase/sharedStrings" + . "']"; + $xpath = self::getArrayItem($relsWorkbook->xpath($relType)); + if ($xpath) { - //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main" - $xmlStrings = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - if (isset($xmlStrings, $xmlStrings->si)) { + $xmlStrings = $this->loadZip("$dir/$xpath[Target]", $mainNS); + if (isset($xmlStrings->si)) { foreach ($xmlStrings->si as $val) { if (isset($val->t)) { $sharedStrings[] = StringHelper::controlCharacterOOXML2PHP((string) $val->t); @@ -442,14 +502,16 @@ class Xlsx extends BaseReader $worksheets = []; $macros = $customUI = null; - foreach ($relsWorkbook->Relationship as $ele) { + foreach ($relsWorkbook->Relationship as $elex) { + $ele = self::getAttributes($elex); switch ($ele['Type']) { - case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet': + case Namespaces::WORKSHEET: + case Namespaces::PURL_WORKSHEET: $worksheets[(string) $ele['Id']] = $ele['Target']; break; // a vbaProject ? (: some macros) - case 'http://schemas.microsoft.com/office/2006/relationships/vbaProject': + case Namespaces::VBA: $macros = $ele['Target']; break; @@ -469,26 +531,38 @@ class Xlsx extends BaseReader } } - $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']")); - //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main" - $xmlStyles = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $relType = "rel:Relationship[@Type='" + . "$xmlNamespaceBase/styles" + . "']"; + $xpath = self::getArrayItem(self::xpathNoFalse($relsWorkbook, $relType)); + + if ($xpath === null) { + $xmlStyles = self::testSimpleXml(null); + } else { + // I think Nonamespace is okay because I'm using xpath. + $xmlStyles = $this->loadZipNonamespace("$dir/$xpath[Target]", $mainNS); + } + + $xmlStyles->registerXPathNamespace('smm', Namespaces::MAIN); + $fills = self::xpathNoFalse($xmlStyles, 'smm:fills/smm:fill'); + $fonts = self::xpathNoFalse($xmlStyles, 'smm:fonts/smm:font'); + $borders = self::xpathNoFalse($xmlStyles, 'smm:borders/smm:border'); + $xfTags = self::xpathNoFalse($xmlStyles, 'smm:cellXfs/smm:xf'); + $cellXfTags = self::xpathNoFalse($xmlStyles, 'smm:cellStyleXfs/smm:xf'); $styles = []; $cellStyles = []; $numFmts = null; - if ($xmlStyles && $xmlStyles->numFmts[0]) { + if (/*$xmlStyles && */ $xmlStyles->numFmts[0]) { $numFmts = $xmlStyles->numFmts[0]; } if (isset($numFmts) && ($numFmts !== null)) { - $numFmts->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); + $numFmts->registerXPathNamespace('sml', $mainNS); } - if (!$this->readDataOnly && $xmlStyles) { - foreach ($xmlStyles->cellXfs->xf as $xf) { - $numFmt = NumberFormat::FORMAT_GENERAL; + if (!$this->readDataOnly/* && $xmlStyles*/) { + foreach ($xfTags as $xfTag) { + $xf = self::getAttributes($xfTag); + $numFmt = null; if ($xf['numFmtId']) { if (isset($numFmts)) { @@ -503,24 +577,22 @@ class Xlsx extends BaseReader // But there's a lot of naughty homebrew xlsx writers that do use "reserved" id values that aren't actually used // So we make allowance for them rather than lose formatting masks if ( + $numFmt === null && (int) $xf['numFmtId'] < 164 && NumberFormat::builtInFormatCode((int) $xf['numFmtId']) !== '' ) { $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']); } } - $quotePrefix = false; - if (isset($xf['quotePrefix'])) { - $quotePrefix = (bool) $xf['quotePrefix']; - } + $quotePrefix = (bool) ($xf['quotePrefix'] ?? false); $style = (object) [ - 'numFmt' => $numFmt, - 'font' => $xmlStyles->fonts->font[(int) ($xf['fontId'])], - 'fill' => $xmlStyles->fills->fill[(int) ($xf['fillId'])], - 'border' => $xmlStyles->borders->border[(int) ($xf['borderId'])], - 'alignment' => $xf->alignment, - 'protection' => $xf->protection, + 'numFmt' => $numFmt ?? NumberFormat::FORMAT_GENERAL, + 'font' => $fonts[(int) ($xf['fontId'])], + 'fill' => $fills[(int) ($xf['fillId'])], + 'border' => $borders[(int) ($xf['borderId'])], + 'alignment' => $xfTag->alignment, + 'protection' => $xfTag->protection, 'quotePrefix' => $quotePrefix, ]; $styles[] = $style; @@ -528,10 +600,15 @@ class Xlsx extends BaseReader // add style to cellXf collection $objStyle = new Style(); self::readStyle($objStyle, $style); + if ($addingFirstCellXf) { + $excel->removeCellXfByIndex(0); // remove the default style + $addingFirstCellXf = false; + } $excel->addCellXf($objStyle); } - foreach (isset($xmlStyles->cellStyleXfs->xf) ? $xmlStyles->cellStyleXfs->xf : [] as $xf) { + foreach ($cellXfTags as $xfTag) { + $xf = self::getAttributes($xfTag); $numFmt = NumberFormat::FORMAT_GENERAL; if ($numFmts && $xf['numFmtId']) { $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]")); @@ -542,13 +619,15 @@ class Xlsx extends BaseReader } } + $quotePrefix = (bool) ($xf['quotePrefix'] ?? false); + $cellStyle = (object) [ 'numFmt' => $numFmt, - 'font' => $xmlStyles->fonts->font[(int) ($xf['fontId'])], - 'fill' => $xmlStyles->fills->fill[(int) ($xf['fillId'])], - 'border' => $xmlStyles->borders->border[(int) ($xf['borderId'])], - 'alignment' => $xf->alignment, - 'protection' => $xf->protection, + 'font' => $fonts[(int) ($xf['fontId'])], + 'fill' => $fills[((int) $xf['fillId'])], + 'border' => $borders[(int) ($xf['borderId'])], + 'alignment' => $xfTag->alignment, + 'protection' => $xfTag->protection, 'quotePrefix' => $quotePrefix, ]; $cellStyles[] = $cellStyle; @@ -556,27 +635,27 @@ class Xlsx extends BaseReader // add style to cellStyleXf collection $objStyle = new Style(); self::readStyle($objStyle, $cellStyle); + if ($addingFirstCellStyleXf) { + $excel->removeCellStyleXfByIndex(0); // remove the default style + $addingFirstCellStyleXf = false; + } $excel->addCellStyleXf($objStyle); } } - $styleReader = new Styles($xmlStyles); $styleReader->setStyleBaseData(self::$theme, $styles, $cellStyles); $dxfs = $styleReader->dxfs($this->readDataOnly); $styles = $styleReader->styles(); - //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main" - $xmlWorkbook = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, "{$rel['Target']}")), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $xmlWorkbook = $this->loadZipNoNamespace($relTarget, $mainNS); + $xmlWorkbookNS = $this->loadZip($relTarget, $mainNS); // Set base date - if ($xmlWorkbook->workbookPr) { + if ($xmlWorkbookNS->workbookPr) { Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - if (isset($xmlWorkbook->workbookPr['date1904'])) { - if (self::boolean((string) $xmlWorkbook->workbookPr['date1904'])) { + $attrs1904 = self::getAttributes($xmlWorkbookNS->workbookPr); + if (isset($attrs1904['date1904'])) { + if (self::boolean((string) $attrs1904['date1904'])) { Date::setExcelCalendar(Date::CALENDAR_MAC_1904); } } @@ -592,13 +671,14 @@ class Xlsx extends BaseReader $charts = $chartDetails = []; - if ($xmlWorkbook->sheets) { + if ($xmlWorkbookNS->sheets) { /** @var SimpleXMLElement $eleSheet */ - foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { + foreach ($xmlWorkbookNS->sheets->sheet as $eleSheet) { + $eleSheetAttr = self::getAttributes($eleSheet); ++$oldSheetId; // Check if sheet should be skipped - if (isset($this->loadSheetsOnly) && !in_array((string) $eleSheet['name'], $this->loadSheetsOnly)) { + if (is_array($this->loadSheetsOnly) && !in_array((string) $eleSheetAttr['name'], $this->loadSheetsOnly)) { ++$countSkippedSheets; $mapSheetId[$oldSheetId] = null; @@ -615,24 +695,25 @@ class Xlsx extends BaseReader // references in formula cells... during the load, all formulae should be correct, // and we're simply bringing the worksheet name in line with the formula, not the // reverse - $docSheet->setTitle((string) $eleSheet['name'], false, false); - $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')]; - //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main" - $xmlSheet = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, "$dir/$fileWorksheet")), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $docSheet->setTitle((string) $eleSheetAttr['name'], false, false); + $fileWorksheet = (string) $worksheets[(string) self::getArrayItem(self::getAttributes($eleSheet, $xmlNamespaceBase), 'id')]; + $xmlSheet = $this->loadZipNoNamespace("$dir/$fileWorksheet", $mainNS); + $xmlSheetNS = $this->loadZip("$dir/$fileWorksheet", $mainNS); $sharedFormulas = []; - if (isset($eleSheet['state']) && (string) $eleSheet['state'] != '') { - $docSheet->setSheetState((string) $eleSheet['state']); + if (isset($eleSheetAttr['state']) && (string) $eleSheetAttr['state'] != '') { + $docSheet->setSheetState((string) $eleSheetAttr['state']); } - - if ($xmlSheet) { - if (isset($xmlSheet->sheetViews, $xmlSheet->sheetViews->sheetView)) { - $sheetViews = new SheetViews($xmlSheet->sheetViews->sheetView, $docSheet); + if ($xmlSheetNS) { + $xmlSheetMain = $xmlSheetNS->children($mainNS); + // Setting Conditional Styles adjusts selected cells, so we need to execute this + // before reading the sheet view data to get the actual selected cells + if (!$this->readDataOnly && $xmlSheet->conditionalFormatting) { + (new ConditionalStyles($docSheet, $xmlSheet, $dxfs))->load(); + } + if (isset($xmlSheetMain->sheetViews, $xmlSheetMain->sheetViews->sheetView)) { + $sheetViews = new SheetViews($xmlSheetMain->sheetViews->sheetView, $docSheet); $sheetViews->load(); } @@ -643,16 +724,17 @@ class Xlsx extends BaseReader ->load($this->getReadFilter(), $this->getReadDataOnly()); } - if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) { + if ($xmlSheetNS && $xmlSheetNS->sheetData && $xmlSheetNS->sheetData->row) { $cIndex = 1; // Cell Start from 1 - foreach ($xmlSheet->sheetData->row as $row) { + foreach ($xmlSheetNS->sheetData->row as $row) { $rowIndex = 1; foreach ($row->c as $c) { - $r = (string) $c['r']; + $cAttr = self::getAttributes($c); + $r = (string) $cAttr['r']; if ($r == '') { $r = Coordinate::stringFromColumnIndex($rowIndex) . $cIndex; } - $cellDataType = (string) $c['t']; + $cellDataType = (string) $cAttr['t']; $value = null; $calculatedValue = null; @@ -661,7 +743,7 @@ class Xlsx extends BaseReader $coordinates = Coordinate::coordinateFromString($r); if (!$this->getReadFilter()->readCell($coordinates[0], (int) $coordinates[1], $docSheet->getTitle())) { - if (isset($c->f)) { + if (isset($cAttr->f)) { $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError'); } ++$rowIndex; @@ -720,6 +802,10 @@ class Xlsx extends BaseReader } else { // Formula $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToString'); + if (isset($c->f['t'])) { + $attributes = $c->f['t']; + $docSheet->getCell($r)->setFormulaAttributes(['t' => (string) $attributes]); + } } break; @@ -735,6 +821,10 @@ class Xlsx extends BaseReader $cell = $docSheet->getCell($r); // Assign value if ($cellDataType != '') { + // it is possible, that datatype is numeric but with an empty string, which result in an error + if ($cellDataType === DataType::TYPE_NUMERIC && $value === '') { + $cellDataType = DataType::TYPE_STRING; + } $cell->setValueExplicit($value, $cellDataType); } else { $cell->setValue($value); @@ -744,10 +834,10 @@ class Xlsx extends BaseReader } // Style information? - if ($c['s'] && !$this->readDataOnly) { + if ($cAttr['s'] && !$this->readDataOnly) { // no style index means 0, it seems - $cell->setXfIndex(isset($styles[(int) ($c['s'])]) ? - (int) ($c['s']) : 0); + $cell->setXfIndex(isset($styles[(int) ($cAttr['s'])]) ? + (int) ($cAttr['s']) : 0); } } ++$rowIndex; @@ -756,10 +846,6 @@ class Xlsx extends BaseReader } } - if (!$this->readDataOnly && $xmlSheet && $xmlSheet->conditionalFormatting) { - (new ConditionalStyles($docSheet, $xmlSheet, $dxfs))->load(); - } - $aKeys = ['sheet', 'objects', 'scenarios', 'formatCells', 'formatColumns', 'formatRows', 'insertColumns', 'insertRows', 'insertHyperlinks', 'deleteColumns', 'deleteRows', 'selectLockedCells', 'sort', 'autoFilter', 'pivotTables', 'selectUnlockedCells']; if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) { foreach ($aKeys as $key) { @@ -772,8 +858,8 @@ class Xlsx extends BaseReader $this->readSheetProtection($docSheet, $xmlSheet); } - if ($xmlSheet && $xmlSheet->autoFilter && !$this->readDataOnly) { - (new AutoFilter($docSheet, $xmlSheet))->load(); + if ($this->readDataOnly === false) { + $this->readAutoFilterTables($xmlSheet, $docSheet, $dir, $fileWorksheet, $zip); } if ($xmlSheet && $xmlSheet->mergeCells && $xmlSheet->mergeCells->mergeCell && !$this->readDataOnly) { @@ -789,15 +875,32 @@ class Xlsx extends BaseReader $unparsedLoadedData = (new PageSetup($docSheet, $xmlSheet))->load($unparsedLoadedData); } + if ($xmlSheet !== false && isset($xmlSheet->extLst, $xmlSheet->extLst->ext, $xmlSheet->extLst->ext['uri']) && ($xmlSheet->extLst->ext['uri'] == '{CCE6A557-97BC-4b89-ADB6-D9C93CAAB3DF}')) { + // Create dataValidations node if does not exists, maybe is better inside the foreach ? + if (!$xmlSheet->dataValidations) { + $xmlSheet->addChild('dataValidations'); + } + + foreach ($xmlSheet->extLst->ext->children('x14', true)->dataValidations->dataValidation as $item) { + $node = $xmlSheet->dataValidations->addChild('dataValidation'); + foreach ($item->attributes() ?? [] as $attr) { + $node->addAttribute($attr->getName(), $attr); + } + $node->addAttribute('sqref', $item->children('xm', true)->sqref); + $node->addChild('formula1', $item->formula1->children('xm', true)->f); + } + } + if ($xmlSheet && $xmlSheet->dataValidations && !$this->readDataOnly) { (new DataValidations($docSheet, $xmlSheet))->load(); } // unparsed sheet AlternateContent if ($xmlSheet && !$this->readDataOnly) { - $mc = $xmlSheet->children('http://schemas.openxmlformats.org/markup-compatibility/2006'); + $mc = $xmlSheet->children(Namespaces::COMPATIBILITY); if ($mc->AlternateContent) { foreach ($mc->AlternateContent as $alternateContent) { + $alternateContent = self::testSimpleXml($alternateContent); $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['AlternateContents'][] = $alternateContent->asXML(); } } @@ -809,20 +912,13 @@ class Xlsx extends BaseReader // Locate hyperlink relations $relationsFileName = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; if ($zip->locateName($relationsFileName)) { - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $relsWorksheet = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, $relationsFileName) - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $relsWorksheet = $this->loadZip($relationsFileName, Namespaces::RELATIONSHIPS); $hyperlinkReader->readHyperlinks($relsWorksheet); } // Loop through hyperlinks - if ($xmlSheet && $xmlSheet->hyperlinks) { - $hyperlinkReader->setHyperlinks($xmlSheet->hyperlinks); + if ($xmlSheetNS && $xmlSheetNS->children($mainNS)->hyperlinks) { + $hyperlinkReader->setHyperlinks($xmlSheetNS->children($mainNS)->hyperlinks); } } @@ -831,20 +927,15 @@ class Xlsx extends BaseReader $vmlComments = []; if (!$this->readDataOnly) { // Locate comment relations - if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) { - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $relsWorksheet = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - foreach ($relsWorksheet->Relationship as $ele) { - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments') { + $commentRelations = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; + if ($zip->locateName($commentRelations)) { + $relsWorksheet = $this->loadZip($commentRelations, Namespaces::RELATIONSHIPS); + foreach ($relsWorksheet->Relationship as $elex) { + $ele = self::getAttributes($elex); + if ($ele['Type'] == Namespaces::COMMENTS) { $comments[(string) $ele['Id']] = (string) $ele['Target']; } - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') { + if ($ele['Type'] == Namespaces::VML) { $vmlComments[(string) $ele['Id']] = (string) $ele['Target']; } } @@ -854,26 +945,26 @@ class Xlsx extends BaseReader foreach ($comments as $relName => $relPath) { // Load comments file $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath); - $commentsFile = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, $relPath)), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + // okay to ignore namespace - using xpath + $commentsFile = $this->loadZip($relPath, ''); // Utility variables $authors = []; - - // Loop through authors - foreach ($commentsFile->authors->author as $author) { + $commentsFile->registerXpathNamespace('com', $mainNS); + $authorPath = self::xpathNoFalse($commentsFile, 'com:authors/com:author'); + foreach ($authorPath as $author) { $authors[] = (string) $author; } // Loop through contents - foreach ($commentsFile->commentList->comment as $comment) { - if (!empty($comment['authorId'])) { - $docSheet->getComment((string) $comment['ref'])->setAuthor($authors[(string) $comment['authorId']]); + $contentPath = self::xpathNoFalse($commentsFile, 'com:commentList/com:comment'); + foreach ($contentPath as $comment) { + $commentx = $comment->attributes(); + $commentModel = $docSheet->getComment((string) $commentx['ref']); + if (isset($commentx['authorId'])) { + $commentModel->setAuthor($authors[(int) $commentx['authorId']]); } - $docSheet->getComment((string) $comment['ref'])->setText($this->parseRichText($comment->text)); + $commentModel->setText($this->parseRichText($comment->children($mainNS)->text)); } } @@ -886,20 +977,17 @@ class Xlsx extends BaseReader $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath); try { - $vmlCommentsFile = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, $relPath)), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - $vmlCommentsFile->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); + // no namespace okay - processed with Xpath + $vmlCommentsFile = $this->loadZip($relPath, ''); + $vmlCommentsFile->registerXPathNamespace('v', Namespaces::URN_VML); } catch (Throwable $ex) { //Ignore unparsable vmlDrawings. Later they will be moved from $unparsedVmlDrawings to $unparsedLoadedData continue; } - $shapes = $vmlCommentsFile->xpath('//v:shape'); + $shapes = self::xpathNoFalse($vmlCommentsFile, '//v:shape'); foreach ($shapes as $shape) { - $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); + $shape->registerXPathNamespace('v', Namespaces::URN_VML); if (isset($shape['style'])) { $style = (string) $shape['style']; @@ -973,62 +1061,44 @@ class Xlsx extends BaseReader // Header/footer images if ($xmlSheet && $xmlSheet->legacyDrawingHF && !$this->readDataOnly) { if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) { - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $relsWorksheet = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $relsWorksheet = $this->loadZipNoNamespace(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels', Namespaces::RELATIONSHIPS); $vmlRelationship = ''; foreach ($relsWorksheet->Relationship as $ele) { - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') { + if ($ele['Type'] == Namespaces::VML) { $vmlRelationship = self::dirAdd("$dir/$fileWorksheet", $ele['Target']); } } if ($vmlRelationship != '') { // Fetch linked images - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $relsVML = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels') - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $relsVML = $this->loadZipNoNamespace(dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels', Namespaces::RELATIONSHIPS); $drawings = []; if (isset($relsVML->Relationship)) { foreach ($relsVML->Relationship as $ele) { - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') { + if ($ele['Type'] == Namespaces::IMAGE) { $drawings[(string) $ele['Id']] = self::dirAdd($vmlRelationship, $ele['Target']); } } } // Fetch VML document - $vmlDrawing = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, $vmlRelationship)), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - $vmlDrawing->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); + $vmlDrawing = $this->loadZipNoNamespace($vmlRelationship, ''); + $vmlDrawing->registerXPathNamespace('v', Namespaces::URN_VML); $hfImages = []; - $shapes = $vmlDrawing->xpath('//v:shape'); + $shapes = self::xpathNoFalse($vmlDrawing, '//v:shape'); foreach ($shapes as $idx => $shape) { - $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); + $shape->registerXPathNamespace('v', Namespaces::URN_VML); $imageData = $shape->xpath('//v:imagedata'); - if (!$imageData) { + if (empty($imageData)) { continue; } $imageData = $imageData[$idx]; - $imageData = $imageData->attributes('urn:schemas-microsoft-com:office:office'); + $imageData = self::getAttributes($imageData, Namespaces::URN_MSOFFICE); $style = self::toCSSArray((string) $shape['style']); $hfImages[(string) $shape['id']] = new HeaderFooterDrawing(); @@ -1054,44 +1124,37 @@ class Xlsx extends BaseReader } // TODO: Autoshapes from twoCellAnchors! - if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) { - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $relsWorksheet = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $drawingFilename = dirname("$dir/$fileWorksheet") + . '/_rels/' + . basename($fileWorksheet) + . '.rels'; + if ($zip->locateName($drawingFilename)) { + $relsWorksheet = $this->loadZipNoNamespace($drawingFilename, Namespaces::RELATIONSHIPS); $drawings = []; foreach ($relsWorksheet->Relationship as $ele) { - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing') { + if ((string) $ele['Type'] === "$xmlNamespaceBase/drawing") { $drawings[(string) $ele['Id']] = self::dirAdd("$dir/$fileWorksheet", $ele['Target']); } } if ($xmlSheet->drawing && !$this->readDataOnly) { $unparsedDrawings = []; + $fileDrawing = null; foreach ($xmlSheet->drawing as $drawing) { - $drawingRelId = (string) self::getArrayItem($drawing->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id'); + $drawingRelId = (string) self::getArrayItem(self::getAttributes($drawing, $xmlNamespaceBase), 'id'); $fileDrawing = $drawings[$drawingRelId]; - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $relsDrawing = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels') - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $drawingFilename = dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels'; + $relsDrawing = $this->loadZipNoNamespace($drawingFilename, $xmlNamespaceBase); $images = []; $hyperlinks = []; if ($relsDrawing && $relsDrawing->Relationship) { foreach ($relsDrawing->Relationship as $ele) { - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink') { + $eleType = (string) $ele['Type']; + if ($eleType === Namespaces::HYPERLINK) { $hyperlinks[(string) $ele['Id']] = (string) $ele['Target']; } - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') { + if ($eleType === "$xmlNamespaceBase/image") { $images[(string) $ele['Id']] = self::dirAdd($fileDrawing, $ele['Target']); - } elseif ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart') { + } elseif ($eleType === "$xmlNamespaceBase/chart") { if ($this->includeCharts) { $charts[self::dirAdd($fileDrawing, $ele['Target'])] = [ 'id' => (string) $ele['Id'], @@ -1101,124 +1164,160 @@ class Xlsx extends BaseReader } } } - $xmlDrawing = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, $fileDrawing)), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - $xmlDrawingChildren = $xmlDrawing->children('http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing'); + $xmlDrawing = $this->loadZipNoNamespace($fileDrawing, ''); + $xmlDrawingChildren = $xmlDrawing->children(Namespaces::SPREADSHEET_DRAWING); if ($xmlDrawingChildren->oneCellAnchor) { foreach ($xmlDrawingChildren->oneCellAnchor as $oneCellAnchor) { if ($oneCellAnchor->pic->blipFill) { /** @var SimpleXMLElement $blip */ - $blip = $oneCellAnchor->pic->blipFill->children('http://schemas.openxmlformats.org/drawingml/2006/main')->blip; + $blip = $oneCellAnchor->pic->blipFill->children(Namespaces::DRAWINGML)->blip; /** @var SimpleXMLElement $xfrm */ - $xfrm = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->xfrm; + $xfrm = $oneCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->xfrm; /** @var SimpleXMLElement $outerShdw */ - $outerShdw = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->effectLst->outerShdw; + $outerShdw = $oneCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->effectLst->outerShdw; /** @var SimpleXMLElement $hlinkClick */ - $hlinkClick = $oneCellAnchor->pic->nvPicPr->cNvPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->hlinkClick; + $hlinkClick = $oneCellAnchor->pic->nvPicPr->cNvPr->children(Namespaces::DRAWINGML)->hlinkClick; $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing(); - $objDrawing->setName((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name')); - $objDrawing->setDescription((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'descr')); - $objDrawing->setPath( - 'zip://' . File::realpath($filename) . '#' . - $images[(string) self::getArrayItem( - $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), - 'embed' - )], - false + $objDrawing->setName((string) self::getArrayItem(self::getAttributes($oneCellAnchor->pic->nvPicPr->cNvPr), 'name')); + $objDrawing->setDescription((string) self::getArrayItem(self::getAttributes($oneCellAnchor->pic->nvPicPr->cNvPr), 'descr')); + $embedImageKey = (string) self::getArrayItem( + self::getAttributes($blip, $xmlNamespaceBase), + 'embed' ); - $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((string) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1)); - $objDrawing->setOffsetX(Drawing::EMUToPixels($oneCellAnchor->from->colOff)); + if (isset($images[$embedImageKey])) { + $objDrawing->setPath( + 'zip://' . File::realpath($filename) . '#' . + $images[$embedImageKey], + false + ); + } else { + $linkImageKey = (string) self::getArrayItem( + $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), + 'link' + ); + if (isset($images[$linkImageKey])) { + $url = str_replace('xl/drawings/', '', $images[$linkImageKey]); + $objDrawing->setPath($url); + } + } + $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((int) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1)); + + $objDrawing->setOffsetX((int) Drawing::EMUToPixels($oneCellAnchor->from->colOff)); $objDrawing->setOffsetY(Drawing::EMUToPixels($oneCellAnchor->from->rowOff)); $objDrawing->setResizeProportional(false); - $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cx'))); - $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cy'))); + $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem((int) self::getAttributes($oneCellAnchor->ext), 'cx'))); + $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem((int) self::getAttributes($oneCellAnchor->ext), 'cy'))); if ($xfrm) { - $objDrawing->setRotation(Drawing::angleToDegrees((int) self::getArrayItem($xfrm->attributes(), 'rot'))); + $objDrawing->setRotation((int) Drawing::angleToDegrees(self::getArrayItem(self::getAttributes($xfrm), 'rot'))); } if ($outerShdw) { $shadow = $objDrawing->getShadow(); $shadow->setVisible(true); - $shadow->setBlurRadius(Drawing::EMUToPixels((int) self::getArrayItem($outerShdw->attributes(), 'blurRad'))); - $shadow->setDistance(Drawing::EMUToPixels((int) self::getArrayItem($outerShdw->attributes(), 'dist'))); - $shadow->setDirection(Drawing::angleToDegrees((int) self::getArrayItem($outerShdw->attributes(), 'dir'))); - $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), 'algn')); - $clr = isset($outerShdw->srgbClr) ? $outerShdw->srgbClr : $outerShdw->prstClr; - $shadow->getColor()->setRGB(self::getArrayItem($clr->attributes(), 'val')); - $shadow->setAlpha(self::getArrayItem($clr->alpha->attributes(), 'val') / 1000); + $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($outerShdw), 'blurRad'))); + $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($outerShdw), 'dist'))); + $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem(self::getAttributes($outerShdw), 'dir'))); + $shadow->setAlignment((string) self::getArrayItem(self::getAttributes($outerShdw), 'algn')); + $clr = $outerShdw->srgbClr ?? $outerShdw->prstClr; + $shadow->getColor()->setRGB(self::getArrayItem(self::getAttributes($clr), 'val')); + $shadow->setAlpha(self::getArrayItem(self::getAttributes($clr->alpha), 'val') / 1000); } $this->readHyperLinkDrawing($objDrawing, $oneCellAnchor, $hyperlinks); $objDrawing->setWorksheet($docSheet); - } else { - // ? Can charts be positioned with a oneCellAnchor ? - $coordinates = Coordinate::stringFromColumnIndex(((string) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1); + } elseif ($this->includeCharts && $oneCellAnchor->graphicFrame) { + // Exported XLSX from Google Sheets positions charts with a oneCellAnchor + $coordinates = Coordinate::stringFromColumnIndex(((int) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1); $offsetX = Drawing::EMUToPixels($oneCellAnchor->from->colOff); $offsetY = Drawing::EMUToPixels($oneCellAnchor->from->rowOff); - $width = Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cx')); - $height = Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cy')); + $width = Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($oneCellAnchor->ext), 'cx')); + $height = Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($oneCellAnchor->ext), 'cy')); + + $graphic = $oneCellAnchor->graphicFrame->children(Namespaces::DRAWINGML)->graphic; + /** @var SimpleXMLElement $chartRef */ + $chartRef = $graphic->graphicData->children(Namespaces::CHART)->chart; + $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase); + + $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [ + 'fromCoordinate' => $coordinates, + 'fromOffsetX' => $offsetX, + 'fromOffsetY' => $offsetY, + 'width' => $width, + 'height' => $height, + 'worksheetTitle' => $docSheet->getTitle(), + ]; } } } if ($xmlDrawingChildren->twoCellAnchor) { foreach ($xmlDrawingChildren->twoCellAnchor as $twoCellAnchor) { if ($twoCellAnchor->pic->blipFill) { - $blip = $twoCellAnchor->pic->blipFill->children('http://schemas.openxmlformats.org/drawingml/2006/main')->blip; - $xfrm = $twoCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->xfrm; - $outerShdw = $twoCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->effectLst->outerShdw; - $hlinkClick = $twoCellAnchor->pic->nvPicPr->cNvPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->hlinkClick; + $blip = $twoCellAnchor->pic->blipFill->children(Namespaces::DRAWINGML)->blip; + $xfrm = $twoCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->xfrm; + $outerShdw = $twoCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->effectLst->outerShdw; + $hlinkClick = $twoCellAnchor->pic->nvPicPr->cNvPr->children(Namespaces::DRAWINGML)->hlinkClick; $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing(); - $objDrawing->setName((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name')); - $objDrawing->setDescription((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'descr')); - $objDrawing->setPath( - 'zip://' . File::realpath($filename) . '#' . - $images[(string) self::getArrayItem( - $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), - 'embed' - )], - false + $objDrawing->setName((string) self::getArrayItem(self::getAttributes($twoCellAnchor->pic->nvPicPr->cNvPr), 'name')); + $objDrawing->setDescription((string) self::getArrayItem(self::getAttributes($twoCellAnchor->pic->nvPicPr->cNvPr), 'descr')); + $embedImageKey = (string) self::getArrayItem( + self::getAttributes($blip, $xmlNamespaceBase), + 'embed' ); - $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((string) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1)); + if (isset($images[$embedImageKey])) { + $objDrawing->setPath( + 'zip://' . File::realpath($filename) . '#' . + $images[$embedImageKey], + false + ); + } else { + $linkImageKey = (string) self::getArrayItem( + $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), + 'link' + ); + if (isset($images[$linkImageKey])) { + $url = str_replace('xl/drawings/', '', $images[$linkImageKey]); + $objDrawing->setPath($url); + } + } + $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1)); + $objDrawing->setOffsetX(Drawing::EMUToPixels($twoCellAnchor->from->colOff)); $objDrawing->setOffsetY(Drawing::EMUToPixels($twoCellAnchor->from->rowOff)); $objDrawing->setResizeProportional(false); if ($xfrm) { - $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), 'cx'))); - $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), 'cy'))); - $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), 'rot'))); + $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($xfrm->ext), 'cx'))); + $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($xfrm->ext), 'cy'))); + $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItem(self::getAttributes($xfrm), 'rot'))); } if ($outerShdw) { $shadow = $objDrawing->getShadow(); $shadow->setVisible(true); - $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItem($outerShdw->attributes(), 'blurRad'))); - $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItem($outerShdw->attributes(), 'dist'))); - $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), 'dir'))); - $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), 'algn')); - $clr = isset($outerShdw->srgbClr) ? $outerShdw->srgbClr : $outerShdw->prstClr; - $shadow->getColor()->setRGB(self::getArrayItem($clr->attributes(), 'val')); - $shadow->setAlpha(self::getArrayItem($clr->alpha->attributes(), 'val') / 1000); + $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($outerShdw), 'blurRad'))); + $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($outerShdw), 'dist'))); + $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem(self::getAttributes($outerShdw), 'dir'))); + $shadow->setAlignment((string) self::getArrayItem(self::getAttributes($outerShdw), 'algn')); + $clr = $outerShdw->srgbClr ?? $outerShdw->prstClr; + $shadow->getColor()->setRGB(self::getArrayItem(self::getAttributes($clr), 'val')); + $shadow->setAlpha(self::getArrayItem(self::getAttributes($clr->alpha), 'val') / 1000); } $this->readHyperLinkDrawing($objDrawing, $twoCellAnchor, $hyperlinks); $objDrawing->setWorksheet($docSheet); } elseif (($this->includeCharts) && ($twoCellAnchor->graphicFrame)) { - $fromCoordinate = Coordinate::stringFromColumnIndex(((string) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1); + $fromCoordinate = Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1); $fromOffsetX = Drawing::EMUToPixels($twoCellAnchor->from->colOff); $fromOffsetY = Drawing::EMUToPixels($twoCellAnchor->from->rowOff); - $toCoordinate = Coordinate::stringFromColumnIndex(((string) $twoCellAnchor->to->col) + 1) . ($twoCellAnchor->to->row + 1); + $toCoordinate = Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->to->col) + 1) . ($twoCellAnchor->to->row + 1); $toOffsetX = Drawing::EMUToPixels($twoCellAnchor->to->colOff); $toOffsetY = Drawing::EMUToPixels($twoCellAnchor->to->rowOff); - $graphic = $twoCellAnchor->graphicFrame->children('http://schemas.openxmlformats.org/drawingml/2006/main')->graphic; + $graphic = $twoCellAnchor->graphicFrame->children(Namespaces::DRAWINGML)->graphic; /** @var SimpleXMLElement $chartRef */ - $chartRef = $graphic->graphicData->children('http://schemas.openxmlformats.org/drawingml/2006/chart')->chart; - $thisChart = (string) $chartRef->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $chartRef = $graphic->graphicData->children(Namespaces::CHART)->chart; + $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase); $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [ 'fromCoordinate' => $fromCoordinate, @@ -1232,7 +1331,7 @@ class Xlsx extends BaseReader } } } - if ($relsDrawing === false && $xmlDrawing->count() == 0) { + if (empty($relsDrawing) && $xmlDrawing->count() == 0) { // Save Drawing without rels and children as unparsed $unparsedDrawings[$drawingRelId] = $xmlDrawing->asXML(); } @@ -1241,7 +1340,7 @@ class Xlsx extends BaseReader // store original rId of drawing files $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'] = []; foreach ($relsWorksheet->Relationship as $ele) { - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing') { + if ((string) $ele['Type'] === "$xmlNamespaceBase/drawing") { $drawingRelId = (string) $ele['Id']; $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'][(string) $ele['Target']] = $drawingRelId; if (isset($unparsedDrawings[$drawingRelId])) { @@ -1251,22 +1350,19 @@ class Xlsx extends BaseReader } // unparsed drawing AlternateContent - $xmlAltDrawing = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, $fileDrawing)), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - )->children('http://schemas.openxmlformats.org/markup-compatibility/2006'); + $xmlAltDrawing = $this->loadZip($fileDrawing, Namespaces::COMPATIBILITY); if ($xmlAltDrawing->AlternateContent) { foreach ($xmlAltDrawing->AlternateContent as $alternateContent) { + $alternateContent = self::testSimpleXml($alternateContent); $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingAlternateContents'][] = $alternateContent->asXML(); } } } } - $this->readFormControlProperties($excel, $zip, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData); - $this->readPrinterSettings($excel, $zip, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData); + $this->readFormControlProperties($excel, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData); + $this->readPrinterSettings($excel, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData); // Loop through definedNames if ($xmlWorkbook->definedNames) { @@ -1407,11 +1503,11 @@ class Xlsx extends BaseReader } } - if ((!$this->readDataOnly || !empty($this->loadSheetsOnly)) && isset($xmlWorkbook->bookViews->workbookView)) { - $workbookView = $xmlWorkbook->bookViews->workbookView; - + $workbookView = $xmlWorkbook->children($mainNS)->bookViews->workbookView; + if ((!$this->readDataOnly || !empty($this->loadSheetsOnly)) && !empty($workbookView)) { + $workbookViewAttributes = self::testSimpleXml(self::getAttributes($workbookView)); // active sheet index - $activeTab = (int) ($workbookView['activeTab']); // refers to old sheet index + $activeTab = (int) $workbookViewAttributes->activeTab; // refers to old sheet index // keep active sheet index if sheet is still loaded, else first sheet is set as the active if (isset($mapSheetId[$activeTab]) && $mapSheetId[$activeTab] !== null) { @@ -1423,43 +1519,43 @@ class Xlsx extends BaseReader $excel->setActiveSheetIndex(0); } - if (isset($workbookView['showHorizontalScroll'])) { - $showHorizontalScroll = (string) $workbookView['showHorizontalScroll']; + if (isset($workbookViewAttributes->showHorizontalScroll)) { + $showHorizontalScroll = (string) $workbookViewAttributes->showHorizontalScroll; $excel->setShowHorizontalScroll($this->castXsdBooleanToBool($showHorizontalScroll)); } - if (isset($workbookView['showVerticalScroll'])) { - $showVerticalScroll = (string) $workbookView['showVerticalScroll']; + if (isset($workbookViewAttributes->showVerticalScroll)) { + $showVerticalScroll = (string) $workbookViewAttributes->showVerticalScroll; $excel->setShowVerticalScroll($this->castXsdBooleanToBool($showVerticalScroll)); } - if (isset($workbookView['showSheetTabs'])) { - $showSheetTabs = (string) $workbookView['showSheetTabs']; + if (isset($workbookViewAttributes->showSheetTabs)) { + $showSheetTabs = (string) $workbookViewAttributes->showSheetTabs; $excel->setShowSheetTabs($this->castXsdBooleanToBool($showSheetTabs)); } - if (isset($workbookView['minimized'])) { - $minimized = (string) $workbookView['minimized']; + if (isset($workbookViewAttributes->minimized)) { + $minimized = (string) $workbookViewAttributes->minimized; $excel->setMinimized($this->castXsdBooleanToBool($minimized)); } - if (isset($workbookView['autoFilterDateGrouping'])) { - $autoFilterDateGrouping = (string) $workbookView['autoFilterDateGrouping']; + if (isset($workbookViewAttributes->autoFilterDateGrouping)) { + $autoFilterDateGrouping = (string) $workbookViewAttributes->autoFilterDateGrouping; $excel->setAutoFilterDateGrouping($this->castXsdBooleanToBool($autoFilterDateGrouping)); } - if (isset($workbookView['firstSheet'])) { - $firstSheet = (string) $workbookView['firstSheet']; + if (isset($workbookViewAttributes->firstSheet)) { + $firstSheet = (string) $workbookViewAttributes->firstSheet; $excel->setFirstSheetIndex((int) $firstSheet); } - if (isset($workbookView['visibility'])) { - $visibility = (string) $workbookView['visibility']; + if (isset($workbookViewAttributes->visibility)) { + $visibility = (string) $workbookViewAttributes->visibility; $excel->setVisibility($visibility); } - if (isset($workbookView['tabRatio'])) { - $tabRatio = (string) $workbookView['tabRatio']; + if (isset($workbookViewAttributes->tabRatio)) { + $tabRatio = (string) $workbookViewAttributes->tabRatio; $excel->setTabRatio((int) $tabRatio); } } @@ -1469,13 +1565,7 @@ class Xlsx extends BaseReader } if (!$this->readDataOnly) { - $contentTypes = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, '[Content_Types].xml') - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $contentTypes = $this->loadZip('[Content_Types].xml'); // Default content types foreach ($contentTypes->Default as $contentType) { @@ -1492,14 +1582,8 @@ class Xlsx extends BaseReader switch ($contentType['ContentType']) { case 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml': if ($this->includeCharts) { - $chartEntryRef = ltrim($contentType['PartName'], '/'); - $chartElements = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, $chartEntryRef) - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $chartEntryRef = ltrim((string) $contentType['PartName'], '/'); + $chartElements = $this->loadZip($chartEntryRef); $objChart = Chart::readChart($chartElements, basename($chartEntryRef, '.xml')); if (isset($charts[$chartEntryRef])) { @@ -1508,7 +1592,10 @@ class Xlsx extends BaseReader $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart); $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet'])); $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']); - $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']); + if (array_key_exists('toCoordinate', $chartDetails[$chartPositionRef])) { + // For oneCellAnchor positioned charts, toCoordinate is not in the data. Does it need to be calculated? + $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']); + } } } } @@ -1531,31 +1618,6 @@ class Xlsx extends BaseReader return $excel; } - private static function readColor($color, $background = false) - { - if (isset($color['rgb'])) { - return (string) $color['rgb']; - } elseif (isset($color['indexed'])) { - return Color::indexedColor($color['indexed'] - 7, $background)->getARGB(); - } elseif (isset($color['theme'])) { - if (self::$theme !== null) { - $returnColour = self::$theme->getColourByIndex((int) $color['theme']); - if (isset($color['tint'])) { - $tintAdjust = (float) $color['tint']; - $returnColour = Color::changeBrightness($returnColour, $tintAdjust); - } - - return 'FF' . $returnColour; - } - } - - if ($background) { - return 'FFFFFFFF'; - } - - return 'FF000000'; - } - /** * @param SimpleXMLElement|stdClass $style */ @@ -1565,116 +1627,28 @@ class Xlsx extends BaseReader // font if (isset($style->font)) { - $docStyle->getFont()->setName((string) $style->font->name['val']); - $docStyle->getFont()->setSize((float) $style->font->sz['val']); - if (isset($style->font->b)) { - $docStyle->getFont()->setBold(!isset($style->font->b['val']) || self::boolean((string) $style->font->b['val'])); - } - if (isset($style->font->i)) { - $docStyle->getFont()->setItalic(!isset($style->font->i['val']) || self::boolean((string) $style->font->i['val'])); - } - if (isset($style->font->strike)) { - $docStyle->getFont()->setStrikethrough(!isset($style->font->strike['val']) || self::boolean((string) $style->font->strike['val'])); - } - $docStyle->getFont()->getColor()->setARGB(self::readColor($style->font->color)); - - if (isset($style->font->u) && !isset($style->font->u['val'])) { - $docStyle->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE); - } elseif (isset($style->font->u, $style->font->u['val'])) { - $docStyle->getFont()->setUnderline((string) $style->font->u['val']); - } - - if (isset($style->font->vertAlign, $style->font->vertAlign['val'])) { - $vertAlign = strtolower((string) $style->font->vertAlign['val']); - if ($vertAlign == 'superscript') { - $docStyle->getFont()->setSuperscript(true); - } - if ($vertAlign == 'subscript') { - $docStyle->getFont()->setSubscript(true); - } - } + Styles::readFontStyle($docStyle->getFont(), $style->font); } // fill if (isset($style->fill)) { - if ($style->fill->gradientFill) { - /** @var SimpleXMLElement $gradientFill */ - $gradientFill = $style->fill->gradientFill[0]; - if (!empty($gradientFill['type'])) { - $docStyle->getFill()->setFillType((string) $gradientFill['type']); - } - $docStyle->getFill()->setRotation((float) ($gradientFill['degree'])); - $gradientFill->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); - $docStyle->getFill()->getStartColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=0]'))->color)); - $docStyle->getFill()->getEndColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=1]'))->color)); - } elseif ($style->fill->patternFill) { - $patternType = (string) $style->fill->patternFill['patternType'] != '' ? (string) $style->fill->patternFill['patternType'] : 'solid'; - $docStyle->getFill()->setFillType($patternType); - if ($style->fill->patternFill->fgColor) { - $docStyle->getFill()->getStartColor()->setARGB(self::readColor($style->fill->patternFill->fgColor, true)); - } - if ($style->fill->patternFill->bgColor) { - $docStyle->getFill()->getEndColor()->setARGB(self::readColor($style->fill->patternFill->bgColor, true)); - } - } + Styles::readFillStyle($docStyle->getFill(), $style->fill); } // border if (isset($style->border)) { - $diagonalUp = self::boolean((string) $style->border['diagonalUp']); - $diagonalDown = self::boolean((string) $style->border['diagonalDown']); - if (!$diagonalUp && !$diagonalDown) { - $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_NONE); - } elseif ($diagonalUp && !$diagonalDown) { - $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_UP); - } elseif (!$diagonalUp && $diagonalDown) { - $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_DOWN); - } else { - $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_BOTH); - } - self::readBorder($docStyle->getBorders()->getLeft(), $style->border->left); - self::readBorder($docStyle->getBorders()->getRight(), $style->border->right); - self::readBorder($docStyle->getBorders()->getTop(), $style->border->top); - self::readBorder($docStyle->getBorders()->getBottom(), $style->border->bottom); - self::readBorder($docStyle->getBorders()->getDiagonal(), $style->border->diagonal); + Styles::readBorderStyle($docStyle->getBorders(), $style->border); } // alignment if (isset($style->alignment)) { - $docStyle->getAlignment()->setHorizontal((string) $style->alignment['horizontal']); - $docStyle->getAlignment()->setVertical((string) $style->alignment['vertical']); - - $textRotation = 0; - if ((int) $style->alignment['textRotation'] <= 90) { - $textRotation = (int) $style->alignment['textRotation']; - } elseif ((int) $style->alignment['textRotation'] > 90) { - $textRotation = 90 - (int) $style->alignment['textRotation']; - } - - $docStyle->getAlignment()->setTextRotation((int) $textRotation); - $docStyle->getAlignment()->setWrapText(self::boolean((string) $style->alignment['wrapText'])); - $docStyle->getAlignment()->setShrinkToFit(self::boolean((string) $style->alignment['shrinkToFit'])); - $docStyle->getAlignment()->setIndent((int) ((string) $style->alignment['indent']) > 0 ? (int) ((string) $style->alignment['indent']) : 0); - $docStyle->getAlignment()->setReadOrder((int) ((string) $style->alignment['readingOrder']) > 0 ? (int) ((string) $style->alignment['readingOrder']) : 0); + Styles::readAlignmentStyle($docStyle->getAlignment(), $style->alignment); } // protection if (isset($style->protection)) { - if (isset($style->protection['locked'])) { - if (self::boolean((string) $style->protection['locked'])) { - $docStyle->getProtection()->setLocked(Protection::PROTECTION_PROTECTED); - } else { - $docStyle->getProtection()->setLocked(Protection::PROTECTION_UNPROTECTED); - } - } - - if (isset($style->protection['hidden'])) { - if (self::boolean((string) $style->protection['hidden'])) { - $docStyle->getProtection()->setHidden(Protection::PROTECTION_PROTECTED); - } else { - $docStyle->getProtection()->setHidden(Protection::PROTECTION_UNPROTECTED); - } - } + Styles::readProtectionLocked($docStyle, $style); + Styles::readProtectionHidden($docStyle, $style); } // top-level style settings @@ -1684,24 +1658,9 @@ class Xlsx extends BaseReader } /** - * @param SimpleXMLElement $eleBorder - */ - private static function readBorder(Border $docBorder, $eleBorder): void - { - if (isset($eleBorder['style'])) { - $docBorder->setBorderStyle((string) $eleBorder['style']); - } - if (isset($eleBorder->color)) { - $docBorder->getColor()->setARGB(self::readColor($eleBorder->color)); - } - } - - /** - * @param SimpleXMLElement | null $is - * * @return RichText */ - private function parseRichText($is) + private function parseRichText(?SimpleXMLElement $is) { $value = new RichText(); @@ -1709,52 +1668,71 @@ class Xlsx extends BaseReader $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $is->t)); } else { if (is_object($is->r)) { + + /** @var SimpleXMLElement $run */ foreach ($is->r as $run) { if (!isset($run->rPr)) { $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $run->t)); } else { $objText = $value->createTextRun(StringHelper::controlCharacterOOXML2PHP((string) $run->t)); - if (isset($run->rPr->rFont['val'])) { - $objText->getFont()->setName((string) $run->rPr->rFont['val']); + $attr = $run->rPr->rFont->attributes(); + if (isset($attr['val'])) { + $objText->getFont()->setName((string) $attr['val']); } - if (isset($run->rPr->sz['val'])) { - $objText->getFont()->setSize((float) $run->rPr->sz['val']); + $attr = $run->rPr->sz->attributes(); + if (isset($attr['val'])) { + $objText->getFont()->setSize((float) $attr['val']); } if (isset($run->rPr->color)) { - $objText->getFont()->setColor(new Color(self::readColor($run->rPr->color))); + $objText->getFont()->setColor(new Color(Styles::readColor($run->rPr->color))); } - if ( - (isset($run->rPr->b['val']) && self::boolean((string) $run->rPr->b['val'])) || - (isset($run->rPr->b) && !isset($run->rPr->b['val'])) - ) { - $objText->getFont()->setBold(true); - } - if ( - (isset($run->rPr->i['val']) && self::boolean((string) $run->rPr->i['val'])) || - (isset($run->rPr->i) && !isset($run->rPr->i['val'])) - ) { - $objText->getFont()->setItalic(true); - } - if (isset($run->rPr->vertAlign, $run->rPr->vertAlign['val'])) { - $vertAlign = strtolower((string) $run->rPr->vertAlign['val']); - if ($vertAlign == 'superscript') { - $objText->getFont()->setSuperscript(true); - } - if ($vertAlign == 'subscript') { - $objText->getFont()->setSubscript(true); + if (isset($run->rPr->b)) { + $attr = $run->rPr->b->attributes(); + if ( + (isset($attr['val']) && self::boolean((string) $attr['val'])) || + (!isset($attr['val'])) + ) { + $objText->getFont()->setBold(true); } } - if (isset($run->rPr->u) && !isset($run->rPr->u['val'])) { - $objText->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE); - } elseif (isset($run->rPr->u, $run->rPr->u['val'])) { - $objText->getFont()->setUnderline((string) $run->rPr->u['val']); + if (isset($run->rPr->i)) { + $attr = $run->rPr->i->attributes(); + if ( + (isset($attr['val']) && self::boolean((string) $attr['val'])) || + (!isset($attr['val'])) + ) { + $objText->getFont()->setItalic(true); + } } - if ( - (isset($run->rPr->strike['val']) && self::boolean((string) $run->rPr->strike['val'])) || - (isset($run->rPr->strike) && !isset($run->rPr->strike['val'])) - ) { - $objText->getFont()->setStrikethrough(true); + if (isset($run->rPr->vertAlign)) { + $attr = $run->rPr->vertAlign->attributes(); + if (isset($attr['val'])) { + $vertAlign = strtolower((string) $attr['val']); + if ($vertAlign == 'superscript') { + $objText->getFont()->setSuperscript(true); + } + if ($vertAlign == 'subscript') { + $objText->getFont()->setSubscript(true); + } + } + } + if (isset($run->rPr->u)) { + $attr = $run->rPr->u->attributes(); + if (!isset($attr['val'])) { + $objText->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE); + } else { + $objText->getFont()->setUnderline((string) $attr['val']); + } + } + if (isset($run->rPr->strike)) { + $attr = $run->rPr->strike->attributes(); + if ( + (isset($attr['val']) && self::boolean((string) $attr['val'])) || + (!isset($attr['val'])) + ) { + $objText->getFont()->setStrikethrough(true); + } } } } @@ -1764,11 +1742,7 @@ class Xlsx extends BaseReader return $value; } - /** - * @param mixed $customUITarget - * @param mixed $zip - */ - private function readRibbon(Spreadsheet $excel, $customUITarget, $zip): void + private function readRibbon(Spreadsheet $excel, string $customUITarget, ZipArchive $zip): void { $baseDir = dirname($customUITarget); $nameCustomUI = basename($customUITarget); @@ -1789,7 +1763,7 @@ class Xlsx extends BaseReader if (false !== $UIRels) { // we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image foreach ($UIRels->Relationship as $ele) { - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') { + if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/image') { // an image ? $customUIImagesNames[(string) $ele['Id']] = (string) $ele['Target']; $customUIImagesBinaries[(string) $ele['Target']] = $this->getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']); @@ -1875,16 +1849,16 @@ class Xlsx extends BaseReader */ private function readHyperLinkDrawing($objDrawing, $cellAnchor, $hyperlinks): void { - $hlinkClick = $cellAnchor->pic->nvPicPr->cNvPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->hlinkClick; + $hlinkClick = $cellAnchor->pic->nvPicPr->cNvPr->children(Namespaces::DRAWINGML)->hlinkClick; if ($hlinkClick->count() === 0) { return; } - $hlinkId = (string) $hlinkClick->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships')['id']; + $hlinkId = (string) self::getAttributes($hlinkClick, Namespaces::SCHEMA_OFFICE_DOCUMENT)['id']; $hyperlink = new Hyperlink( $hyperlinks[$hlinkId], - (string) self::getArrayItem($cellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name') + (string) self::getArrayItem(self::getAttributes($cellAnchor->pic->nvPicPr->cNvPr), 'name') ); $objDrawing->setHyperlink($hyperlink); } @@ -1895,44 +1869,49 @@ class Xlsx extends BaseReader return; } - if ($xmlWorkbook->workbookProtection['lockRevision']) { - $excel->getSecurity()->setLockRevision((bool) $xmlWorkbook->workbookProtection['lockRevision']); - } - - if ($xmlWorkbook->workbookProtection['lockStructure']) { - $excel->getSecurity()->setLockStructure((bool) $xmlWorkbook->workbookProtection['lockStructure']); - } - - if ($xmlWorkbook->workbookProtection['lockWindows']) { - $excel->getSecurity()->setLockWindows((bool) $xmlWorkbook->workbookProtection['lockWindows']); - } + $excel->getSecurity()->setLockRevision(self::getLockValue($xmlWorkbook->workbookProtection, 'lockRevision')); + $excel->getSecurity()->setLockStructure(self::getLockValue($xmlWorkbook->workbookProtection, 'lockStructure')); + $excel->getSecurity()->setLockWindows(self::getLockValue($xmlWorkbook->workbookProtection, 'lockWindows')); if ($xmlWorkbook->workbookProtection['revisionsPassword']) { - $excel->getSecurity()->setRevisionsPassword((string) $xmlWorkbook->workbookProtection['revisionsPassword'], true); + $excel->getSecurity()->setRevisionsPassword( + (string) $xmlWorkbook->workbookProtection['revisionsPassword'], + true + ); } if ($xmlWorkbook->workbookProtection['workbookPassword']) { - $excel->getSecurity()->setWorkbookPassword((string) $xmlWorkbook->workbookProtection['workbookPassword'], true); + $excel->getSecurity()->setWorkbookPassword( + (string) $xmlWorkbook->workbookProtection['workbookPassword'], + true + ); } } - private function readFormControlProperties(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData): void + private static function getLockValue(SimpleXmlElement $protection, string $key): ?bool { + $returnValue = null; + $protectKey = $protection[$key]; + if (!empty($protectKey)) { + $protectKey = (string) $protectKey; + $returnValue = $protectKey !== 'false' && (bool) $protectKey; + } + + return $returnValue; + } + + private function readFormControlProperties(Spreadsheet $excel, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData): void + { + $zip = $this->zip; if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) { return; } - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $relsWorksheet = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $filename = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; + $relsWorksheet = $this->loadZipNoNamespace($filename, Namespaces::RELATIONSHIPS); $ctrlProps = []; foreach ($relsWorksheet->Relationship as $ele) { - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/ctrlProp') { + if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/ctrlProp') { $ctrlProps[(string) $ele['Id']] = $ele; } } @@ -1948,23 +1927,18 @@ class Xlsx extends BaseReader unset($unparsedCtrlProps); } - private function readPrinterSettings(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData): void + private function readPrinterSettings(Spreadsheet $excel, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData): void { + $zip = $this->zip; if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) { return; } - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $relsWorksheet = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $filename = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; + $relsWorksheet = $this->loadZipNoNamespace($filename, Namespaces::RELATIONSHIPS); $sheetPrinterSettings = []; foreach ($relsWorksheet->Relationship as $ele) { - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings') { + if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/printerSettings') { $sheetPrinterSettings[(string) $ele['Id']] = $ele; } } @@ -2003,38 +1977,30 @@ class Xlsx extends BaseReader return (bool) $xsdBoolean; } - /** - * @param ZipArchive $zip Opened zip archive - * - * @return string basename of the used excel workbook - */ - private function getWorkbookBaseName(ZipArchive $zip) + private function getWorkbookBaseName(): array { $workbookBasename = ''; + $xmlNamespaceBase = ''; // check if it is an OOXML archive - $rels = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, '_rels/.rels') - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - if ($rels !== false) { - foreach ($rels->Relationship as $rel) { - switch ($rel['Type']) { - case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument': - $basename = basename($rel['Target']); - if (preg_match('/workbook.*\.xml/', $basename)) { - $workbookBasename = $basename; - } + $rels = $this->loadZip(self::INITIAL_FILE); + foreach ($rels->children(Namespaces::RELATIONSHIPS)->Relationship as $rel) { + $rel = self::getAttributes($rel); + $type = (string) $rel['Type']; + switch ($type) { + case Namespaces::OFFICE_DOCUMENT: + case Namespaces::PURL_OFFICE_DOCUMENT: + $basename = basename((string) $rel['Target']); + $xmlNamespaceBase = dirname($type); + if (preg_match('/workbook.*\.xml/', $basename)) { + $workbookBasename = $basename; + } - break; - } + break; } } - return $workbookBasename; + return [$workbookBasename, $xmlNamespaceBase]; } private function readSheetProtection(Worksheet $docSheet, SimpleXMLElement $xmlSheet): void @@ -2061,4 +2027,52 @@ class Xlsx extends BaseReader } } } + + private function readAutoFilterTables( + SimpleXMLElement $xmlSheet, + Worksheet $docSheet, + string $dir, + string $fileWorksheet, + ZipArchive $zip + ): void { + if ($xmlSheet && $xmlSheet->autoFilter) { + // In older files, autofilter structure is defined in the worksheet file + (new AutoFilter($docSheet, $xmlSheet))->load(); + } elseif ($xmlSheet && $xmlSheet->tableParts && $xmlSheet->tableParts['count'] > 0) { + // But for Office365, MS decided to make it all just a bit more complicated + $this->readAutoFilterTablesInTablesFile($xmlSheet, $dir, $fileWorksheet, $zip, $docSheet); + } + } + + private function readAutoFilterTablesInTablesFile( + SimpleXMLElement $xmlSheet, + string $dir, + string $fileWorksheet, + ZipArchive $zip, + Worksheet $docSheet + ): void { + foreach ($xmlSheet->tableParts->tablePart as $tablePart) { + $relation = self::getAttributes($tablePart, Namespaces::SCHEMA_OFFICE_DOCUMENT); + $tablePartRel = (string) $relation['id']; + $relationsFileName = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; + + if ($zip->locateName($relationsFileName)) { + $relsTableReferences = $this->loadZip($relationsFileName, Namespaces::RELATIONSHIPS); + foreach ($relsTableReferences->Relationship as $relationship) { + $relationshipAttributes = self::getAttributes($relationship, ''); + + if ((string) $relationshipAttributes['Id'] === $tablePartRel) { + $relationshipFileName = (string) $relationshipAttributes['Target']; + $relationshipFilePath = dirname("$dir/$fileWorksheet") . '/' . $relationshipFileName; + $relationshipFilePath = File::realpath($relationshipFilePath); + + if ($this->fileExistsInArchive($this->zip, $relationshipFilePath)) { + $autoFilter = $this->loadZip($relationshipFilePath); + (new AutoFilter($docSheet, $autoFilter))->load(); + } + } + } + } + } + } } diff --git a/src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php b/src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php index f52bfd41..5f333cd3 100644 --- a/src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php +++ b/src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php @@ -89,7 +89,7 @@ class AutoFilter $customFilters = $filterColumn->customFilters; // Custom filters can an AND or an OR join; // and there should only ever be one or two entries - if ((isset($customFilters['and'])) && ($customFilters['and'] == 1)) { + if ((isset($customFilters['and'])) && ((string) $customFilters['and'] === '1')) { $column->setJoin(Column::AUTOFILTER_COLUMN_JOIN_AND); } foreach ($customFilters->customFilter as $filterRule) { @@ -130,12 +130,12 @@ class AutoFilter // We should only ever have one top10 filter foreach ($filterColumn->top10 as $filterRule) { $column->createRule()->setRule( - (((isset($filterRule['percent'])) && ($filterRule['percent'] == 1)) + (((isset($filterRule['percent'])) && ((string) $filterRule['percent'] === '1')) ? Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT : Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE ), (string) $filterRule['val'], - (((isset($filterRule['top'])) && ($filterRule['top'] == 1)) + (((isset($filterRule['top'])) && ((string) $filterRule['top'] === '1')) ? Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP : Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM ) diff --git a/src/PhpSpreadsheet/Reader/Xlsx/Chart.php b/src/PhpSpreadsheet/Reader/Xlsx/Chart.php index c9a230c2..667e3674 100644 --- a/src/PhpSpreadsheet/Reader/Xlsx/Chart.php +++ b/src/PhpSpreadsheet/Reader/Xlsx/Chart.php @@ -31,7 +31,9 @@ class Chart } elseif ($format == 'integer') { return (int) $attributes[$name]; } elseif ($format == 'boolean') { - return (bool) ($attributes[$name] === '0' || $attributes[$name] !== 'true') ? false : true; + $value = (string) $attributes[$name]; + + return $value === 'true' || $value === '1'; } return (float) $attributes[$name]; @@ -61,7 +63,7 @@ class Chart $XaxisLabel = $YaxisLabel = $legend = $title = null; $dispBlanksAs = $plotVisOnly = null; - + $plotArea = null; foreach ($chartElementsC as $chartElementKey => $chartElement) { switch ($chartElementKey) { case 'chart': @@ -90,8 +92,22 @@ class Chart break; case 'valAx': - if (isset($chartDetail->title)) { - $YaxisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta); + if (isset($chartDetail->title, $chartDetail->axPos)) { + $axisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta); + $axPos = self::getAttribute($chartDetail->axPos, 'val', 'string'); + + switch ($axPos) { + case 't': + case 'b': + $XaxisLabel = $axisLabel; + + break; + case 'r': + case 'l': + $YaxisLabel = $axisLabel; + + break; + } } break; @@ -328,26 +344,51 @@ class Chart { if (isset($seriesDetail->strRef)) { $seriesSource = (string) $seriesDetail->strRef->f; - $seriesData = self::chartDataSeriesValues($seriesDetail->strRef->strCache->children($namespacesChartMeta['c']), 's'); + $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, null, null, null, $marker); - return new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker); + if (isset($seriesDetail->strRef->strCache)) { + $seriesData = self::chartDataSeriesValues($seriesDetail->strRef->strCache->children($namespacesChartMeta['c']), 's'); + $seriesValues + ->setFormatCode($seriesData['formatCode']) + ->setDataValues($seriesData['dataValues']); + } + + return $seriesValues; } elseif (isset($seriesDetail->numRef)) { $seriesSource = (string) $seriesDetail->numRef->f; - $seriesData = self::chartDataSeriesValues($seriesDetail->numRef->numCache->children($namespacesChartMeta['c'])); + $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, $seriesSource, null, null, null, $marker); + if (isset($seriesDetail->numRef->numCache)) { + $seriesData = self::chartDataSeriesValues($seriesDetail->numRef->numCache->children($namespacesChartMeta['c'])); + $seriesValues + ->setFormatCode($seriesData['formatCode']) + ->setDataValues($seriesData['dataValues']); + } - return new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker); + return $seriesValues; } elseif (isset($seriesDetail->multiLvlStrRef)) { $seriesSource = (string) $seriesDetail->multiLvlStrRef->f; - $seriesData = self::chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlStrRef->multiLvlStrCache->children($namespacesChartMeta['c']), 's'); - $seriesData['pointCount'] = count($seriesData['dataValues']); + $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, null, null, null, $marker); - return new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker); + if (isset($seriesDetail->multiLvlStrRef->multiLvlStrCache)) { + $seriesData = self::chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlStrRef->multiLvlStrCache->children($namespacesChartMeta['c']), 's'); + $seriesValues + ->setFormatCode($seriesData['formatCode']) + ->setDataValues($seriesData['dataValues']); + } + + return $seriesValues; } elseif (isset($seriesDetail->multiLvlNumRef)) { $seriesSource = (string) $seriesDetail->multiLvlNumRef->f; - $seriesData = self::chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlNumRef->multiLvlNumCache->children($namespacesChartMeta['c']), 's'); - $seriesData['pointCount'] = count($seriesData['dataValues']); + $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, null, null, null, $marker); - return new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker); + if (isset($seriesDetail->multiLvlNumRef->multiLvlNumCache)) { + $seriesData = self::chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlNumRef->multiLvlNumCache->children($namespacesChartMeta['c']), 's'); + $seriesValues + ->setFormatCode($seriesData['formatCode']) + ->setDataValues($seriesData['dataValues']); + } + + return $seriesValues; } return null; @@ -443,7 +484,7 @@ class Chart } $fontSize = (self::getAttribute($titleDetailElement->rPr, 'sz', 'integer')); - if ($fontSize !== null) { + if (is_int($fontSize)) { $objText->getFont()->setSize(floor($fontSize / 100)); } @@ -500,7 +541,7 @@ class Chart { $plotAttributes = []; if (isset($chartDetail->dLbls)) { - if (isset($chartDetail->dLbls->howLegendKey)) { + if (isset($chartDetail->dLbls->showLegendKey)) { $plotAttributes['showLegendKey'] = self::getAttribute($chartDetail->dLbls->showLegendKey, 'val', 'string'); } if (isset($chartDetail->dLbls->showVal)) { diff --git a/src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php b/src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php index 4134b2f1..2f7619f7 100644 --- a/src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php +++ b/src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php @@ -3,6 +3,7 @@ namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter; use PhpOffice\PhpSpreadsheet\Reader\IReadFilter; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; @@ -91,6 +92,10 @@ class ColumnAndRowAttributes extends BaseParserClass $rowsAttributes = $this->readRowAttributes($this->worksheetXml->sheetData->row, $readDataOnly); } + if ($readFilter !== null && get_class($readFilter) === DefaultReadFilter::class) { + $readFilter = null; + } + // set columns/rows attributes $columnsAttributesAreSet = []; foreach ($columnsAttributes as $columnCoordinate => $columnAttributes) { diff --git a/src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php b/src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php index 4aa48e17..dcd7ad12 100644 --- a/src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php +++ b/src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php @@ -3,6 +3,9 @@ namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Style\Conditional; +use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalDataBar; +use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalFormattingRuleExtension; +use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalFormatValueObject; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; @@ -25,7 +28,8 @@ class ConditionalStyles { $this->setConditionalStyles( $this->worksheet, - $this->readConditionalStyles($this->worksheetXml) + $this->readConditionalStyles($this->worksheetXml), + $this->worksheetXml->extLst ); } @@ -34,15 +38,9 @@ class ConditionalStyles $conditionals = []; foreach ($xmlSheet->conditionalFormatting as $conditional) { foreach ($conditional->cfRule as $cfRule) { - if ( - ((string) $cfRule['type'] == Conditional::CONDITION_NONE - || (string) $cfRule['type'] == Conditional::CONDITION_CELLIS - || (string) $cfRule['type'] == Conditional::CONDITION_CONTAINSTEXT - || (string) $cfRule['type'] == Conditional::CONDITION_CONTAINSBLANKS - || (string) $cfRule['type'] == Conditional::CONDITION_NOTCONTAINSBLANKS - || (string) $cfRule['type'] == Conditional::CONDITION_EXPRESSION) - && isset($this->dxfs[(int) ($cfRule['dxfId'])]) - ) { + if (Conditional::isValidConditionType((string) $cfRule['type']) && isset($this->dxfs[(int) ($cfRule['dxfId'])])) { + $conditionals[(string) $conditional['sqref']][(int) ($cfRule['priority'])] = $cfRule; + } elseif ((string) $cfRule['type'] == Conditional::CONDITION_DATABAR) { $conditionals[(string) $conditional['sqref']][(int) ($cfRule['priority'])] = $cfRule; } } @@ -51,11 +49,11 @@ class ConditionalStyles return $conditionals; } - private function setConditionalStyles(Worksheet $worksheet, array $conditionals): void + private function setConditionalStyles(Worksheet $worksheet, array $conditionals, $xmlExtLst): void { foreach ($conditionals as $ref => $cfRules) { ksort($cfRules); - $conditionalStyles = $this->readStyleRules($cfRules); + $conditionalStyles = $this->readStyleRules($cfRules, $xmlExtLst); // Extract all cell references in $ref $cellBlocks = explode(' ', str_replace('$', '', strtoupper($ref))); @@ -65,8 +63,9 @@ class ConditionalStyles } } - private function readStyleRules($cfRules) + private function readStyleRules($cfRules, $extLst) { + $conditionalFormattingRuleExtensions = ConditionalFormattingRuleExtension::parseExtLstXml($extLst); $conditionalStyles = []; foreach ($cfRules as $cfRule) { $objConditional = new Conditional(); @@ -88,10 +87,63 @@ class ConditionalStyles } else { $objConditional->addCondition((string) $cfRule->formula); } - $objConditional->setStyle(clone $this->dxfs[(int) ($cfRule['dxfId'])]); + + if (isset($cfRule->dataBar)) { + $objConditional->setDataBar( + $this->readDataBarOfConditionalRule($cfRule, $conditionalFormattingRuleExtensions) + ); + } else { + $objConditional->setStyle(clone $this->dxfs[(int) ($cfRule['dxfId'])]); + } + $conditionalStyles[] = $objConditional; } return $conditionalStyles; } + + private function readDataBarOfConditionalRule($cfRule, $conditionalFormattingRuleExtensions): ConditionalDataBar + { + $dataBar = new ConditionalDataBar(); + //dataBar attribute + if (isset($cfRule->dataBar['showValue'])) { + $dataBar->setShowValue((bool) $cfRule->dataBar['showValue']); + } + + //dataBar children + //conditionalFormatValueObjects + $cfvoXml = $cfRule->dataBar->cfvo; + $cfvoIndex = 0; + foreach ((count($cfvoXml) > 1 ? $cfvoXml : [$cfvoXml]) as $cfvo) { + if ($cfvoIndex === 0) { + $dataBar->setMinimumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $cfvo['type'], (string) $cfvo['val'])); + } + if ($cfvoIndex === 1) { + $dataBar->setMaximumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $cfvo['type'], (string) $cfvo['val'])); + } + ++$cfvoIndex; + } + + //color + if (isset($cfRule->dataBar->color)) { + $dataBar->setColor((string) $cfRule->dataBar->color['rgb']); + } + //extLst + $this->readDataBarExtLstOfConditionalRule($dataBar, $cfRule, $conditionalFormattingRuleExtensions); + + return $dataBar; + } + + private function readDataBarExtLstOfConditionalRule(ConditionalDataBar $dataBar, $cfRule, $conditionalFormattingRuleExtensions): void + { + if (isset($cfRule->extLst)) { + $ns = $cfRule->extLst->getNamespaces(true); + foreach ((count($cfRule->extLst) > 0 ? $cfRule->extLst->ext : [$cfRule->extLst->ext]) as $ext) { + $extId = (string) $ext->children($ns['x14'])->id; + if (isset($conditionalFormattingRuleExtensions[$extId]) && (string) $ext['uri'] === '{B025F937-C7B1-47D3-B67F-A62EFF666E3E}') { + $dataBar->setConditionalFormattingRuleExt($conditionalFormattingRuleExtensions[$extId]); + } + } + } + } } diff --git a/src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php b/src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php index 41a8c9fb..b699cb57 100644 --- a/src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php +++ b/src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php @@ -34,16 +34,18 @@ class DataValidations $docValidation->setType((string) $dataValidation['type']); $docValidation->setErrorStyle((string) $dataValidation['errorStyle']); $docValidation->setOperator((string) $dataValidation['operator']); - $docValidation->setAllowBlank($dataValidation['allowBlank'] != 0); - $docValidation->setShowDropDown($dataValidation['showDropDown'] == 0); - $docValidation->setShowInputMessage($dataValidation['showInputMessage'] != 0); - $docValidation->setShowErrorMessage($dataValidation['showErrorMessage'] != 0); + $docValidation->setAllowBlank(filter_var($dataValidation['allowBlank'], FILTER_VALIDATE_BOOLEAN)); + // showDropDown is inverted (works as hideDropDown if true) + $docValidation->setShowDropDown(!filter_var($dataValidation['showDropDown'], FILTER_VALIDATE_BOOLEAN)); + $docValidation->setShowInputMessage(filter_var($dataValidation['showInputMessage'], FILTER_VALIDATE_BOOLEAN)); + $docValidation->setShowErrorMessage(filter_var($dataValidation['showErrorMessage'], FILTER_VALIDATE_BOOLEAN)); $docValidation->setErrorTitle((string) $dataValidation['errorTitle']); $docValidation->setError((string) $dataValidation['error']); $docValidation->setPromptTitle((string) $dataValidation['promptTitle']); $docValidation->setPrompt((string) $dataValidation['prompt']); $docValidation->setFormula1((string) $dataValidation->formula1); $docValidation->setFormula2((string) $dataValidation->formula2); + $docValidation->setSqref($range); } } } diff --git a/src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php b/src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php index 106fd44e..dbc8c085 100644 --- a/src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php +++ b/src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php @@ -3,6 +3,7 @@ namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; @@ -19,26 +20,30 @@ class Hyperlinks public function readHyperlinks(SimpleXMLElement $relsWorksheet): void { - foreach ($relsWorksheet->Relationship as $element) { - if ($element['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink') { - $this->hyperlinks[(string) $element['Id']] = (string) $element['Target']; + foreach ($relsWorksheet->children(Namespaces::RELATIONSHIPS)->Relationship as $elementx) { + $element = Xlsx::getAttributes($elementx); + if ($element->Type == Namespaces::HYPERLINK) { + $this->hyperlinks[(string) $element->Id] = (string) $element->Target; } } } public function setHyperlinks(SimpleXMLElement $worksheetXml): void { - foreach ($worksheetXml->hyperlink as $hyperlink) { - $this->setHyperlink($hyperlink, $this->worksheet); + foreach ($worksheetXml->children(Namespaces::MAIN)->hyperlink as $hyperlink) { + if ($hyperlink !== null) { + $this->setHyperlink($hyperlink, $this->worksheet); + } } } private function setHyperlink(SimpleXMLElement $hyperlink, Worksheet $worksheet): void { // Link url - $linkRel = $hyperlink->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $linkRel = Xlsx::getAttributes($hyperlink, Namespaces::SCHEMA_OFFICE_DOCUMENT); - foreach (Coordinate::extractAllCellReferencesInRange($hyperlink['ref']) as $cellReference) { + $attributes = Xlsx::getAttributes($hyperlink); + foreach (Coordinate::extractAllCellReferencesInRange($attributes->ref) as $cellReference) { $cell = $worksheet->getCell($cellReference); if (isset($linkRel['id'])) { $hyperlinkUrl = $this->hyperlinks[(string) $linkRel['id']] ?? null; diff --git a/src/PhpSpreadsheet/Reader/Xlsx/Namespaces.php b/src/PhpSpreadsheet/Reader/Xlsx/Namespaces.php new file mode 100644 index 00000000..54f56d72 --- /dev/null +++ b/src/PhpSpreadsheet/Reader/Xlsx/Namespaces.php @@ -0,0 +1,76 @@ +setPageOrder((string) $xmlSheet->pageSetup['pageOrder']); } - $relAttributes = $xmlSheet->pageSetup->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $relAttributes = $xmlSheet->pageSetup->attributes(Namespaces::SCHEMA_OFFICE_DOCUMENT); if (isset($relAttributes['id'])) { $unparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId'] = (string) $relAttributes['id']; } diff --git a/src/PhpSpreadsheet/Reader/Xlsx/Properties.php b/src/PhpSpreadsheet/Reader/Xlsx/Properties.php index b6f3c61f..82b5172b 100644 --- a/src/PhpSpreadsheet/Reader/Xlsx/Properties.php +++ b/src/PhpSpreadsheet/Reader/Xlsx/Properties.php @@ -9,8 +9,10 @@ use SimpleXMLElement; class Properties { + /** @var XmlScanner */ private $securityScanner; + /** @var DocumentProperties */ private $docProps; public function __construct(XmlScanner $securityScanner, DocumentProperties $docProps) @@ -19,28 +21,39 @@ class Properties $this->docProps = $docProps; } - private function extractPropertyData($propertyData) + /** + * @param mixed $obj + */ + private static function nullOrSimple($obj): ?SimpleXMLElement { - return simplexml_load_string( + return ($obj instanceof SimpleXMLElement) ? $obj : null; + } + + private function extractPropertyData(string $propertyData): ?SimpleXMLElement + { + // okay to omit namespace because everything will be processed by xpath + $obj = simplexml_load_string( $this->securityScanner->scan($propertyData), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions() ); + + return self::nullOrSimple($obj); } - public function readCoreProperties($propertyData): void + public function readCoreProperties(string $propertyData): void { $xmlCore = $this->extractPropertyData($propertyData); if (is_object($xmlCore)) { - $xmlCore->registerXPathNamespace('dc', 'http://purl.org/dc/elements/1.1/'); - $xmlCore->registerXPathNamespace('dcterms', 'http://purl.org/dc/terms/'); - $xmlCore->registerXPathNamespace('cp', 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties'); + $xmlCore->registerXPathNamespace('dc', Namespaces::DC_ELEMENTS); + $xmlCore->registerXPathNamespace('dcterms', Namespaces::DC_TERMS); + $xmlCore->registerXPathNamespace('cp', Namespaces::CORE_PROPERTIES2); $this->docProps->setCreator((string) self::getArrayItem($xmlCore->xpath('dc:creator'))); $this->docProps->setLastModifiedBy((string) self::getArrayItem($xmlCore->xpath('cp:lastModifiedBy'))); - $this->docProps->setCreated(strtotime(self::getArrayItem($xmlCore->xpath('dcterms:created')))); //! respect xsi:type - $this->docProps->setModified(strtotime(self::getArrayItem($xmlCore->xpath('dcterms:modified')))); //! respect xsi:type + $this->docProps->setCreated((string) self::getArrayItem($xmlCore->xpath('dcterms:created'))); //! respect xsi:type + $this->docProps->setModified((string) self::getArrayItem($xmlCore->xpath('dcterms:modified'))); //! respect xsi:type $this->docProps->setTitle((string) self::getArrayItem($xmlCore->xpath('dc:title'))); $this->docProps->setDescription((string) self::getArrayItem($xmlCore->xpath('dc:description'))); $this->docProps->setSubject((string) self::getArrayItem($xmlCore->xpath('dc:subject'))); @@ -49,7 +62,7 @@ class Properties } } - public function readExtendedProperties($propertyData): void + public function readExtendedProperties(string $propertyData): void { $xmlCore = $this->extractPropertyData($propertyData); @@ -63,7 +76,7 @@ class Properties } } - public function readCustomProperties($propertyData): void + public function readCustomProperties(string $propertyData): void { $xmlCore = $this->extractPropertyData($propertyData); @@ -85,8 +98,12 @@ class Properties } } - private static function getArrayItem(array $array, $key = 0) + /** + * @param array|false $array + * @param mixed $key + */ + private static function getArrayItem($array, $key = 0): ?SimpleXMLElement { - return $array[$key] ?? null; + return is_array($array) ? ($array[$key] ?? null) : null; } } diff --git a/src/PhpSpreadsheet/Reader/Xlsx/SheetViews.php b/src/PhpSpreadsheet/Reader/Xlsx/SheetViews.php index f6c47929..b2bc99f0 100644 --- a/src/PhpSpreadsheet/Reader/Xlsx/SheetViews.php +++ b/src/PhpSpreadsheet/Reader/Xlsx/SheetViews.php @@ -3,23 +3,31 @@ namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; class SheetViews extends BaseParserClass { + /** @var SimpleXMLElement */ private $sheetViewXml; + /** @var SimpleXMLElement */ + private $sheetViewAttributes; + + /** @var Worksheet */ private $worksheet; public function __construct(SimpleXMLElement $sheetViewXml, Worksheet $workSheet) { $this->sheetViewXml = $sheetViewXml; + $this->sheetViewAttributes = Xlsx::testSimpleXml($sheetViewXml->attributes()); $this->worksheet = $workSheet; } public function load(): void { + $this->topLeft(); $this->zoomScale(); $this->view(); $this->gridLines(); @@ -30,15 +38,15 @@ class SheetViews extends BaseParserClass if (isset($this->sheetViewXml->pane)) { $this->pane(); } - if (isset($this->sheetViewXml->selection, $this->sheetViewXml->selection['sqref'])) { + if (isset($this->sheetViewXml->selection, $this->sheetViewXml->selection->attributes()->sqref)) { $this->selection(); } } private function zoomScale(): void { - if (isset($this->sheetViewXml['zoomScale'])) { - $zoomScale = (int) ($this->sheetViewXml['zoomScale']); + if (isset($this->sheetViewAttributes->zoomScale)) { + $zoomScale = (int) ($this->sheetViewAttributes->zoomScale); if ($zoomScale <= 0) { // setZoomScale will throw an Exception if the scale is less than or equals 0 // that is OK when manually creating documents, but we should be able to read all documents @@ -48,8 +56,8 @@ class SheetViews extends BaseParserClass $this->worksheet->getSheetView()->setZoomScale($zoomScale); } - if (isset($this->sheetViewXml['zoomScaleNormal'])) { - $zoomScaleNormal = (int) ($this->sheetViewXml['zoomScaleNormal']); + if (isset($this->sheetViewAttributes->zoomScaleNormal)) { + $zoomScaleNormal = (int) ($this->sheetViewAttributes->zoomScaleNormal); if ($zoomScaleNormal <= 0) { // setZoomScaleNormal will throw an Exception if the scale is less than or equals 0 // that is OK when manually creating documents, but we should be able to read all documents @@ -62,43 +70,50 @@ class SheetViews extends BaseParserClass private function view(): void { - if (isset($this->sheetViewXml['view'])) { - $this->worksheet->getSheetView()->setView((string) $this->sheetViewXml['view']); + if (isset($this->sheetViewAttributes->view)) { + $this->worksheet->getSheetView()->setView((string) $this->sheetViewAttributes->view); + } + } + + private function topLeft(): void + { + if (isset($this->sheetViewAttributes->topLeftCell)) { + $this->worksheet->setTopLeftCell($this->sheetViewAttributes->topLeftCell); } } private function gridLines(): void { - if (isset($this->sheetViewXml['showGridLines'])) { + if (isset($this->sheetViewAttributes->showGridLines)) { $this->worksheet->setShowGridLines( - self::boolean((string) $this->sheetViewXml['showGridLines']) + self::boolean((string) $this->sheetViewAttributes->showGridLines) ); } } private function headers(): void { - if (isset($this->sheetViewXml['showRowColHeaders'])) { + if (isset($this->sheetViewAttributes->showRowColHeaders)) { $this->worksheet->setShowRowColHeaders( - self::boolean((string) $this->sheetViewXml['showRowColHeaders']) + self::boolean((string) $this->sheetViewAttributes->showRowColHeaders) ); } } private function direction(): void { - if (isset($this->sheetViewXml['rightToLeft'])) { + if (isset($this->sheetViewAttributes->rightToLeft)) { $this->worksheet->setRightToLeft( - self::boolean((string) $this->sheetViewXml['rightToLeft']) + self::boolean((string) $this->sheetViewAttributes->rightToLeft) ); } } private function showZeros(): void { - if (isset($this->sheetViewXml['showZeros'])) { + if (isset($this->sheetViewAttributes->showZeros)) { $this->worksheet->getSheetView()->setShowZeros( - self::boolean((string) $this->sheetViewXml['showZeros']) + self::boolean((string) $this->sheetViewAttributes->showZeros) ); } } @@ -108,17 +123,18 @@ class SheetViews extends BaseParserClass $xSplit = 0; $ySplit = 0; $topLeftCell = null; + $paneAttributes = $this->sheetViewXml->pane->attributes(); - if (isset($this->sheetViewXml->pane['xSplit'])) { - $xSplit = (int) ($this->sheetViewXml->pane['xSplit']); + if (isset($paneAttributes->xSplit)) { + $xSplit = (int) ($paneAttributes->xSplit); } - if (isset($this->sheetViewXml->pane['ySplit'])) { - $ySplit = (int) ($this->sheetViewXml->pane['ySplit']); + if (isset($paneAttributes->ySplit)) { + $ySplit = (int) ($paneAttributes->ySplit); } - if (isset($this->sheetViewXml->pane['topLeftCell'])) { - $topLeftCell = (string) $this->sheetViewXml->pane['topLeftCell']; + if (isset($paneAttributes->topLeftCell)) { + $topLeftCell = (string) $paneAttributes->topLeftCell; } $this->worksheet->freezePane( @@ -129,10 +145,12 @@ class SheetViews extends BaseParserClass private function selection(): void { - $sqref = (string) $this->sheetViewXml->selection['sqref']; - $sqref = explode(' ', $sqref); - $sqref = $sqref[0]; - - $this->worksheet->setSelectedCells($sqref); + $attributes = $this->sheetViewXml->selection->attributes(); + if ($attributes !== null) { + $sqref = (string) $attributes->sqref; + $sqref = explode(' ', $sqref); + $sqref = $sqref[0]; + $this->worksheet->setSelectedCells($sqref); + } } } diff --git a/src/PhpSpreadsheet/Reader/Xlsx/Styles.php b/src/PhpSpreadsheet/Reader/Xlsx/Styles.php index 43de8787..72e66a99 100644 --- a/src/PhpSpreadsheet/Reader/Xlsx/Styles.php +++ b/src/PhpSpreadsheet/Reader/Xlsx/Styles.php @@ -2,6 +2,7 @@ namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; +use PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Borders; @@ -20,7 +21,7 @@ class Styles extends BaseParserClass * * @var Theme */ - private static $theme = null; + private static $theme; private $styles = []; @@ -40,11 +41,14 @@ class Styles extends BaseParserClass $this->cellStyles = $cellStyles; } - private static function readFontStyle(Font $fontStyle, SimpleXMLElement $fontStyleXml): void + public static function readFontStyle(Font $fontStyle, SimpleXMLElement $fontStyleXml): void { - $fontStyle->setName((string) $fontStyleXml->name['val']); - $fontStyle->setSize((float) $fontStyleXml->sz['val']); - + if (isset($fontStyleXml->name, $fontStyleXml->name['val'])) { + $fontStyle->setName((string) $fontStyleXml->name['val']); + } + if (isset($fontStyleXml->sz, $fontStyleXml->sz['val'])) { + $fontStyle->setSize((float) $fontStyleXml->sz['val']); + } if (isset($fontStyleXml->b)) { $fontStyle->setBold(!isset($fontStyleXml->b['val']) || self::boolean((string) $fontStyleXml->b['val'])); } @@ -52,7 +56,9 @@ class Styles extends BaseParserClass $fontStyle->setItalic(!isset($fontStyleXml->i['val']) || self::boolean((string) $fontStyleXml->i['val'])); } if (isset($fontStyleXml->strike)) { - $fontStyle->setStrikethrough(!isset($fontStyleXml->strike['val']) || self::boolean((string) $fontStyleXml->strike['val'])); + $fontStyle->setStrikethrough( + !isset($fontStyleXml->strike['val']) || self::boolean((string) $fontStyleXml->strike['val']) + ); } $fontStyle->getColor()->setARGB(self::readColor($fontStyleXml->color)); @@ -66,8 +72,7 @@ class Styles extends BaseParserClass $verticalAlign = strtolower((string) $fontStyleXml->vertAlign['val']); if ($verticalAlign === 'superscript') { $fontStyle->setSuperscript(true); - } - if ($verticalAlign === 'subscript') { + } elseif ($verticalAlign === 'subscript') { $fontStyle->setSubscript(true); } } @@ -78,13 +83,13 @@ class Styles extends BaseParserClass if ($numfmtStyleXml->count() === 0) { return; } - $numfmt = $numfmtStyleXml->attributes(); + $numfmt = Xlsx::getAttributes($numfmtStyleXml); if ($numfmt->count() > 0 && isset($numfmt['formatCode'])) { $numfmtStyle->setFormatCode((string) $numfmt['formatCode']); } } - private static function readFillStyle(Fill $fillStyle, SimpleXMLElement $fillStyleXml): void + public static function readFillStyle(Fill $fillStyle, SimpleXMLElement $fillStyleXml): void { if ($fillStyleXml->gradientFill) { /** @var SimpleXMLElement $gradientFill */ @@ -93,24 +98,29 @@ class Styles extends BaseParserClass $fillStyle->setFillType((string) $gradientFill['type']); } $fillStyle->setRotation((float) ($gradientFill['degree'])); - $gradientFill->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); + $gradientFill->registerXPathNamespace('sml', Namespaces::MAIN); $fillStyle->getStartColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=0]'))->color)); $fillStyle->getEndColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=1]'))->color)); } elseif ($fillStyleXml->patternFill) { - $patternType = (string) $fillStyleXml->patternFill['patternType'] != '' ? (string) $fillStyleXml->patternFill['patternType'] : 'solid'; - $fillStyle->setFillType($patternType); + $defaultFillStyle = Fill::FILL_NONE; if ($fillStyleXml->patternFill->fgColor) { $fillStyle->getStartColor()->setARGB(self::readColor($fillStyleXml->patternFill->fgColor, true)); - } else { - $fillStyle->getStartColor()->setARGB('FF000000'); + $defaultFillStyle = Fill::FILL_SOLID; } if ($fillStyleXml->patternFill->bgColor) { $fillStyle->getEndColor()->setARGB(self::readColor($fillStyleXml->patternFill->bgColor, true)); + $defaultFillStyle = Fill::FILL_SOLID; } + + $patternType = (string) $fillStyleXml->patternFill['patternType'] != '' + ? (string) $fillStyleXml->patternFill['patternType'] + : $defaultFillStyle; + + $fillStyle->setFillType($patternType); } } - private static function readBorderStyle(Borders $borderStyle, SimpleXMLElement $borderStyleXml): void + public static function readBorderStyle(Borders $borderStyle, SimpleXMLElement $borderStyleXml): void { $diagonalUp = self::boolean((string) $borderStyleXml['diagonalUp']); $diagonalDown = self::boolean((string) $borderStyleXml['diagonalDown']); @@ -141,23 +151,27 @@ class Styles extends BaseParserClass } } - private static function readAlignmentStyle(Alignment $alignment, SimpleXMLElement $alignmentXml): void + public static function readAlignmentStyle(Alignment $alignment, SimpleXMLElement $alignmentXml): void { - $alignment->setHorizontal((string) $alignmentXml->alignment['horizontal']); - $alignment->setVertical((string) $alignmentXml->alignment['vertical']); + $alignment->setHorizontal((string) $alignmentXml['horizontal']); + $alignment->setVertical((string) $alignmentXml['vertical']); $textRotation = 0; - if ((int) $alignmentXml->alignment['textRotation'] <= 90) { - $textRotation = (int) $alignmentXml->alignment['textRotation']; - } elseif ((int) $alignmentXml->alignment['textRotation'] > 90) { - $textRotation = 90 - (int) $alignmentXml->alignment['textRotation']; + if ((int) $alignmentXml['textRotation'] <= 90) { + $textRotation = (int) $alignmentXml['textRotation']; + } elseif ((int) $alignmentXml['textRotation'] > 90) { + $textRotation = 90 - (int) $alignmentXml['textRotation']; } $alignment->setTextRotation((int) $textRotation); - $alignment->setWrapText(self::boolean((string) $alignmentXml->alignment['wrapText'])); - $alignment->setShrinkToFit(self::boolean((string) $alignmentXml->alignment['shrinkToFit'])); - $alignment->setIndent((int) ((string) $alignmentXml->alignment['indent']) > 0 ? (int) ((string) $alignmentXml->alignment['indent']) : 0); - $alignment->setReadOrder((int) ((string) $alignmentXml->alignment['readingOrder']) > 0 ? (int) ((string) $alignmentXml->alignment['readingOrder']) : 0); + $alignment->setWrapText(self::boolean((string) $alignmentXml['wrapText'])); + $alignment->setShrinkToFit(self::boolean((string) $alignmentXml['shrinkToFit'])); + $alignment->setIndent( + (int) ((string) $alignmentXml['indent']) > 0 ? (int) ((string) $alignmentXml['indent']) : 0 + ); + $alignment->setReadOrder( + (int) ((string) $alignmentXml['readingOrder']) > 0 ? (int) ((string) $alignmentXml['readingOrder']) : 0 + ); } private function readStyle(Style $docStyle, $style): void @@ -186,8 +200,8 @@ class Styles extends BaseParserClass // protection if (isset($style->protection)) { - $this->readProtectionLocked($docStyle, $style); - $this->readProtectionHidden($docStyle, $style); + self::readProtectionLocked($docStyle, $style); + self::readProtectionHidden($docStyle, $style); } // top-level style settings @@ -196,7 +210,7 @@ class Styles extends BaseParserClass } } - private function readProtectionLocked(Style $docStyle, $style): void + public static function readProtectionLocked(Style $docStyle, $style): void { if (isset($style->protection['locked'])) { if (self::boolean((string) $style->protection['locked'])) { @@ -207,7 +221,7 @@ class Styles extends BaseParserClass } } - private function readProtectionHidden(Style $docStyle, $style): void + public static function readProtectionHidden(Style $docStyle, $style): void { if (isset($style->protection['hidden'])) { if (self::boolean((string) $style->protection['hidden'])) { @@ -218,7 +232,7 @@ class Styles extends BaseParserClass } } - private static function readColor($color, $background = false) + public static function readColor($color, $background = false) { if (isset($color['rgb'])) { return (string) $color['rgb']; @@ -253,7 +267,8 @@ class Styles extends BaseParserClass } // Cell Styles if ($this->styleXml->cellStyles) { - foreach ($this->styleXml->cellStyles->cellStyle as $cellStyle) { + foreach ($this->styleXml->cellStyles->cellStyle as $cellStylex) { + $cellStyle = Xlsx::getAttributes($cellStylex); if ((int) ($cellStyle['builtinId']) == 0) { if (isset($this->cellStyles[(int) ($cellStyle['xfId'])])) { // Set default style diff --git a/src/PhpSpreadsheet/Reader/Xlsx/Theme.php b/src/PhpSpreadsheet/Reader/Xlsx/Theme.php index c105f3c1..1f2b863c 100644 --- a/src/PhpSpreadsheet/Reader/Xlsx/Theme.php +++ b/src/PhpSpreadsheet/Reader/Xlsx/Theme.php @@ -21,16 +21,16 @@ class Theme /** * Colour Map. * - * @var array of string + * @var string[] */ private $colourMap; /** * Create a new Theme. * - * @param mixed $themeName - * @param mixed $colourSchemeName - * @param mixed $colourMap + * @param string $themeName + * @param string $colourSchemeName + * @param string[] $colourMap */ public function __construct($themeName, $colourSchemeName, $colourMap) { @@ -63,9 +63,9 @@ class Theme /** * Get colour Map Value by Position. * - * @param mixed $index + * @param int $index * - * @return string + * @return null|string */ public function getColourByIndex($index) { diff --git a/src/PhpSpreadsheet/Reader/Xml.php b/src/PhpSpreadsheet/Reader/Xml.php index a1d3c9ad..7d9188a9 100644 --- a/src/PhpSpreadsheet/Reader/Xml.php +++ b/src/PhpSpreadsheet/Reader/Xml.php @@ -2,24 +2,22 @@ namespace PhpOffice\PhpSpreadsheet\Reader; +use DateTime; +use DateTimeZone; use PhpOffice\PhpSpreadsheet\Cell\AddressHelper; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\DefinedName; -use PhpOffice\PhpSpreadsheet\Document\Properties; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; use PhpOffice\PhpSpreadsheet\Reader\Xml\PageSettings; +use PhpOffice\PhpSpreadsheet\Reader\Xml\Properties; +use PhpOffice\PhpSpreadsheet\Reader\Xml\Style; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; -use PhpOffice\PhpSpreadsheet\Style\Alignment; -use PhpOffice\PhpSpreadsheet\Style\Border; -use PhpOffice\PhpSpreadsheet\Style\Borders; -use PhpOffice\PhpSpreadsheet\Style\Fill; -use PhpOffice\PhpSpreadsheet\Style\Font; use SimpleXMLElement; /** @@ -45,62 +43,18 @@ class Xml extends BaseReader private $fileContents = ''; - private static $mappings = [ - 'borderStyle' => [ - '1continuous' => Border::BORDER_THIN, - '1dash' => Border::BORDER_DASHED, - '1dashdot' => Border::BORDER_DASHDOT, - '1dashdotdot' => Border::BORDER_DASHDOTDOT, - '1dot' => Border::BORDER_DOTTED, - '1double' => Border::BORDER_DOUBLE, - '2continuous' => Border::BORDER_MEDIUM, - '2dash' => Border::BORDER_MEDIUMDASHED, - '2dashdot' => Border::BORDER_MEDIUMDASHDOT, - '2dashdotdot' => Border::BORDER_MEDIUMDASHDOTDOT, - '2dot' => Border::BORDER_DOTTED, - '2double' => Border::BORDER_DOUBLE, - '3continuous' => Border::BORDER_THICK, - '3dash' => Border::BORDER_MEDIUMDASHED, - '3dashdot' => Border::BORDER_MEDIUMDASHDOT, - '3dashdotdot' => Border::BORDER_MEDIUMDASHDOTDOT, - '3dot' => Border::BORDER_DOTTED, - '3double' => Border::BORDER_DOUBLE, - ], - 'fillType' => [ - 'solid' => Fill::FILL_SOLID, - 'gray75' => Fill::FILL_PATTERN_DARKGRAY, - 'gray50' => Fill::FILL_PATTERN_MEDIUMGRAY, - 'gray25' => Fill::FILL_PATTERN_LIGHTGRAY, - 'gray125' => Fill::FILL_PATTERN_GRAY125, - 'gray0625' => Fill::FILL_PATTERN_GRAY0625, - 'horzstripe' => Fill::FILL_PATTERN_DARKHORIZONTAL, // horizontal stripe - 'vertstripe' => Fill::FILL_PATTERN_DARKVERTICAL, // vertical stripe - 'reversediagstripe' => Fill::FILL_PATTERN_DARKUP, // reverse diagonal stripe - 'diagstripe' => Fill::FILL_PATTERN_DARKDOWN, // diagonal stripe - 'diagcross' => Fill::FILL_PATTERN_DARKGRID, // diagoanl crosshatch - 'thickdiagcross' => Fill::FILL_PATTERN_DARKTRELLIS, // thick diagonal crosshatch - 'thinhorzstripe' => Fill::FILL_PATTERN_LIGHTHORIZONTAL, - 'thinvertstripe' => Fill::FILL_PATTERN_LIGHTVERTICAL, - 'thinreversediagstripe' => Fill::FILL_PATTERN_LIGHTUP, - 'thindiagstripe' => Fill::FILL_PATTERN_LIGHTDOWN, - 'thinhorzcross' => Fill::FILL_PATTERN_LIGHTGRID, // thin horizontal crosshatch - 'thindiagcross' => Fill::FILL_PATTERN_LIGHTTRELLIS, // thin diagonal crosshatch - ], - ]; - public static function xmlMappings(): array { - return self::$mappings; + return array_merge( + Style\Fill::FILL_MAPPINGS, + Style\Border::BORDER_MAPPINGS + ); } /** * Can the current IReader read the file? - * - * @param string $filename - * - * @return bool */ - public function canRead($filename) + public function canRead(string $filename): bool { // Office xmlns:o="urn:schemas-microsoft-com:office:office" // Excel xmlns:x="urn:schemas-microsoft-com:office:excel" @@ -114,7 +68,7 @@ class Xml extends BaseReader $signature = [ '', + 'xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet', ]; // Open file @@ -172,26 +126,29 @@ class Xml extends BaseReader /** * Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object. * - * @param string $pFilename + * @param string $filename * * @return array */ - public function listWorksheetNames($pFilename) + public function listWorksheetNames($filename) { - File::assertFile($pFilename); - if (!$this->canRead($pFilename)) { - throw new Exception($pFilename . ' is an Invalid Spreadsheet file.'); + File::assertFile($filename); + if (!$this->canRead($filename)) { + throw new Exception($filename . ' is an Invalid Spreadsheet file.'); } $worksheetNames = []; - $xml = $this->trySimpleXMLLoadString($pFilename); + $xml = $this->trySimpleXMLLoadString($filename); + if ($xml === false) { + throw new Exception("Problem reading {$filename}"); + } $namespaces = $xml->getNamespaces(true); $xml_ss = $xml->children($namespaces['ss']); foreach ($xml_ss->Worksheet as $worksheet) { - $worksheet_ss = $worksheet->attributes($namespaces['ss']); + $worksheet_ss = self::getAttributes($worksheet, $namespaces['ss']); $worksheetNames[] = (string) $worksheet_ss['Name']; } @@ -201,27 +158,30 @@ class Xml extends BaseReader /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * - * @param string $pFilename + * @param string $filename * * @return array */ - public function listWorksheetInfo($pFilename) + public function listWorksheetInfo($filename) { - File::assertFile($pFilename); - if (!$this->canRead($pFilename)) { - throw new Exception($pFilename . ' is an Invalid Spreadsheet file.'); + File::assertFile($filename); + if (!$this->canRead($filename)) { + throw new Exception($filename . ' is an Invalid Spreadsheet file.'); } $worksheetInfo = []; - $xml = $this->trySimpleXMLLoadString($pFilename); + $xml = $this->trySimpleXMLLoadString($filename); + if ($xml === false) { + throw new Exception("Problem reading {$filename}"); + } $namespaces = $xml->getNamespaces(true); $worksheetID = 1; $xml_ss = $xml->children($namespaces['ss']); foreach ($xml_ss->Worksheet as $worksheet) { - $worksheet_ss = $worksheet->attributes($namespaces['ss']); + $worksheet_ss = self::getAttributes($worksheet, $namespaces['ss']); $tmpInfo = []; $tmpInfo['worksheetName'] = ''; @@ -272,12 +232,12 @@ class Xml extends BaseReader /** * Loads Spreadsheet from file. * - * @param string $filename - * * @return Spreadsheet */ - public function load($filename) + public function load(string $filename, int $flags = 0) { + $this->processFlags($flags); + // Create new Spreadsheet $spreadsheet = new Spreadsheet(); $spreadsheet->removeSheetByIndex(0); @@ -286,145 +246,41 @@ class Xml extends BaseReader return $this->loadIntoExisting($filename, $spreadsheet); } - private static function identifyFixedStyleValue($styleList, &$styleAttributeValue) - { - $returnValue = false; - $styleAttributeValue = strtolower($styleAttributeValue); - foreach ($styleList as $style) { - if ($styleAttributeValue == strtolower($style)) { - $styleAttributeValue = $style; - $returnValue = true; - - break; - } - } - - return $returnValue; - } - - protected static function hex2str($hex) - { - return mb_chr((int) hexdec($hex[1]), 'UTF-8'); - } - /** * Loads from file into Spreadsheet instance. * - * @param string $pFilename + * @param string $filename * * @return Spreadsheet */ - public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) + public function loadIntoExisting($filename, Spreadsheet $spreadsheet) { - File::assertFile($pFilename); - if (!$this->canRead($pFilename)) { - throw new Exception($pFilename . ' is an Invalid Spreadsheet file.'); + File::assertFile($filename); + if (!$this->canRead($filename)) { + throw new Exception($filename . ' is an Invalid Spreadsheet file.'); } - $xml = $this->trySimpleXMLLoadString($pFilename); + $xml = $this->trySimpleXMLLoadString($filename); + if ($xml === false) { + throw new Exception("Problem reading {$filename}"); + } $namespaces = $xml->getNamespaces(true); - $docProps = $spreadsheet->getProperties(); - if (isset($xml->DocumentProperties[0])) { - foreach ($xml->DocumentProperties[0] as $propertyName => $propertyValue) { - $stringValue = (string) $propertyValue; - switch ($propertyName) { - case 'Title': - $docProps->setTitle($stringValue); + (new Properties($spreadsheet))->readProperties($xml, $namespaces); - break; - case 'Subject': - $docProps->setSubject($stringValue); - - break; - case 'Author': - $docProps->setCreator($stringValue); - - break; - case 'Created': - $creationDate = strtotime($stringValue); - $docProps->setCreated($creationDate); - - break; - case 'LastAuthor': - $docProps->setLastModifiedBy($stringValue); - - break; - case 'LastSaved': - $lastSaveDate = strtotime($stringValue); - $docProps->setModified($lastSaveDate); - - break; - case 'Company': - $docProps->setCompany($stringValue); - - break; - case 'Category': - $docProps->setCategory($stringValue); - - break; - case 'Manager': - $docProps->setManager($stringValue); - - break; - case 'Keywords': - $docProps->setKeywords($stringValue); - - break; - case 'Description': - $docProps->setDescription($stringValue); - - break; - } - } - } - if (isset($xml->CustomDocumentProperties)) { - foreach ($xml->CustomDocumentProperties[0] as $propertyName => $propertyValue) { - $propertyAttributes = $propertyValue->attributes($namespaces['dt']); - $propertyName = preg_replace_callback('/_x([0-9a-f]{4})_/i', ['self', 'hex2str'], $propertyName); - $propertyType = Properties::PROPERTY_TYPE_UNKNOWN; - switch ((string) $propertyAttributes) { - case 'string': - $propertyType = Properties::PROPERTY_TYPE_STRING; - $propertyValue = trim($propertyValue); - - break; - case 'boolean': - $propertyType = Properties::PROPERTY_TYPE_BOOLEAN; - $propertyValue = (bool) $propertyValue; - - break; - case 'integer': - $propertyType = Properties::PROPERTY_TYPE_INTEGER; - $propertyValue = (int) $propertyValue; - - break; - case 'float': - $propertyType = Properties::PROPERTY_TYPE_FLOAT; - $propertyValue = (float) $propertyValue; - - break; - case 'dateTime.tz': - $propertyType = Properties::PROPERTY_TYPE_DATE; - $propertyValue = strtotime(trim($propertyValue)); - - break; - } - $docProps->setCustomProperty($propertyName, $propertyValue, $propertyType); - } - } - - $this->parseStyles($xml, $namespaces); + $this->styles = (new Style())->parseStyles($xml, $namespaces); $worksheetID = 0; $xml_ss = $xml->children($namespaces['ss']); - foreach ($xml_ss->Worksheet as $worksheet) { - $worksheet_ss = $worksheet->attributes($namespaces['ss']); + /** @var null|SimpleXMLElement $worksheetx */ + foreach ($xml_ss->Worksheet as $worksheetx) { + $worksheet = $worksheetx ?? new SimpleXMLElement(''); + $worksheet_ss = self::getAttributes($worksheet, $namespaces['ss']); if ( - (isset($this->loadSheetsOnly)) && (isset($worksheet_ss['Name'])) && + isset($this->loadSheetsOnly, $worksheet_ss['Name']) && (!in_array($worksheet_ss['Name'], $this->loadSheetsOnly)) ) { continue; @@ -433,6 +289,7 @@ class Xml extends BaseReader // Create new Worksheet $spreadsheet->createSheet(); $spreadsheet->setActiveSheetIndex($worksheetID); + $worksheetName = ''; if (isset($worksheet_ss['Name'])) { $worksheetName = (string) $worksheet_ss['Name']; // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in @@ -444,7 +301,7 @@ class Xml extends BaseReader // locally scoped defined names if (isset($worksheet->Names[0])) { foreach ($worksheet->Names[0] as $definedName) { - $definedName_ss = $definedName->attributes($namespaces['ss']); + $definedName_ss = self::getAttributes($definedName, $namespaces['ss']); $name = (string) $definedName_ss['Name']; $definedValue = (string) $definedName_ss['RefersTo']; $convertedValue = AddressHelper::convertFormulaToA1($definedValue); @@ -458,7 +315,7 @@ class Xml extends BaseReader $columnID = 'A'; if (isset($worksheet->Table->Column)) { foreach ($worksheet->Table->Column as $columnData) { - $columnData_ss = $columnData->attributes($namespaces['ss']); + $columnData_ss = self::getAttributes($columnData, $namespaces['ss']); if (isset($columnData_ss['Index'])) { $columnID = Coordinate::stringFromColumnIndex((int) $columnData_ss['Index']); } @@ -475,14 +332,14 @@ class Xml extends BaseReader $additionalMergedCells = 0; foreach ($worksheet->Table->Row as $rowData) { $rowHasData = false; - $row_ss = $rowData->attributes($namespaces['ss']); + $row_ss = self::getAttributes($rowData, $namespaces['ss']); if (isset($row_ss['Index'])) { $rowID = (int) $row_ss['Index']; } $columnID = 'A'; foreach ($rowData->Cell as $cell) { - $cell_ss = $cell->attributes($namespaces['ss']); + $cell_ss = self::getAttributes($cell, $namespaces['ss']); if (isset($cell_ss['Index'])) { $columnID = Coordinate::stringFromColumnIndex((int) $cell_ss['Index']); } @@ -504,7 +361,7 @@ class Xml extends BaseReader $columnTo = $columnID; if (isset($cell_ss['MergeAcross'])) { $additionalMergedCells += (int) $cell_ss['MergeAcross']; - $columnTo = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($columnID) + $cell_ss['MergeAcross']); + $columnTo = Coordinate::stringFromColumnIndex((int) (Coordinate::columnIndexFromString($columnID) + $cell_ss['MergeAcross'])); } $rowTo = $rowID; if (isset($cell_ss['MergeDown'])) { @@ -524,7 +381,7 @@ class Xml extends BaseReader $cellData = $cell->Data; $cellValue = (string) $cellData; $type = DataType::TYPE_NULL; - $cellData_ss = $cellData->attributes($namespaces['ss']); + $cellData_ss = self::getAttributes($cellData, $namespaces['ss']); if (isset($cellData_ss['Type'])) { $cellDataType = $cellData_ss['Type']; switch ($cellDataType) { @@ -556,7 +413,8 @@ class Xml extends BaseReader break; case 'DateTime': $type = DataType::TYPE_NUMERIC; - $cellValue = Date::PHPToExcel(strtotime($cellValue . ' UTC')); + $dateTime = new DateTime($cellValue, new DateTimeZone('UTC')); + $cellValue = Date::PHPToExcel($dateTime); break; case 'Error': @@ -581,14 +439,7 @@ class Xml extends BaseReader } if (isset($cell->Comment)) { - $commentAttributes = $cell->Comment->attributes($namespaces['ss']); - $author = 'unknown'; - if (isset($commentAttributes->Author)) { - $author = (string) $commentAttributes->Author; - } - $node = $cell->Comment->Data->asXML(); - $annotation = strip_tags($node); - $spreadsheet->getActiveSheet()->getComment($columnID . $rowID)->setAuthor($author)->setText($this->parseRichText($annotation)); + $this->parseCellComment($cell->Comment, $namespaces, $spreadsheet, $columnID, $rowID); } if (isset($cell_ss['StyleID'])) { @@ -597,7 +448,8 @@ class Xml extends BaseReader //if (!$spreadsheet->getActiveSheet()->cellExists($columnID . $rowID)) { // $spreadsheet->getActiveSheet()->getCell($columnID . $rowID)->setValue(null); //} - $spreadsheet->getActiveSheet()->getStyle($cellRange)->applyFromArray($this->styles[$style]); + $spreadsheet->getActiveSheet()->getStyle($cellRange) + ->applyFromArray($this->styles[$style]); } } ++$columnID; @@ -610,7 +462,7 @@ class Xml extends BaseReader if ($rowHasData) { if (isset($row_ss['Height'])) { $rowHeight = $row_ss['Height']; - $spreadsheet->getActiveSheet()->getRowDimension($rowID)->setRowHeight($rowHeight); + $spreadsheet->getActiveSheet()->getRowDimension($rowID)->setRowHeight((float) $rowHeight); } } @@ -631,7 +483,7 @@ class Xml extends BaseReader $activeWorksheet = $spreadsheet->setActiveSheetIndex(0); if (isset($xml->Names[0])) { foreach ($xml->Names[0] as $definedName) { - $definedName_ss = $definedName->attributes($namespaces['ss']); + $definedName_ss = self::getAttributes($definedName, $namespaces['ss']); $name = (string) $definedName_ss['Name']; $definedValue = (string) $definedName_ss['RefersTo']; $convertedValue = AddressHelper::convertFormulaToA1($definedValue); @@ -646,254 +498,39 @@ class Xml extends BaseReader return $spreadsheet; } - protected function parseRichText($is) + protected function parseCellComment( + SimpleXMLElement $comment, + array $namespaces, + Spreadsheet $spreadsheet, + string $columnID, + int $rowID + ): void { + $commentAttributes = $comment->attributes($namespaces['ss']); + $author = 'unknown'; + if (isset($commentAttributes->Author)) { + $author = (string) $commentAttributes->Author; + } + + $node = $comment->Data->asXML(); + $annotation = strip_tags((string) $node); + $spreadsheet->getActiveSheet()->getComment($columnID . $rowID) + ->setAuthor($author) + ->setText($this->parseRichText($annotation)); + } + + protected function parseRichText(string $annotation): RichText { $value = new RichText(); - $value->createText($is); + $value->createText($annotation); return $value; } - private function parseStyles(SimpleXMLElement $xml, array $namespaces): void + private static function getAttributes(?SimpleXMLElement $simple, string $node): SimpleXMLElement { - if (!isset($xml->Styles)) { - return; - } - - foreach ($xml->Styles[0] as $style) { - $style_ss = $style->attributes($namespaces['ss']); - $styleID = (string) $style_ss['ID']; - $this->styles[$styleID] = (isset($this->styles['Default'])) ? $this->styles['Default'] : []; - foreach ($style as $styleType => $styleData) { - $styleAttributes = $styleData->attributes($namespaces['ss']); - switch ($styleType) { - case 'Alignment': - $this->parseStyleAlignment($styleID, $styleAttributes); - - break; - case 'Borders': - $this->parseStyleBorders($styleID, $styleData, $namespaces); - - break; - case 'Font': - $this->parseStyleFont($styleID, $styleAttributes); - - break; - case 'Interior': - $this->parseStyleInterior($styleID, $styleAttributes); - - break; - case 'NumberFormat': - $this->parseStyleNumberFormat($styleID, $styleAttributes); - - break; - } - } - } - } - - /** - * @param string $styleID - */ - private function parseStyleAlignment($styleID, SimpleXMLElement $styleAttributes): void - { - $verticalAlignmentStyles = [ - Alignment::VERTICAL_BOTTOM, - Alignment::VERTICAL_TOP, - Alignment::VERTICAL_CENTER, - Alignment::VERTICAL_JUSTIFY, - ]; - $horizontalAlignmentStyles = [ - Alignment::HORIZONTAL_GENERAL, - Alignment::HORIZONTAL_LEFT, - Alignment::HORIZONTAL_RIGHT, - Alignment::HORIZONTAL_CENTER, - Alignment::HORIZONTAL_CENTER_CONTINUOUS, - Alignment::HORIZONTAL_JUSTIFY, - ]; - - foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { - $styleAttributeValue = (string) $styleAttributeValue; - switch ($styleAttributeKey) { - case 'Vertical': - if (self::identifyFixedStyleValue($verticalAlignmentStyles, $styleAttributeValue)) { - $this->styles[$styleID]['alignment']['vertical'] = $styleAttributeValue; - } - - break; - case 'Horizontal': - if (self::identifyFixedStyleValue($horizontalAlignmentStyles, $styleAttributeValue)) { - $this->styles[$styleID]['alignment']['horizontal'] = $styleAttributeValue; - } - - break; - case 'WrapText': - $this->styles[$styleID]['alignment']['wrapText'] = true; - - break; - case 'Rotate': - $this->styles[$styleID]['alignment']['textRotation'] = $styleAttributeValue; - - break; - } - } - } - - private static $borderPositions = ['top', 'left', 'bottom', 'right']; - - /** - * @param $styleID - */ - private function parseStyleBorders($styleID, SimpleXMLElement $styleData, array $namespaces): void - { - $diagonalDirection = ''; - $borderPosition = ''; - foreach ($styleData->Border as $borderStyle) { - $borderAttributes = $borderStyle->attributes($namespaces['ss']); - $thisBorder = []; - $style = (string) $borderAttributes->Weight; - $style .= strtolower((string) $borderAttributes->LineStyle); - $thisBorder['borderStyle'] = self::$mappings['borderStyle'][$style] ?? Border::BORDER_NONE; - foreach ($borderAttributes as $borderStyleKey => $borderStyleValue) { - switch ($borderStyleKey) { - case 'Position': - $borderStyleValue = strtolower((string) $borderStyleValue); - if (in_array($borderStyleValue, self::$borderPositions)) { - $borderPosition = $borderStyleValue; - } elseif ($borderStyleValue == 'diagonalleft') { - $diagonalDirection = $diagonalDirection ? Borders::DIAGONAL_BOTH : Borders::DIAGONAL_DOWN; - } elseif ($borderStyleValue == 'diagonalright') { - $diagonalDirection = $diagonalDirection ? Borders::DIAGONAL_BOTH : Borders::DIAGONAL_UP; - } - - break; - case 'Color': - $borderColour = substr($borderStyleValue, 1); - $thisBorder['color']['rgb'] = $borderColour; - - break; - } - } - if ($borderPosition) { - $this->styles[$styleID]['borders'][$borderPosition] = $thisBorder; - } elseif ($diagonalDirection) { - $this->styles[$styleID]['borders']['diagonalDirection'] = $diagonalDirection; - $this->styles[$styleID]['borders']['diagonal'] = $thisBorder; - } - } - } - - private static $underlineStyles = [ - Font::UNDERLINE_NONE, - Font::UNDERLINE_DOUBLE, - Font::UNDERLINE_DOUBLEACCOUNTING, - Font::UNDERLINE_SINGLE, - Font::UNDERLINE_SINGLEACCOUNTING, - ]; - - private function parseStyleFontUnderline(string $styleID, string $styleAttributeValue): void - { - if (self::identifyFixedStyleValue(self::$underlineStyles, $styleAttributeValue)) { - $this->styles[$styleID]['font']['underline'] = $styleAttributeValue; - } - } - - private function parseStyleFontVerticalAlign(string $styleID, string $styleAttributeValue): void - { - if ($styleAttributeValue == 'Superscript') { - $this->styles[$styleID]['font']['superscript'] = true; - } - if ($styleAttributeValue == 'Subscript') { - $this->styles[$styleID]['font']['subscript'] = true; - } - } - - /** - * @param $styleID - */ - private function parseStyleFont(string $styleID, SimpleXMLElement $styleAttributes): void - { - foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { - $styleAttributeValue = (string) $styleAttributeValue; - switch ($styleAttributeKey) { - case 'FontName': - $this->styles[$styleID]['font']['name'] = $styleAttributeValue; - - break; - case 'Size': - $this->styles[$styleID]['font']['size'] = $styleAttributeValue; - - break; - case 'Color': - $this->styles[$styleID]['font']['color']['rgb'] = substr($styleAttributeValue, 1); - - break; - case 'Bold': - $this->styles[$styleID]['font']['bold'] = true; - - break; - case 'Italic': - $this->styles[$styleID]['font']['italic'] = true; - - break; - case 'Underline': - $this->parseStyleFontUnderline($styleID, $styleAttributeValue); - - break; - case 'VerticalAlign': - $this->parseStyleFontVerticalAlign($styleID, $styleAttributeValue); - - break; - } - } - } - - /** - * @param $styleID - */ - private function parseStyleInterior($styleID, SimpleXMLElement $styleAttributes): void - { - foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { - switch ($styleAttributeKey) { - case 'Color': - $this->styles[$styleID]['fill']['endColor']['rgb'] = substr($styleAttributeValue, 1); - $this->styles[$styleID]['fill']['startColor']['rgb'] = substr($styleAttributeValue, 1); - - break; - case 'PatternColor': - $this->styles[$styleID]['fill']['startColor']['rgb'] = substr($styleAttributeValue, 1); - - break; - case 'Pattern': - $lcStyleAttributeValue = strtolower((string) $styleAttributeValue); - $this->styles[$styleID]['fill']['fillType'] = self::$mappings['fillType'][$lcStyleAttributeValue] ?? Fill::FILL_NONE; - - break; - } - } - } - - /** - * @param $styleID - */ - private function parseStyleNumberFormat($styleID, SimpleXMLElement $styleAttributes): void - { - $fromFormats = ['\-', '\ ']; - $toFormats = ['-', ' ']; - - foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { - $styleAttributeValue = str_replace($fromFormats, $toFormats, $styleAttributeValue); - switch ($styleAttributeValue) { - case 'Short Date': - $styleAttributeValue = 'dd/mm/yyyy'; - - break; - } - - if ($styleAttributeValue > '') { - $this->styles[$styleID]['numberFormat']['formatCode'] = $styleAttributeValue; - } - } + return ($simple === null) + ? new SimpleXMLElement('') + : ($simple->attributes($node) ?? new SimpleXMLElement('')); } } diff --git a/src/PhpSpreadsheet/Reader/Xml/PageSettings.php b/src/PhpSpreadsheet/Reader/Xml/PageSettings.php index e56ac331..c0caca3b 100644 --- a/src/PhpSpreadsheet/Reader/Xml/PageSettings.php +++ b/src/PhpSpreadsheet/Reader/Xml/PageSettings.php @@ -62,6 +62,10 @@ class PageSettings foreach ($xmlX->WorksheetOptions->PageSetup as $pageSetupData) { foreach ($pageSetupData as $pageSetupKey => $pageSetupValue) { $pageSetupAttributes = $pageSetupValue->attributes($namespaces['x']); + if (!$pageSetupAttributes) { + continue; + } + switch ($pageSetupKey) { case 'Layout': $this->setLayout($printDefaults, $pageSetupAttributes); @@ -115,7 +119,7 @@ class PageSettings private function setLayout(stdClass $printDefaults, SimpleXMLElement $pageSetupAttributes): void { - $printDefaults->orientation = (string) strtolower($pageSetupAttributes->Orientation) ?: PageSetup::ORIENTATION_PORTRAIT; + $printDefaults->orientation = (string) strtolower($pageSetupAttributes->Orientation ?? '') ?: PageSetup::ORIENTATION_PORTRAIT; $printDefaults->horizontalCentered = (bool) $pageSetupAttributes->CenterHorizontal ?: false; $printDefaults->verticalCentered = (bool) $pageSetupAttributes->CenterVertical ?: false; } diff --git a/src/PhpSpreadsheet/Reader/Xml/Properties.php b/src/PhpSpreadsheet/Reader/Xml/Properties.php new file mode 100644 index 00000000..1c3e421a --- /dev/null +++ b/src/PhpSpreadsheet/Reader/Xml/Properties.php @@ -0,0 +1,157 @@ +spreadsheet = $spreadsheet; + } + + public function readProperties(SimpleXMLElement $xml, array $namespaces): void + { + $this->readStandardProperties($xml); + $this->readCustomProperties($xml, $namespaces); + } + + protected function readStandardProperties(SimpleXMLElement $xml): void + { + if (isset($xml->DocumentProperties[0])) { + $docProps = $this->spreadsheet->getProperties(); + + foreach ($xml->DocumentProperties[0] as $propertyName => $propertyValue) { + $propertyValue = (string) $propertyValue; + + $this->processStandardProperty($docProps, $propertyName, $propertyValue); + } + } + } + + protected function readCustomProperties(SimpleXMLElement $xml, array $namespaces): void + { + if (isset($xml->CustomDocumentProperties)) { + $docProps = $this->spreadsheet->getProperties(); + + foreach ($xml->CustomDocumentProperties[0] as $propertyName => $propertyValue) { + $propertyAttributes = self::getAttributes($propertyValue, $namespaces['dt']); + $propertyName = preg_replace_callback('/_x([0-9a-f]{4})_/i', [$this, 'hex2str'], $propertyName); + + $this->processCustomProperty($docProps, $propertyName, $propertyValue, $propertyAttributes); + } + } + } + + protected function processStandardProperty( + DocumentProperties $docProps, + string $propertyName, + string $stringValue + ): void { + switch ($propertyName) { + case 'Title': + $docProps->setTitle($stringValue); + + break; + case 'Subject': + $docProps->setSubject($stringValue); + + break; + case 'Author': + $docProps->setCreator($stringValue); + + break; + case 'Created': + $docProps->setCreated($stringValue); + + break; + case 'LastAuthor': + $docProps->setLastModifiedBy($stringValue); + + break; + case 'LastSaved': + $docProps->setModified($stringValue); + + break; + case 'Company': + $docProps->setCompany($stringValue); + + break; + case 'Category': + $docProps->setCategory($stringValue); + + break; + case 'Manager': + $docProps->setManager($stringValue); + + break; + case 'Keywords': + $docProps->setKeywords($stringValue); + + break; + case 'Description': + $docProps->setDescription($stringValue); + + break; + } + } + + protected function processCustomProperty( + DocumentProperties $docProps, + string $propertyName, + ?SimpleXMLElement $propertyValue, + SimpleXMLElement $propertyAttributes + ): void { + $propertyType = DocumentProperties::PROPERTY_TYPE_UNKNOWN; + + switch ((string) $propertyAttributes) { + case 'string': + $propertyType = DocumentProperties::PROPERTY_TYPE_STRING; + $propertyValue = trim((string) $propertyValue); + + break; + case 'boolean': + $propertyType = DocumentProperties::PROPERTY_TYPE_BOOLEAN; + $propertyValue = (bool) $propertyValue; + + break; + case 'integer': + $propertyType = DocumentProperties::PROPERTY_TYPE_INTEGER; + $propertyValue = (int) $propertyValue; + + break; + case 'float': + $propertyType = DocumentProperties::PROPERTY_TYPE_FLOAT; + $propertyValue = (float) $propertyValue; + + break; + case 'dateTime.tz': + $propertyType = DocumentProperties::PROPERTY_TYPE_DATE; + $propertyValue = trim((string) $propertyValue); + + break; + } + + $docProps->setCustomProperty($propertyName, $propertyValue, $propertyType); + } + + protected function hex2str(array $hex): string + { + return mb_chr((int) hexdec($hex[1]), 'UTF-8'); + } + + private static function getAttributes(?SimpleXMLElement $simple, string $node): SimpleXMLElement + { + return ($simple === null) + ? new SimpleXMLElement('') + : ($simple->attributes($node) ?? new SimpleXMLElement('')); + } +} diff --git a/src/PhpSpreadsheet/Reader/Xml/Style.php b/src/PhpSpreadsheet/Reader/Xml/Style.php new file mode 100644 index 00000000..0e3cd16d --- /dev/null +++ b/src/PhpSpreadsheet/Reader/Xml/Style.php @@ -0,0 +1,83 @@ +Styles)) { + return []; + } + + $alignmentStyleParser = new Style\Alignment(); + $borderStyleParser = new Style\Border(); + $fontStyleParser = new Style\Font(); + $fillStyleParser = new Style\Fill(); + $numberFormatStyleParser = new Style\NumberFormat(); + + foreach ($xml->Styles[0] as $style) { + $style_ss = self::getAttributes($style, $namespaces['ss']); + $styleID = (string) $style_ss['ID']; + $this->styles[$styleID] = $this->styles['Default'] ?? []; + + $alignment = $border = $font = $fill = $numberFormat = []; + + foreach ($style as $styleType => $styleDatax) { + $styleData = $styleDatax ?? new SimpleXMLElement(''); + $styleAttributes = $styleData->attributes($namespaces['ss']); + + switch ($styleType) { + case 'Alignment': + if ($styleAttributes) { + $alignment = $alignmentStyleParser->parseStyle($styleAttributes); + } + + break; + case 'Borders': + $border = $borderStyleParser->parseStyle($styleData, $namespaces); + + break; + case 'Font': + if ($styleAttributes) { + $font = $fontStyleParser->parseStyle($styleAttributes); + } + + break; + case 'Interior': + if ($styleAttributes) { + $fill = $fillStyleParser->parseStyle($styleAttributes); + } + + break; + case 'NumberFormat': + if ($styleAttributes) { + $numberFormat = $numberFormatStyleParser->parseStyle($styleAttributes); + } + + break; + } + } + + $this->styles[$styleID] = array_merge($alignment, $border, $font, $fill, $numberFormat); + } + + return $this->styles; + } + + protected static function getAttributes(?SimpleXMLElement $simple, string $node): SimpleXMLElement + { + return ($simple === null) + ? new SimpleXMLElement('') + : ($simple->attributes($node) ?? new SimpleXMLElement('')); + } +} diff --git a/src/PhpSpreadsheet/Reader/Xml/Style/Alignment.php b/src/PhpSpreadsheet/Reader/Xml/Style/Alignment.php new file mode 100644 index 00000000..d1363548 --- /dev/null +++ b/src/PhpSpreadsheet/Reader/Xml/Style/Alignment.php @@ -0,0 +1,58 @@ + $styleAttributeValue) { + $styleAttributeValue = (string) $styleAttributeValue; + switch ($styleAttributeKey) { + case 'Vertical': + if (self::identifyFixedStyleValue(self::VERTICAL_ALIGNMENT_STYLES, $styleAttributeValue)) { + $style['alignment']['vertical'] = $styleAttributeValue; + } + + break; + case 'Horizontal': + if (self::identifyFixedStyleValue(self::HORIZONTAL_ALIGNMENT_STYLES, $styleAttributeValue)) { + $style['alignment']['horizontal'] = $styleAttributeValue; + } + + break; + case 'WrapText': + $style['alignment']['wrapText'] = true; + + break; + case 'Rotate': + $style['alignment']['textRotation'] = $styleAttributeValue; + + break; + } + } + + return $style; + } +} diff --git a/src/PhpSpreadsheet/Reader/Xml/Style/Border.php b/src/PhpSpreadsheet/Reader/Xml/Style/Border.php new file mode 100644 index 00000000..8aefd9c9 --- /dev/null +++ b/src/PhpSpreadsheet/Reader/Xml/Style/Border.php @@ -0,0 +1,98 @@ + [ + '1continuous' => BorderStyle::BORDER_THIN, + '1dash' => BorderStyle::BORDER_DASHED, + '1dashdot' => BorderStyle::BORDER_DASHDOT, + '1dashdotdot' => BorderStyle::BORDER_DASHDOTDOT, + '1dot' => BorderStyle::BORDER_DOTTED, + '1double' => BorderStyle::BORDER_DOUBLE, + '2continuous' => BorderStyle::BORDER_MEDIUM, + '2dash' => BorderStyle::BORDER_MEDIUMDASHED, + '2dashdot' => BorderStyle::BORDER_MEDIUMDASHDOT, + '2dashdotdot' => BorderStyle::BORDER_MEDIUMDASHDOTDOT, + '2dot' => BorderStyle::BORDER_DOTTED, + '2double' => BorderStyle::BORDER_DOUBLE, + '3continuous' => BorderStyle::BORDER_THICK, + '3dash' => BorderStyle::BORDER_MEDIUMDASHED, + '3dashdot' => BorderStyle::BORDER_MEDIUMDASHDOT, + '3dashdotdot' => BorderStyle::BORDER_MEDIUMDASHDOTDOT, + '3dot' => BorderStyle::BORDER_DOTTED, + '3double' => BorderStyle::BORDER_DOUBLE, + ], + ]; + + public function parseStyle(SimpleXMLElement $styleData, array $namespaces): array + { + $style = []; + + $diagonalDirection = ''; + $borderPosition = ''; + foreach ($styleData->Border as $borderStyle) { + $borderAttributes = self::getAttributes($borderStyle, $namespaces['ss']); + $thisBorder = []; + $styleType = (string) $borderAttributes->Weight; + $styleType .= strtolower((string) $borderAttributes->LineStyle); + $thisBorder['borderStyle'] = self::BORDER_MAPPINGS['borderStyle'][$styleType] ?? BorderStyle::BORDER_NONE; + + foreach ($borderAttributes as $borderStyleKey => $borderStyleValuex) { + $borderStyleValue = (string) $borderStyleValuex; + switch ($borderStyleKey) { + case 'Position': + [$borderPosition, $diagonalDirection] = + $this->parsePosition($borderStyleValue, $diagonalDirection); + + break; + case 'Color': + $borderColour = substr($borderStyleValue, 1); + $thisBorder['color']['rgb'] = $borderColour; + + break; + } + } + + if ($borderPosition) { + $style['borders'][$borderPosition] = $thisBorder; + } elseif ($diagonalDirection) { + $style['borders']['diagonalDirection'] = $diagonalDirection; + $style['borders']['diagonal'] = $thisBorder; + } + } + + return $style; + } + + protected function parsePosition(string $borderStyleValue, string $diagonalDirection): array + { + $borderStyleValue = strtolower($borderStyleValue); + + if (in_array($borderStyleValue, self::BORDER_POSITIONS)) { + $borderPosition = $borderStyleValue; + } elseif ($borderStyleValue === 'diagonalleft') { + $diagonalDirection = $diagonalDirection ? Borders::DIAGONAL_BOTH : Borders::DIAGONAL_DOWN; + } elseif ($borderStyleValue === 'diagonalright') { + $diagonalDirection = $diagonalDirection ? Borders::DIAGONAL_BOTH : Borders::DIAGONAL_UP; + } + + return [$borderPosition ?? null, $diagonalDirection]; + } +} diff --git a/src/PhpSpreadsheet/Reader/Xml/Style/Fill.php b/src/PhpSpreadsheet/Reader/Xml/Style/Fill.php new file mode 100644 index 00000000..9a612152 --- /dev/null +++ b/src/PhpSpreadsheet/Reader/Xml/Style/Fill.php @@ -0,0 +1,63 @@ + [ + 'solid' => FillStyles::FILL_SOLID, + 'gray75' => FillStyles::FILL_PATTERN_DARKGRAY, + 'gray50' => FillStyles::FILL_PATTERN_MEDIUMGRAY, + 'gray25' => FillStyles::FILL_PATTERN_LIGHTGRAY, + 'gray125' => FillStyles::FILL_PATTERN_GRAY125, + 'gray0625' => FillStyles::FILL_PATTERN_GRAY0625, + 'horzstripe' => FillStyles::FILL_PATTERN_DARKHORIZONTAL, // horizontal stripe + 'vertstripe' => FillStyles::FILL_PATTERN_DARKVERTICAL, // vertical stripe + 'reversediagstripe' => FillStyles::FILL_PATTERN_DARKUP, // reverse diagonal stripe + 'diagstripe' => FillStyles::FILL_PATTERN_DARKDOWN, // diagonal stripe + 'diagcross' => FillStyles::FILL_PATTERN_DARKGRID, // diagoanl crosshatch + 'thickdiagcross' => FillStyles::FILL_PATTERN_DARKTRELLIS, // thick diagonal crosshatch + 'thinhorzstripe' => FillStyles::FILL_PATTERN_LIGHTHORIZONTAL, + 'thinvertstripe' => FillStyles::FILL_PATTERN_LIGHTVERTICAL, + 'thinreversediagstripe' => FillStyles::FILL_PATTERN_LIGHTUP, + 'thindiagstripe' => FillStyles::FILL_PATTERN_LIGHTDOWN, + 'thinhorzcross' => FillStyles::FILL_PATTERN_LIGHTGRID, // thin horizontal crosshatch + 'thindiagcross' => FillStyles::FILL_PATTERN_LIGHTTRELLIS, // thin diagonal crosshatch + ], + ]; + + public function parseStyle(SimpleXMLElement $styleAttributes): array + { + $style = []; + + foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValuex) { + $styleAttributeValue = (string) $styleAttributeValuex; + switch ($styleAttributeKey) { + case 'Color': + $style['fill']['endColor']['rgb'] = substr($styleAttributeValue, 1); + $style['fill']['startColor']['rgb'] = substr($styleAttributeValue, 1); + + break; + case 'PatternColor': + $style['fill']['startColor']['rgb'] = substr($styleAttributeValue, 1); + + break; + case 'Pattern': + $lcStyleAttributeValue = strtolower((string) $styleAttributeValue); + $style['fill']['fillType'] + = self::FILL_MAPPINGS['fillType'][$lcStyleAttributeValue] ?? FillStyles::FILL_NONE; + + break; + } + } + + return $style; + } +} diff --git a/src/PhpSpreadsheet/Reader/Xml/Style/Font.php b/src/PhpSpreadsheet/Reader/Xml/Style/Font.php new file mode 100644 index 00000000..16ab44d8 --- /dev/null +++ b/src/PhpSpreadsheet/Reader/Xml/Style/Font.php @@ -0,0 +1,79 @@ + $styleAttributeValue) { + $styleAttributeValue = (string) $styleAttributeValue; + switch ($styleAttributeKey) { + case 'FontName': + $style['font']['name'] = $styleAttributeValue; + + break; + case 'Size': + $style['font']['size'] = $styleAttributeValue; + + break; + case 'Color': + $style['font']['color']['rgb'] = substr($styleAttributeValue, 1); + + break; + case 'Bold': + $style['font']['bold'] = true; + + break; + case 'Italic': + $style['font']['italic'] = true; + + break; + case 'Underline': + $style = $this->parseUnderline($style, $styleAttributeValue); + + break; + case 'VerticalAlign': + $style = $this->parseVerticalAlign($style, $styleAttributeValue); + + break; + } + } + + return $style; + } +} diff --git a/src/PhpSpreadsheet/Reader/Xml/Style/NumberFormat.php b/src/PhpSpreadsheet/Reader/Xml/Style/NumberFormat.php new file mode 100644 index 00000000..a31aa9eb --- /dev/null +++ b/src/PhpSpreadsheet/Reader/Xml/Style/NumberFormat.php @@ -0,0 +1,33 @@ + $styleAttributeValue) { + $styleAttributeValue = str_replace($fromFormats, $toFormats, $styleAttributeValue); + + switch ($styleAttributeValue) { + case 'Short Date': + $styleAttributeValue = 'dd/mm/yyyy'; + + break; + } + + if ($styleAttributeValue > '') { + $style['numberFormat']['formatCode'] = $styleAttributeValue; + } + } + + return $style; + } +} diff --git a/src/PhpSpreadsheet/Reader/Xml/Style/StyleBase.php b/src/PhpSpreadsheet/Reader/Xml/Style/StyleBase.php new file mode 100644 index 00000000..fc9ace82 --- /dev/null +++ b/src/PhpSpreadsheet/Reader/Xml/Style/StyleBase.php @@ -0,0 +1,32 @@ +') + : ($simple->attributes($node) ?? new SimpleXMLElement('')); + } +} diff --git a/src/PhpSpreadsheet/ReferenceHelper.php b/src/PhpSpreadsheet/ReferenceHelper.php index ef95b893..31f5ecef 100644 --- a/src/PhpSpreadsheet/ReferenceHelper.php +++ b/src/PhpSpreadsheet/ReferenceHelper.php @@ -233,22 +233,22 @@ class ReferenceHelper /** * Update data validations when inserting/deleting rows/columns. * - * @param Worksheet $pSheet The worksheet that we're editing + * @param Worksheet $worksheet The worksheet that we're editing * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) */ - protected function adjustDataValidations(Worksheet $pSheet, $pBefore, $pNumCols, $pNumRows): void + protected function adjustDataValidations(Worksheet $worksheet, $pBefore, $pNumCols, $pNumRows): void { - $aDataValidationCollection = $pSheet->getDataValidationCollection(); + $aDataValidationCollection = $worksheet->getDataValidationCollection(); ($pNumCols > 0 || $pNumRows > 0) ? uksort($aDataValidationCollection, ['self', 'cellReverseSort']) : uksort($aDataValidationCollection, ['self', 'cellSort']); foreach ($aDataValidationCollection as $key => $value) { $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); if ($key != $newReference) { - $pSheet->setDataValidation($newReference, $value); - $pSheet->setDataValidation($key, null); + $worksheet->setDataValidation($newReference, $value); + $worksheet->setDataValidation($key, null); } } } @@ -363,18 +363,17 @@ class ReferenceHelper $remove = ($numberOfColumns < 0 || $numberOfRows < 0); $allCoordinates = $worksheet->getCoordinates(); - // Get coordinate of $pBefore - [$beforeColumn, $beforeRow] = Coordinate::coordinateFromString($beforeCellAddress); - $beforeColumnIndex = Coordinate::columnIndexFromString($beforeColumn); + // Get coordinate of $beforeCellAddress + [$beforeColumn, $beforeRow] = Coordinate::indexesFromString($beforeCellAddress); // Clear cells if we are removing columns or rows $highestColumn = $worksheet->getHighestColumn(); $highestRow = $worksheet->getHighestRow(); // 1. Clear column strips if we are removing columns - if ($numberOfColumns < 0 && $beforeColumnIndex - 2 + $numberOfColumns > 0) { + if ($numberOfColumns < 0 && $beforeColumn - 2 + $numberOfColumns > 0) { for ($i = 1; $i <= $highestRow - 1; ++$i) { - for ($j = $beforeColumnIndex - 1 + $numberOfColumns; $j <= $beforeColumnIndex - 2; ++$j) { + for ($j = $beforeColumn - 1 + $numberOfColumns; $j <= $beforeColumn - 2; ++$j) { $coordinate = Coordinate::stringFromColumnIndex($j + 1) . $i; $worksheet->removeConditionalStyles($coordinate); if ($worksheet->cellExists($coordinate)) { @@ -387,7 +386,7 @@ class ReferenceHelper // 2. Clear row strips if we are removing rows if ($numberOfRows < 0 && $beforeRow - 1 + $numberOfRows > 0) { - for ($i = $beforeColumnIndex - 1; $i <= Coordinate::columnIndexFromString($highestColumn) - 1; ++$i) { + for ($i = $beforeColumn - 1; $i <= Coordinate::columnIndexFromString($highestColumn) - 1; ++$i) { for ($j = $beforeRow + $numberOfRows; $j <= $beforeRow - 1; ++$j) { $coordinate = Coordinate::stringFromColumnIndex($i + 1) . $j; $worksheet->removeConditionalStyles($coordinate); @@ -416,7 +415,7 @@ class ReferenceHelper $newCoordinate = Coordinate::stringFromColumnIndex($cellIndex + $numberOfColumns) . ($cell->getRow() + $numberOfRows); // Should the cell be updated? Move value and cellXf index from one cell to another. - if (($cellIndex >= $beforeColumnIndex) && ($cell->getRow() >= $beforeRow)) { + if (($cellIndex >= $beforeColumn) && ($cell->getRow() >= $beforeRow)) { // Update cell styles $worksheet->getCell($newCoordinate)->setXfIndex($cell->getXfIndex()); @@ -446,15 +445,15 @@ class ReferenceHelper $highestColumn = $worksheet->getHighestColumn(); $highestRow = $worksheet->getHighestRow(); - if ($numberOfColumns > 0 && $beforeColumnIndex - 2 > 0) { + if ($numberOfColumns > 0 && $beforeColumn - 2 > 0) { for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) { // Style - $coordinate = Coordinate::stringFromColumnIndex($beforeColumnIndex - 1) . $i; + $coordinate = Coordinate::stringFromColumnIndex($beforeColumn - 1) . $i; if ($worksheet->cellExists($coordinate)) { $xfIndex = $worksheet->getCell($coordinate)->getXfIndex(); $conditionalStyles = $worksheet->conditionalStylesExists($coordinate) ? $worksheet->getConditionalStyles($coordinate) : false; - for ($j = $beforeColumnIndex; $j <= $beforeColumnIndex - 1 + $numberOfColumns; ++$j) { + for ($j = $beforeColumn; $j <= $beforeColumn - 1 + $numberOfColumns; ++$j) { $worksheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex); if ($conditionalStyles) { $cloned = []; @@ -469,7 +468,7 @@ class ReferenceHelper } if ($numberOfRows > 0 && $beforeRow - 1 > 0) { - for ($i = $beforeColumnIndex; $i <= Coordinate::columnIndexFromString($highestColumn); ++$i) { + for ($i = $beforeColumn; $i <= Coordinate::columnIndexFromString($highestColumn); ++$i) { // Style $coordinate = Coordinate::stringFromColumnIndex($i) . ($beforeRow - 1); if ($worksheet->cellExists($coordinate)) { @@ -494,13 +493,13 @@ class ReferenceHelper $this->adjustColumnDimensions($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); // Update worksheet: row dimensions - $this->adjustRowDimensions($worksheet, $beforeCellAddress, $numberOfColumns, (int) $beforeRow, $numberOfRows); + $this->adjustRowDimensions($worksheet, $beforeCellAddress, $numberOfColumns, $beforeRow, $numberOfRows); // Update worksheet: page breaks - $this->adjustPageBreaks($worksheet, $beforeCellAddress, $beforeColumnIndex, $numberOfColumns, (int) $beforeRow, $numberOfRows); + $this->adjustPageBreaks($worksheet, $beforeCellAddress, $beforeColumn, $numberOfColumns, $beforeRow, $numberOfRows); // Update worksheet: comments - $this->adjustComments($worksheet, $beforeCellAddress, $beforeColumnIndex, $numberOfColumns, (int) $beforeRow, $numberOfRows); + $this->adjustComments($worksheet, $beforeCellAddress, $beforeColumn, $numberOfColumns, $beforeRow, $numberOfRows); // Update worksheet: hyperlinks $this->adjustHyperlinks($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); @@ -571,8 +570,8 @@ class ReferenceHelper // Update worksheet: freeze pane if ($worksheet->getFreezePane()) { - $splitCell = $worksheet->getFreezePane(); - $topLeftCell = $worksheet->getTopLeftCell(); + $splitCell = $worksheet->getFreezePane() ?? ''; + $topLeftCell = $worksheet->getTopLeftCell() ?? ''; $splitCell = $this->updateCellReference($splitCell, $beforeCellAddress, $numberOfColumns, $numberOfRows); $topLeftCell = $this->updateCellReference($topLeftCell, $beforeCellAddress, $numberOfColumns, $numberOfRows); @@ -597,7 +596,7 @@ class ReferenceHelper // Update workbook: define names if (count($worksheet->getParent()->getDefinedNames()) > 0) { foreach ($worksheet->getParent()->getDefinedNames() as $definedName) { - if ($definedName->getWorksheet()->getHashCode() === $worksheet->getHashCode()) { + if ($definedName->getWorksheet() !== null && $definedName->getWorksheet()->getHashCode() === $worksheet->getHashCode()) { $definedName->setValue($this->updateCellReference($definedName->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows)); } } @@ -643,7 +642,7 @@ class ReferenceHelper $toString .= $modified3 . ':' . $modified4; // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more $column = 100000; - $row = 10000000 + trim($match[3], '$'); + $row = 10000000 + (int) trim($match[3], '$'); $cellIndex = $column . $row; $newCellTokens[$cellIndex] = preg_quote($toString, '/'); @@ -694,7 +693,7 @@ class ReferenceHelper [$column, $row] = Coordinate::coordinateFromString($match[3]); // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000; - $row = trim($row, '$') + 10000000; + $row = (int) trim($row, '$') + 10000000; $cellIndex = $column . $row; $newCellTokens[$cellIndex] = preg_quote($toString, '/'); @@ -720,7 +719,7 @@ class ReferenceHelper [$column, $row] = Coordinate::coordinateFromString($match[3]); // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000; - $row = trim($row, '$') + 10000000; + $row = (int) trim($row, '$') + 10000000; $cellIndex = $row . $column; $newCellTokens[$cellIndex] = preg_quote($toString, '/'); @@ -1010,7 +1009,7 @@ class ReferenceHelper // Create new row reference if ($updateRow) { - $newRow = $newRow + $numberOfRows; + $newRow = (int) $newRow + $numberOfRows; } // Return new reference diff --git a/src/PhpSpreadsheet/RichText/ITextElement.php b/src/PhpSpreadsheet/RichText/ITextElement.php index 69954676..39b70c86 100644 --- a/src/PhpSpreadsheet/RichText/ITextElement.php +++ b/src/PhpSpreadsheet/RichText/ITextElement.php @@ -14,7 +14,7 @@ interface ITextElement /** * Set text. * - * @param $text string Text + * @param string $text Text * * @return ITextElement */ diff --git a/src/PhpSpreadsheet/RichText/TextElement.php b/src/PhpSpreadsheet/RichText/TextElement.php index 8e906bf7..6bec005b 100644 --- a/src/PhpSpreadsheet/RichText/TextElement.php +++ b/src/PhpSpreadsheet/RichText/TextElement.php @@ -35,7 +35,7 @@ class TextElement implements ITextElement /** * Set text. * - * @param $text string Text + * @param string $text Text * * @return $this */ diff --git a/src/PhpSpreadsheet/Settings.php b/src/PhpSpreadsheet/Settings.php index 4d561252..765ae8c8 100644 --- a/src/PhpSpreadsheet/Settings.php +++ b/src/PhpSpreadsheet/Settings.php @@ -24,7 +24,7 @@ class Settings * * @var int */ - private static $libXmlLoaderOptions = null; + private static $libXmlLoaderOptions; /** * Allow/disallow libxml_disable_entity_loader() call when not thread safe. @@ -68,6 +68,11 @@ class Settings return Calculation::getInstance()->setLocale($locale); } + public static function getLocale(): string + { + return Calculation::getInstance()->getLocale(); + } + /** * Identify to PhpSpreadsheet the external library to use for rendering charts. * @@ -89,11 +94,16 @@ class Settings * @return null|string Class name of the chart renderer * eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph */ - public static function getChartRenderer(): string + public static function getChartRenderer(): ?string { return self::$chartRenderer; } + public static function htmlEntityFlags(): int + { + return \ENT_COMPAT; + } + /** * Set default options for libxml loader. * @@ -118,7 +128,7 @@ class Settings if (self::$libXmlLoaderOptions === null && defined('LIBXML_DTDLOAD')) { self::setLibXmlLoaderOptions(LIBXML_DTDLOAD | LIBXML_DTDATTR); } elseif (self::$libXmlLoaderOptions === null) { - self::$libXmlLoaderOptions = true; + self::$libXmlLoaderOptions = 0; } return self::$libXmlLoaderOptions; diff --git a/src/PhpSpreadsheet/Shared/CodePage.php b/src/PhpSpreadsheet/Shared/CodePage.php index 1d5d8933..8718a613 100644 --- a/src/PhpSpreadsheet/Shared/CodePage.php +++ b/src/PhpSpreadsheet/Shared/CodePage.php @@ -8,6 +8,7 @@ class CodePage { public const DEFAULT_CODE_PAGE = 'CP1252'; + /** @var array */ private static $pageArray = [ 0 => 'CP1252', // CodePage is not always correctly set when the xls file was saved by Apple's Numbers program 367 => 'ASCII', // ASCII @@ -56,7 +57,7 @@ class CodePage 10010 => 'MACROMANIA', // Macintosh Romania 10017 => 'MACUKRAINE', // Macintosh Ukraine 10021 => 'MACTHAI', // Macintosh Thai - 10029 => 'MACCENTRALEUROPE', // Macintosh Central Europe + 10029 => ['MACCENTRALEUROPE', 'MAC-CENTRALEUROPE'], // Macintosh Central Europe 10079 => 'MACICELAND', // Macintosh Icelandic 10081 => 'MACTURKISH', // Macintosh Turkish 10082 => 'MACCROATIAN', // Macintosh Croatian @@ -65,6 +66,7 @@ class CodePage //32769 => 'unsupported', // ANSI Latin I (BIFF2-BIFF3) 65000 => 'UTF-7', // Unicode (UTF-7) 65001 => 'UTF-8', // Unicode (UTF-8) + 99999 => ['unsupported'], // Unicode (UTF-8) ]; public static function validate(string $codePage): bool @@ -83,7 +85,20 @@ class CodePage public static function numberToName(int $codePage): string { if (array_key_exists($codePage, self::$pageArray)) { - return self::$pageArray[$codePage]; + $value = self::$pageArray[$codePage]; + if (is_array($value)) { + foreach ($value as $encoding) { + if (@iconv('UTF-8', $encoding, ' ') !== false) { + self::$pageArray[$codePage] = $encoding; + + return $encoding; + } + } + + throw new PhpSpreadsheetException("Code page $codePage not implemented on this system."); + } else { + return $value; + } } if ($codePage == 720 || $codePage == 32769) { throw new PhpSpreadsheetException("Code page $codePage not supported."); // OEM Arabic diff --git a/src/PhpSpreadsheet/Shared/Date.php b/src/PhpSpreadsheet/Shared/Date.php index b02e01f1..b755ec3a 100644 --- a/src/PhpSpreadsheet/Shared/Date.php +++ b/src/PhpSpreadsheet/Shared/Date.php @@ -2,9 +2,10 @@ namespace PhpOffice\PhpSpreadsheet\Shared; +use DateTime; use DateTimeInterface; use DateTimeZone; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; +use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; @@ -96,7 +97,7 @@ class Date /** * Set the Default timezone to use for dates. * - * @param DateTimeZone|string $timeZone The timezone to set for all Excel datetimestamp to PHP DateTime Object conversions + * @param null|DateTimeZone|string $timeZone The timezone to set for all Excel datetimestamp to PHP DateTime Object conversions * * @return bool Success or failure */ @@ -114,29 +115,39 @@ class Date } /** - * Return the Default timezone being used for dates. - * - * @return DateTimeZone The timezone being used as default for Excel timestamp to PHP DateTime object + * Return the Default timezone, or UTC if default not set. */ - public static function getDefaultTimezone() + public static function getDefaultTimezone(): DateTimeZone { - if (self::$defaultTimeZone === null) { - self::$defaultTimeZone = new DateTimeZone('UTC'); - } + return self::$defaultTimeZone ?? new DateTimeZone('UTC'); + } + /** + * Return the Default timezone, or local timezone if default is not set. + */ + public static function getDefaultOrLocalTimezone(): DateTimeZone + { + return self::$defaultTimeZone ?? new DateTimeZone(date_default_timezone_get()); + } + + /** + * Return the Default timezone even if null. + */ + public static function getDefaultTimezoneOrNull(): ?DateTimeZone + { return self::$defaultTimeZone; } /** * Validate a timezone. * - * @param DateTimeZone|string $timeZone The timezone to validate, either as a timezone string or object + * @param null|DateTimeZone|string $timeZone The timezone to validate, either as a timezone string or object * - * @return DateTimeZone The timezone as a timezone object + * @return ?DateTimeZone The timezone as a timezone object */ private static function validateTimeZone($timeZone) { - if ($timeZone instanceof DateTimeZone) { + if ($timeZone instanceof DateTimeZone || $timeZone === null) { return $timeZone; } if (in_array($timeZone, DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC))) { @@ -154,26 +165,26 @@ class Date * if you don't want to treat it as a UTC value * Use the default (UST) unless you absolutely need a conversion * - * @return \DateTime PHP date/time object + * @return DateTime PHP date/time object */ public static function excelToDateTimeObject($excelTimestamp, $timeZone = null) { $timeZone = ($timeZone === null) ? self::getDefaultTimezone() : self::validateTimeZone($timeZone); if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) { - if ($excelTimestamp < 1.0) { + if ($excelTimestamp < 1 && self::$excelCalendar === self::CALENDAR_WINDOWS_1900) { // Unix timestamp base date - $baseDate = new \DateTime('1970-01-01', $timeZone); + $baseDate = new DateTime('1970-01-01', $timeZone); } else { // MS Excel calendar base dates if (self::$excelCalendar == self::CALENDAR_WINDOWS_1900) { // Allow adjustment for 1900 Leap Year in MS Excel - $baseDate = ($excelTimestamp < 60) ? new \DateTime('1899-12-31', $timeZone) : new \DateTime('1899-12-30', $timeZone); + $baseDate = ($excelTimestamp < 60) ? new DateTime('1899-12-31', $timeZone) : new DateTime('1899-12-30', $timeZone); } else { - $baseDate = new \DateTime('1904-01-01', $timeZone); + $baseDate = new DateTime('1904-01-01', $timeZone); } } } else { - $baseDate = new \DateTime('1899-12-30', $timeZone); + $baseDate = new DateTime('1899-12-30', $timeZone); } $days = floor($excelTimestamp); @@ -254,7 +265,7 @@ class Date * * @param int $unixTimestamp Unix Timestamp * - * @return float MS Excel serialized date/time value + * @return false|float MS Excel serialized date/time value */ public static function timestampToExcel($unixTimestamp) { @@ -262,7 +273,7 @@ class Date return false; } - return self::dateTimeToExcel(new \DateTime('@' . $unixTimestamp)); + return self::dateTimeToExcel(new DateTime('@' . $unixTimestamp)); } /** @@ -303,8 +314,8 @@ class Date } // Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0) - $century = substr($year, 0, 2); - $decade = substr($year, 2, 2); + $century = (int) substr($year, 0, 2); + $decade = (int) substr($year, 2, 2); $excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $myexcelBaseDate + $excel1900isLeapYear; $excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400; @@ -436,14 +447,14 @@ class Date return false; } - $dateValueNew = DateTime::DATEVALUE($dateValue); + $dateValueNew = DateTimeExcel\DateValue::fromString($dateValue); if ($dateValueNew === Functions::VALUE()) { return false; } if (strpos($dateValue, ':') !== false) { - $timeValue = DateTime::TIMEVALUE($dateValue); + $timeValue = DateTimeExcel\TimeValue::fromString($dateValue); if ($timeValue === Functions::VALUE()) { return false; } @@ -489,4 +500,19 @@ class Date return $day; } + + public static function dateTimeFromTimestamp(string $date, ?DateTimeZone $timeZone = null): DateTime + { + $dtobj = DateTime::createFromFormat('U', $date) ?: new DateTime(); + $dtobj->setTimeZone($timeZone ?? self::getDefaultOrLocalTimezone()); + + return $dtobj; + } + + public static function formattedDateTimeFromTimestamp(string $date, string $format, ?DateTimeZone $timeZone = null): string + { + $dtobj = self::dateTimeFromTimestamp($date, $timeZone); + + return $dtobj->format($format); + } } diff --git a/src/PhpSpreadsheet/Shared/Drawing.php b/src/PhpSpreadsheet/Shared/Drawing.php index 65b8521e..04ce1430 100644 --- a/src/PhpSpreadsheet/Shared/Drawing.php +++ b/src/PhpSpreadsheet/Shared/Drawing.php @@ -3,32 +3,34 @@ namespace PhpOffice\PhpSpreadsheet\Shared; use GdImage; +use SimpleXMLElement; class Drawing { /** * Convert pixels to EMU. * - * @param int $pxValue Value in pixels + * @param int $pixelValue Value in pixels * * @return int Value in EMU */ - public static function pixelsToEMU($pxValue) + public static function pixelsToEMU($pixelValue) { - return round($pxValue * 9525); + return $pixelValue * 9525; } /** * Convert EMU to pixels. * - * @param int $emValue Value in EMU + * @param int|SimpleXMLElement $emuValue Value in EMU * * @return int Value in pixels */ - public static function EMUToPixels($emValue) + public static function EMUToPixels($emuValue) { - if ($emValue != 0) { - return round($emValue / 9525); + $emuValue = (int) $emuValue; + if ($emuValue != 0) { + return (int) round($emuValue / 9525); } return 0; @@ -39,12 +41,11 @@ class Drawing * By inspection of a real Excel file using Calibri 11, one finds 1000px ~ 142.85546875 * This gives a conversion factor of 7. Also, we assume that pixels and font size are proportional. * - * @param int $pxValue Value in pixels - * @param \PhpOffice\PhpSpreadsheet\Style\Font $defaultFont Default font of the workbook + * @param int $pixelValue Value in pixels * - * @return int Value in cell dimension + * @return float|int Value in cell dimension */ - public static function pixelsToCellDimension($pxValue, \PhpOffice\PhpSpreadsheet\Style\Font $defaultFont) + public static function pixelsToCellDimension($pixelValue, \PhpOffice\PhpSpreadsheet\Style\Font $defaultFont) { // Font name and size $name = $defaultFont->getName(); @@ -52,25 +53,25 @@ class Drawing if (isset(Font::$defaultColumnWidths[$name][$size])) { // Exact width can be determined - $colWidth = $pxValue * Font::$defaultColumnWidths[$name][$size]['width'] / Font::$defaultColumnWidths[$name][$size]['px']; - } else { - // We don't have data for this particular font and size, use approximation by - // extrapolating from Calibri 11 - $colWidth = $pxValue * 11 * Font::$defaultColumnWidths['Calibri'][11]['width'] / Font::$defaultColumnWidths['Calibri'][11]['px'] / $size; + return $pixelValue * Font::$defaultColumnWidths[$name][$size]['width'] + / Font::$defaultColumnWidths[$name][$size]['px']; } - return $colWidth; + // We don't have data for this particular font and size, use approximation by + // extrapolating from Calibri 11 + return $pixelValue * 11 * Font::$defaultColumnWidths['Calibri'][11]['width'] + / Font::$defaultColumnWidths['Calibri'][11]['px'] / $size; } /** * Convert column width from (intrinsic) Excel units to pixels. * - * @param float $excelSize Value in cell dimension + * @param float $cellWidth Value in cell dimension * @param \PhpOffice\PhpSpreadsheet\Style\Font $pDefaultFont Default font of the workbook * * @return int Value in pixels */ - public static function cellDimensionToPixels($excelSize, \PhpOffice\PhpSpreadsheet\Style\Font $pDefaultFont) + public static function cellDimensionToPixels($cellWidth, \PhpOffice\PhpSpreadsheet\Style\Font $pDefaultFont) { // Font name and size $name = $pDefaultFont->getName(); @@ -78,11 +79,13 @@ class Drawing if (isset(Font::$defaultColumnWidths[$name][$size])) { // Exact width can be determined - $colWidth = $excelSize * Font::$defaultColumnWidths[$name][$size]['px'] / Font::$defaultColumnWidths[$name][$size]['width']; + $colWidth = $cellWidth * Font::$defaultColumnWidths[$name][$size]['px'] + / Font::$defaultColumnWidths[$name][$size]['width']; } else { // We don't have data for this particular font and size, use approximation by // extrapolating from Calibri 11 - $colWidth = $excelSize * $size * Font::$defaultColumnWidths['Calibri'][11]['px'] / Font::$defaultColumnWidths['Calibri'][11]['width'] / 11; + $colWidth = $cellWidth * $size * Font::$defaultColumnWidths['Calibri'][11]['px'] + / Font::$defaultColumnWidths['Calibri'][11]['width'] / 11; } // Round pixels to closest integer @@ -94,26 +97,26 @@ class Drawing /** * Convert pixels to points. * - * @param int $pxValue Value in pixels + * @param int $pixelValue Value in pixels * * @return float Value in points */ - public static function pixelsToPoints($pxValue) + public static function pixelsToPoints($pixelValue) { - return $pxValue * 0.75; + return $pixelValue * 0.75; } /** * Convert points to pixels. * - * @param int $ptValue Value in points + * @param int $pointValue Value in points * * @return int Value in pixels */ - public static function pointsToPixels($ptValue) + public static function pointsToPixels($pointValue) { - if ($ptValue != 0) { - return (int) ceil($ptValue / 0.75); + if ($pointValue != 0) { + return (int) ceil($pointValue / 0.75); } return 0; @@ -134,14 +137,15 @@ class Drawing /** * Convert angle to degrees. * - * @param int $angle Angle + * @param int|SimpleXMLElement $angle Angle * * @return int Degrees */ public static function angleToDegrees($angle) { + $pValue = (int) $angle; if ($angle != 0) { - return round($angle / 60000); + return (int) round($angle / 60000); } return 0; @@ -171,6 +175,8 @@ class Drawing // Process the header // Structure: http://www.fastgraph.com/help/bmp_header_format.html + $width = 0; + $height = 0; if (substr($header, 0, 4) == '424d') { // Cut it in parts of 2 bytes $header_parts = str_split($header, 2); diff --git a/src/PhpSpreadsheet/Shared/File.php b/src/PhpSpreadsheet/Shared/File.php index 1704e957..83103b49 100644 --- a/src/PhpSpreadsheet/Shared/File.php +++ b/src/PhpSpreadsheet/Shared/File.php @@ -2,7 +2,8 @@ namespace PhpOffice\PhpSpreadsheet\Shared; -use InvalidArgumentException; +use PhpOffice\PhpSpreadsheet\Exception; +use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException; use ZipArchive; class File @@ -16,47 +17,57 @@ class File /** * Set the flag indicating whether the File Upload Temp directory should be used for temporary files. - * - * @param bool $useUploadTempDir Use File Upload Temporary directory (true or false) */ - public static function setUseUploadTempDirectory($useUploadTempDir): void + public static function setUseUploadTempDirectory(bool $useUploadTempDir): void { self::$useUploadTempDirectory = (bool) $useUploadTempDir; } /** * Get the flag indicating whether the File Upload Temp directory should be used for temporary files. - * - * @return bool Use File Upload Temporary directory (true or false) */ - public static function getUseUploadTempDirectory() + public static function getUseUploadTempDirectory(): bool { return self::$useUploadTempDirectory; } + // https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT + // Section 4.3.7 + // Looks like there might be endian-ness considerations + private const ZIP_FIRST_4 = [ + "\x50\x4b\x03\x04", // what it looks like on my system + "\x04\x03\x4b\x50", // what it says in documentation + ]; + + private static function validateZipFirst4(string $zipFile): bool + { + $contents = @file_get_contents($zipFile, false, null, 0, 4); + + return in_array($contents, self::ZIP_FIRST_4, true); + } + /** * Verify if a file exists. - * - * @param string $filename Filename - * - * @return bool */ - public static function fileExists($filename) + public static function fileExists(string $filename): bool { // Sick construction, but it seems that // file_exists returns strange values when // doing the original file_exists on ZIP archives... - if (strtolower(substr($filename, 0, 3)) == 'zip') { + if (strtolower(substr($filename, 0, 6)) == 'zip://') { // Open ZIP file and verify if the file exists $zipFile = substr($filename, 6, strpos($filename, '#') - 6); $archiveFile = substr($filename, strpos($filename, '#') + 1); - $zip = new ZipArchive(); - if ($zip->open($zipFile) === true) { - $returnValue = ($zip->getFromName($archiveFile) !== false); - $zip->close(); + if (self::validateZipFirst4($zipFile)) { + $zip = new ZipArchive(); + $res = $zip->open($zipFile, ZipArchive::CHECKCONS); + if ($res === true) { + $returnValue = ($zip->getFromName($archiveFile) !== false); + $zip->close(); - return $returnValue; + return $returnValue; + } } return false; @@ -67,23 +78,19 @@ class File /** * Returns canonicalized absolute pathname, also for ZIP archives. - * - * @param string $filename - * - * @return string */ - public static function realpath($filename) + public static function realpath(string $filename): string { // Returnvalue $returnValue = ''; // Try using realpath() if (file_exists($filename)) { - $returnValue = realpath($filename); + $returnValue = realpath($filename) ?: ''; } // Found something? - if ($returnValue == '' || ($returnValue === null)) { + if ($returnValue === '') { $pathArray = explode('/', $filename); while (in_array('..', $pathArray) && $pathArray[0] != '..') { $iMax = count($pathArray); @@ -104,39 +111,76 @@ class File /** * Get the systems temporary directory. - * - * @return string */ - public static function sysGetTempDir() + public static function sysGetTempDir(): string { + $path = sys_get_temp_dir(); if (self::$useUploadTempDirectory) { // use upload-directory when defined to allow running on environments having very restricted // open_basedir configs if (ini_get('upload_tmp_dir') !== false) { if ($temp = ini_get('upload_tmp_dir')) { if (file_exists($temp)) { - return realpath($temp); + $path = $temp; } } } } - return realpath(sys_get_temp_dir()); + return realpath($path) ?: ''; + } + + public static function temporaryFilename(): string + { + $filename = tempnam(self::sysGetTempDir(), 'phpspreadsheet'); + if ($filename === false) { + throw new Exception('Could not create temporary file'); + } + + return $filename; } /** * Assert that given path is an existing file and is readable, otherwise throw exception. - * - * @param string $filename */ - public static function assertFile($filename): void + public static function assertFile(string $filename, string $zipMember = ''): void { if (!is_file($filename)) { - throw new InvalidArgumentException('File "' . $filename . '" does not exist.'); + throw new ReaderException('File "' . $filename . '" does not exist.'); } if (!is_readable($filename)) { - throw new InvalidArgumentException('Could not open "' . $filename . '" for reading.'); + throw new ReaderException('Could not open "' . $filename . '" for reading.'); + } + + if ($zipMember !== '') { + $zipfile = "zip://$filename#$zipMember"; + if (!self::fileExists($zipfile)) { + throw new ReaderException("Could not find zip member $zipfile"); + } } } + + /** + * Same as assertFile, except return true/false and don't throw Exception. + */ + public static function testFileNoThrow(string $filename, string $zipMember = ''): bool + { + if (!is_file($filename)) { + return false; + } + + if (!is_readable($filename)) { + return false; + } + + if ($zipMember !== '') { + $zipfile = "zip://$filename#$zipMember"; + if (!self::fileExists($zipfile)) { + return false; + } + } + + return true; + } } diff --git a/src/PhpSpreadsheet/Shared/Font.php b/src/PhpSpreadsheet/Shared/Font.php index 188a987b..9a74befe 100644 --- a/src/PhpSpreadsheet/Shared/Font.php +++ b/src/PhpSpreadsheet/Shared/Font.php @@ -4,6 +4,7 @@ namespace PhpOffice\PhpSpreadsheet\Shared; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\RichText\RichText; +use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Font as FontStyle; class Font @@ -45,10 +46,10 @@ class Font const ARIAL_ITALIC = 'ariali.ttf'; const ARIAL_BOLD_ITALIC = 'arialbi.ttf'; - const CALIBRI = 'CALIBRI.TTF'; - const CALIBRI_BOLD = 'CALIBRIB.TTF'; - const CALIBRI_ITALIC = 'CALIBRII.TTF'; - const CALIBRI_BOLD_ITALIC = 'CALIBRIZ.TTF'; + const CALIBRI = 'calibri.ttf'; + const CALIBRI_BOLD = 'calibrib.ttf'; + const CALIBRI_ITALIC = 'calibrii.ttf'; + const CALIBRI_BOLD_ITALIC = 'calibriz.ttf'; const COMIC_SANS_MS = 'comic.ttf'; const COMIC_SANS_MS_BOLD = 'comicbd.ttf'; @@ -112,7 +113,7 @@ class Font * * @var string */ - private static $trueTypeFontPath = null; + private static $trueTypeFontPath; /** * How wide is a default column for a given default font and size? @@ -232,7 +233,7 @@ class Font } // Special case if there are one or more newline characters ("\n") - if (strpos($cellText, "\n") !== false) { + if (strpos($cellText ?? '', "\n") !== false) { $lineTexts = explode("\n", $cellText); $lineWidths = []; foreach ($lineTexts as $lineText) { @@ -244,6 +245,7 @@ class Font // Try to get the exact text width in pixels $approximate = self::$autoSizeMethod == self::AUTOSIZE_METHOD_APPROX; + $columnWidth = 0; if (!$approximate) { $columnWidthAdjust = ceil(self::getTextWidthPixelsExact('n', $font, 0) * 1.07); @@ -264,22 +266,16 @@ class Font } // Convert from pixel width to column width - $columnWidth = Drawing::pixelsToCellDimension($columnWidth, $defaultFont); + $columnWidth = Drawing::pixelsToCellDimension((int) $columnWidth, $defaultFont); // Return - return round($columnWidth, 6); + return (int) round($columnWidth, 6); } /** * Get GD text width in pixels for a string of text in a certain font at a certain rotation angle. - * - * @param string $text - * @param FontStyle - * @param int $rotation - * - * @return int */ - public static function getTextWidthPixelsExact($text, FontStyle $font, $rotation = 0) + public static function getTextWidthPixelsExact(string $text, FontStyle $font, int $rotation = 0): int { if (!function_exists('imagettfbbox')) { throw new PhpSpreadsheetException('GD library needs to be enabled'); @@ -343,7 +339,7 @@ class Font // Calculate approximate rotated column width if ($rotation !== 0) { - if ($rotation == -165) { + if ($rotation == Alignment::TEXTROTATION_STACK_PHPSPREADSHEET) { // stacked text $columnWidth = 4; // approximation } else { diff --git a/src/PhpSpreadsheet/Shared/IntOrFloat.php b/src/PhpSpreadsheet/Shared/IntOrFloat.php new file mode 100644 index 00000000..060f09c8 --- /dev/null +++ b/src/PhpSpreadsheet/Shared/IntOrFloat.php @@ -0,0 +1,21 @@ +getRowDimension() == $this->m) { if ($this->isspd) { - $X = $B->getArrayCopy(); + $X = $B->getArray(); $nx = $B->getColumnDimension(); for ($k = 0; $k < $this->m; ++$k) { diff --git a/src/PhpSpreadsheet/Shared/JAMA/EigenvalueDecomposition.php b/src/PhpSpreadsheet/Shared/JAMA/EigenvalueDecomposition.php index 4c67c3a9..5c6ccfd3 100644 --- a/src/PhpSpreadsheet/Shared/JAMA/EigenvalueDecomposition.php +++ b/src/PhpSpreadsheet/Shared/JAMA/EigenvalueDecomposition.php @@ -18,9 +18,9 @@ namespace PhpOffice\PhpSpreadsheet\Shared\JAMA; * conditioned, or even singular, so the validity of the equation * A = V*D*inverse(V) depends upon V.cond(). * - * @author Paul Meagher + * @author Paul Meagher * - * @version 1.1 + * @version 1.1 */ class EigenvalueDecomposition { @@ -70,6 +70,11 @@ class EigenvalueDecomposition private $cdivi; + /** + * @var array + */ + private $A; + /** * Symmetric Householder reduction to tridiagonal form. */ @@ -80,6 +85,7 @@ class EigenvalueDecomposition // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding // Fortran subroutine in EISPACK. $this->d = $this->V[$this->n - 1]; + $j = 0; // Householder reduction to tridiagonal form. for ($i = $this->n - 1; $i > 0; --$i) { $i_ = $i - 1; @@ -781,9 +787,9 @@ class EigenvalueDecomposition /** * Constructor: Check for symmetry, then construct the eigenvalue decomposition. * - * @param mixed $Arg A Square matrix + * @param Matrix $Arg A Square matrix */ - public function __construct($Arg) + public function __construct(Matrix $Arg) { $this->A = $Arg->getArray(); $this->n = $Arg->getColumnDimension(); @@ -848,6 +854,7 @@ class EigenvalueDecomposition */ public function getD() { + $D = []; for ($i = 0; $i < $this->n; ++$i) { $D[$i] = array_fill(0, $this->n, 0.0); $D[$i][$i] = $this->d[$i]; diff --git a/src/PhpSpreadsheet/Shared/JAMA/LUDecomposition.php b/src/PhpSpreadsheet/Shared/JAMA/LUDecomposition.php index 4aecff73..ecfe42ba 100644 --- a/src/PhpSpreadsheet/Shared/JAMA/LUDecomposition.php +++ b/src/PhpSpreadsheet/Shared/JAMA/LUDecomposition.php @@ -135,6 +135,7 @@ class LUDecomposition */ public function getL() { + $L = []; for ($i = 0; $i < $this->m; ++$i) { for ($j = 0; $j < $this->n; ++$j) { if ($i > $j) { @@ -159,6 +160,7 @@ class LUDecomposition */ public function getU() { + $U = []; for ($i = 0; $i < $this->n; ++$i) { for ($j = 0; $j < $this->n; ++$j) { if ($i <= $j) { @@ -219,7 +221,7 @@ class LUDecomposition /** * Count determinants. * - * @return array d matrix deterninat + * @return float */ public function det() { @@ -240,11 +242,11 @@ class LUDecomposition /** * Solve A*X = B. * - * @param mixed $B a Matrix with as many rows as A and any number of columns + * @param Matrix $B a Matrix with as many rows as A and any number of columns * * @return Matrix X so that L*U*X = B(piv,:) */ - public function solve($B) + public function solve(Matrix $B) { if ($B->getRowDimension() == $this->m) { if ($this->isNonsingular()) { diff --git a/src/PhpSpreadsheet/Shared/JAMA/Matrix.php b/src/PhpSpreadsheet/Shared/JAMA/Matrix.php index a5cb6de0..adf399ac 100644 --- a/src/PhpSpreadsheet/Shared/JAMA/Matrix.php +++ b/src/PhpSpreadsheet/Shared/JAMA/Matrix.php @@ -147,7 +147,7 @@ class Matrix * @param int $i Row position * @param int $j Column position * - * @return mixed Element (int/float/double) + * @return float|int */ public function get($i = null, $j = null) { @@ -323,11 +323,9 @@ class Matrix * * @param int $i Row position * @param int $j Column position - * @param mixed $c Int/float/double value - * - * @return mixed Element (int/float/double) + * @param float|int $c value */ - public function set($i = null, $j = null, $c = null) + public function set($i = null, $j = null, $c = null): void { // Optimized set version just has this $this->A[$i][$j] = $c; @@ -456,17 +454,6 @@ class Matrix return $s; } - /** - * uminus. - * - * Unary minus matrix -A - * - * @return Matrix Unary minus matrix - */ - public function uminus() - { - } - /** * plus. * @@ -1164,7 +1151,7 @@ class Matrix * * @return Matrix ... Solution if A is square, least squares solution otherwise */ - public function solve($B) + public function solve(self $B) { if ($this->m == $this->n) { $LU = new LUDecomposition($this); diff --git a/src/PhpSpreadsheet/Shared/JAMA/QRDecomposition.php b/src/PhpSpreadsheet/Shared/JAMA/QRDecomposition.php index 3bb8a10e..9b51f413 100644 --- a/src/PhpSpreadsheet/Shared/JAMA/QRDecomposition.php +++ b/src/PhpSpreadsheet/Shared/JAMA/QRDecomposition.php @@ -15,9 +15,9 @@ use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalculationException; * of simultaneous linear equations. This will fail if isFullRank() * returns false. * - * @author Paul Meagher + * @author Paul Meagher * - * @version 1.1 + * @version 1.1 */ class QRDecomposition { @@ -54,47 +54,43 @@ class QRDecomposition /** * QR Decomposition computed by Householder reflections. * - * @param matrix $A Rectangular matrix + * @param Matrix $A Rectangular matrix */ - public function __construct($A) + public function __construct(Matrix $A) { - if ($A instanceof Matrix) { - // Initialize. - $this->QR = $A->getArray(); - $this->m = $A->getRowDimension(); - $this->n = $A->getColumnDimension(); - // Main loop. - for ($k = 0; $k < $this->n; ++$k) { - // Compute 2-norm of k-th column without under/overflow. - $nrm = 0.0; - for ($i = $k; $i < $this->m; ++$i) { - $nrm = hypo($nrm, $this->QR[$i][$k]); - } - if ($nrm != 0.0) { - // Form k-th Householder vector. - if ($this->QR[$k][$k] < 0) { - $nrm = -$nrm; - } - for ($i = $k; $i < $this->m; ++$i) { - $this->QR[$i][$k] /= $nrm; - } - $this->QR[$k][$k] += 1.0; - // Apply transformation to remaining columns. - for ($j = $k + 1; $j < $this->n; ++$j) { - $s = 0.0; - for ($i = $k; $i < $this->m; ++$i) { - $s += $this->QR[$i][$k] * $this->QR[$i][$j]; - } - $s = -$s / $this->QR[$k][$k]; - for ($i = $k; $i < $this->m; ++$i) { - $this->QR[$i][$j] += $s * $this->QR[$i][$k]; - } - } - } - $this->Rdiag[$k] = -$nrm; + // Initialize. + $this->QR = $A->getArray(); + $this->m = $A->getRowDimension(); + $this->n = $A->getColumnDimension(); + // Main loop. + for ($k = 0; $k < $this->n; ++$k) { + // Compute 2-norm of k-th column without under/overflow. + $nrm = 0.0; + for ($i = $k; $i < $this->m; ++$i) { + $nrm = hypo($nrm, $this->QR[$i][$k]); } - } else { - throw new CalculationException(Matrix::ARGUMENT_TYPE_EXCEPTION); + if ($nrm != 0.0) { + // Form k-th Householder vector. + if ($this->QR[$k][$k] < 0) { + $nrm = -$nrm; + } + for ($i = $k; $i < $this->m; ++$i) { + $this->QR[$i][$k] /= $nrm; + } + $this->QR[$k][$k] += 1.0; + // Apply transformation to remaining columns. + for ($j = $k + 1; $j < $this->n; ++$j) { + $s = 0.0; + for ($i = $k; $i < $this->m; ++$i) { + $s += $this->QR[$i][$k] * $this->QR[$i][$j]; + } + $s = -$s / $this->QR[$k][$k]; + for ($i = $k; $i < $this->m; ++$i) { + $this->QR[$i][$j] += $s * $this->QR[$i][$k]; + } + } + } + $this->Rdiag[$k] = -$nrm; } } @@ -205,13 +201,13 @@ class QRDecomposition * * @return Matrix matrix that minimizes the two norm of Q*R*X-B */ - public function solve($B) + public function solve(Matrix $B) { if ($B->getRowDimension() == $this->m) { if ($this->isFullRank()) { // Copy right hand side $nx = $B->getColumnDimension(); - $X = $B->getArrayCopy(); + $X = $B->getArray(); // Compute Y = transpose(Q)*B for ($k = 0; $k < $this->n; ++$k) { for ($j = 0; $j < $nx; ++$j) { diff --git a/src/PhpSpreadsheet/Shared/JAMA/SingularValueDecomposition.php b/src/PhpSpreadsheet/Shared/JAMA/SingularValueDecomposition.php index b997fb7c..6c8999d0 100644 --- a/src/PhpSpreadsheet/Shared/JAMA/SingularValueDecomposition.php +++ b/src/PhpSpreadsheet/Shared/JAMA/SingularValueDecomposition.php @@ -65,7 +65,7 @@ class SingularValueDecomposition public function __construct($Arg) { // Initialize. - $A = $Arg->getArrayCopy(); + $A = $Arg->getArray(); $this->m = $Arg->getRowDimension(); $this->n = $Arg->getColumnDimension(); $nu = min($this->m, $this->n); @@ -476,6 +476,7 @@ class SingularValueDecomposition */ public function getS() { + $S = []; for ($i = 0; $i < $this->n; ++$i) { for ($j = 0; $j < $this->n; ++$j) { $S[$i][$j] = 0.0; diff --git a/src/PhpSpreadsheet/Shared/OLE.php b/src/PhpSpreadsheet/Shared/OLE.php index a8ed779f..ca975737 100644 --- a/src/PhpSpreadsheet/Shared/OLE.php +++ b/src/PhpSpreadsheet/Shared/OLE.php @@ -21,6 +21,7 @@ namespace PhpOffice\PhpSpreadsheet\Shared; // +----------------------------------------------------------------------+ // +use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException; use PhpOffice\PhpSpreadsheet\Shared\OLE\ChainedBlockStream; use PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\Root; @@ -227,7 +228,8 @@ class OLE // in OLE_ChainedBlockStream::stream_open(). // Object is removed from self::$instances in OLE_Stream::close(). $GLOBALS['_OLE_INSTANCES'][] = $this; - $instanceId = end(array_keys($GLOBALS['_OLE_INSTANCES'])); + $keys = array_keys($GLOBALS['_OLE_INSTANCES']); + $instanceId = end($keys); $path = 'ole-chainedblockstream://oleInstanceId=' . $instanceId; if ($blockIdOrPps instanceof OLE\PPS) { @@ -316,7 +318,7 @@ class OLE break; default: - break; + throw new Exception('Unsupported PPS type'); } fseek($fh, 1, SEEK_CUR); $pps->Type = $type; @@ -489,42 +491,33 @@ class OLE * Utility function * Returns a string for the OLE container with the date given. * - * @param int $date A timestamp + * @param float|int $date A timestamp * * @return string The string for the OLE container */ public static function localDateToOLE($date) { - if (!isset($date)) { + if (!$date) { return "\x00\x00\x00\x00\x00\x00\x00\x00"; } - - // factor used for separating numbers into 4 bytes parts - $factor = 2 ** 32; + $dateTime = Date::dateTimeFromTimestamp("$date"); // days from 1-1-1601 until the beggining of UNIX era $days = 134774; // calculate seconds - $big_date = $days * 24 * 3600 + mktime((int) date('H', $date), (int) date('i', $date), (int) date('s', $date), (int) date('m', $date), (int) date('d', $date), (int) date('Y', $date)); + $big_date = $days * 24 * 3600 + (float) $dateTime->format('U'); // multiply just to make MS happy $big_date *= 10000000; - $high_part = floor($big_date / $factor); - // lower 4 bytes - $low_part = floor((($big_date / $factor) - $high_part) * $factor); - // Make HEX string $res = ''; - for ($i = 0; $i < 4; ++$i) { - $hex = $low_part % 0x100; - $res .= pack('c', $hex); - $low_part /= 0x100; - } - for ($i = 0; $i < 4; ++$i) { - $hex = $high_part % 0x100; - $res .= pack('c', $hex); - $high_part /= 0x100; + $factor = 2 ** 56; + while ($factor >= 1) { + $hex = (int) floor($big_date / $factor); + $res = pack('c', $hex) . $res; + $big_date = fmod($big_date, $factor); + $factor /= 256; } return $res; @@ -535,7 +528,7 @@ class OLE * * @param string $oleTimestamp A binary string with the encoded date * - * @return int The Unix timestamp corresponding to the string + * @return float|int The Unix timestamp corresponding to the string */ public static function OLE2LocalDate($oleTimestamp) { @@ -558,9 +551,6 @@ class OLE // translate to seconds since 1970: $unixTimestamp = floor(65536.0 * 65536.0 * $timestampHigh + $timestampLow - $days * 24 * 3600 + 0.5); - $iTimestamp = (int) $unixTimestamp; - - // Overflow conditions can't happen on 64-bit system - return ($iTimestamp == $unixTimestamp) ? $iTimestamp : ($unixTimestamp >= 0.0 ? PHP_INT_MAX : PHP_INT_MIN); + return IntOrFloat::evaluate($unixTimestamp); } } diff --git a/src/PhpSpreadsheet/Shared/OLE/ChainedBlockStream.php b/src/PhpSpreadsheet/Shared/OLE/ChainedBlockStream.php index cee5cd99..43e4804d 100644 --- a/src/PhpSpreadsheet/Shared/OLE/ChainedBlockStream.php +++ b/src/PhpSpreadsheet/Shared/OLE/ChainedBlockStream.php @@ -9,7 +9,7 @@ class ChainedBlockStream /** * The OLE container of the file that is being read. * - * @var OLE + * @var null|OLE */ public $ole; @@ -42,7 +42,7 @@ class ChainedBlockStream * ole-chainedblockstream://oleInstanceId=1 * @param string $mode only "r" is supported * @param int $options mask of STREAM_REPORT_ERRORS and STREAM_USE_PATH - * @param string &$openedPath absolute path of the opened stream (out parameter) + * @param string $openedPath absolute path of the opened stream (out parameter) * * @return bool true on success */ @@ -112,7 +112,7 @@ class ChainedBlockStream * * @param int $count maximum number of bytes to read * - * @return string + * @return false|string */ public function stream_read($count) // @codingStandardsIgnoreLine { diff --git a/src/PhpSpreadsheet/Shared/OLE/PPS.php b/src/PhpSpreadsheet/Shared/OLE/PPS.php index cf764d0b..8b9e92a8 100644 --- a/src/PhpSpreadsheet/Shared/OLE/PPS.php +++ b/src/PhpSpreadsheet/Shared/OLE/PPS.php @@ -74,14 +74,14 @@ class PPS /** * A timestamp. * - * @var int + * @var float|int */ public $Time1st; /** * A timestamp. * - * @var int + * @var float|int */ public $Time2nd; @@ -129,8 +129,8 @@ class PPS * @param int $prev The index of the previous PPS * @param int $next The index of the next PPS * @param int $dir The index of it's first child if this is a Dir or Root PPS - * @param int $time_1st A timestamp - * @param int $time_2nd A timestamp + * @param null|float|int $time_1st A timestamp + * @param null|float|int $time_2nd A timestamp * @param string $data The (usually binary) source data of the PPS * @param array $children Array containing children PPS for this PPS */ @@ -142,8 +142,8 @@ class PPS $this->PrevPps = $prev; $this->NextPps = $next; $this->DirPps = $dir; - $this->Time1st = $time_1st; - $this->Time2nd = $time_2nd; + $this->Time1st = $time_1st ?? 0; + $this->Time2nd = $time_2nd ?? 0; $this->_data = $data; $this->children = $children; if ($data != '') { @@ -189,7 +189,7 @@ class PPS . "\x00\x00\x00\x00" // 100 . OLE::localDateToOLE($this->Time1st) // 108 . OLE::localDateToOLE($this->Time2nd) // 116 - . pack('V', isset($this->startBlock) ? $this->startBlock : 0) // 120 + . pack('V', $this->startBlock ?? 0) // 120 . pack('V', $this->Size) // 124 . pack('V', 0); // 128 @@ -200,7 +200,7 @@ class PPS * Updates index and pointers to previous, next and children PPS's for this * PPS. I don't think it'll work with Dir PPS's. * - * @param array &$raList Reference to the array of PPS's for the whole OLE + * @param array $raList Reference to the array of PPS's for the whole OLE * container * @param mixed $to_save * @param mixed $depth diff --git a/src/PhpSpreadsheet/Shared/OLE/PPS/Root.php b/src/PhpSpreadsheet/Shared/OLE/PPS/Root.php index 5466d2bc..c9b99a85 100644 --- a/src/PhpSpreadsheet/Shared/OLE/PPS/Root.php +++ b/src/PhpSpreadsheet/Shared/OLE/PPS/Root.php @@ -46,8 +46,8 @@ class Root extends PPS private $bigBlockSize; /** - * @param int $time_1st A timestamp - * @param int $time_2nd A timestamp + * @param null|float|int $time_1st A timestamp + * @param null|float|int $time_2nd A timestamp * @param File[] $raChild */ public function __construct($time_1st, $time_2nd, $raChild) @@ -237,7 +237,7 @@ class Root extends PPS * Saving big data (PPS's with data bigger than \PhpOffice\PhpSpreadsheet\Shared\OLE::OLE_DATA_SIZE_SMALL). * * @param int $iStBlk - * @param array &$raList Reference to array of PPS's + * @param array $raList Reference to array of PPS's */ private function saveBigData($iStBlk, &$raList): void { @@ -267,7 +267,7 @@ class Root extends PPS /** * get small data (PPS's with data smaller than \PhpOffice\PhpSpreadsheet\Shared\OLE::OLE_DATA_SIZE_SMALL). * - * @param array &$raList Reference to array of PPS's + * @param array $raList Reference to array of PPS's * * @return string */ diff --git a/src/PhpSpreadsheet/Shared/OLERead.php b/src/PhpSpreadsheet/Shared/OLERead.php index a431f89f..91f1d044 100644 --- a/src/PhpSpreadsheet/Shared/OLERead.php +++ b/src/PhpSpreadsheet/Shared/OLERead.php @@ -92,10 +92,8 @@ class OLERead /** * Read the file. - * - * @param $filename string Filename */ - public function read($filename): void + public function read(string $filename): void { File::assertFile($filename); @@ -190,7 +188,7 @@ class OLERead * * @param int $stream * - * @return string + * @return null|string */ public function getStream($stream) { diff --git a/src/PhpSpreadsheet/Shared/PasswordHasher.php b/src/PhpSpreadsheet/Shared/PasswordHasher.php index aa2c279a..0d58a868 100644 --- a/src/PhpSpreadsheet/Shared/PasswordHasher.php +++ b/src/PhpSpreadsheet/Shared/PasswordHasher.php @@ -2,11 +2,13 @@ namespace PhpOffice\PhpSpreadsheet\Shared; -use PhpOffice\PhpSpreadsheet\Exception; +use PhpOffice\PhpSpreadsheet\Exception as SpException; use PhpOffice\PhpSpreadsheet\Worksheet\Protection; class PasswordHasher { + const MAX_PASSWORD_LENGTH = 255; + /** * Get algorithm name for PHP. */ @@ -34,36 +36,40 @@ class PasswordHasher return $mapping[$algorithmName]; } - throw new Exception('Unsupported password algorithm: ' . $algorithmName); + throw new SpException('Unsupported password algorithm: ' . $algorithmName); } /** * Create a password hash from a given string. * - * This method is based on the algorithm provided by + * This method is based on the spec at: + * https://interoperability.blob.core.windows.net/files/MS-OFFCRYPTO/[MS-OFFCRYPTO].pdf + * 2.3.7.1 Binary Document Password Verifier Derivation Method 1 + * + * It replaces a method based on the algorithm provided by * Daniel Rentz of OpenOffice and the PEAR package * Spreadsheet_Excel_Writer by Xavier Noguer . * + * Scrutinizer will squawk at the use of bitwise operations here, + * but it should ultimately pass. + * * @param string $password Password to hash */ private static function defaultHashPassword(string $password): string { - $passwordValue = 0x0000; - $charPos = 1; // char position - - // split the plain text password in its component characters - $chars = preg_split('//', $password, -1, PREG_SPLIT_NO_EMPTY); - foreach ($chars as $char) { - $value = ord($char) << $charPos++; // shifted ASCII value - $rotated_bits = $value >> 15; // rotated bits beyond bit 15 - $value &= 0x7fff; // first 15 bits - $passwordValue ^= ($value | $rotated_bits); + $verifier = 0; + $pwlen = strlen($password); + $passwordArray = pack('c', $pwlen) . $password; + for ($i = $pwlen; $i >= 0; --$i) { + $intermediate1 = (($verifier & 0x4000) === 0) ? 0 : 1; + $intermediate2 = 2 * $verifier; + $intermediate2 = $intermediate2 & 0x7fff; + $intermediate3 = $intermediate1 | $intermediate2; + $verifier = $intermediate3 ^ ord($passwordArray[$i]); } + $verifier ^= 0xCE4B; - $passwordValue ^= strlen($password); - $passwordValue ^= 0xCE4B; - - return strtoupper(dechex($passwordValue)); + return strtoupper(dechex($verifier)); } /** @@ -82,6 +88,9 @@ class PasswordHasher */ public static function hashPassword(string $password, string $algorithm = '', string $salt = '', int $spinCount = 10000): string { + if (strlen($password) > self::MAX_PASSWORD_LENGTH) { + throw new SpException('Password exceeds ' . self::MAX_PASSWORD_LENGTH . ' characters'); + } $phpAlgorithm = self::getAlgorithm($algorithm); if (!$phpAlgorithm) { return self::defaultHashPassword($password); diff --git a/src/PhpSpreadsheet/Shared/StringHelper.php b/src/PhpSpreadsheet/Shared/StringHelper.php index 12bc82b0..d1422c76 100644 --- a/src/PhpSpreadsheet/Shared/StringHelper.php +++ b/src/PhpSpreadsheet/Shared/StringHelper.php @@ -464,7 +464,7 @@ class StringHelper */ public static function countCharacters($textValue, $encoding = 'UTF-8') { - return mb_strlen($textValue, $encoding); + return mb_strlen($textValue ?? '', $encoding); } /** @@ -502,7 +502,7 @@ class StringHelper */ public static function strToLower($textValue) { - return mb_convert_case($textValue, MB_CASE_LOWER, 'UTF-8'); + return mb_convert_case($textValue ?? '', MB_CASE_LOWER, 'UTF-8'); } /** @@ -556,7 +556,7 @@ class StringHelper * Identify whether a string contains a fractional numeric value, * and convert it to a numeric if it is. * - * @param string &$operand string value to test + * @param string $operand string value to test * * @return bool */ diff --git a/src/PhpSpreadsheet/Shared/TimeZone.php b/src/PhpSpreadsheet/Shared/TimeZone.php index 58b3e4eb..dabb88f2 100644 --- a/src/PhpSpreadsheet/Shared/TimeZone.php +++ b/src/PhpSpreadsheet/Shared/TimeZone.php @@ -58,24 +58,20 @@ class TimeZone * Return the Timezone offset used for date/time conversions to/from UST * This requires both the timezone and the calculated date/time to allow for local DST. * - * @param string $timezoneName The timezone for finding the adjustment to UST - * @param int $timestamp PHP date/time value + * @param ?string $timezoneName The timezone for finding the adjustment to UST + * @param float|int $timestamp PHP date/time value * * @return int Number of seconds for timezone adjustment */ public static function getTimeZoneAdjustment($timezoneName, $timestamp) { - if ($timezoneName !== null) { - if (!self::validateTimezone($timezoneName)) { - throw new PhpSpreadsheetException('Invalid timezone ' . $timezoneName); - } - } else { - $timezoneName = self::$timezone; + $timezoneName = $timezoneName ?? self::$timezone; + $dtobj = Date::dateTimeFromTimestamp("$timestamp"); + if (!self::validateTimezone($timezoneName)) { + throw new PhpSpreadsheetException("Invalid timezone $timezoneName"); } + $dtobj->setTimeZone(new DateTimeZone($timezoneName)); - $objTimezone = new DateTimeZone($timezoneName); - $transitions = $objTimezone->getTransitions($timestamp, $timestamp); - - return (count($transitions) > 0) ? $transitions[0]['offset'] : 0; + return $dtobj->getOffset(); } } diff --git a/src/PhpSpreadsheet/Shared/Trend/BestFit.php b/src/PhpSpreadsheet/Shared/Trend/BestFit.php index c9499722..7df48953 100644 --- a/src/PhpSpreadsheet/Shared/Trend/BestFit.php +++ b/src/PhpSpreadsheet/Shared/Trend/BestFit.php @@ -2,7 +2,7 @@ namespace PhpOffice\PhpSpreadsheet\Shared\Trend; -class BestFit +abstract class BestFit { /** * Indicator flag for a calculation error. @@ -96,24 +96,18 @@ class BestFit * * @param float $xValue X-Value * - * @return bool Y-Value + * @return float Y-Value */ - public function getValueOfYForX($xValue) - { - return false; - } + abstract public function getValueOfYForX($xValue); /** * Return the X-Value for a specified value of Y. * * @param float $yValue Y-Value * - * @return bool X-Value + * @return float X-Value */ - public function getValueOfXForY($yValue) - { - return false; - } + abstract public function getValueOfXForY($yValue); /** * Return the original set of X-Values. @@ -130,12 +124,9 @@ class BestFit * * @param int $dp Number of places of decimal precision to display * - * @return bool + * @return string */ - public function getEquation($dp = 0) - { - return false; - } + abstract public function getEquation($dp = 0); /** * Return the Slope of the line. @@ -348,13 +339,13 @@ class BestFit $bestFitY = $this->yBestFitValues[$xKey] = $this->getValueOfYForX($xValue); $SSres += ($this->yValues[$xKey] - $bestFitY) * ($this->yValues[$xKey] - $bestFitY); - if ($const) { + if ($const === true) { $SStot += ($this->yValues[$xKey] - $meanY) * ($this->yValues[$xKey] - $meanY); } else { $SStot += $this->yValues[$xKey] * $this->yValues[$xKey]; } $SScov += ($this->xValues[$xKey] - $meanX) * ($this->yValues[$xKey] - $meanY); - if ($const) { + if ($const === true) { $SSsex += ($this->xValues[$xKey] - $meanX) * ($this->xValues[$xKey] - $meanX); } else { $SSsex += $this->xValues[$xKey] * $this->xValues[$xKey]; @@ -362,7 +353,7 @@ class BestFit } $this->SSResiduals = $SSres; - $this->DFResiduals = $this->valueCount - 1 - $const; + $this->DFResiduals = $this->valueCount - 1 - ($const === true ? 1 : 0); if ($this->DFResiduals == 0.0) { $this->stdevOfResiduals = 0.0; @@ -395,27 +386,39 @@ class BestFit } } + private function sumSquares(array $values) + { + return array_sum( + array_map( + function ($value) { + return $value ** 2; + }, + $values + ) + ); + } + /** * @param float[] $yValues * @param float[] $xValues - * @param bool $const */ - protected function leastSquareFit(array $yValues, array $xValues, $const): void + protected function leastSquareFit(array $yValues, array $xValues, bool $const): void { // calculate sums - $x_sum = array_sum($xValues); - $y_sum = array_sum($yValues); - $meanX = $x_sum / $this->valueCount; - $meanY = $y_sum / $this->valueCount; - $mBase = $mDivisor = $xx_sum = $xy_sum = $yy_sum = 0.0; + $sumValuesX = array_sum($xValues); + $sumValuesY = array_sum($yValues); + $meanValueX = $sumValuesX / $this->valueCount; + $meanValueY = $sumValuesY / $this->valueCount; + $sumSquaresX = $this->sumSquares($xValues); + $sumSquaresY = $this->sumSquares($yValues); + $mBase = $mDivisor = 0.0; + $xy_sum = 0.0; for ($i = 0; $i < $this->valueCount; ++$i) { $xy_sum += $xValues[$i] * $yValues[$i]; - $xx_sum += $xValues[$i] * $xValues[$i]; - $yy_sum += $yValues[$i] * $yValues[$i]; - if ($const) { - $mBase += ($xValues[$i] - $meanX) * ($yValues[$i] - $meanY); - $mDivisor += ($xValues[$i] - $meanX) * ($xValues[$i] - $meanX); + if ($const === true) { + $mBase += ($xValues[$i] - $meanValueX) * ($yValues[$i] - $meanValueY); + $mDivisor += ($xValues[$i] - $meanValueX) * ($xValues[$i] - $meanValueX); } else { $mBase += $xValues[$i] * $yValues[$i]; $mDivisor += $xValues[$i] * $xValues[$i]; @@ -426,13 +429,9 @@ class BestFit $this->slope = $mBase / $mDivisor; // calculate intersect - if ($const) { - $this->intersect = $meanY - ($this->slope * $meanX); - } else { - $this->intersect = 0; - } + $this->intersect = ($const === true) ? $meanValueY - ($this->slope * $meanValueX) : 0.0; - $this->calculateGoodnessOfFit($x_sum, $y_sum, $xx_sum, $yy_sum, $xy_sum, $meanX, $meanY, $const); + $this->calculateGoodnessOfFit($sumValuesX, $sumValuesY, $sumSquaresX, $sumSquaresY, $xy_sum, $meanValueX, $meanValueY, $const); } /** @@ -440,23 +439,22 @@ class BestFit * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param bool $const */ - public function __construct($yValues, $xValues = [], $const = true) + public function __construct($yValues, $xValues = []) { // Calculate number of points - $nY = count($yValues); - $nX = count($xValues); + $yValueCount = count($yValues); + $xValueCount = count($xValues); // Define X Values if necessary - if ($nX == 0) { - $xValues = range(1, $nY); - } elseif ($nY != $nX) { + if ($xValueCount === 0) { + $xValues = range(1, $yValueCount); + } elseif ($yValueCount !== $xValueCount) { // Ensure both arrays of points are the same size $this->error = true; } - $this->valueCount = $nY; + $this->valueCount = $yValueCount; $this->xValues = $xValues; $this->yValues = $yValues; } diff --git a/src/PhpSpreadsheet/Shared/Trend/ExponentialBestFit.php b/src/PhpSpreadsheet/Shared/Trend/ExponentialBestFit.php index 82866dee..eb8cd746 100644 --- a/src/PhpSpreadsheet/Shared/Trend/ExponentialBestFit.php +++ b/src/PhpSpreadsheet/Shared/Trend/ExponentialBestFit.php @@ -88,20 +88,17 @@ class ExponentialBestFit extends BestFit * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param bool $const */ - private function exponentialRegression($yValues, $xValues, $const): void + private function exponentialRegression(array $yValues, array $xValues, bool $const): void { - foreach ($yValues as &$value) { - if ($value < 0.0) { - $value = 0 - log(abs($value)); - } elseif ($value > 0.0) { - $value = log($value); - } - } - unset($value); + $adjustedYValues = array_map( + function ($value) { + return ($value < 0.0) ? 0 - log(abs($value)) : log($value); + }, + $yValues + ); - $this->leastSquareFit($yValues, $xValues, $const); + $this->leastSquareFit($adjustedYValues, $xValues, $const); } /** @@ -116,7 +113,7 @@ class ExponentialBestFit extends BestFit parent::__construct($yValues, $xValues); if (!$this->error) { - $this->exponentialRegression($yValues, $xValues, $const); + $this->exponentialRegression($yValues, $xValues, (bool) $const); } } } diff --git a/src/PhpSpreadsheet/Shared/Trend/LinearBestFit.php b/src/PhpSpreadsheet/Shared/Trend/LinearBestFit.php index 26a562c5..65d6b4ff 100644 --- a/src/PhpSpreadsheet/Shared/Trend/LinearBestFit.php +++ b/src/PhpSpreadsheet/Shared/Trend/LinearBestFit.php @@ -56,9 +56,8 @@ class LinearBestFit extends BestFit * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param bool $const */ - private function linearRegression($yValues, $xValues, $const): void + private function linearRegression(array $yValues, array $xValues, bool $const): void { $this->leastSquareFit($yValues, $xValues, $const); } @@ -75,7 +74,7 @@ class LinearBestFit extends BestFit parent::__construct($yValues, $xValues); if (!$this->error) { - $this->linearRegression($yValues, $xValues, $const); + $this->linearRegression($yValues, $xValues, (bool) $const); } } } diff --git a/src/PhpSpreadsheet/Shared/Trend/LogarithmicBestFit.php b/src/PhpSpreadsheet/Shared/Trend/LogarithmicBestFit.php index c469067d..2366dc63 100644 --- a/src/PhpSpreadsheet/Shared/Trend/LogarithmicBestFit.php +++ b/src/PhpSpreadsheet/Shared/Trend/LogarithmicBestFit.php @@ -48,7 +48,7 @@ class LogarithmicBestFit extends BestFit $slope = $this->getSlope($dp); $intersect = $this->getIntersect($dp); - return 'Y = ' . $intersect . ' + ' . $slope . ' * log(X)'; + return 'Y = ' . $slope . ' * log(' . $intersect . ' * X)'; } /** @@ -56,20 +56,17 @@ class LogarithmicBestFit extends BestFit * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param bool $const */ - private function logarithmicRegression($yValues, $xValues, $const): void + private function logarithmicRegression(array $yValues, array $xValues, bool $const): void { - foreach ($xValues as &$value) { - if ($value < 0.0) { - $value = 0 - log(abs($value)); - } elseif ($value > 0.0) { - $value = log($value); - } - } - unset($value); + $adjustedYValues = array_map( + function ($value) { + return ($value < 0.0) ? 0 - log(abs($value)) : log($value); + }, + $yValues + ); - $this->leastSquareFit($yValues, $xValues, $const); + $this->leastSquareFit($adjustedYValues, $xValues, $const); } /** @@ -84,7 +81,7 @@ class LogarithmicBestFit extends BestFit parent::__construct($yValues, $xValues); if (!$this->error) { - $this->logarithmicRegression($yValues, $xValues, $const); + $this->logarithmicRegression($yValues, $xValues, (bool) $const); } } } diff --git a/src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php b/src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php index d959eddb..2c8eea5b 100644 --- a/src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php +++ b/src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php @@ -42,6 +42,7 @@ class PolynomialBestFit extends BestFit { $retVal = $this->getIntersect(); $slope = $this->getSlope(); + // @phpstan-ignore-next-line foreach ($slope as $key => $value) { if ($value != 0.0) { $retVal += $value * $xValue ** ($key + 1); @@ -76,6 +77,7 @@ class PolynomialBestFit extends BestFit $intersect = $this->getIntersect($dp); $equation = 'Y = ' . $intersect; + // @phpstan-ignore-next-line foreach ($slope as $key => $value) { if ($value != 0.0) { $equation .= ' + ' . $value . ' * X'; @@ -93,7 +95,7 @@ class PolynomialBestFit extends BestFit * * @param int $dp Number of places of decimal precision to display * - * @return string + * @return float */ public function getSlope($dp = 0) { @@ -103,6 +105,7 @@ class PolynomialBestFit extends BestFit $coefficients[] = round($coefficient, $dp); } + // @phpstan-ignore-next-line return $coefficients; } @@ -178,9 +181,8 @@ class PolynomialBestFit extends BestFit * @param int $order Order of Polynomial for this regression * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param bool $const */ - public function __construct($order, $yValues, $xValues = [], $const = true) + public function __construct($order, $yValues, $xValues = []) { parent::__construct($yValues, $xValues); diff --git a/src/PhpSpreadsheet/Shared/Trend/PowerBestFit.php b/src/PhpSpreadsheet/Shared/Trend/PowerBestFit.php index c53eab63..cafd0115 100644 --- a/src/PhpSpreadsheet/Shared/Trend/PowerBestFit.php +++ b/src/PhpSpreadsheet/Shared/Trend/PowerBestFit.php @@ -72,28 +72,23 @@ class PowerBestFit extends BestFit * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param bool $const */ - private function powerRegression($yValues, $xValues, $const): void + private function powerRegression(array $yValues, array $xValues, bool $const): void { - foreach ($xValues as &$value) { - if ($value < 0.0) { - $value = 0 - log(abs($value)); - } elseif ($value > 0.0) { - $value = log($value); - } - } - unset($value); - foreach ($yValues as &$value) { - if ($value < 0.0) { - $value = 0 - log(abs($value)); - } elseif ($value > 0.0) { - $value = log($value); - } - } - unset($value); + $adjustedYValues = array_map( + function ($value) { + return ($value < 0.0) ? 0 - log(abs($value)) : log($value); + }, + $yValues + ); + $adjustedXValues = array_map( + function ($value) { + return ($value < 0.0) ? 0 - log(abs($value)) : log($value); + }, + $xValues + ); - $this->leastSquareFit($yValues, $xValues, $const); + $this->leastSquareFit($adjustedYValues, $adjustedXValues, $const); } /** @@ -108,7 +103,7 @@ class PowerBestFit extends BestFit parent::__construct($yValues, $xValues); if (!$this->error) { - $this->powerRegression($yValues, $xValues, $const); + $this->powerRegression($yValues, $xValues, (bool) $const); } } } diff --git a/src/PhpSpreadsheet/Shared/Trend/Trend.php b/src/PhpSpreadsheet/Shared/Trend/Trend.php index 1b7b3901..61d1183a 100644 --- a/src/PhpSpreadsheet/Shared/Trend/Trend.php +++ b/src/PhpSpreadsheet/Shared/Trend/Trend.php @@ -44,7 +44,7 @@ class Trend /** * Cached results for each method when trying to identify which provides the best fit. * - * @var bestFit[] + * @var BestFit[] */ private static $trendCache = []; @@ -55,10 +55,9 @@ class Trend $nX = count($xValues); // Define X Values if necessary - if ($nX == 0) { + if ($nX === 0) { $xValues = range(1, $nY); - $nX = $nY; - } elseif ($nY != $nX) { + } elseif ($nY !== $nX) { // Ensure both arrays of points are the same size trigger_error('Trend(): Number of elements in coordinate arrays do not match.', E_USER_ERROR); } @@ -84,7 +83,7 @@ class Trend case self::TREND_POLYNOMIAL_6: if (!isset(self::$trendCache[$key])) { $order = substr($trendType, -1); - self::$trendCache[$key] = new PolynomialBestFit($order, $yValues, $xValues, $const); + self::$trendCache[$key] = new PolynomialBestFit($order, $yValues, $xValues); } return self::$trendCache[$key]; @@ -92,6 +91,8 @@ class Trend case self::TREND_BEST_FIT_NO_POLY: // If the request is to determine the best fit regression, then we test each Trend line in turn // Start by generating an instance of each available Trend method + $bestFit = []; + $bestFitValue = []; foreach (self::$trendTypes as $trendMethod) { $className = '\PhpOffice\PhpSpreadsheet\Shared\Trend\\' . $trendType . 'BestFit'; $bestFit[$trendMethod] = new $className($yValues, $xValues, $const); @@ -100,7 +101,7 @@ class Trend if ($trendType != self::TREND_BEST_FIT_NO_POLY) { foreach (self::$trendTypePolynomialOrders as $trendMethod) { $order = substr($trendMethod, -1); - $bestFit[$trendMethod] = new PolynomialBestFit($order, $yValues, $xValues, $const); + $bestFit[$trendMethod] = new PolynomialBestFit($order, $yValues, $xValues); if ($bestFit[$trendMethod]->getError()) { unset($bestFit[$trendMethod]); } else { diff --git a/src/PhpSpreadsheet/Shared/Xls.php b/src/PhpSpreadsheet/Shared/Xls.php index f6c95e72..2c3198b0 100644 --- a/src/PhpSpreadsheet/Shared/Xls.php +++ b/src/PhpSpreadsheet/Shared/Xls.php @@ -3,6 +3,7 @@ namespace PhpOffice\PhpSpreadsheet\Shared; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Helper\Dimension; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Xls @@ -76,12 +77,11 @@ class Xls } elseif ($worksheet->getDefaultRowDimension()->getRowHeight() != -1) { // then we have a default row dimension with explicit height $defaultRowDimension = $worksheet->getDefaultRowDimension(); - $rowHeight = $defaultRowDimension->getRowHeight(); - $pixelRowHeight = Drawing::pointsToPixels((int) $rowHeight); + $pixelRowHeight = $defaultRowDimension->getRowHeight(Dimension::UOM_PIXELS); } else { // we don't even have any default row dimension. Height depends on default font $pointRowHeight = Font::getDefaultRowHeightByFont($font); - $pixelRowHeight = Font::fontSizeToPixels($pointRowHeight); + $pixelRowHeight = Font::fontSizeToPixels((int) $pointRowHeight); } // now find the effective row height in pixels @@ -91,7 +91,7 @@ class Xls $effectivePixelRowHeight = $pixelRowHeight; } - return $effectivePixelRowHeight; + return (int) $effectivePixelRowHeight; } /** @@ -204,12 +204,11 @@ class Xls * @param int $width Width in pixels * @param int $height Height in pixels * - * @return array + * @return null|array */ public static function oneAnchor2twoAnchor(Worksheet $worksheet, $coordinates, $offsetX, $offsetY, $width, $height) { - [$column, $row] = Coordinate::coordinateFromString($coordinates); - $col_start = Coordinate::columnIndexFromString($column); + [$col_start, $row] = Coordinate::indexesFromString($coordinates); $row_start = $row - 1; $x1 = $offsetX; @@ -245,16 +244,16 @@ class Xls // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell // with zero height or width. if (self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start)) == 0) { - return; + return null; } if (self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end)) == 0) { - return; + return null; } if (self::sizeRow($worksheet, $row_start + 1) == 0) { - return; + return null; } if (self::sizeRow($worksheet, $row_end + 1) == 0) { - return; + return null; } // Convert the pixel values to the percentage value expected by Excel diff --git a/src/PhpSpreadsheet/Spreadsheet.php b/src/PhpSpreadsheet/Spreadsheet.php index 81ee3aa3..78efc789 100644 --- a/src/PhpSpreadsheet/Spreadsheet.php +++ b/src/PhpSpreadsheet/Spreadsheet.php @@ -55,7 +55,7 @@ class Spreadsheet /** * Calculation Engine. * - * @var Calculation + * @var null|Calculation */ private $calculationEngine; @@ -69,7 +69,7 @@ class Spreadsheet /** * Named ranges. * - * @var NamedRange[] + * @var DefinedName[] */ private $definedNames = []; @@ -104,21 +104,21 @@ class Spreadsheet /** * macrosCode : all macros code as binary data (the vbaProject.bin file, this include form, code, etc.), null if no macro. * - * @var string + * @var null|string */ private $macrosCode; /** * macrosCertificate : if macros are signed, contains binary data vbaProjectSignature.bin file, null if not signed. * - * @var string + * @var null|string */ private $macrosCertificate; /** * ribbonXMLData : null if workbook is'nt Excel 2007 or not contain a customized UI. * - * @var null|string + * @var null|array{target: string, data: string} */ private $ribbonXMLData; @@ -298,11 +298,9 @@ class Spreadsheet /** * retrieve ribbon XML Data. * - * return string|null|array - * * @param string $what * - * @return string + * @return null|array|string */ public function getRibbonXMLData($what = 'all') //we need some constants here... { @@ -373,7 +371,9 @@ class Spreadsheet */ private function getExtensionOnly($path) { - return pathinfo($path, PATHINFO_EXTENSION); + $extension = pathinfo($path, PATHINFO_EXTENSION); + + return is_array($extension) ? '' : $extension; } /** @@ -453,7 +453,7 @@ class Spreadsheet * * @param string $codeName Sheet name * - * @return Worksheet + * @return null|Worksheet */ public function getSheetByCodeName($codeName) { @@ -503,8 +503,10 @@ class Spreadsheet */ public function __destruct() { - $this->calculationEngine = null; $this->disconnectWorksheets(); + $this->calculationEngine = null; + $this->cellXfCollection = []; + $this->cellStyleXfCollection = []; } /** @@ -513,19 +515,17 @@ class Spreadsheet */ public function disconnectWorksheets(): void { - $worksheet = null; - foreach ($this->workSheetCollection as $k => &$worksheet) { + foreach ($this->workSheetCollection as $worksheet) { $worksheet->disconnectCells(); - $this->workSheetCollection[$k] = null; + unset($worksheet); } - unset($worksheet); $this->workSheetCollection = []; } /** * Return the calculation engine for this worksheet. * - * @return Calculation + * @return null|Calculation */ public function getCalculationEngine() { @@ -748,7 +748,7 @@ class Spreadsheet public function setIndexByName($worksheetName, $newIndexPosition) { $oldIndex = $this->getIndex($this->getSheetByName($worksheetName)); - $pSheet = array_splice( + $worksheet = array_splice( $this->workSheetCollection, $oldIndex, 1 @@ -757,7 +757,7 @@ class Spreadsheet $this->workSheetCollection, $newIndexPosition, 0, - $pSheet + $worksheet ); return $newIndexPosition; @@ -875,7 +875,7 @@ class Spreadsheet /** * Get an array of all Named Ranges. * - * @return NamedRange[] + * @return DefinedName[] */ public function getNamedRanges(): array { @@ -890,7 +890,7 @@ class Spreadsheet /** * Get an array of all Named Formulae. * - * @return NamedFormula[] + * @return DefinedName[] */ public function getNamedFormulae(): array { @@ -995,13 +995,13 @@ class Spreadsheet return null; } - private function getLocalDefinedNameByType(string $name, bool $type, ?Worksheet $pSheet = null): ?DefinedName + private function getLocalDefinedNameByType(string $name, bool $type, ?Worksheet $worksheet = null): ?DefinedName { if ( - ($pSheet !== null) && isset($this->definedNames[$pSheet->getTitle() . '!' . $name]) - && $this->definedNames[$pSheet->getTitle() . '!' . $name]->isFormula() === $type + ($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $name]) + && $this->definedNames[$worksheet->getTitle() . '!' . $name]->isFormula() === $type ) { - return $this->definedNames[$pSheet->getTitle() . '!' . $name]; + return $this->definedNames[$worksheet->getTitle() . '!' . $name]; } return null; @@ -1123,6 +1123,7 @@ class Spreadsheet */ public function __clone() { + // @phpstan-ignore-next-line foreach ($this as $key => $val) { if (is_object($val) || (is_array($val))) { $this->{$key} = unserialize(serialize($val)); @@ -1342,6 +1343,7 @@ class Spreadsheet // remove cellXfs without references and create mapping so we can update xfIndex // for all cells and columns $countNeededCellXfs = 0; + $map = []; foreach ($this->cellXfCollection as $index => $cellXf) { if ($countReferencesCellXf[$index] > 0 || $index == 0) { // we must never remove the first cellXf ++$countNeededCellXfs; diff --git a/src/PhpSpreadsheet/Style/Alignment.php b/src/PhpSpreadsheet/Style/Alignment.php index 43b0ead2..1b3ed6ac 100644 --- a/src/PhpSpreadsheet/Style/Alignment.php +++ b/src/PhpSpreadsheet/Style/Alignment.php @@ -35,21 +35,21 @@ class Alignment extends Supervisor /** * Horizontal alignment. * - * @var string + * @var null|string */ protected $horizontal = self::HORIZONTAL_GENERAL; /** * Vertical alignment. * - * @var string + * @var null|string */ protected $vertical = self::VERTICAL_BOTTOM; /** * Text rotation. * - * @var int + * @var null|int */ protected $textRotation = 0; @@ -179,7 +179,7 @@ class Alignment extends Supervisor /** * Get Horizontal. * - * @return string + * @return null|string */ public function getHorizontal() { @@ -216,7 +216,7 @@ class Alignment extends Supervisor /** * Get Vertical. * - * @return string + * @return null|string */ public function getVertical() { @@ -253,7 +253,7 @@ class Alignment extends Supervisor /** * Get TextRotation. * - * @return int + * @return null|int */ public function getTextRotation() { @@ -392,7 +392,8 @@ class Alignment extends Supervisor if ( $this->getHorizontal() != self::HORIZONTAL_GENERAL && $this->getHorizontal() != self::HORIZONTAL_LEFT && - $this->getHorizontal() != self::HORIZONTAL_RIGHT + $this->getHorizontal() != self::HORIZONTAL_RIGHT && + $this->getHorizontal() != self::HORIZONTAL_DISTRIBUTED ) { $indent = 0; // indent not supported } diff --git a/src/PhpSpreadsheet/Style/Border.php b/src/PhpSpreadsheet/Style/Border.php index b8f277e4..9fabf366 100644 --- a/src/PhpSpreadsheet/Style/Border.php +++ b/src/PhpSpreadsheet/Style/Border.php @@ -37,7 +37,7 @@ class Border extends Supervisor protected $color; /** - * @var int + * @var null|int */ public $colorIndex; @@ -47,11 +47,8 @@ class Border extends Supervisor * @param bool $isSupervisor Flag indicating if this is a supervisor or not * Leave this value at default unless you understand exactly what * its ramifications are - * @param bool $isConditional Flag indicating if this is a conditional style or not - * Leave this value at default unless you understand exactly what - * its ramifications are */ - public function __construct($isSupervisor = false, $isConditional = false) + public function __construct($isSupervisor = false) { // Supervisor? parent::__construct($isSupervisor); @@ -73,17 +70,19 @@ class Border extends Supervisor */ public function getSharedComponent() { + /** @var Borders $sharedComponent */ + $sharedComponent = $this->parent->getSharedComponent(); switch ($this->parentPropertyName) { case 'bottom': - return $this->parent->getSharedComponent()->getBottom(); + return $sharedComponent->getBottom(); case 'diagonal': - return $this->parent->getSharedComponent()->getDiagonal(); + return $sharedComponent->getDiagonal(); case 'left': - return $this->parent->getSharedComponent()->getLeft(); + return $sharedComponent->getLeft(); case 'right': - return $this->parent->getSharedComponent()->getRight(); + return $sharedComponent->getRight(); case 'top': - return $this->parent->getSharedComponent()->getTop(); + return $sharedComponent->getTop(); } throw new PhpSpreadsheetException('Cannot get shared component for a pseudo-border.'); @@ -163,7 +162,7 @@ class Border extends Supervisor if (empty($style)) { $style = self::BORDER_NONE; } elseif (is_bool($style)) { - $style = $style ? self::BORDER_MEDIUM : self::BORDER_NONE; + $style = self::BORDER_MEDIUM; } if ($this->isSupervisor) { diff --git a/src/PhpSpreadsheet/Style/Borders.php b/src/PhpSpreadsheet/Style/Borders.php index 1b1b6ab6..5d92f935 100644 --- a/src/PhpSpreadsheet/Style/Borders.php +++ b/src/PhpSpreadsheet/Style/Borders.php @@ -95,21 +95,18 @@ class Borders extends Supervisor * @param bool $isSupervisor Flag indicating if this is a supervisor or not * Leave this value at default unless you understand exactly what * its ramifications are - * @param bool $isConditional Flag indicating if this is a conditional style or not - * Leave this value at default unless you understand exactly what - * its ramifications are */ - public function __construct($isSupervisor = false, $isConditional = false) + public function __construct($isSupervisor = false) { // Supervisor? parent::__construct($isSupervisor); // Initialise values - $this->left = new Border($isSupervisor, $isConditional); - $this->right = new Border($isSupervisor, $isConditional); - $this->top = new Border($isSupervisor, $isConditional); - $this->bottom = new Border($isSupervisor, $isConditional); - $this->diagonal = new Border($isSupervisor, $isConditional); + $this->left = new Border($isSupervisor); + $this->right = new Border($isSupervisor); + $this->top = new Border($isSupervisor); + $this->bottom = new Border($isSupervisor); + $this->diagonal = new Border($isSupervisor); $this->diagonalDirection = self::DIAGONAL_NONE; // Specially for supervisor diff --git a/src/PhpSpreadsheet/Style/Color.php b/src/PhpSpreadsheet/Style/Color.php index e3defb6a..182eb15c 100644 --- a/src/PhpSpreadsheet/Style/Color.php +++ b/src/PhpSpreadsheet/Style/Color.php @@ -75,14 +75,16 @@ class Color extends Supervisor */ public function getSharedComponent() { + /** @var Border|Fill $sharedComponent */ + $sharedComponent = $this->parent->getSharedComponent(); if ($this->parentPropertyName === 'endColor') { - return $this->parent->getSharedComponent()->getEndColor(); + return $sharedComponent->getEndColor(); } if ($this->parentPropertyName === 'startColor') { - return $this->parent->getSharedComponent()->getStartColor(); + return $sharedComponent->getStartColor(); } - return $this->parent->getSharedComponent()->getColor(); + return $sharedComponent->getColor(); } /** @@ -132,10 +134,8 @@ class Color extends Supervisor /** * Get ARGB. - * - * @return string */ - public function getARGB(): ?string + public function getARGB(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getARGB(); @@ -171,16 +171,14 @@ class Color extends Supervisor /** * Get RGB. - * - * @return string */ - public function getRGB(): ?string + public function getRGB(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getRGB(); } - return substr($this->argb, 2); + return substr($this->argb ?? '', 2); } /** @@ -216,7 +214,7 @@ class Color extends Supervisor * @param bool $hex Flag indicating whether the component should be returned as a hex or a * decimal value * - * @return string The extracted colour component + * @return int|string The extracted colour component */ private static function getColourComponent($rgbValue, $offset, $hex = true) { @@ -232,7 +230,7 @@ class Color extends Supervisor * @param bool $hex Flag indicating whether the component should be returned as a hex or a * decimal value * - * @return string The red colour component + * @return int|string The red colour component */ public static function getRed($rgbValue, $hex = true) { @@ -246,7 +244,7 @@ class Color extends Supervisor * @param bool $hex Flag indicating whether the component should be returned as a hex or a * decimal value * - * @return string The green colour component + * @return int|string The green colour component */ public static function getGreen($rgbValue, $hex = true) { @@ -260,7 +258,7 @@ class Color extends Supervisor * @param bool $hex Flag indicating whether the component should be returned as a hex or a * decimal value * - * @return string The blue colour component + * @return int|string The blue colour component */ public static function getBlue($rgbValue, $hex = true) { @@ -280,8 +278,11 @@ class Color extends Supervisor $rgba = (strlen($hexColourValue) === 8); $adjustPercentage = max(-1.0, min(1.0, $adjustPercentage)); + /** @var int $red */ $red = self::getRed($hexColourValue, false); + /** @var int $green */ $green = self::getGreen($hexColourValue, false); + /** @var int $blue */ $blue = self::getBlue($hexColourValue, false); if ($adjustPercentage > 0) { $red += (255 - $red) * $adjustPercentage; @@ -307,7 +308,7 @@ class Color extends Supervisor * * @param int $colorIndex Index entry point into the colour array * @param bool $background Flag to indicate whether default background or foreground colour - * should be returned if the indexed colour doesn't exist + * should be returned if the indexed colour doesn't exist * * @return Color */ diff --git a/src/PhpSpreadsheet/Style/Conditional.php b/src/PhpSpreadsheet/Style/Conditional.php index 25c39dff..3f84a4c9 100644 --- a/src/PhpSpreadsheet/Style/Conditional.php +++ b/src/PhpSpreadsheet/Style/Conditional.php @@ -3,6 +3,7 @@ namespace PhpOffice\PhpSpreadsheet\Style; use PhpOffice\PhpSpreadsheet\IComparable; +use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalDataBar; class Conditional implements IComparable { @@ -13,6 +14,19 @@ class Conditional implements IComparable const CONDITION_EXPRESSION = 'expression'; const CONDITION_CONTAINSBLANKS = 'containsBlanks'; const CONDITION_NOTCONTAINSBLANKS = 'notContainsBlanks'; + const CONDITION_DATABAR = 'dataBar'; + const CONDITION_NOTCONTAINSTEXT = 'notContainsText'; + + private const CONDITION_TYPES = [ + self::CONDITION_CELLIS, + self::CONDITION_CONTAINSBLANKS, + self::CONDITION_CONTAINSTEXT, + self::CONDITION_DATABAR, + self::CONDITION_EXPRESSION, + self::CONDITION_NONE, + self::CONDITION_NOTCONTAINSBLANKS, + self::CONDITION_NOTCONTAINSTEXT, + ]; // Operator types const OPERATOR_NONE = ''; @@ -64,6 +78,11 @@ class Conditional implements IComparable */ private $condition = []; + /** + * @var ConditionalDataBar + */ + private $dataBar; + /** * Style. * @@ -206,13 +225,13 @@ class Conditional implements IComparable /** * Add Condition. * - * @param string $comdition Condition + * @param string $condition Condition * * @return $this */ - public function addCondition($comdition) + public function addCondition($condition) { - $this->condition[] = $comdition; + $this->condition[] = $condition; return $this; } @@ -241,6 +260,28 @@ class Conditional implements IComparable return $this; } + /** + * get DataBar. + * + * @return null|ConditionalDataBar + */ + public function getDataBar() + { + return $this->dataBar; + } + + /** + * set DataBar. + * + * @return $this + */ + public function setDataBar(ConditionalDataBar $dataBar) + { + $this->dataBar = $dataBar; + + return $this; + } + /** * Get hash code. * @@ -271,4 +312,12 @@ class Conditional implements IComparable } } } + + /** + * Verify if param is valid condition type. + */ + public static function isValidConditionType(string $type): bool + { + return in_array($type, self::CONDITION_TYPES); + } } diff --git a/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php b/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php new file mode 100644 index 00000000..54513670 --- /dev/null +++ b/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php @@ -0,0 +1,102 @@ + attribute */ + + /** @var null|bool */ + private $showValue; + + /** children */ + + /** @var ConditionalFormatValueObject */ + private $minimumConditionalFormatValueObject; + + /** @var ConditionalFormatValueObject */ + private $maximumConditionalFormatValueObject; + + /** @var string */ + private $color; + + /** */ + + /** @var ConditionalFormattingRuleExtension */ + private $conditionalFormattingRuleExt; + + /** + * @return null|bool + */ + public function getShowValue() + { + return $this->showValue; + } + + /** + * @param bool $showValue + */ + public function setShowValue($showValue) + { + $this->showValue = $showValue; + + return $this; + } + + /** + * @return ConditionalFormatValueObject + */ + public function getMinimumConditionalFormatValueObject() + { + return $this->minimumConditionalFormatValueObject; + } + + public function setMinimumConditionalFormatValueObject(ConditionalFormatValueObject $minimumConditionalFormatValueObject) + { + $this->minimumConditionalFormatValueObject = $minimumConditionalFormatValueObject; + + return $this; + } + + /** + * @return ConditionalFormatValueObject + */ + public function getMaximumConditionalFormatValueObject() + { + return $this->maximumConditionalFormatValueObject; + } + + public function setMaximumConditionalFormatValueObject(ConditionalFormatValueObject $maximumConditionalFormatValueObject) + { + $this->maximumConditionalFormatValueObject = $maximumConditionalFormatValueObject; + + return $this; + } + + public function getColor(): string + { + return $this->color; + } + + public function setColor(string $color): self + { + $this->color = $color; + + return $this; + } + + /** + * @return ConditionalFormattingRuleExtension + */ + public function getConditionalFormattingRuleExt() + { + return $this->conditionalFormattingRuleExt; + } + + public function setConditionalFormattingRuleExt(ConditionalFormattingRuleExtension $conditionalFormattingRuleExt) + { + $this->conditionalFormattingRuleExt = $conditionalFormattingRuleExt; + + return $this; + } +} diff --git a/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php b/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php new file mode 100644 index 00000000..c709cf3e --- /dev/null +++ b/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php @@ -0,0 +1,290 @@ + attributes */ + + /** @var int */ + private $minLength; + + /** @var int */ + private $maxLength; + + /** @var null|bool */ + private $border; + + /** @var null|bool */ + private $gradient; + + /** @var string */ + private $direction; + + /** @var null|bool */ + private $negativeBarBorderColorSameAsPositive; + + /** @var string */ + private $axisPosition; + + // children + + /** @var ConditionalFormatValueObject */ + private $maximumConditionalFormatValueObject; + + /** @var ConditionalFormatValueObject */ + private $minimumConditionalFormatValueObject; + + /** @var string */ + private $borderColor; + + /** @var string */ + private $negativeFillColor; + + /** @var string */ + private $negativeBorderColor; + + /** @var array */ + private $axisColor = [ + 'rgb' => null, + 'theme' => null, + 'tint' => null, + ]; + + public function getXmlAttributes() + { + $ret = []; + foreach (['minLength', 'maxLength', 'direction', 'axisPosition'] as $attrKey) { + if (null !== $this->{$attrKey}) { + $ret[$attrKey] = $this->{$attrKey}; + } + } + foreach (['border', 'gradient', 'negativeBarBorderColorSameAsPositive'] as $attrKey) { + if (null !== $this->{$attrKey}) { + $ret[$attrKey] = $this->{$attrKey} ? '1' : '0'; + } + } + + return $ret; + } + + public function getXmlElements() + { + $ret = []; + $elms = ['borderColor', 'negativeFillColor', 'negativeBorderColor']; + foreach ($elms as $elmKey) { + if (null !== $this->{$elmKey}) { + $ret[$elmKey] = ['rgb' => $this->{$elmKey}]; + } + } + foreach (array_filter($this->axisColor) as $attrKey => $axisColorAttr) { + if (!isset($ret['axisColor'])) { + $ret['axisColor'] = []; + } + $ret['axisColor'][$attrKey] = $axisColorAttr; + } + + return $ret; + } + + /** + * @return int + */ + public function getMinLength() + { + return $this->minLength; + } + + public function setMinLength(int $minLength): self + { + $this->minLength = $minLength; + + return $this; + } + + /** + * @return int + */ + public function getMaxLength() + { + return $this->maxLength; + } + + public function setMaxLength(int $maxLength): self + { + $this->maxLength = $maxLength; + + return $this; + } + + /** + * @return null|bool + */ + public function getBorder() + { + return $this->border; + } + + public function setBorder(bool $border): self + { + $this->border = $border; + + return $this; + } + + /** + * @return null|bool + */ + public function getGradient() + { + return $this->gradient; + } + + public function setGradient(bool $gradient): self + { + $this->gradient = $gradient; + + return $this; + } + + /** + * @return string + */ + public function getDirection() + { + return $this->direction; + } + + public function setDirection(string $direction): self + { + $this->direction = $direction; + + return $this; + } + + /** + * @return null|bool + */ + public function getNegativeBarBorderColorSameAsPositive() + { + return $this->negativeBarBorderColorSameAsPositive; + } + + public function setNegativeBarBorderColorSameAsPositive(bool $negativeBarBorderColorSameAsPositive): self + { + $this->negativeBarBorderColorSameAsPositive = $negativeBarBorderColorSameAsPositive; + + return $this; + } + + /** + * @return string + */ + public function getAxisPosition() + { + return $this->axisPosition; + } + + public function setAxisPosition(string $axisPosition): self + { + $this->axisPosition = $axisPosition; + + return $this; + } + + /** + * @return ConditionalFormatValueObject + */ + public function getMaximumConditionalFormatValueObject() + { + return $this->maximumConditionalFormatValueObject; + } + + public function setMaximumConditionalFormatValueObject(ConditionalFormatValueObject $maximumConditionalFormatValueObject) + { + $this->maximumConditionalFormatValueObject = $maximumConditionalFormatValueObject; + + return $this; + } + + /** + * @return ConditionalFormatValueObject + */ + public function getMinimumConditionalFormatValueObject() + { + return $this->minimumConditionalFormatValueObject; + } + + public function setMinimumConditionalFormatValueObject(ConditionalFormatValueObject $minimumConditionalFormatValueObject) + { + $this->minimumConditionalFormatValueObject = $minimumConditionalFormatValueObject; + + return $this; + } + + /** + * @return string + */ + public function getBorderColor() + { + return $this->borderColor; + } + + public function setBorderColor(string $borderColor): self + { + $this->borderColor = $borderColor; + + return $this; + } + + /** + * @return string + */ + public function getNegativeFillColor() + { + return $this->negativeFillColor; + } + + public function setNegativeFillColor(string $negativeFillColor): self + { + $this->negativeFillColor = $negativeFillColor; + + return $this; + } + + /** + * @return string + */ + public function getNegativeBorderColor() + { + return $this->negativeBorderColor; + } + + public function setNegativeBorderColor(string $negativeBorderColor): self + { + $this->negativeBorderColor = $negativeBorderColor; + + return $this; + } + + public function getAxisColor(): array + { + return $this->axisColor; + } + + /** + * @param mixed $rgb + * @param null|mixed $theme + * @param null|mixed $tint + */ + public function setAxisColor($rgb, $theme = null, $tint = null): self + { + $this->axisColor = [ + 'rgb' => $rgb, + 'theme' => $theme, + 'tint' => $tint, + ]; + + return $this; + } +} diff --git a/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php b/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php new file mode 100644 index 00000000..107969bf --- /dev/null +++ b/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php @@ -0,0 +1,78 @@ +type = $type; + $this->value = $value; + $this->cellFormula = $cellFormula; + } + + /** + * @return mixed + */ + public function getType() + { + return $this->type; + } + + /** + * @param mixed $type + */ + public function setType($type) + { + $this->type = $type; + + return $this; + } + + /** + * @return mixed + */ + public function getValue() + { + return $this->value; + } + + /** + * @param mixed $value + */ + public function setValue($value) + { + $this->value = $value; + + return $this; + } + + /** + * @return mixed + */ + public function getCellFormula() + { + return $this->cellFormula; + } + + /** + * @param mixed $cellFormula + */ + public function setCellFormula($cellFormula) + { + $this->cellFormula = $cellFormula; + + return $this; + } +} diff --git a/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php b/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php new file mode 100644 index 00000000..d8ef990c --- /dev/null +++ b/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php @@ -0,0 +1,208 @@ + attributes */ + private $id; + + /** @var string Conditional Formatting Rule */ + private $cfRule; + + /** children */ + + /** @var ConditionalDataBarExtension */ + private $dataBar; + + /** @var string Sequence of References */ + private $sqref; + + /** + * ConditionalFormattingRuleExtension constructor. + */ + public function __construct($id = null, string $cfRule = self::CONDITION_EXTENSION_DATABAR) + { + if (null === $id) { + $this->id = '{' . $this->generateUuid() . '}'; + } else { + $this->id = $id; + } + $this->cfRule = $cfRule; + } + + private function generateUuid() + { + $chars = str_split('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'); + + foreach ($chars as $i => $char) { + if ($char === 'x') { + $chars[$i] = dechex(random_int(0, 15)); + } elseif ($char === 'y') { + $chars[$i] = dechex(random_int(8, 11)); + } + } + + return implode('', $chars); + } + + public static function parseExtLstXml($extLstXml) + { + $conditionalFormattingRuleExtensions = []; + $conditionalFormattingRuleExtensionXml = null; + if ($extLstXml instanceof SimpleXMLElement) { + foreach ((count($extLstXml) > 0 ? $extLstXml : [$extLstXml]) as $extLst) { + //this uri is conditionalFormattings + //https://docs.microsoft.com/en-us/openspecs/office_standards/ms-xlsx/07d607af-5618-4ca2-b683-6a78dc0d9627 + if (isset($extLst->ext['uri']) && (string) $extLst->ext['uri'] === '{78C0D931-6437-407d-A8EE-F0AAD7539E65}') { + $conditionalFormattingRuleExtensionXml = $extLst->ext; + } + } + + if ($conditionalFormattingRuleExtensionXml) { + $ns = $conditionalFormattingRuleExtensionXml->getNamespaces(true); + $extFormattingsXml = $conditionalFormattingRuleExtensionXml->children($ns['x14']); + + foreach ($extFormattingsXml->children($ns['x14']) as $extFormattingXml) { + $extCfRuleXml = $extFormattingXml->cfRule; + $attributes = $extCfRuleXml->attributes(); + if (!$attributes || ((string) $attributes->type) !== Conditional::CONDITION_DATABAR) { + continue; + } + + $extFormattingRuleObj = new self((string) $attributes->id); + $extFormattingRuleObj->setSqref((string) $extFormattingXml->children($ns['xm'])->sqref); + $conditionalFormattingRuleExtensions[$extFormattingRuleObj->getId()] = $extFormattingRuleObj; + + $extDataBarObj = new ConditionalDataBarExtension(); + $extFormattingRuleObj->setDataBarExt($extDataBarObj); + $dataBarXml = $extCfRuleXml->dataBar; + self::parseExtDataBarAttributesFromXml($extDataBarObj, $dataBarXml); + self::parseExtDataBarElementChildrenFromXml($extDataBarObj, $dataBarXml, $ns); + } + } + } + + return $conditionalFormattingRuleExtensions; + } + + private static function parseExtDataBarAttributesFromXml( + ConditionalDataBarExtension $extDataBarObj, + SimpleXMLElement $dataBarXml + ): void { + $dataBarAttribute = $dataBarXml->attributes(); + if ($dataBarAttribute->minLength) { + $extDataBarObj->setMinLength((int) $dataBarAttribute->minLength); + } + if ($dataBarAttribute->maxLength) { + $extDataBarObj->setMaxLength((int) $dataBarAttribute->maxLength); + } + if ($dataBarAttribute->border) { + $extDataBarObj->setBorder((bool) (string) $dataBarAttribute->border); + } + if ($dataBarAttribute->gradient) { + $extDataBarObj->setGradient((bool) (string) $dataBarAttribute->gradient); + } + if ($dataBarAttribute->direction) { + $extDataBarObj->setDirection((string) $dataBarAttribute->direction); + } + if ($dataBarAttribute->negativeBarBorderColorSameAsPositive) { + $extDataBarObj->setNegativeBarBorderColorSameAsPositive((bool) (string) $dataBarAttribute->negativeBarBorderColorSameAsPositive); + } + if ($dataBarAttribute->axisPosition) { + $extDataBarObj->setAxisPosition((string) $dataBarAttribute->axisPosition); + } + } + + private static function parseExtDataBarElementChildrenFromXml(ConditionalDataBarExtension $extDataBarObj, SimpleXMLElement $dataBarXml, $ns): void + { + if ($dataBarXml->borderColor) { + $extDataBarObj->setBorderColor((string) $dataBarXml->borderColor->attributes()['rgb']); + } + if ($dataBarXml->negativeFillColor) { + $extDataBarObj->setNegativeFillColor((string) $dataBarXml->negativeFillColor->attributes()['rgb']); + } + if ($dataBarXml->negativeBorderColor) { + $extDataBarObj->setNegativeBorderColor((string) $dataBarXml->negativeBorderColor->attributes()['rgb']); + } + if ($dataBarXml->axisColor) { + $axisColorAttr = $dataBarXml->axisColor->attributes(); + $extDataBarObj->setAxisColor((string) $axisColorAttr['rgb'], (string) $axisColorAttr['theme'], (string) $axisColorAttr['tint']); + } + $cfvoIndex = 0; + foreach ($dataBarXml->cfvo as $cfvo) { + $f = (string) $cfvo->children($ns['xm'])->f; + $attributes = $cfvo->attributes(); + if (!($attributes)) { + continue; + } + + if ($cfvoIndex === 0) { + $extDataBarObj->setMinimumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $attributes['type'], null, (empty($f) ? null : $f))); + } + if ($cfvoIndex === 1) { + $extDataBarObj->setMaximumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $attributes['type'], null, (empty($f) ? null : $f))); + } + ++$cfvoIndex; + } + } + + /** + * @return mixed + */ + public function getId() + { + return $this->id; + } + + /** + * @param mixed $id + */ + public function setId($id): self + { + $this->id = $id; + + return $this; + } + + public function getCfRule(): string + { + return $this->cfRule; + } + + public function setCfRule(string $cfRule): self + { + $this->cfRule = $cfRule; + + return $this; + } + + public function getDataBarExt(): ConditionalDataBarExtension + { + return $this->dataBar; + } + + public function setDataBarExt(ConditionalDataBarExtension $dataBar): self + { + $this->dataBar = $dataBar; + + return $this; + } + + public function getSqref(): string + { + return $this->sqref; + } + + public function setSqref(string $sqref): self + { + $this->sqref = $sqref; + + return $this; + } +} diff --git a/src/PhpSpreadsheet/Style/Fill.php b/src/PhpSpreadsheet/Style/Fill.php index 29ff05a7..1a7331eb 100644 --- a/src/PhpSpreadsheet/Style/Fill.php +++ b/src/PhpSpreadsheet/Style/Fill.php @@ -28,19 +28,19 @@ class Fill extends Supervisor const FILL_PATTERN_MEDIUMGRAY = 'mediumGray'; /** - * @var int + * @var null|int */ public $startcolorIndex; /** - * @var int + * @var null|int */ public $endcolorIndex; /** * Fill type. * - * @var string + * @var null|string */ protected $fillType = self::FILL_NONE; @@ -168,7 +168,7 @@ class Fill extends Supervisor /** * Get Fill Type. * - * @return string + * @return null|string */ public function getFillType() { diff --git a/src/PhpSpreadsheet/Style/Font.php b/src/PhpSpreadsheet/Style/Font.php index 969cc96a..63a75cc5 100644 --- a/src/PhpSpreadsheet/Style/Font.php +++ b/src/PhpSpreadsheet/Style/Font.php @@ -14,56 +14,56 @@ class Font extends Supervisor /** * Font Name. * - * @var string + * @var null|string */ protected $name = 'Calibri'; /** * Font Size. * - * @var float + * @var null|float */ protected $size = 11; /** * Bold. * - * @var bool + * @var null|bool */ protected $bold = false; /** * Italic. * - * @var bool + * @var null|bool */ protected $italic = false; /** * Superscript. * - * @var bool + * @var null|bool */ protected $superscript = false; /** * Subscript. * - * @var bool + * @var null|bool */ protected $subscript = false; /** * Underline. * - * @var string + * @var null|string */ protected $underline = self::UNDERLINE_NONE; /** * Strikethrough. * - * @var bool + * @var null|bool */ protected $strikethrough = false; @@ -75,7 +75,7 @@ class Font extends Supervisor protected $color; /** - * @var int + * @var null|int */ public $colorIndex; @@ -199,7 +199,7 @@ class Font extends Supervisor /** * Get Name. * - * @return string + * @return null|string */ public function getName() { @@ -213,20 +213,20 @@ class Font extends Supervisor /** * Set Name. * - * @param string $fontName + * @param string $fontname * * @return $this */ - public function setName($fontName) + public function setName($fontname) { - if ($fontName == '') { - $fontName = 'Calibri'; + if ($fontname == '') { + $fontname = 'Calibri'; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['name' => $fontName]); + $styleArray = $this->getStyleArray(['name' => $fontname]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->name = $fontName; + $this->name = $fontname; } return $this; @@ -235,7 +235,7 @@ class Font extends Supervisor /** * Get Size. * - * @return float + * @return null|float */ public function getSize() { @@ -249,20 +249,27 @@ class Font extends Supervisor /** * Set Size. * - * @param float $fontSize + * @param mixed $sizeInPoints A float representing the value of a positive measurement in points (1/72 of an inch) * * @return $this */ - public function setSize($fontSize) + public function setSize($sizeInPoints) { - if ($fontSize == '') { - $fontSize = 10; + if (is_string($sizeInPoints) || is_int($sizeInPoints)) { + $sizeInPoints = (float) $sizeInPoints; // $pValue = 0 if given string is not numeric } + + // Size must be a positive floating point number + // ECMA-376-1:2016, part 1, chapter 18.4.11 sz (Font Size), p. 1536 + if (!is_float($sizeInPoints) || !($sizeInPoints > 0)) { + $sizeInPoints = 10.0; + } + if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['size' => $fontSize]); + $styleArray = $this->getStyleArray(['size' => $sizeInPoints]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->size = $fontSize; + $this->size = $sizeInPoints; } return $this; @@ -271,7 +278,7 @@ class Font extends Supervisor /** * Get Bold. * - * @return bool + * @return null|bool */ public function getBold() { @@ -307,7 +314,7 @@ class Font extends Supervisor /** * Get Italic. * - * @return bool + * @return null|bool */ public function getItalic() { @@ -343,7 +350,7 @@ class Font extends Supervisor /** * Get Superscript. * - * @return bool + * @return null|bool */ public function getSuperscript() { @@ -377,7 +384,7 @@ class Font extends Supervisor /** * Get Subscript. * - * @return bool + * @return null|bool */ public function getSubscript() { @@ -411,7 +418,7 @@ class Font extends Supervisor /** * Get Underline. * - * @return string + * @return null|string */ public function getUnderline() { @@ -451,7 +458,7 @@ class Font extends Supervisor /** * Get Strikethrough. * - * @return bool + * @return null|bool */ public function getStrikethrough() { diff --git a/src/PhpSpreadsheet/Style/NumberFormat.php b/src/PhpSpreadsheet/Style/NumberFormat.php index d00a352a..a4569283 100644 --- a/src/PhpSpreadsheet/Style/NumberFormat.php +++ b/src/PhpSpreadsheet/Style/NumberFormat.php @@ -2,10 +2,6 @@ namespace PhpOffice\PhpSpreadsheet\Style; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PhpOffice\PhpSpreadsheet\Shared\StringHelper; - class NumberFormat extends Supervisor { // Pre-defined formats @@ -68,14 +64,14 @@ class NumberFormat extends Supervisor /** * Format Code. * - * @var string + * @var null|string */ protected $formatCode = self::FORMAT_GENERAL; /** * Built-in format Code. * - * @var string + * @var false|int */ protected $builtInFormatCode = 0; @@ -154,7 +150,7 @@ class NumberFormat extends Supervisor /** * Get Format Code. * - * @return string + * @return null|string */ public function getFormatCode() { @@ -194,7 +190,7 @@ class NumberFormat extends Supervisor /** * Get Built-In Format Code. * - * @return int + * @return false|int */ public function getBuiltInFormatCode() { @@ -389,428 +385,6 @@ class NumberFormat extends Supervisor ); } - /** - * Search/replace values to convert Excel date/time format masks to PHP format masks. - * - * @var array - */ - private static $dateFormatReplacements = [ - // first remove escapes related to non-format characters - '\\' => '', - // 12-hour suffix - 'am/pm' => 'A', - // 4-digit year - 'e' => 'Y', - 'yyyy' => 'Y', - // 2-digit year - 'yy' => 'y', - // first letter of month - no php equivalent - 'mmmmm' => 'M', - // full month name - 'mmmm' => 'F', - // short month name - 'mmm' => 'M', - // mm is minutes if time, but can also be month w/leading zero - // so we try to identify times be the inclusion of a : separator in the mask - // It isn't perfect, but the best way I know how - ':mm' => ':i', - 'mm:' => 'i:', - // month leading zero - 'mm' => 'm', - // month no leading zero - 'm' => 'n', - // full day of week name - 'dddd' => 'l', - // short day of week name - 'ddd' => 'D', - // days leading zero - 'dd' => 'd', - // days no leading zero - 'd' => 'j', - // seconds - 'ss' => 's', - // fractional seconds - no php equivalent - '.s' => '', - ]; - - /** - * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock). - * - * @var array - */ - private static $dateFormatReplacements24 = [ - 'hh' => 'H', - 'h' => 'G', - ]; - - /** - * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock). - * - * @var array - */ - private static $dateFormatReplacements12 = [ - 'hh' => 'h', - 'h' => 'g', - ]; - - private static function setLowercaseCallback($matches) - { - return mb_strtolower($matches[0]); - } - - private static function escapeQuotesCallback($matches) - { - return '\\' . implode('\\', str_split($matches[1])); - } - - private static function formatAsDate(&$value, &$format): void - { - // strip off first part containing e.g. [$-F800] or [$USD-409] - // general syntax: [$-] - // language info is in hexadecimal - // strip off chinese part like [DBNum1][$-804] - $format = preg_replace('/^(\[[0-9A-Za-z]*\])*(\[\$[A-Z]*-[0-9A-F]*\])/i', '', $format); - - // OpenOffice.org uses upper-case number formats, e.g. 'YYYY', convert to lower-case; - // but we don't want to change any quoted strings - $format = preg_replace_callback('/(?:^|")([^"]*)(?:$|")/', ['self', 'setLowercaseCallback'], $format); - - // Only process the non-quoted blocks for date format characters - $blocks = explode('"', $format); - foreach ($blocks as $key => &$block) { - if ($key % 2 == 0) { - $block = strtr($block, self::$dateFormatReplacements); - if (!strpos($block, 'A')) { - // 24-hour time format - // when [h]:mm format, the [h] should replace to the hours of the value * 24 - if (false !== strpos($block, '[h]')) { - $hours = (int) ($value * 24); - $block = str_replace('[h]', $hours, $block); - - continue; - } - $block = strtr($block, self::$dateFormatReplacements24); - } else { - // 12-hour time format - $block = strtr($block, self::$dateFormatReplacements12); - } - } - } - $format = implode('"', $blocks); - - // escape any quoted characters so that DateTime format() will render them correctly - $format = preg_replace_callback('/"(.*)"/U', ['self', 'escapeQuotesCallback'], $format); - - $dateObj = Date::excelToDateTimeObject($value); - $value = $dateObj->format($format); - } - - private static function formatAsPercentage(&$value, &$format): void - { - if ($format === self::FORMAT_PERCENTAGE) { - $value = round((100 * $value), 0) . '%'; - } else { - if (preg_match('/\.[#0]+/', $format, $m)) { - $s = substr($m[0], 0, 1) . (strlen($m[0]) - 1); - $format = str_replace($m[0], $s, $format); - } - if (preg_match('/^[#0]+/', $format, $m)) { - $format = str_replace($m[0], strlen($m[0]), $format); - } - $format = '%' . str_replace('%', 'f%%', $format); - - $value = sprintf($format, 100 * $value); - } - } - - private static function formatAsFraction(&$value, &$format): void - { - $sign = ($value < 0) ? '-' : ''; - - $integerPart = floor(abs($value)); - $decimalPart = trim(fmod(abs($value), 1), '0.'); - $decimalLength = strlen($decimalPart); - $decimalDivisor = 10 ** $decimalLength; - - $GCD = MathTrig::GCD($decimalPart, $decimalDivisor); - - $adjustedDecimalPart = $decimalPart / $GCD; - $adjustedDecimalDivisor = $decimalDivisor / $GCD; - - if ((strpos($format, '0') !== false)) { - $value = "$sign$integerPart $adjustedDecimalPart/$adjustedDecimalDivisor"; - } elseif ((strpos($format, '#') !== false)) { - if ($integerPart == 0) { - $value = "$sign$adjustedDecimalPart/$adjustedDecimalDivisor"; - } else { - $value = "$sign$integerPart $adjustedDecimalPart/$adjustedDecimalDivisor"; - } - } elseif ((substr($format, 0, 3) == '? ?')) { - if ($integerPart == 0) { - $integerPart = ''; - } - $value = "$sign$integerPart $adjustedDecimalPart/$adjustedDecimalDivisor"; - } else { - $adjustedDecimalPart += $integerPart * $adjustedDecimalDivisor; - $value = "$sign$adjustedDecimalPart/$adjustedDecimalDivisor"; - } - } - - private static function mergeComplexNumberFormatMasks($numbers, $masks) - { - $decimalCount = strlen($numbers[1]); - $postDecimalMasks = []; - - do { - $tempMask = array_pop($masks); - $postDecimalMasks[] = $tempMask; - $decimalCount -= strlen($tempMask); - } while ($decimalCount > 0); - - return [ - implode('.', $masks), - implode('.', array_reverse($postDecimalMasks)), - ]; - } - - private static function processComplexNumberFormatMask($number, $mask) - { - $result = $number; - $maskingBlockCount = preg_match_all('/0+/', $mask, $maskingBlocks, PREG_OFFSET_CAPTURE); - - if ($maskingBlockCount > 1) { - $maskingBlocks = array_reverse($maskingBlocks[0]); - - foreach ($maskingBlocks as $block) { - $divisor = 1 . $block[0]; - $size = strlen($block[0]); - $offset = $block[1]; - - $blockValue = sprintf( - '%0' . $size . 'd', - fmod($number, $divisor) - ); - $number = floor($number / $divisor); - $mask = substr_replace($mask, $blockValue, $offset, $size); - } - if ($number > 0) { - $mask = substr_replace($mask, $number, $offset, 0); - } - $result = $mask; - } - - return $result; - } - - private static function complexNumberFormatMask($number, $mask, $splitOnPoint = true) - { - $sign = ($number < 0.0); - $number = abs($number); - - if ($splitOnPoint && strpos($mask, '.') !== false && strpos($number, '.') !== false) { - $numbers = explode('.', $number); - $masks = explode('.', $mask); - if (count($masks) > 2) { - $masks = self::mergeComplexNumberFormatMasks($numbers, $masks); - } - $result1 = self::complexNumberFormatMask($numbers[0], $masks[0], false); - $result2 = strrev(self::complexNumberFormatMask(strrev($numbers[1]), strrev($masks[1]), false)); - - return (($sign) ? '-' : '') . $result1 . '.' . $result2; - } - - $result = self::processComplexNumberFormatMask($number, $mask); - - return (($sign) ? '-' : '') . $result; - } - - private static function formatStraightNumericValue($value, $format, array $matches, $useThousands, $number_regex) - { - $left = $matches[1]; - $dec = $matches[2]; - $right = $matches[3]; - - // minimun width of formatted number (including dot) - $minWidth = strlen($left) + strlen($dec) + strlen($right); - if ($useThousands) { - $value = number_format( - $value, - strlen($right), - StringHelper::getDecimalSeparator(), - StringHelper::getThousandsSeparator() - ); - $value = preg_replace($number_regex, $value, $format); - } else { - if (preg_match('/[0#]E[+-]0/i', $format)) { - // Scientific format - $value = sprintf('%5.2E', $value); - } elseif (preg_match('/0([^\d\.]+)0/', $format) || substr_count($format, '.') > 1) { - if ($value == (int) $value && substr_count($format, '.') === 1) { - $value *= 10 ** strlen(explode('.', $format)[1]); - } - $value = self::complexNumberFormatMask($value, $format); - } else { - $sprintf_pattern = "%0$minWidth." . strlen($right) . 'f'; - $value = sprintf($sprintf_pattern, $value); - $value = preg_replace($number_regex, $value, $format); - } - } - - return $value; - } - - private static function formatAsNumber($value, $format) - { - // The "_" in this string has already been stripped out, - // so this test is never true. Furthermore, testing - // on Excel shows this format uses Euro symbol, not "EUR". - //if ($format === self::FORMAT_CURRENCY_EUR_SIMPLE) { - // return 'EUR ' . sprintf('%1.2f', $value); - //} - - // Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols - $format = str_replace(['"', '*'], '', $format); - - // Find out if we need thousands separator - // This is indicated by a comma enclosed by a digit placeholder: - // #,# or 0,0 - $useThousands = preg_match('/(#,#|0,0)/', $format); - if ($useThousands) { - $format = preg_replace('/0,0/', '00', $format); - $format = preg_replace('/#,#/', '##', $format); - } - - // Scale thousands, millions,... - // This is indicated by a number of commas after a digit placeholder: - // #, or 0.0,, - $scale = 1; // same as no scale - $matches = []; - if (preg_match('/(#|0)(,+)/', $format, $matches)) { - $scale = 1000 ** strlen($matches[2]); - - // strip the commas - $format = preg_replace('/0,+/', '0', $format); - $format = preg_replace('/#,+/', '#', $format); - } - - if (preg_match('/#?.*\?\/\?/', $format, $m)) { - if ($value != (int) $value) { - self::formatAsFraction($value, $format); - } - } else { - // Handle the number itself - - // scale number - $value = $value / $scale; - // Strip # - $format = preg_replace('/\\#/', '0', $format); - // Remove locale code [$-###] - $format = preg_replace('/\[\$\-.*\]/', '', $format); - - $n = '/\\[[^\\]]+\\]/'; - $m = preg_replace($n, '', $format); - $number_regex = '/(0+)(\\.?)(0*)/'; - if (preg_match($number_regex, $m, $matches)) { - $value = self::formatStraightNumericValue($value, $format, $matches, $useThousands, $number_regex); - } - } - - if (preg_match('/\[\$(.*)\]/u', $format, $m)) { - // Currency or Accounting - $currencyCode = $m[1]; - [$currencyCode] = explode('-', $currencyCode); - if ($currencyCode == '') { - $currencyCode = StringHelper::getCurrencyCode(); - } - $value = preg_replace('/\[\$([^\]]*)\]/u', $currencyCode, $value); - } - - return $value; - } - - private static function splitFormatCompare($value, $cond, $val, $dfcond, $dfval) - { - if (!$cond) { - $cond = $dfcond; - $val = $dfval; - } - switch ($cond) { - case '>': - return $value > $val; - - case '<': - return $value < $val; - - case '<=': - return $value <= $val; - - case '<>': - return $value != $val; - - case '=': - return $value == $val; - } - - return $value >= $val; - } - - private static function splitFormat($sections, $value) - { - // Extract the relevant section depending on whether number is positive, negative, or zero? - // Text not supported yet. - // Here is how the sections apply to various values in Excel: - // 1 section: [POSITIVE/NEGATIVE/ZERO/TEXT] - // 2 sections: [POSITIVE/ZERO/TEXT] [NEGATIVE] - // 3 sections: [POSITIVE/TEXT] [NEGATIVE] [ZERO] - // 4 sections: [POSITIVE] [NEGATIVE] [ZERO] [TEXT] - $cnt = count($sections); - $color_regex = '/\\[(' . implode('|', Color::NAMED_COLORS) . ')\\]/'; - $cond_regex = '/\\[(>|>=|<|<=|=|<>)([+-]?\\d+([.]\\d+)?)\\]/'; - $colors = ['', '', '', '', '']; - $condops = ['', '', '', '', '']; - $condvals = [0, 0, 0, 0, 0]; - for ($idx = 0; $idx < $cnt; ++$idx) { - if (preg_match($color_regex, $sections[$idx], $matches)) { - $colors[$idx] = $matches[0]; - $sections[$idx] = preg_replace($color_regex, '', $sections[$idx]); - } - if (preg_match($cond_regex, $sections[$idx], $matches)) { - $condops[$idx] = $matches[1]; - $condvals[$idx] = $matches[2]; - $sections[$idx] = preg_replace($cond_regex, '', $sections[$idx]); - } - } - $color = $colors[0]; - $format = $sections[0]; - $absval = $value; - switch ($cnt) { - case 2: - $absval = abs($value); - if (!self::splitFormatCompare($value, $condops[0], $condvals[0], '>=', 0)) { - $color = $colors[1]; - $format = $sections[1]; - } - - break; - case 3: - case 4: - $absval = abs($value); - if (!self::splitFormatCompare($value, $condops[0], $condvals[0], '>', 0)) { - if (self::splitFormatCompare($value, $condops[1], $condvals[1], '<', 0)) { - $color = $colors[1]; - $format = $sections[1]; - } else { - $color = $colors[2]; - $format = $sections[2]; - } - } - - break; - } - - return [$color, $format, $absval]; - } - /** * Convert a value in a pre-defined format to a PHP string. * @@ -822,53 +396,7 @@ class NumberFormat extends Supervisor */ public static function toFormattedString($value, $format, $callBack = null) { - // For now we do not treat strings although section 4 of a format code affects strings - if (!is_numeric($value)) { - return $value; - } - - // For 'General' format code, we just pass the value although this is not entirely the way Excel does it, - // it seems to round numbers to a total of 10 digits. - if (($format === self::FORMAT_GENERAL) || ($format === self::FORMAT_TEXT)) { - return $value; - } - - // Convert any other escaped characters to quoted strings, e.g. (\T to "T") - $format = preg_replace('/(\\\(((.)(?!((AM\/PM)|(A\/P))))|([^ ])))(?=(?:[^"]|"[^"]*")*$)/u', '"${2}"', $format); - - // Get the sections, there can be up to four sections, separated with a semi-colon (but only if not a quoted literal) - $sections = preg_split('/(;)(?=(?:[^"]|"[^"]*")*$)/u', $format); - - [$colors, $format, $value] = self::splitFormat($sections, $value); - - // In Excel formats, "_" is used to add spacing, - // The following character indicates the size of the spacing, which we can't do in HTML, so we just use a standard space - $format = preg_replace('/_./', ' ', $format); - - // Let's begin inspecting the format and converting the value to a formatted string - - // Check for date/time characters (not inside quotes) - if (preg_match('/(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy](?=(?:[^"]|"[^"]*")*$)/miu', $format, $matches)) { - // datetime format - self::formatAsDate($value, $format); - } else { - if (substr($format, 0, 1) === '"' && substr($format, -1, 1) === '"') { - $value = substr($format, 1, -1); - } elseif (preg_match('/%$/', $format)) { - // % number format - self::formatAsPercentage($value, $format); - } else { - $value = self::formatAsNumber($value, $format); - } - } - - // Additional formatting provided by callback function - if ($callBack !== null) { - [$writerInstance, $function] = $callBack; - $value = $writerInstance->$function($value, $colors); - } - - return $value; + return NumberFormat\Formatter::toFormattedString($value, $format, $callBack); } protected function exportArray1(): array diff --git a/src/PhpSpreadsheet/Style/NumberFormat/BaseFormatter.php b/src/PhpSpreadsheet/Style/NumberFormat/BaseFormatter.php new file mode 100644 index 00000000..7988143c --- /dev/null +++ b/src/PhpSpreadsheet/Style/NumberFormat/BaseFormatter.php @@ -0,0 +1,12 @@ + '', + // 12-hour suffix + 'am/pm' => 'A', + // 4-digit year + 'e' => 'Y', + 'yyyy' => 'Y', + // 2-digit year + 'yy' => 'y', + // first letter of month - no php equivalent + 'mmmmm' => 'M', + // full month name + 'mmmm' => 'F', + // short month name + 'mmm' => 'M', + // mm is minutes if time, but can also be month w/leading zero + // so we try to identify times be the inclusion of a : separator in the mask + // It isn't perfect, but the best way I know how + ':mm' => ':i', + 'mm:' => 'i:', + // month leading zero + 'mm' => 'm', + // month no leading zero + 'm' => 'n', + // full day of week name + 'dddd' => 'l', + // short day of week name + 'ddd' => 'D', + // days leading zero + 'dd' => 'd', + // days no leading zero + 'd' => 'j', + // seconds + 'ss' => 's', + // fractional seconds - no php equivalent + '.s' => '', + ]; + + /** + * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock). + * + * @var array + */ + private static $dateFormatReplacements24 = [ + 'hh' => 'H', + 'h' => 'G', + ]; + + /** + * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock). + * + * @var array + */ + private static $dateFormatReplacements12 = [ + 'hh' => 'h', + 'h' => 'g', + ]; + + public static function format($value, string $format): string + { + // strip off first part containing e.g. [$-F800] or [$USD-409] + // general syntax: [$-] + // language info is in hexadecimal + // strip off chinese part like [DBNum1][$-804] + $format = preg_replace('/^(\[DBNum\d\])*(\[\$[^\]]*\])/i', '', $format); + + // OpenOffice.org uses upper-case number formats, e.g. 'YYYY', convert to lower-case; + // but we don't want to change any quoted strings + $format = preg_replace_callback('/(?:^|")([^"]*)(?:$|")/', ['self', 'setLowercaseCallback'], $format); + + // Only process the non-quoted blocks for date format characters + $blocks = explode('"', $format); + foreach ($blocks as $key => &$block) { + if ($key % 2 == 0) { + $block = strtr($block, self::$dateFormatReplacements); + if (!strpos($block, 'A')) { + // 24-hour time format + // when [h]:mm format, the [h] should replace to the hours of the value * 24 + if (false !== strpos($block, '[h]')) { + $hours = (int) ($value * 24); + $block = str_replace('[h]', $hours, $block); + + continue; + } + $block = strtr($block, self::$dateFormatReplacements24); + } else { + // 12-hour time format + $block = strtr($block, self::$dateFormatReplacements12); + } + } + } + $format = implode('"', $blocks); + + // escape any quoted characters so that DateTime format() will render them correctly + $format = preg_replace_callback('/"(.*)"/U', ['self', 'escapeQuotesCallback'], $format); + + $dateObj = Date::excelToDateTimeObject($value); + // If the colon preceding minute had been quoted, as happens in + // Excel 2003 XML formats, m will not have been changed to i above. + // Change it now. + $format = \preg_replace('/\\\\:m/', ':i', $format); + + return $dateObj->format($format); + } + + private static function setLowercaseCallback($matches): string + { + return mb_strtolower($matches[0]); + } + + private static function escapeQuotesCallback($matches): string + { + return '\\' . implode('\\', str_split($matches[1])); + } +} diff --git a/src/PhpSpreadsheet/Style/NumberFormat/Formatter.php b/src/PhpSpreadsheet/Style/NumberFormat/Formatter.php new file mode 100644 index 00000000..01407e64 --- /dev/null +++ b/src/PhpSpreadsheet/Style/NumberFormat/Formatter.php @@ -0,0 +1,162 @@ +': + return $value > $val; + + case '<': + return $value < $val; + + case '<=': + return $value <= $val; + + case '<>': + return $value != $val; + + case '=': + return $value == $val; + } + + return $value >= $val; + } + + private static function splitFormat($sections, $value) + { + // Extract the relevant section depending on whether number is positive, negative, or zero? + // Text not supported yet. + // Here is how the sections apply to various values in Excel: + // 1 section: [POSITIVE/NEGATIVE/ZERO/TEXT] + // 2 sections: [POSITIVE/ZERO/TEXT] [NEGATIVE] + // 3 sections: [POSITIVE/TEXT] [NEGATIVE] [ZERO] + // 4 sections: [POSITIVE] [NEGATIVE] [ZERO] [TEXT] + $cnt = count($sections); + $color_regex = '/\\[(' . implode('|', Color::NAMED_COLORS) . ')\\]/mui'; + $cond_regex = '/\\[(>|>=|<|<=|=|<>)([+-]?\\d+([.]\\d+)?)\\]/'; + $colors = ['', '', '', '', '']; + $condops = ['', '', '', '', '']; + $condvals = [0, 0, 0, 0, 0]; + for ($idx = 0; $idx < $cnt; ++$idx) { + if (preg_match($color_regex, $sections[$idx], $matches)) { + $colors[$idx] = $matches[0]; + $sections[$idx] = preg_replace($color_regex, '', $sections[$idx]); + } + if (preg_match($cond_regex, $sections[$idx], $matches)) { + $condops[$idx] = $matches[1]; + $condvals[$idx] = $matches[2]; + $sections[$idx] = preg_replace($cond_regex, '', $sections[$idx]); + } + } + $color = $colors[0]; + $format = $sections[0]; + $absval = $value; + switch ($cnt) { + case 2: + $absval = abs($value); + if (!self::splitFormatCompare($value, $condops[0], $condvals[0], '>=', 0)) { + $color = $colors[1]; + $format = $sections[1]; + } + + break; + case 3: + case 4: + $absval = abs($value); + if (!self::splitFormatCompare($value, $condops[0], $condvals[0], '>', 0)) { + if (self::splitFormatCompare($value, $condops[1], $condvals[1], '<', 0)) { + $color = $colors[1]; + $format = $sections[1]; + } else { + $color = $colors[2]; + $format = $sections[2]; + } + } + + break; + } + + return [$color, $format, $absval]; + } + + /** + * Convert a value in a pre-defined format to a PHP string. + * + * @param mixed $value Value to format + * @param string $format Format code, see = NumberFormat::FORMAT_* + * @param array $callBack Callback function for additional formatting of string + * + * @return string Formatted string + */ + public static function toFormattedString($value, $format, $callBack = null) + { + // For now we do not treat strings although section 4 of a format code affects strings + if (!is_numeric($value)) { + return $value; + } + + // For 'General' format code, we just pass the value although this is not entirely the way Excel does it, + // it seems to round numbers to a total of 10 digits. + if (($format === NumberFormat::FORMAT_GENERAL) || ($format === NumberFormat::FORMAT_TEXT)) { + return $value; + } + + $format = preg_replace_callback( + '/(["])(?:(?=(\\\\?))\\2.)*?\\1/u', + function ($matches) { + return str_replace('.', chr(0x00), $matches[0]); + }, + $format + ); + + // Convert any other escaped characters to quoted strings, e.g. (\T to "T") + $format = preg_replace('/(\\\(((.)(?!((AM\/PM)|(A\/P))))|([^ ])))(?=(?:[^"]|"[^"]*")*$)/ui', '"${2}"', $format); + + // Get the sections, there can be up to four sections, separated with a semi-colon (but only if not a quoted literal) + $sections = preg_split('/(;)(?=(?:[^"]|"[^"]*")*$)/u', $format); + + [$colors, $format, $value] = self::splitFormat($sections, $value); + + // In Excel formats, "_" is used to add spacing, + // The following character indicates the size of the spacing, which we can't do in HTML, so we just use a standard space + $format = preg_replace('/_.?/ui', ' ', $format); + + // Let's begin inspecting the format and converting the value to a formatted string + + // Check for date/time characters (not inside quotes) + if (preg_match('/(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy](?=(?:[^"]|"[^"]*")*$)/miu', $format, $matches)) { + // datetime format + $value = DateFormatter::format($value, $format); + } else { + if (substr($format, 0, 1) === '"' && substr($format, -1, 1) === '"' && substr_count($format, '"') === 2) { + $value = substr($format, 1, -1); + } elseif (preg_match('/[0#, ]%/', $format)) { + // % number format + $value = PercentageFormatter::format($value, $format); + } else { + $value = NumberFormatter::format($value, $format); + } + } + + // Additional formatting provided by callback function + if ($callBack !== null) { + [$writerInstance, $function] = $callBack; + $value = $writerInstance->$function($value, $colors); + } + + $value = str_replace(chr(0x00), '.', $value); + + return $value; + } +} diff --git a/src/PhpSpreadsheet/Style/NumberFormat/FractionFormatter.php b/src/PhpSpreadsheet/Style/NumberFormat/FractionFormatter.php new file mode 100644 index 00000000..46f27cc3 --- /dev/null +++ b/src/PhpSpreadsheet/Style/NumberFormat/FractionFormatter.php @@ -0,0 +1,64 @@ + 0); + + return [ + implode('.', $masks), + implode('.', array_reverse($postDecimalMasks)), + ]; + } + + /** + * @param mixed $number + */ + private static function processComplexNumberFormatMask($number, string $mask): string + { + $result = $number; + $maskingBlockCount = preg_match_all('/0+/', $mask, $maskingBlocks, PREG_OFFSET_CAPTURE); + + if ($maskingBlockCount > 1) { + $maskingBlocks = array_reverse($maskingBlocks[0]); + + $offset = 0; + foreach ($maskingBlocks as $block) { + $size = strlen($block[0]); + $divisor = 10 ** $size; + $offset = $block[1]; + + $blockValue = sprintf("%0{$size}d", fmod($number, $divisor)); + $number = floor($number / $divisor); + $mask = substr_replace($mask, $blockValue, $offset, $size); + } + if ($number > 0) { + $mask = substr_replace($mask, $number, $offset, 0); + } + $result = $mask; + } + + return self::makeString($result); + } + + /** + * @param mixed $number + */ + private static function complexNumberFormatMask($number, string $mask, bool $splitOnPoint = true): string + { + $sign = ($number < 0.0) ? '-' : ''; + $number = (string) abs($number); + + if ($splitOnPoint && strpos($mask, '.') !== false && strpos($number, '.') !== false) { + $numbers = explode('.', $number); + $masks = explode('.', $mask); + if (count($masks) > 2) { + $masks = self::mergeComplexNumberFormatMasks($numbers, $masks); + } + $integerPart = self::complexNumberFormatMask($numbers[0], $masks[0], false); + $decimalPart = strrev(self::complexNumberFormatMask(strrev($numbers[1]), strrev($masks[1]), false)); + + return "{$sign}{$integerPart}.{$decimalPart}"; + } + + $result = self::processComplexNumberFormatMask($number, $mask); + + return "{$sign}{$result}"; + } + + /** + * @param mixed $value + */ + private static function formatStraightNumericValue($value, string $format, array $matches, bool $useThousands): string + { + $left = $matches[1]; + $dec = $matches[2]; + $right = $matches[3]; + + // minimun width of formatted number (including dot) + $minWidth = strlen($left) + strlen($dec) + strlen($right); + if ($useThousands) { + $value = number_format( + $value, + strlen($right), + StringHelper::getDecimalSeparator(), + StringHelper::getThousandsSeparator() + ); + + return self::pregReplace(self::NUMBER_REGEX, $value, $format); + } + + if (preg_match('/[0#]E[+-]0/i', $format)) { + // Scientific format + return sprintf('%5.2E', $value); + } elseif (preg_match('/0([^\d\.]+)0/', $format) || substr_count($format, '.') > 1) { + if ($value == (int) $value && substr_count($format, '.') === 1) { + $value *= 10 ** strlen(explode('.', $format)[1]); + } + + return self::complexNumberFormatMask($value, $format); + } + + $sprintf_pattern = "%0$minWidth." . strlen($right) . 'f'; + $value = sprintf($sprintf_pattern, $value); + + return self::pregReplace(self::NUMBER_REGEX, $value, $format); + } + + /** + * @param mixed $value + */ + public static function format($value, string $format): string + { + // The "_" in this string has already been stripped out, + // so this test is never true. Furthermore, testing + // on Excel shows this format uses Euro symbol, not "EUR". + //if ($format === NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE) { + // return 'EUR ' . sprintf('%1.2f', $value); + //} + + // Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols + $format = self::makeString(str_replace(['"', '*'], '', $format)); + + // Find out if we need thousands separator + // This is indicated by a comma enclosed by a digit placeholder: + // #,# or 0,0 + $useThousands = (bool) preg_match('/(#,#|0,0)/', $format); + if ($useThousands) { + $format = self::pregReplace('/0,0/', '00', $format); + $format = self::pregReplace('/#,#/', '##', $format); + } + + // Scale thousands, millions,... + // This is indicated by a number of commas after a digit placeholder: + // #, or 0.0,, + $scale = 1; // same as no scale + $matches = []; + if (preg_match('/(#|0)(,+)/', $format, $matches)) { + $scale = 1000 ** strlen($matches[2]); + + // strip the commas + $format = self::pregReplace('/0,+/', '0', $format); + $format = self::pregReplace('/#,+/', '#', $format); + } + if (preg_match('/#?.*\?\/\?/', $format, $m)) { + $value = FractionFormatter::format($value, $format); + } else { + // Handle the number itself + + // scale number + $value = $value / $scale; + // Strip # + $format = self::pregReplace('/\\#/', '0', $format); + // Remove locale code [$-###] + $format = self::pregReplace('/\[\$\-.*\]/', '', $format); + + $n = '/\\[[^\\]]+\\]/'; + $m = self::pregReplace($n, '', $format); + if (preg_match(self::NUMBER_REGEX, $m, $matches)) { + // There are placeholders for digits, so inject digits from the value into the mask + $value = self::formatStraightNumericValue($value, $format, $matches, $useThousands); + } elseif ($format !== NumberFormat::FORMAT_GENERAL) { + // Yes, I know that this is basically just a hack; + // if there's no placeholders for digits, just return the format mask "as is" + $value = self::makeString(str_replace('?', '', $format)); + } + } + + if (preg_match('/\[\$(.*)\]/u', $format, $m)) { + // Currency or Accounting + $currencyCode = $m[1]; + [$currencyCode] = explode('-', $currencyCode); + if ($currencyCode == '') { + $currencyCode = StringHelper::getCurrencyCode(); + } + $value = self::pregReplace('/\[\$([^\]]*)\]/u', $currencyCode, (string) $value); + } + + return (string) $value; + } + + /** + * @param mixed $value + */ + private static function makeString($value): string + { + return is_array($value) ? '' : (string) $value; + } + + private static function pregReplace(string $pattern, string $replacement, string $subject): string + { + return self::makeString(preg_replace($pattern, $replacement, $subject)); + } +} diff --git a/src/PhpSpreadsheet/Style/NumberFormat/PercentageFormatter.php b/src/PhpSpreadsheet/Style/NumberFormat/PercentageFormatter.php new file mode 100644 index 00000000..cf1731ec --- /dev/null +++ b/src/PhpSpreadsheet/Style/NumberFormat/PercentageFormatter.php @@ -0,0 +1,42 @@ +, hashByObjId: array} + * + * @var array + */ + private static $cachedStyles; + /** * Create a new Style. * @@ -80,7 +101,7 @@ class Style extends Supervisor // Initialise values $this->font = new Font($isSupervisor, $isConditional); $this->fill = new Fill($isSupervisor, $isConditional); - $this->borders = new Borders($isSupervisor, $isConditional); + $this->borders = new Borders($isSupervisor); $this->alignment = new Alignment($isSupervisor, $isConditional); $this->numberFormat = new NumberFormat($isSupervisor, $isConditional); $this->protection = new Protection($isSupervisor, $isConditional); @@ -200,18 +221,17 @@ class Style extends Supervisor // Calculate range outer borders $rangeStart = Coordinate::coordinateFromString($rangeA); $rangeEnd = Coordinate::coordinateFromString($rangeB); + $rangeStartIndexes = Coordinate::indexesFromString($rangeA); + $rangeEndIndexes = Coordinate::indexesFromString($rangeB); - // Translate column into index - $rangeStart0 = $rangeStart[0]; - $rangeEnd0 = $rangeEnd[0]; - $rangeStart[0] = Coordinate::columnIndexFromString($rangeStart[0]); - $rangeEnd[0] = Coordinate::columnIndexFromString($rangeEnd[0]); + $columnStart = $rangeStart[0]; + $columnEnd = $rangeEnd[0]; // Make sure we can loop upwards on rows and columns - if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) { - $tmp = $rangeStart; - $rangeStart = $rangeEnd; - $rangeEnd = $tmp; + if ($rangeStartIndexes[0] > $rangeEndIndexes[0] && $rangeStartIndexes[1] > $rangeEndIndexes[1]) { + $tmp = $rangeStartIndexes; + $rangeStartIndexes = $rangeEndIndexes; + $rangeEndIndexes = $tmp; } // ADVANCED MODE: @@ -247,19 +267,19 @@ class Style extends Supervisor unset($styleArray['borders']['inside']); // not needed any more } // width and height characteristics of selection, 1, 2, or 3 (for 3 or more) - $xMax = min($rangeEnd[0] - $rangeStart[0] + 1, 3); - $yMax = min($rangeEnd[1] - $rangeStart[1] + 1, 3); + $xMax = min($rangeEndIndexes[0] - $rangeStartIndexes[0] + 1, 3); + $yMax = min($rangeEndIndexes[1] - $rangeStartIndexes[1] + 1, 3); // loop through up to 3 x 3 = 9 regions for ($x = 1; $x <= $xMax; ++$x) { // start column index for region $colStart = ($x == 3) ? - Coordinate::stringFromColumnIndex($rangeEnd[0]) - : Coordinate::stringFromColumnIndex($rangeStart[0] + $x - 1); + Coordinate::stringFromColumnIndex($rangeEndIndexes[0]) + : Coordinate::stringFromColumnIndex($rangeStartIndexes[0] + $x - 1); // end column index for region $colEnd = ($x == 1) ? - Coordinate::stringFromColumnIndex($rangeStart[0]) - : Coordinate::stringFromColumnIndex($rangeEnd[0] - $xMax + $x); + Coordinate::stringFromColumnIndex($rangeStartIndexes[0]) + : Coordinate::stringFromColumnIndex($rangeEndIndexes[0] - $xMax + $x); for ($y = 1; $y <= $yMax; ++$y) { // which edges are touching the region @@ -283,11 +303,11 @@ class Style extends Supervisor // start row index for region $rowStart = ($y == 3) ? - $rangeEnd[1] : $rangeStart[1] + $y - 1; + $rangeEndIndexes[1] : $rangeStartIndexes[1] + $y - 1; // end row index for region $rowEnd = ($y == 1) ? - $rangeStart[1] : $rangeEnd[1] - $yMax + $y; + $rangeStartIndexes[1] : $rangeEndIndexes[1] - $yMax + $y; // build range for region $range = $colStart . $rowStart . ':' . $colEnd . $rowEnd; @@ -340,68 +360,75 @@ class Style extends Supervisor // Selection type, inspect if (preg_match('/^[A-Z]+1:[A-Z]+1048576$/', $pRange)) { $selectionType = 'COLUMN'; + + // Enable caching of styles + self::$cachedStyles = ['hashByObjId' => [], 'styleByHash' => []]; } elseif (preg_match('/^A\d+:XFD\d+$/', $pRange)) { $selectionType = 'ROW'; + + // Enable caching of styles + self::$cachedStyles = ['hashByObjId' => [], 'styleByHash' => []]; } else { $selectionType = 'CELL'; } // First loop through columns, rows, or cells to find out which styles are affected by this operation - switch ($selectionType) { - case 'COLUMN': - $oldXfIndexes = []; - for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { - $oldXfIndexes[$this->getActiveSheet()->getColumnDimensionByColumn($col)->getXfIndex()] = true; - } - foreach ($this->getActiveSheet()->getColumnIterator($rangeStart0, $rangeEnd0) as $columnIterator) { - $cellIterator = $columnIterator->getCellIterator(); - $cellIterator->setIterateOnlyExistingCells(true); - foreach ($cellIterator as $columnCell) { - $columnCell->getStyle()->applyFromArray($pStyles); - } - } - - break; - case 'ROW': - $oldXfIndexes = []; - for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { - if ($this->getActiveSheet()->getRowDimension($row)->getXfIndex() == null) { - $oldXfIndexes[0] = true; // row without explicit style should be formatted based on default style - } else { - $oldXfIndexes[$this->getActiveSheet()->getRowDimension($row)->getXfIndex()] = true; - } - } - foreach ($this->getActiveSheet()->getRowIterator((int) $rangeStart[1], (int) $rangeEnd[1]) as $rowIterator) { - $cellIterator = $rowIterator->getCellIterator(); - $cellIterator->setIterateOnlyExistingCells(true); - foreach ($cellIterator as $rowCell) { - $rowCell->getStyle()->applyFromArray($pStyles); - } - } - - break; - case 'CELL': - $oldXfIndexes = []; - for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { - for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { - $oldXfIndexes[$this->getActiveSheet()->getCellByColumnAndRow($col, $row)->getXfIndex()] = true; - } - } - - break; - } + $oldXfIndexes = $this->getOldXfIndexes($selectionType, $rangeStartIndexes, $rangeEndIndexes, $columnStart, $columnEnd, $styleArray); // clone each of the affected styles, apply the style array, and add the new styles to the workbook $workbook = $this->getActiveSheet()->getParent(); + $newXfIndexes = []; foreach ($oldXfIndexes as $oldXfIndex => $dummy) { $style = $workbook->getCellXfByIndex($oldXfIndex); - $newStyle = clone $style; - $newStyle->applyFromArray($styleArray); - if ($existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode())) { + // $cachedStyles is set when applying style for a range of cells, either column or row + if (self::$cachedStyles === null) { + // Clone the old style and apply style-array + $newStyle = clone $style; + $newStyle->applyFromArray($styleArray); + + // Look for existing style we can use instead (reduce memory usage) + $existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode()); + } else { + // Style cache is stored by Style::getHashCode(). But calling this method is + // expensive. So we cache the php obj id -> hash. + $objId = spl_object_id($style); + + // Look for the original HashCode + $styleHash = self::$cachedStyles['hashByObjId'][$objId] ?? null; + if ($styleHash === null) { + // This object_id is not cached, store the hashcode in case encounter again + $styleHash = self::$cachedStyles['hashByObjId'][$objId] = $style->getHashCode(); + } + + // Find existing style by hash. + $existingStyle = self::$cachedStyles['styleByHash'][$styleHash] ?? null; + + if (!$existingStyle) { + // The old style combined with the new style array is not cached, so we create it now + $newStyle = clone $style; + $newStyle->applyFromArray($styleArray); + + // Look for similar style in workbook to reduce memory usage + $existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode()); + + // Cache the new style by original hashcode + self::$cachedStyles['styleByHash'][$styleHash] = $existingStyle instanceof self ? $existingStyle : $newStyle; + } + } + + if ($existingStyle) { // there is already such cell Xf in our collection $newXfIndexes[$oldXfIndex] = $existingStyle->getIndex(); } else { + if (!isset($newStyle)) { + // Handle bug in PHPStan, see https://github.com/phpstan/phpstan/issues/5805 + // $newStyle should always be defined. + // This block might not be needed in the future + $newStyle = clone $style; + $newStyle->applyFromArray($styleArray); + } + // we don't have such a cell Xf, need to add $workbook->addCellXf($newStyle); $newXfIndexes[$oldXfIndex] = $newStyle->getIndex(); @@ -411,25 +438,31 @@ class Style extends Supervisor // Loop through columns, rows, or cells again and update the XF index switch ($selectionType) { case 'COLUMN': - for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { + for ($col = $rangeStartIndexes[0]; $col <= $rangeEndIndexes[0]; ++$col) { $columnDimension = $this->getActiveSheet()->getColumnDimensionByColumn($col); $oldXfIndex = $columnDimension->getXfIndex(); $columnDimension->setXfIndex($newXfIndexes[$oldXfIndex]); } + // Disable caching of styles + self::$cachedStyles = null; + break; case 'ROW': - for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { + for ($row = $rangeStartIndexes[1]; $row <= $rangeEndIndexes[1]; ++$row) { $rowDimension = $this->getActiveSheet()->getRowDimension($row); - $oldXfIndex = $rowDimension->getXfIndex() === null ? - 0 : $rowDimension->getXfIndex(); // row without explicit style should be formatted based on default style + // row without explicit style should be formatted based on default style + $oldXfIndex = $rowDimension->getXfIndex() ?? 0; $rowDimension->setXfIndex($newXfIndexes[$oldXfIndex]); } + // Disable caching of styles + self::$cachedStyles = null; + break; case 'CELL': - for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { - for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { + for ($col = $rangeStartIndexes[0]; $col <= $rangeEndIndexes[0]; ++$col) { + for ($row = $rangeStartIndexes[1]; $row <= $rangeEndIndexes[1]; ++$row) { $cell = $this->getActiveSheet()->getCellByColumnAndRow($col, $row); $oldXfIndex = $cell->getXfIndex(); $cell->setXfIndex($newXfIndexes[$oldXfIndex]); @@ -466,6 +499,57 @@ class Style extends Supervisor return $this; } + private function getOldXfIndexes(string $selectionType, array $rangeStart, array $rangeEnd, string $columnStart, string $columnEnd, array $styleArray): array + { + $oldXfIndexes = []; + switch ($selectionType) { + case 'COLUMN': + for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { + $oldXfIndexes[$this->getActiveSheet()->getColumnDimensionByColumn($col)->getXfIndex()] = true; + } + foreach ($this->getActiveSheet()->getColumnIterator($columnStart, $columnEnd) as $columnIterator) { + $cellIterator = $columnIterator->getCellIterator(); + $cellIterator->setIterateOnlyExistingCells(true); + foreach ($cellIterator as $columnCell) { + if ($columnCell !== null) { + $columnCell->getStyle()->applyFromArray($styleArray); + } + } + } + + break; + case 'ROW': + for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { + if ($this->getActiveSheet()->getRowDimension($row)->getXfIndex() === null) { + $oldXfIndexes[0] = true; // row without explicit style should be formatted based on default style + } else { + $oldXfIndexes[$this->getActiveSheet()->getRowDimension($row)->getXfIndex()] = true; + } + } + foreach ($this->getActiveSheet()->getRowIterator((int) $rangeStart[1], (int) $rangeEnd[1]) as $rowIterator) { + $cellIterator = $rowIterator->getCellIterator(); + $cellIterator->setIterateOnlyExistingCells(true); + foreach ($cellIterator as $rowCell) { + if ($rowCell !== null) { + $rowCell->getStyle()->applyFromArray($styleArray); + } + } + } + + break; + case 'CELL': + for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { + for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { + $oldXfIndexes[$this->getActiveSheet()->getCellByColumnAndRow($col, $row)->getXfIndex()] = true; + } + } + + break; + } + + return $oldXfIndexes; + } + /** * Get Fill. * diff --git a/src/PhpSpreadsheet/Worksheet/AutoFilter.php b/src/PhpSpreadsheet/Worksheet/AutoFilter.php index c2ded195..f9b16437 100644 --- a/src/PhpSpreadsheet/Worksheet/AutoFilter.php +++ b/src/PhpSpreadsheet/Worksheet/AutoFilter.php @@ -2,19 +2,22 @@ namespace PhpOffice\PhpSpreadsheet\Worksheet; +use DateTime; +use DateTimeZone; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Calculation\Internal\WildcardMatch; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Shared\Date; +use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule; class AutoFilter { /** * Autofilter Worksheet. * - * @var Worksheet + * @var null|Worksheet */ private $workSheet; @@ -36,18 +39,18 @@ class AutoFilter * Create a new AutoFilter. * * @param string $pRange Cell range (i.e. A1:E10) - * @param Worksheet $pSheet + * @param Worksheet $worksheet */ - public function __construct($pRange = '', ?Worksheet $pSheet = null) + public function __construct($pRange = '', ?Worksheet $worksheet = null) { $this->range = $pRange; - $this->workSheet = $pSheet; + $this->workSheet = $worksheet; } /** * Get AutoFilter Parent Worksheet. * - * @return Worksheet + * @return null|Worksheet */ public function getParent() { @@ -57,13 +60,13 @@ class AutoFilter /** * Set AutoFilter Parent Worksheet. * - * @param Worksheet $pSheet + * @param Worksheet $worksheet * * @return $this */ - public function setParent(?Worksheet $pSheet = null) + public function setParent(?Worksheet $worksheet = null) { - $this->workSheet = $pSheet; + $this->workSheet = $worksheet; return $this; } @@ -89,26 +92,25 @@ class AutoFilter { // extract coordinate [$worksheet, $pRange] = Worksheet::extractSheetTitle($pRange, true); - - if (strpos($pRange, ':') !== false) { - $this->range = $pRange; - } elseif (empty($pRange)) { - $this->range = ''; - } else { - throw new PhpSpreadsheetException('Autofilter must be set on a range of cells.'); - } - if (empty($pRange)) { // Discard all column rules $this->columns = []; - } else { - // Discard any column rules that are no longer valid within this range - [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); - foreach ($this->columns as $key => $value) { - $colIndex = Coordinate::columnIndexFromString($key); - if (($rangeStart[0] > $colIndex) || ($rangeEnd[0] < $colIndex)) { - unset($this->columns[$key]); - } + $this->range = ''; + + return $this; + } + + if (strpos($pRange, ':') === false) { + throw new PhpSpreadsheetException('Autofilter must be set on a range of cells.'); + } + + $this->range = $pRange; + // Discard any column rules that are no longer valid within this range + [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); + foreach ($this->columns as $key => $value) { + $colIndex = Coordinate::columnIndexFromString($key); + if (($rangeStart[0] > $colIndex) || ($rangeEnd[0] < $colIndex)) { + unset($this->columns[$key]); } } @@ -213,7 +215,7 @@ class AutoFilter if (is_string($pColumn)) { $this->columns[$pColumn] = new AutoFilter\Column($pColumn, $this); - } elseif (is_object($pColumn) && ($pColumn instanceof AutoFilter\Column)) { + } else { $pColumn->setParent($this); $this->columns[$column] = $pColumn; } @@ -304,20 +306,22 @@ class AutoFilter if (($cellValue == '') || ($cellValue === null)) { return $blanks; } + $timeZone = new DateTimeZone('UTC'); if (is_numeric($cellValue)) { - $dateValue = Date::excelToTimestamp($cellValue); + $dateTime = Date::excelToDateTimeObject((float) $cellValue, $timeZone); + $cellValue = (float) $cellValue; if ($cellValue < 1) { // Just the time part - $dtVal = date('His', $dateValue); + $dtVal = $dateTime->format('His'); $dateSet = $dateSet['time']; } elseif ($cellValue == floor($cellValue)) { // Just the date part - $dtVal = date('Ymd', $dateValue); + $dtVal = $dateTime->format('Ymd'); $dateSet = $dateSet['date']; } else { // date and time parts - $dtVal = date('YmdHis', $dateValue); + $dtVal = $dateTime->format('YmdHis'); $dateSet = $dateSet['dateTime']; } foreach ($dateSet as $dateValue) { @@ -358,38 +362,38 @@ class AutoFilter if (is_numeric($rule['value'])) { // Numeric values are tested using the appropriate operator switch ($rule['operator']) { - case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL: + case Rule::AUTOFILTER_COLUMN_RULE_EQUAL: $retVal = ($cellValue == $rule['value']); break; - case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: + case Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: $retVal = ($cellValue != $rule['value']); break; - case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN: + case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN: $retVal = ($cellValue > $rule['value']); break; - case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL: + case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL: $retVal = ($cellValue >= $rule['value']); break; - case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN: + case Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN: $retVal = ($cellValue < $rule['value']); break; - case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL: + case Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL: $retVal = ($cellValue <= $rule['value']); break; } } elseif ($rule['value'] == '') { switch ($rule['operator']) { - case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL: + case Rule::AUTOFILTER_COLUMN_RULE_EQUAL: $retVal = (($cellValue == '') || ($cellValue === null)); break; - case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: + case Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: $retVal = (($cellValue != '') && ($cellValue !== null)); break; @@ -439,7 +443,8 @@ class AutoFilter } if (is_numeric($cellValue)) { - $dateValue = date('m', Date::excelToTimestamp($cellValue)); + $dateObject = Date::excelToDateTimeObject((float) $cellValue, new DateTimeZone('UTC')); + $dateValue = (int) $dateObject->format('m'); if (in_array($dateValue, $monthSet)) { return true; } @@ -448,14 +453,223 @@ class AutoFilter return false; } - /** - * Search/Replace arrays to convert Excel wildcard syntax to a regexp syntax for preg_matching. - * - * @var array - */ - private static $fromReplace = ['\*', '\?', '~~', '~.*', '~.?']; + private static function makeDateObject(int $year, int $month, int $day, int $hour = 0, int $minute = 0, int $second = 0): DateTime + { + $baseDate = new DateTime(); + $baseDate->setDate($year, $month, $day); + $baseDate->setTime($hour, $minute, $second); - private static $toReplace = ['.*', '.', '~', '\*', '\?']; + return $baseDate; + } + + private const DATE_FUNCTIONS = [ + Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH => 'dynamicLastMonth', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER => 'dynamicLastQuarter', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK => 'dynamicLastWeek', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR => 'dynamicLastYear', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH => 'dynamicNextMonth', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER => 'dynamicNextQuarter', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK => 'dynamicNextWeek', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR => 'dynamicNextYear', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH => 'dynamicThisMonth', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER => 'dynamicThisQuarter', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK => 'dynamicThisWeek', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR => 'dynamicThisYear', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_TODAY => 'dynamicToday', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW => 'dynamicTomorrow', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE => 'dynamicYearToDate', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY => 'dynamicYesterday', + ]; + + private static function dynamicLastMonth(): array + { + $maxval = new DateTime(); + $year = (int) $maxval->format('Y'); + $month = (int) $maxval->format('m'); + $maxval->setDate($year, $month, 1); + $maxval->setTime(0, 0, 0); + $val = clone $maxval; + $val->modify('-1 month'); + + return [$val, $maxval]; + } + + private static function firstDayOfQuarter(): DateTime + { + $val = new DateTime(); + $year = (int) $val->format('Y'); + $month = (int) $val->format('m'); + $month = 3 * intdiv($month - 1, 3) + 1; + $val->setDate($year, $month, 1); + $val->setTime(0, 0, 0); + + return $val; + } + + private static function dynamicLastQuarter(): array + { + $maxval = self::firstDayOfQuarter(); + $val = clone $maxval; + $val->modify('-3 months'); + + return [$val, $maxval]; + } + + private static function dynamicLastWeek(): array + { + $val = new DateTime(); + $val->setTime(0, 0, 0); + $dayOfWeek = (int) $val->format('w'); // Sunday is 0 + $subtract = $dayOfWeek + 7; // revert to prior Sunday + $val->modify("-$subtract days"); + $maxval = clone $val; + $maxval->modify('+7 days'); + + return [$val, $maxval]; + } + + private static function dynamicLastYear(): array + { + $val = new DateTime(); + $year = (int) $val->format('Y'); + $val = self::makeDateObject($year - 1, 1, 1); + $maxval = self::makeDateObject($year, 1, 1); + + return [$val, $maxval]; + } + + private static function dynamicNextMonth(): array + { + $val = new DateTime(); + $year = (int) $val->format('Y'); + $month = (int) $val->format('m'); + $val->setDate($year, $month, 1); + $val->setTime(0, 0, 0); + $val->modify('+1 month'); + $maxval = clone $val; + $maxval->modify('+1 month'); + + return [$val, $maxval]; + } + + private static function dynamicNextQuarter(): array + { + $val = self::firstDayOfQuarter(); + $val->modify('+3 months'); + $maxval = clone $val; + $maxval->modify('+3 months'); + + return [$val, $maxval]; + } + + private static function dynamicNextWeek(): array + { + $val = new DateTime(); + $val->setTime(0, 0, 0); + $dayOfWeek = (int) $val->format('w'); // Sunday is 0 + $add = 7 - $dayOfWeek; // move to next Sunday + $val->modify("+$add days"); + $maxval = clone $val; + $maxval->modify('+7 days'); + + return [$val, $maxval]; + } + + private static function dynamicNextYear(): array + { + $val = new DateTime(); + $year = (int) $val->format('Y'); + $val = self::makeDateObject($year + 1, 1, 1); + $maxval = self::makeDateObject($year + 2, 1, 1); + + return [$val, $maxval]; + } + + private static function dynamicThisMonth(): array + { + $baseDate = new DateTime(); + $baseDate->setTime(0, 0, 0); + $year = (int) $baseDate->format('Y'); + $month = (int) $baseDate->format('m'); + $val = self::makeDateObject($year, $month, 1); + $maxval = clone $val; + $maxval->modify('+1 month'); + + return [$val, $maxval]; + } + + private static function dynamicThisQuarter(): array + { + $val = self::firstDayOfQuarter(); + $maxval = clone $val; + $maxval->modify('+3 months'); + + return [$val, $maxval]; + } + + private static function dynamicThisWeek(): array + { + $val = new DateTime(); + $val->setTime(0, 0, 0); + $dayOfWeek = (int) $val->format('w'); // Sunday is 0 + $subtract = $dayOfWeek; // revert to Sunday + $val->modify("-$subtract days"); + $maxval = clone $val; + $maxval->modify('+7 days'); + + return [$val, $maxval]; + } + + private static function dynamicThisYear(): array + { + $val = new DateTime(); + $year = (int) $val->format('Y'); + $val = self::makeDateObject($year, 1, 1); + $maxval = self::makeDateObject($year + 1, 1, 1); + + return [$val, $maxval]; + } + + private static function dynamicToday(): array + { + $val = new DateTime(); + $val->setTime(0, 0, 0); + $maxval = clone $val; + $maxval->modify('+1 day'); + + return [$val, $maxval]; + } + + private static function dynamicTomorrow(): array + { + $val = new DateTime(); + $val->setTime(0, 0, 0); + $val->modify('+1 day'); + $maxval = clone $val; + $maxval->modify('+1 day'); + + return [$val, $maxval]; + } + + private static function dynamicYearToDate(): array + { + $maxval = new DateTime(); + $maxval->setTime(0, 0, 0); + $val = self::makeDateObject((int) $maxval->format('Y'), 1, 1); + $maxval->modify('+1 day'); + + return [$val, $maxval]; + } + + private static function dynamicYesterday(): array + { + $maxval = new DateTime(); + $maxval->setTime(0, 0, 0); + $val = clone $maxval; + $val->modify('-1 day'); + + return [$val, $maxval]; + } /** * Convert a dynamic rule daterange to a custom filter range expression for ease of calculation. @@ -467,135 +681,59 @@ class AutoFilter */ private function dynamicFilterDateRange($dynamicRuleType, &$filterColumn) { - $rDateType = Functions::getReturnDateType(); - Functions::setReturnDateType(Functions::RETURNDATE_PHP_NUMERIC); - $val = $maxVal = null; - $ruleValues = []; - $baseDate = DateTime::DATENOW(); + $callBack = [__CLASS__, self::DATE_FUNCTIONS[$dynamicRuleType]]; // What if not found? // Calculate start/end dates for the required date range based on current date - switch ($dynamicRuleType) { - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK: - $baseDate = strtotime('-7 days', $baseDate); - - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK: - $baseDate = strtotime('-7 days', $baseDate); - - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH: - $baseDate = strtotime('-1 month', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); - - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH: - $baseDate = strtotime('+1 month', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); - - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER: - $baseDate = strtotime('-3 month', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); - - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER: - $baseDate = strtotime('+3 month', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); - - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR: - $baseDate = strtotime('-1 year', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); - - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR: - $baseDate = strtotime('+1 year', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); - - break; - } - - switch ($dynamicRuleType) { - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_TODAY: - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY: - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW: - $maxVal = (int) Date::PHPtoExcel(strtotime('+1 day', $baseDate)); - $val = (int) Date::PHPToExcel($baseDate); - - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE: - $maxVal = (int) Date::PHPtoExcel(strtotime('+1 day', $baseDate)); - $val = (int) Date::PHPToExcel(gmmktime(0, 0, 0, 1, 1, date('Y', $baseDate))); - - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR: - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR: - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR: - $maxVal = (int) Date::PHPToExcel(gmmktime(0, 0, 0, 31, 12, date('Y', $baseDate))); - ++$maxVal; - $val = (int) Date::PHPToExcel(gmmktime(0, 0, 0, 1, 1, date('Y', $baseDate))); - - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER: - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER: - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER: - $thisMonth = date('m', $baseDate); - $thisQuarter = floor(--$thisMonth / 3); - $maxVal = (int) Date::PHPtoExcel(gmmktime(0, 0, 0, date('t', $baseDate), (1 + $thisQuarter) * 3, date('Y', $baseDate))); - ++$maxVal; - $val = (int) Date::PHPToExcel(gmmktime(0, 0, 0, 1, 1 + $thisQuarter * 3, date('Y', $baseDate))); - - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH: - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH: - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH: - $maxVal = (int) Date::PHPtoExcel(gmmktime(0, 0, 0, date('t', $baseDate), date('m', $baseDate), date('Y', $baseDate))); - ++$maxVal; - $val = (int) Date::PHPToExcel(gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); - - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK: - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK: - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK: - $dayOfWeek = date('w', $baseDate); - $val = (int) Date::PHPToExcel($baseDate) - $dayOfWeek; - $maxVal = $val + 7; - - break; - } - - switch ($dynamicRuleType) { - // Adjust Today dates for Yesterday and Tomorrow - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY: - --$maxVal; - --$val; - - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW: - ++$maxVal; - ++$val; - - break; + // Val is lowest permitted value. + // Maxval is greater than highest permitted value + $val = $maxval = 0; + if (is_callable($callBack)) { + [$val, $maxval] = $callBack(); } + $val = Date::dateTimeToExcel($val); + $maxval = Date::dateTimeToExcel($maxval); // Set the filter column rule attributes ready for writing - $filterColumn->setAttributes(['val' => $val, 'maxVal' => $maxVal]); + $filterColumn->setAttributes(['val' => $val, 'maxVal' => $maxval]); // Set the rules for identifying rows for hide/show - $ruleValues[] = ['operator' => AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, 'value' => $val]; - $ruleValues[] = ['operator' => AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN, 'value' => $maxVal]; - Functions::setReturnDateType($rDateType); + $ruleValues[] = ['operator' => Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, 'value' => $val]; + $ruleValues[] = ['operator' => Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN, 'value' => $maxval]; return ['method' => 'filterTestInCustomDataSet', 'arguments' => ['filterRules' => $ruleValues, 'join' => AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND]]; } + /** + * Apply the AutoFilter rules to the AutoFilter Range. + * + * @param string $columnID + * @param int $startRow + * @param int $endRow + * @param ?string $ruleType + * @param mixed $ruleValue + * + * @return mixed + */ private function calculateTopTenValue($columnID, $startRow, $endRow, $ruleType, $ruleValue) { $range = $columnID . $startRow . ':' . $columnID . $endRow; - $dataValues = Functions::flattenArray($this->workSheet->rangeToArray($range, null, true, false)); + $retVal = null; + if ($this->workSheet !== null) { + $dataValues = Functions::flattenArray($this->workSheet->rangeToArray($range, null, true, false)); + $dataValues = array_filter($dataValues); - $dataValues = array_filter($dataValues); - if ($ruleType == AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) { - rsort($dataValues); - } else { - sort($dataValues); + if ($ruleType == Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) { + rsort($dataValues); + } else { + sort($dataValues); + } + + $slice = array_slice($dataValues, 0, $ruleValue); + + $retVal = array_pop($slice); } - return array_pop(array_slice($dataValues, 0, $ruleValue)); + return $retVal; } /** @@ -605,6 +743,9 @@ class AutoFilter */ public function showHideRows() { + if ($this->workSheet === null) { + return $this; + } [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); // The heading row should always be visible @@ -628,7 +769,7 @@ class AutoFilter if (count($ruleValues) != count($ruleDataSet)) { $blanks = true; } - if ($ruleType == AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_FILTER) { + if ($ruleType == Rule::AUTOFILTER_RULETYPE_FILTER) { // Filter on absolute values $columnFilterTests[$columnID] = [ 'method' => 'filterTestInSimpleDataSet', @@ -642,42 +783,45 @@ class AutoFilter 'dateTime' => [], ]; foreach ($ruleDataSet as $ruleValue) { + if (!is_array($ruleValue)) { + continue; + } $date = $time = ''; if ( - (isset($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR])) && - ($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR] !== '') + (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR])) && + ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR] !== '') ) { - $date .= sprintf('%04d', $ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR]); + $date .= sprintf('%04d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR]); } if ( - (isset($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH])) && - ($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH] != '') + (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH])) && + ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH] != '') ) { - $date .= sprintf('%02d', $ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH]); + $date .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH]); } if ( - (isset($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY])) && - ($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY] !== '') + (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY])) && + ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY] !== '') ) { - $date .= sprintf('%02d', $ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY]); + $date .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY]); } if ( - (isset($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR])) && - ($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR] !== '') + (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR])) && + ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR] !== '') ) { - $time .= sprintf('%02d', $ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR]); + $time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR]); } if ( - (isset($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE])) && - ($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE] !== '') + (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE])) && + ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE] !== '') ) { - $time .= sprintf('%02d', $ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE]); + $time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE]); } if ( - (isset($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND])) && - ($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND] !== '') + (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND])) && + ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND] !== '') ) { - $time .= sprintf('%02d', $ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND]); + $time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND]); } $dateTime = $date . $time; $arguments['date'][] = $date; @@ -701,10 +845,9 @@ class AutoFilter // Build a list of the filter value selections foreach ($rules as $rule) { $ruleValue = $rule->getValue(); - if (!is_numeric($ruleValue)) { + if (!is_array($ruleValue) && !is_numeric($ruleValue)) { // Convert to a regexp allowing for regexp reserved characters, wildcards and escaped wildcards - $ruleValue = preg_quote($ruleValue); - $ruleValue = str_replace(self::$fromReplace, self::$toReplace, $ruleValue); + $ruleValue = WildcardMatch::wildcard($ruleValue); if (trim($ruleValue) == '') { $customRuleForBlanks = true; $ruleValue = trim($ruleValue); @@ -725,17 +868,18 @@ class AutoFilter // We should only ever have one Dynamic Filter Rule anyway $dynamicRuleType = $rule->getGrouping(); if ( - ($dynamicRuleType == AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) || - ($dynamicRuleType == AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE) + ($dynamicRuleType == Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) || + ($dynamicRuleType == Rule::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE) ) { // Number (Average) based // Calculate the average $averageFormula = '=AVERAGE(' . $columnID . ($rangeStart[1] + 1) . ':' . $columnID . $rangeEnd[1] . ')'; - $average = Calculation::getInstance()->calculateFormula($averageFormula, null, $this->workSheet->getCell('A1')); + $spreadsheet = ($this->workSheet === null) ? null : $this->workSheet->getParent(); + $average = Calculation::getInstance($spreadsheet)->calculateFormula($averageFormula, null, $this->workSheet->getCell('A1')); // Set above/below rule based on greaterThan or LessTan - $operator = ($dynamicRuleType === AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) - ? AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN - : AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN; + $operator = ($dynamicRuleType === Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) + ? Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN + : Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN; $ruleValues[] = [ 'operator' => $operator, 'value' => $average, @@ -777,27 +921,30 @@ class AutoFilter case AutoFilter\Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER: $ruleValues = []; $dataRowCount = $rangeEnd[1] - $rangeStart[1]; + $toptenRuleType = null; + $ruleValue = 0; + $ruleOperator = null; foreach ($rules as $rule) { // We should only ever have one Dynamic Filter Rule anyway $toptenRuleType = $rule->getGrouping(); $ruleValue = $rule->getValue(); $ruleOperator = $rule->getOperator(); } - if ($ruleOperator === AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) { - $ruleValue = floor($ruleValue * ($dataRowCount / 100)); + if (is_numeric($ruleValue) && $ruleOperator === Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) { + $ruleValue = floor((float) $ruleValue * ($dataRowCount / 100)); } - if ($ruleValue < 1) { + if (!is_array($ruleValue) && $ruleValue < 1) { $ruleValue = 1; } - if ($ruleValue > 500) { + if (!is_array($ruleValue) && $ruleValue > 500) { $ruleValue = 500; } - $maxVal = $this->calculateTopTenValue($columnID, $rangeStart[1] + 1, $rangeEnd[1], $toptenRuleType, $ruleValue); + $maxVal = $this->calculateTopTenValue($columnID, $rangeStart[1] + 1, (int) $rangeEnd[1], $toptenRuleType, $ruleValue); - $operator = ($toptenRuleType == AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) - ? AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL - : AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL; + $operator = ($toptenRuleType == Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) + ? Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL + : Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL; $ruleValues[] = ['operator' => $operator, 'value' => $maxVal]; $columnFilterTests[$columnID] = [ 'method' => 'filterTestInCustomDataSet', @@ -815,18 +962,16 @@ class AutoFilter foreach ($columnFilterTests as $columnID => $columnFilterTest) { $cellValue = $this->workSheet->getCell($columnID . $row)->getCalculatedValue(); // Execute the filter test - $result = $result && - call_user_func_array( - [self::class, $columnFilterTest['method']], - [$cellValue, $columnFilterTest['arguments']] - ); + $result = // $result && // phpstan says $result is always true here + // @phpstan-ignore-next-line + call_user_func_array([self::class, $columnFilterTest['method']], [$cellValue, $columnFilterTest['arguments']]); // If filter test has resulted in FALSE, exit the loop straightaway rather than running any more tests if (!$result) { break; } } // Set show/hide for the row based on the result of the autoFilter result - $this->workSheet->getRowDimension($row)->setVisible($result); + $this->workSheet->getRowDimension((int) $row)->setVisible($result); } return $this; diff --git a/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php b/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php index 09584a7a..3c4bee47 100644 --- a/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php +++ b/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php @@ -49,7 +49,7 @@ class Column /** * Autofilter. * - * @var AutoFilter + * @var null|AutoFilter */ private $parent; @@ -77,14 +77,14 @@ class Column /** * Autofilter Column Rules. * - * @var array of Column\Rule + * @var Column\Rule[] */ private $ruleset = []; /** * Autofilter Column Dynamic Attributes. * - * @var array of mixed + * @var mixed[] */ private $attributes = []; @@ -133,7 +133,7 @@ class Column /** * Get this Column's AutoFilter Parent. * - * @return AutoFilter + * @return null|AutoFilter */ public function getParent() { @@ -215,11 +215,11 @@ class Column /** * Set AutoFilter Attributes. * - * @param string[] $attributes + * @param mixed[] $attributes * * @return $this */ - public function setAttributes(array $attributes) + public function setAttributes($attributes) { $this->attributes = $attributes; @@ -244,7 +244,7 @@ class Column /** * Get AutoFilter Column Attributes. * - * @return string[] + * @return int[]|string[] */ public function getAttributes() { @@ -256,7 +256,7 @@ class Column * * @param string $pName Attribute Name * - * @return string + * @return null|int|string */ public function getAttribute($pName) { @@ -267,6 +267,11 @@ class Column return null; } + public function ruleCount(): int + { + return count($this->ruleset); + } + /** * Get all AutoFilter Column Rules. * @@ -370,8 +375,6 @@ class Column $cloned->setParent($this); // attach the new cloned Rule to this new cloned Autofilter Cloned object $this->ruleset[$k] = $cloned; } - } elseif (is_object($value)) { - $this->$key = clone $value; } else { $this->$key = $value; } diff --git a/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php b/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php index 1aacb0cb..37ea070b 100644 --- a/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php +++ b/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php @@ -13,7 +13,7 @@ class Rule const AUTOFILTER_RULETYPE_DYNAMICFILTER = 'dynamicFilter'; const AUTOFILTER_RULETYPE_TOPTENFILTER = 'top10Filter'; - private static $ruleTypes = [ + private const RULE_TYPES = [ // Currently we're not handling // colorFilter // extLst @@ -32,7 +32,7 @@ class Rule const AUTOFILTER_RULETYPE_DATEGROUP_MINUTE = 'minute'; const AUTOFILTER_RULETYPE_DATEGROUP_SECOND = 'second'; - private static $dateTimeGroups = [ + private const DATE_TIME_GROUPS = [ self::AUTOFILTER_RULETYPE_DATEGROUP_YEAR, self::AUTOFILTER_RULETYPE_DATEGROUP_MONTH, self::AUTOFILTER_RULETYPE_DATEGROUP_DAY, @@ -88,7 +88,7 @@ class Rule const AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE = 'aboveAverage'; const AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE = 'belowAverage'; - private static $dynamicTypes = [ + private const DYNAMIC_TYPES = [ self::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY, self::AUTOFILTER_RULETYPE_DYNAMIC_TODAY, self::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW, @@ -141,7 +141,7 @@ class Rule const AUTOFILTER_COLUMN_RULE_LESSTHAN = 'lessThan'; const AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL = 'lessThanOrEqual'; - private static $operators = [ + private const OPERATORS = [ self::AUTOFILTER_COLUMN_RULE_EQUAL, self::AUTOFILTER_COLUMN_RULE_NOTEQUAL, self::AUTOFILTER_COLUMN_RULE_GREATERTHAN, @@ -153,7 +153,7 @@ class Rule const AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE = 'byValue'; const AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT = 'byPercent'; - private static $topTenValue = [ + private const TOP_TEN_VALUE = [ self::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE, self::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT, ]; @@ -161,7 +161,7 @@ class Rule const AUTOFILTER_COLUMN_RULE_TOPTEN_TOP = 'top'; const AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM = 'bottom'; - private static $topTenType = [ + private const TOP_TEN_TYPE = [ self::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP, self::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM, ]; @@ -203,7 +203,7 @@ class Rule /** * Autofilter Column. * - * @var Column + * @var ?Column */ private $parent; @@ -217,7 +217,7 @@ class Rule /** * Autofilter Rule Value. * - * @var string + * @var int|int[]|string|string[] */ private $value = ''; @@ -237,8 +237,6 @@ class Rule /** * Create a new Rule. - * - * @param Column $pParent */ public function __construct(?Column $pParent = null) { @@ -264,7 +262,7 @@ class Rule */ public function setRuleType($pRuleType) { - if (!in_array($pRuleType, self::$ruleTypes)) { + if (!in_array($pRuleType, self::RULE_TYPES)) { throw new PhpSpreadsheetException('Invalid rule type for column AutoFilter Rule.'); } @@ -276,7 +274,7 @@ class Rule /** * Get AutoFilter Rule Value. * - * @return string + * @return int|int[]|string|string[] */ public function getValue() { @@ -286,7 +284,7 @@ class Rule /** * Set AutoFilter Rule Value. * - * @param string|string[] $pValue + * @param int|int[]|string|string[] $pValue * * @return $this */ @@ -296,19 +294,19 @@ class Rule $grouping = -1; foreach ($pValue as $key => $value) { // Validate array entries - if (!in_array($key, self::$dateTimeGroups)) { + if (!in_array($key, self::DATE_TIME_GROUPS)) { // Remove any invalid entries from the value array unset($pValue[$key]); } else { // Work out what the dateTime grouping will be - $grouping = max($grouping, array_search($key, self::$dateTimeGroups)); + $grouping = max($grouping, array_search($key, self::DATE_TIME_GROUPS)); } } if (count($pValue) == 0) { throw new PhpSpreadsheetException('Invalid rule value for column AutoFilter Rule.'); } // Set the dateTime grouping that we've anticipated - $this->setGrouping(self::$dateTimeGroups[$grouping]); + $this->setGrouping(self::DATE_TIME_GROUPS[$grouping]); } $this->value = $pValue; @@ -338,8 +336,8 @@ class Rule $pOperator = self::AUTOFILTER_COLUMN_RULE_EQUAL; } if ( - (!in_array($pOperator, self::$operators)) && - (!in_array($pOperator, self::$topTenValue)) + (!in_array($pOperator, self::OPERATORS)) && + (!in_array($pOperator, self::TOP_TEN_VALUE)) ) { throw new PhpSpreadsheetException('Invalid operator for column AutoFilter Rule.'); } @@ -369,11 +367,11 @@ class Rule { if ( ($pGrouping !== null) && - (!in_array($pGrouping, self::$dateTimeGroups)) && - (!in_array($pGrouping, self::$dynamicTypes)) && - (!in_array($pGrouping, self::$topTenType)) + (!in_array($pGrouping, self::DATE_TIME_GROUPS)) && + (!in_array($pGrouping, self::DYNAMIC_TYPES)) && + (!in_array($pGrouping, self::TOP_TEN_TYPE)) ) { - throw new PhpSpreadsheetException('Invalid rule type for column AutoFilter Rule.'); + throw new PhpSpreadsheetException('Invalid grouping for column AutoFilter Rule.'); } $this->grouping = $pGrouping; @@ -384,7 +382,7 @@ class Rule * Set AutoFilter Rule. * * @param string $pOperator see self::AUTOFILTER_COLUMN_RULE_* - * @param string|string[] $pValue + * @param int|int[]|string|string[] $pValue * @param string $pGrouping * * @return $this @@ -406,7 +404,7 @@ class Rule /** * Get this Rule's AutoFilter Column Parent. * - * @return Column + * @return ?Column */ public function getParent() { @@ -416,8 +414,6 @@ class Rule /** * Set this Rule's AutoFilter Column Parent. * - * @param Column $pParent - * * @return $this */ public function setParent(?Column $pParent = null) @@ -435,11 +431,9 @@ class Rule $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { - if ($key == 'parent') { + if ($key == 'parent') { // this is only object // Detach from autofilter column parent $this->$key = null; - } else { - $this->$key = clone $value; } } else { $this->$key = $value; diff --git a/src/PhpSpreadsheet/Worksheet/BaseDrawing.php b/src/PhpSpreadsheet/Worksheet/BaseDrawing.php index be2f23df..5829671b 100644 --- a/src/PhpSpreadsheet/Worksheet/BaseDrawing.php +++ b/src/PhpSpreadsheet/Worksheet/BaseDrawing.php @@ -39,7 +39,7 @@ class BaseDrawing implements IComparable /** * Worksheet. * - * @var Worksheet + * @var null|Worksheet */ protected $worksheet; @@ -190,7 +190,7 @@ class BaseDrawing implements IComparable /** * Get Worksheet. * - * @return Worksheet + * @return null|Worksheet */ public function getWorksheet() { @@ -330,7 +330,7 @@ class BaseDrawing implements IComparable // Resize proportional? if ($this->resizeProportional && $pValue != 0) { $ratio = $this->height / ($this->width != 0 ? $this->width : 1); - $this->height = round($ratio * $pValue); + $this->height = (int) round($ratio * $pValue); } // Set width @@ -361,7 +361,7 @@ class BaseDrawing implements IComparable // Resize proportional? if ($this->resizeProportional && $pValue != 0) { $ratio = $this->width / ($this->height != 0 ? $this->height : 1); - $this->width = round($ratio * $pValue); + $this->width = (int) round($ratio * $pValue); } // Set height @@ -392,10 +392,10 @@ class BaseDrawing implements IComparable $yratio = $height / ($this->height != 0 ? $this->height : 1); if ($this->resizeProportional && !($width == 0 || $height == 0)) { if (($xratio * $this->height) < $height) { - $this->height = ceil($xratio * $this->height); + $this->height = (int) ceil($xratio * $this->height); $this->width = $width; } else { - $this->width = ceil($yratio * $this->width); + $this->width = (int) ceil($yratio * $this->width); $this->height = $height; } } else { diff --git a/src/PhpSpreadsheet/Worksheet/CellIterator.php b/src/PhpSpreadsheet/Worksheet/CellIterator.php index 45f76cab..31f6ae65 100644 --- a/src/PhpSpreadsheet/Worksheet/CellIterator.php +++ b/src/PhpSpreadsheet/Worksheet/CellIterator.php @@ -25,15 +25,14 @@ abstract class CellIterator implements Iterator */ public function __destruct() { + // @phpstan-ignore-next-line $this->worksheet = null; } /** * Get loop only existing cells. - * - * @return bool */ - public function getIterateOnlyExistingCells() + public function getIterateOnlyExistingCells(): bool { return $this->onlyExistingCells; } @@ -45,10 +44,8 @@ abstract class CellIterator implements Iterator /** * Set the iterator to loop only existing cells. - * - * @param bool $value */ - public function setIterateOnlyExistingCells($value): void + public function setIterateOnlyExistingCells(bool $value): void { $this->onlyExistingCells = (bool) $value; diff --git a/src/PhpSpreadsheet/Worksheet/Column.php b/src/PhpSpreadsheet/Worksheet/Column.php index 410e8073..8abbabe5 100644 --- a/src/PhpSpreadsheet/Worksheet/Column.php +++ b/src/PhpSpreadsheet/Worksheet/Column.php @@ -36,15 +36,14 @@ class Column */ public function __destruct() { + // @phpstan-ignore-next-line $this->parent = null; } /** * Get column index as string eg: 'A'. - * - * @return string */ - public function getColumnIndex() + public function getColumnIndex(): string { return $this->columnIndex; } diff --git a/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php b/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php index 714ee7ce..65772114 100644 --- a/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php +++ b/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php @@ -2,6 +2,7 @@ namespace PhpOffice\PhpSpreadsheet\Worksheet; +use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; @@ -17,7 +18,7 @@ class ColumnCellIterator extends CellIterator /** * Column index. * - * @var string + * @var int */ private $columnIndex; @@ -59,7 +60,7 @@ class ColumnCellIterator extends CellIterator * * @return $this */ - public function resetStart($startRow = 1) + public function resetStart(int $startRow = 1) { $this->startRow = $startRow; $this->adjustForExistingOnlyRange(); @@ -77,7 +78,7 @@ class ColumnCellIterator extends CellIterator */ public function resetEnd($endRow = null) { - $this->endRow = ($endRow) ? $endRow : $this->worksheet->getHighestRow(); + $this->endRow = $endRow ?: $this->worksheet->getHighestRow(); $this->adjustForExistingOnlyRange(); return $this; @@ -90,7 +91,7 @@ class ColumnCellIterator extends CellIterator * * @return $this */ - public function seek($row = 1) + public function seek(int $row = 1) { if ($this->onlyExistingCells && !($this->worksheet->cellExistsByColumnAndRow($this->columnIndex, $row))) { throw new PhpSpreadsheetException('In "IterateOnlyExistingCells" mode and Cell does not exist'); @@ -113,20 +114,16 @@ class ColumnCellIterator extends CellIterator /** * Return the current cell in this worksheet column. - * - * @return \PhpOffice\PhpSpreadsheet\Cell\Cell */ - public function current() + public function current(): ?Cell { return $this->worksheet->getCellByColumnAndRow($this->columnIndex, $this->currentRow); } /** * Return the current iterator key. - * - * @return int */ - public function key() + public function key(): int { return $this->currentRow; } @@ -161,10 +158,8 @@ class ColumnCellIterator extends CellIterator /** * Indicate if more rows exist in the worksheet range of rows that we're iterating. - * - * @return bool */ - public function valid() + public function valid(): bool { return $this->currentRow <= $this->endRow && $this->currentRow >= $this->startRow; } diff --git a/src/PhpSpreadsheet/Worksheet/ColumnDimension.php b/src/PhpSpreadsheet/Worksheet/ColumnDimension.php index 4e87a344..4ea30c8f 100644 --- a/src/PhpSpreadsheet/Worksheet/ColumnDimension.php +++ b/src/PhpSpreadsheet/Worksheet/ColumnDimension.php @@ -2,6 +2,8 @@ namespace PhpOffice\PhpSpreadsheet\Worksheet; +use PhpOffice\PhpSpreadsheet\Helper\Dimension as CssDimension; + class ColumnDimension extends Dimension { /** @@ -43,10 +45,8 @@ class ColumnDimension extends Dimension /** * Get column index as string eg: 'A'. - * - * @return string */ - public function getColumnIndex() + public function getColumnIndex(): string { return $this->columnIndex; } @@ -54,13 +54,11 @@ class ColumnDimension extends Dimension /** * Set column index as string eg: 'A'. * - * @param string $pValue - * * @return $this */ - public function setColumnIndex($pValue) + public function setColumnIndex(string $index) { - $this->columnIndex = $pValue; + $this->columnIndex = $index; return $this; } @@ -68,33 +66,39 @@ class ColumnDimension extends Dimension /** * Get Width. * - * @return float + * Each unit of column width is equal to the width of one character in the default font size. + * By default, this will be the return value; but this method also accepts a unit of measure argument and will + * return the value converted to the specified UoM using an approximation method. */ - public function getWidth() + public function getWidth(?string $unitOfMeasure = null): float { - return $this->width; + return ($unitOfMeasure === null || $this->width < 0) + ? $this->width + : (new CssDimension((string) $this->width))->toUnit($unitOfMeasure); } /** * Set Width. * - * @param float $pValue + * Each unit of column width is equal to the width of one character in the default font size. + * By default, this will be the unit of measure for the passed value; but this method accepts a unit of measure + * argument, and will convert the value from the specified UoM using an approximation method. * * @return $this */ - public function setWidth($pValue) + public function setWidth(float $width, ?string $unitOfMeasure = null) { - $this->width = $pValue; + $this->width = ($unitOfMeasure === null || $width < 0) + ? $width + : (new CssDimension("{$width}{$unitOfMeasure}"))->width(); return $this; } /** * Get Auto Size. - * - * @return bool */ - public function getAutoSize() + public function getAutoSize(): bool { return $this->autoSize; } @@ -102,13 +106,11 @@ class ColumnDimension extends Dimension /** * Set Auto Size. * - * @param bool $pValue - * * @return $this */ - public function setAutoSize($pValue) + public function setAutoSize(bool $autosizeEnabled) { - $this->autoSize = $pValue; + $this->autoSize = $autosizeEnabled; return $this; } diff --git a/src/PhpSpreadsheet/Worksheet/ColumnIterator.php b/src/PhpSpreadsheet/Worksheet/ColumnIterator.php index d0bb20cc..179e9f27 100644 --- a/src/PhpSpreadsheet/Worksheet/ColumnIterator.php +++ b/src/PhpSpreadsheet/Worksheet/ColumnIterator.php @@ -57,6 +57,7 @@ class ColumnIterator implements Iterator */ public function __destruct() { + // @phpstan-ignore-next-line $this->worksheet = null; } @@ -67,11 +68,13 @@ class ColumnIterator implements Iterator * * @return $this */ - public function resetStart($startColumn = 'A') + public function resetStart(string $startColumn = 'A') { $startColumnIndex = Coordinate::columnIndexFromString($startColumn); if ($startColumnIndex > Coordinate::columnIndexFromString($this->worksheet->getHighestColumn())) { - throw new Exception("Start column ({$startColumn}) is beyond highest column ({$this->worksheet->getHighestColumn()})"); + throw new Exception( + "Start column ({$startColumn}) is beyond highest column ({$this->worksheet->getHighestColumn()})" + ); } $this->startColumnIndex = $startColumnIndex; @@ -92,7 +95,7 @@ class ColumnIterator implements Iterator */ public function resetEnd($endColumn = null) { - $endColumn = $endColumn ? $endColumn : $this->worksheet->getHighestColumn(); + $endColumn = $endColumn ?: $this->worksheet->getHighestColumn(); $this->endColumnIndex = Coordinate::columnIndexFromString($endColumn); return $this; @@ -105,11 +108,13 @@ class ColumnIterator implements Iterator * * @return $this */ - public function seek($column = 'A') + public function seek(string $column = 'A') { $column = Coordinate::columnIndexFromString($column); if (($column < $this->startColumnIndex) || ($column > $this->endColumnIndex)) { - throw new PhpSpreadsheetException("Column $column is out of range ({$this->startColumnIndex} - {$this->endColumnIndex})"); + throw new PhpSpreadsheetException( + "Column $column is out of range ({$this->startColumnIndex} - {$this->endColumnIndex})" + ); } $this->currentColumnIndex = $column; @@ -126,20 +131,16 @@ class ColumnIterator implements Iterator /** * Return the current column in this worksheet. - * - * @return Column */ - public function current() + public function current(): Column { return new Column($this->worksheet, Coordinate::stringFromColumnIndex($this->currentColumnIndex)); } /** * Return the current iterator key. - * - * @return string */ - public function key() + public function key(): string { return Coordinate::stringFromColumnIndex($this->currentColumnIndex); } @@ -162,10 +163,8 @@ class ColumnIterator implements Iterator /** * Indicate if more columns exist in the worksheet range of columns that we're iterating. - * - * @return bool */ - public function valid() + public function valid(): bool { return $this->currentColumnIndex <= $this->endColumnIndex && $this->currentColumnIndex >= $this->startColumnIndex; } diff --git a/src/PhpSpreadsheet/Worksheet/Dimension.php b/src/PhpSpreadsheet/Worksheet/Dimension.php index a27daf09..4b3a0da8 100644 --- a/src/PhpSpreadsheet/Worksheet/Dimension.php +++ b/src/PhpSpreadsheet/Worksheet/Dimension.php @@ -47,10 +47,8 @@ abstract class Dimension /** * Get Visible. - * - * @return bool */ - public function getVisible() + public function getVisible(): bool { return $this->visible; } @@ -58,23 +56,19 @@ abstract class Dimension /** * Set Visible. * - * @param bool $pValue - * * @return $this */ - public function setVisible($pValue) + public function setVisible(bool $visible) { - $this->visible = (bool) $pValue; + $this->visible = $visible; return $this; } /** * Get Outline Level. - * - * @return int */ - public function getOutlineLevel() + public function getOutlineLevel(): int { return $this->outlineLevel; } @@ -83,27 +77,23 @@ abstract class Dimension * Set Outline Level. * Value must be between 0 and 7. * - * @param int $pValue - * * @return $this */ - public function setOutlineLevel($pValue) + public function setOutlineLevel(int $level) { - if ($pValue < 0 || $pValue > 7) { + if ($level < 0 || $level > 7) { throw new PhpSpreadsheetException('Outline level must range between 0 and 7.'); } - $this->outlineLevel = $pValue; + $this->outlineLevel = $level; return $this; } /** * Get Collapsed. - * - * @return bool */ - public function getCollapsed() + public function getCollapsed(): bool { return $this->collapsed; } @@ -111,13 +101,11 @@ abstract class Dimension /** * Set Collapsed. * - * @param bool $pValue - * * @return $this */ - public function setCollapsed($pValue) + public function setCollapsed(bool $collapsed) { - $this->collapsed = (bool) $pValue; + $this->collapsed = $collapsed; return $this; } @@ -127,7 +115,7 @@ abstract class Dimension * * @return int */ - public function getXfIndex() + public function getXfIndex(): ?int { return $this->xfIndex; } @@ -135,11 +123,9 @@ abstract class Dimension /** * Set index to cellXf. * - * @param int $pValue - * * @return $this */ - public function setXfIndex($pValue) + public function setXfIndex(int $pValue) { $this->xfIndex = $pValue; diff --git a/src/PhpSpreadsheet/Worksheet/Drawing.php b/src/PhpSpreadsheet/Worksheet/Drawing.php index 1f1dae93..a8cbb79d 100644 --- a/src/PhpSpreadsheet/Worksheet/Drawing.php +++ b/src/PhpSpreadsheet/Worksheet/Drawing.php @@ -13,6 +13,13 @@ class Drawing extends BaseDrawing */ private $path; + /** + * Whether or not we are dealing with a URL. + * + * @var bool + */ + private $isUrl; + /** * Create a new Drawing. */ @@ -20,6 +27,7 @@ class Drawing extends BaseDrawing { // Initialise values $this->path = ''; + $this->isUrl = false; // Initialize parent parent::__construct(); @@ -81,9 +89,25 @@ class Drawing extends BaseDrawing public function setPath($pValue, $pVerifyFile = true) { if ($pVerifyFile) { - if (file_exists($pValue)) { + // Check if a URL has been passed. https://stackoverflow.com/a/2058596/1252979 + if (filter_var($pValue, FILTER_VALIDATE_URL)) { + $this->path = $pValue; + // Implicit that it is a URL, rather store info than running check above on value in other places. + $this->isUrl = true; + $imageContents = file_get_contents($pValue); + $filePath = tempnam(sys_get_temp_dir(), 'Drawing'); + if ($filePath) { + file_put_contents($filePath, $imageContents); + if (file_exists($filePath)) { + if ($this->width == 0 && $this->height == 0) { + // Get width/height + [$this->width, $this->height] = getimagesize($filePath); + } + unlink($filePath); + } + } + } elseif (file_exists($pValue)) { $this->path = $pValue; - if ($this->width == 0 && $this->height == 0) { // Get width/height [$this->width, $this->height] = getimagesize($pValue); @@ -98,6 +122,26 @@ class Drawing extends BaseDrawing return $this; } + /** + * Get isURL. + */ + public function getIsURL(): bool + { + return $this->isUrl; + } + + /** + * Set isURL. + * + * @return $this + */ + public function setIsURL(bool $isUrl): self + { + $this->isUrl = $isUrl; + + return $this; + } + /** * Get hash code. * diff --git a/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php b/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php index 01ffed94..0557c83c 100644 --- a/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php +++ b/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php @@ -52,7 +52,7 @@ class Shadow implements IComparable /** * Shadow alignment. * - * @var int + * @var string */ private $alignment; @@ -184,7 +184,7 @@ class Shadow implements IComparable /** * Get Shadow alignment. * - * @return int + * @return string */ public function getAlignment() { @@ -194,7 +194,7 @@ class Shadow implements IComparable /** * Set Shadow alignment. * - * @param int $pValue + * @param string $pValue * * @return $this */ diff --git a/src/PhpSpreadsheet/Worksheet/Iterator.php b/src/PhpSpreadsheet/Worksheet/Iterator.php index 6cfed37a..a4061b78 100644 --- a/src/PhpSpreadsheet/Worksheet/Iterator.php +++ b/src/PhpSpreadsheet/Worksheet/Iterator.php @@ -29,14 +29,6 @@ class Iterator implements \Iterator $this->subject = $subject; } - /** - * Destructor. - */ - public function __destruct() - { - $this->subject = null; - } - /** * Rewind iterator. */ @@ -47,20 +39,16 @@ class Iterator implements \Iterator /** * Current Worksheet. - * - * @return Worksheet */ - public function current() + public function current(): Worksheet { return $this->subject->getSheet($this->position); } /** * Current key. - * - * @return int */ - public function key() + public function key(): int { return $this->position; } @@ -75,10 +63,8 @@ class Iterator implements \Iterator /** * Are there more Worksheet instances available? - * - * @return bool */ - public function valid() + public function valid(): bool { return $this->position < $this->subject->getSheetCount() && $this->position >= 0; } diff --git a/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php b/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php index fb002114..7789543a 100644 --- a/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php +++ b/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php @@ -3,6 +3,7 @@ namespace PhpOffice\PhpSpreadsheet\Worksheet; use GdImage; +use PhpOffice\PhpSpreadsheet\Exception; class MemoryDrawing extends BaseDrawing { @@ -21,7 +22,7 @@ class MemoryDrawing extends BaseDrawing /** * Image resource. * - * @var GdImage|resource + * @var null|GdImage|resource */ private $imageResource; @@ -52,7 +53,6 @@ class MemoryDrawing extends BaseDrawing public function __construct() { // Initialise values - $this->imageResource = null; $this->renderingFunction = self::RENDERING_DEFAULT; $this->mimeType = self::MIMETYPE_DEFAULT; $this->uniqueName = md5(mt_rand(0, 9999) . time() . mt_rand(0, 9999)); @@ -61,10 +61,71 @@ class MemoryDrawing extends BaseDrawing parent::__construct(); } + public function __destruct() + { + if ($this->imageResource) { + imagedestroy($this->imageResource); + $this->imageResource = null; + } + } + + public function __clone() + { + parent::__clone(); + $this->cloneResource(); + } + + private function cloneResource(): void + { + if (!$this->imageResource) { + return; + } + + $width = imagesx($this->imageResource); + $height = imagesy($this->imageResource); + + if (imageistruecolor($this->imageResource)) { + $clone = imagecreatetruecolor($width, $height); + if (!$clone) { + throw new Exception('Could not clone image resource'); + } + + imagealphablending($clone, false); + imagesavealpha($clone, true); + } else { + $clone = imagecreate($width, $height); + if (!$clone) { + throw new Exception('Could not clone image resource'); + } + + // If the image has transparency... + $transparent = imagecolortransparent($this->imageResource); + if ($transparent >= 0) { + $rgb = imagecolorsforindex($this->imageResource, $transparent); + if ($rgb === false) { + throw new Exception('Could not get image colors'); + } + + imagesavealpha($clone, true); + $color = imagecolorallocatealpha($clone, $rgb['red'], $rgb['green'], $rgb['blue'], $rgb['alpha']); + if ($color === false) { + throw new Exception('Could not get image alpha color'); + } + + imagefill($clone, 0, 0, $color); + } + } + + //Create the Clone!! + imagecopy($clone, $this->imageResource, 0, 0, 0, 0, $width, $height); + + $this->imageResource = $clone; + } + /** * Get image resource. * - * @return GdImage|resource + * @return null|GdImage|resource */ public function getImageResource() { diff --git a/src/PhpSpreadsheet/Worksheet/PageSetup.php b/src/PhpSpreadsheet/Worksheet/PageSetup.php index d1a22a7b..7f3f71dc 100644 --- a/src/PhpSpreadsheet/Worksheet/PageSetup.php +++ b/src/PhpSpreadsheet/Worksheet/PageSetup.php @@ -238,7 +238,7 @@ class PageSetup /** * Print area. * - * @var string + * @var null|string */ private $printArea; diff --git a/src/PhpSpreadsheet/Worksheet/Row.php b/src/PhpSpreadsheet/Worksheet/Row.php index 4f48a346..01053c39 100644 --- a/src/PhpSpreadsheet/Worksheet/Row.php +++ b/src/PhpSpreadsheet/Worksheet/Row.php @@ -36,15 +36,14 @@ class Row */ public function __destruct() { + // @phpstan-ignore-next-line $this->worksheet = null; } /** * Get row index. - * - * @return int */ - public function getRowIndex() + public function getRowIndex(): int { return $this->rowIndex; } @@ -64,10 +63,8 @@ class Row /** * Returns bound worksheet. - * - * @return Worksheet */ - public function getWorksheet() + public function getWorksheet(): Worksheet { return $this->worksheet; } diff --git a/src/PhpSpreadsheet/Worksheet/RowCellIterator.php b/src/PhpSpreadsheet/Worksheet/RowCellIterator.php index 9b9d54eb..fc04ccd3 100644 --- a/src/PhpSpreadsheet/Worksheet/RowCellIterator.php +++ b/src/PhpSpreadsheet/Worksheet/RowCellIterator.php @@ -2,6 +2,7 @@ namespace PhpOffice\PhpSpreadsheet\Worksheet; +use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; @@ -59,7 +60,7 @@ class RowCellIterator extends CellIterator * * @return $this */ - public function resetStart($startColumn = 'A') + public function resetStart(string $startColumn = 'A') { $this->startColumnIndex = Coordinate::columnIndexFromString($startColumn); $this->adjustForExistingOnlyRange(); @@ -77,7 +78,7 @@ class RowCellIterator extends CellIterator */ public function resetEnd($endColumn = null) { - $endColumn = $endColumn ? $endColumn : $this->worksheet->getHighestColumn(); + $endColumn = $endColumn ?: $this->worksheet->getHighestColumn(); $this->endColumnIndex = Coordinate::columnIndexFromString($endColumn); $this->adjustForExistingOnlyRange(); @@ -91,7 +92,7 @@ class RowCellIterator extends CellIterator * * @return $this */ - public function seek($column = 'A') + public function seek(string $column = 'A') { $columnx = $column; $column = Coordinate::columnIndexFromString($column); @@ -116,20 +117,16 @@ class RowCellIterator extends CellIterator /** * Return the current cell in this worksheet row. - * - * @return \PhpOffice\PhpSpreadsheet\Cell\Cell */ - public function current() + public function current(): ?Cell { return $this->worksheet->getCellByColumnAndRow($this->currentColumnIndex, $this->rowIndex); } /** * Return the current iterator key. - * - * @return string */ - public function key() + public function key(): string { return Coordinate::stringFromColumnIndex($this->currentColumnIndex); } @@ -156,20 +153,16 @@ class RowCellIterator extends CellIterator /** * Indicate if more columns exist in the worksheet range of columns that we're iterating. - * - * @return bool */ - public function valid() + public function valid(): bool { return $this->currentColumnIndex <= $this->endColumnIndex && $this->currentColumnIndex >= $this->startColumnIndex; } /** * Return the current iterator position. - * - * @return int */ - public function getCurrentColumnIndex() + public function getCurrentColumnIndex(): int { return $this->currentColumnIndex; } diff --git a/src/PhpSpreadsheet/Worksheet/RowDimension.php b/src/PhpSpreadsheet/Worksheet/RowDimension.php index c4a87bdb..006157b2 100644 --- a/src/PhpSpreadsheet/Worksheet/RowDimension.php +++ b/src/PhpSpreadsheet/Worksheet/RowDimension.php @@ -2,6 +2,8 @@ namespace PhpOffice\PhpSpreadsheet\Worksheet; +use PhpOffice\PhpSpreadsheet\Helper\Dimension as CssDimension; + class RowDimension extends Dimension { /** @@ -43,10 +45,8 @@ class RowDimension extends Dimension /** * Get Row Index. - * - * @return int */ - public function getRowIndex() + public function getRowIndex(): int { return $this->rowIndex; } @@ -54,47 +54,51 @@ class RowDimension extends Dimension /** * Set Row Index. * - * @param int $pValue - * * @return $this */ - public function setRowIndex($pValue) + public function setRowIndex(int $index) { - $this->rowIndex = $pValue; + $this->rowIndex = $index; return $this; } /** * Get Row Height. + * By default, this will be in points; but this method accepts a unit of measure + * argument, and will convert the value to the specified UoM. * * @return float */ - public function getRowHeight() + public function getRowHeight(?string $unitOfMeasure = null) { - return $this->height; + return ($unitOfMeasure === null || $this->height < 0) + ? $this->height + : (new CssDimension($this->height . CssDimension::UOM_POINTS))->toUnit($unitOfMeasure); } /** * Set Row Height. * - * @param float $pValue + * @param float $height in points + * By default, this will be the passed argument value; but this method accepts a unit of measure + * argument, and will convert the passed argument value to points from the specified UoM * * @return $this */ - public function setRowHeight($pValue) + public function setRowHeight($height, ?string $unitOfMeasure = null) { - $this->height = $pValue; + $this->height = ($unitOfMeasure === null || $height < 0) + ? $height + : (new CssDimension("{$height}{$unitOfMeasure}"))->height(); return $this; } /** * Get ZeroHeight. - * - * @return bool */ - public function getZeroHeight() + public function getZeroHeight(): bool { return $this->zeroHeight; } @@ -102,11 +106,9 @@ class RowDimension extends Dimension /** * Set ZeroHeight. * - * @param bool $pValue - * * @return $this */ - public function setZeroHeight($pValue) + public function setZeroHeight(bool $pValue) { $this->zeroHeight = $pValue; diff --git a/src/PhpSpreadsheet/Worksheet/RowIterator.php b/src/PhpSpreadsheet/Worksheet/RowIterator.php index 42542533..7fe0f80b 100644 --- a/src/PhpSpreadsheet/Worksheet/RowIterator.php +++ b/src/PhpSpreadsheet/Worksheet/RowIterator.php @@ -50,14 +50,6 @@ class RowIterator implements Iterator $this->resetStart($startRow); } - /** - * Destructor. - */ - public function __destruct() - { - $this->subject = null; - } - /** * (Re)Set the start row and the current row pointer. * @@ -65,10 +57,12 @@ class RowIterator implements Iterator * * @return $this */ - public function resetStart($startRow = 1) + public function resetStart(int $startRow = 1) { if ($startRow > $this->subject->getHighestRow()) { - throw new PhpSpreadsheetException("Start row ({$startRow}) is beyond highest row ({$this->subject->getHighestRow()})"); + throw new PhpSpreadsheetException( + "Start row ({$startRow}) is beyond highest row ({$this->subject->getHighestRow()})" + ); } $this->startRow = $startRow; @@ -89,7 +83,7 @@ class RowIterator implements Iterator */ public function resetEnd($endRow = null) { - $this->endRow = ($endRow) ? $endRow : $this->subject->getHighestRow(); + $this->endRow = $endRow ?: $this->subject->getHighestRow(); return $this; } @@ -101,7 +95,7 @@ class RowIterator implements Iterator * * @return $this */ - public function seek($row = 1) + public function seek(int $row = 1) { if (($row < $this->startRow) || ($row > $this->endRow)) { throw new PhpSpreadsheetException("Row $row is out of range ({$this->startRow} - {$this->endRow})"); @@ -121,20 +115,16 @@ class RowIterator implements Iterator /** * Return the current row in this worksheet. - * - * @return Row */ - public function current() + public function current(): Row { return new Row($this->subject, $this->position); } /** * Return the current iterator key. - * - * @return int */ - public function key() + public function key(): int { return $this->position; } @@ -157,10 +147,8 @@ class RowIterator implements Iterator /** * Indicate if more rows exist in the worksheet range of rows that we're iterating. - * - * @return bool */ - public function valid() + public function valid(): bool { return $this->position <= $this->endRow && $this->position >= $this->startRow; } diff --git a/src/PhpSpreadsheet/Worksheet/Worksheet.php b/src/PhpSpreadsheet/Worksheet/Worksheet.php index 19833b71..f7f28be6 100644 --- a/src/PhpSpreadsheet/Worksheet/Worksheet.php +++ b/src/PhpSpreadsheet/Worksheet/Worksheet.php @@ -96,16 +96,16 @@ class Worksheet implements IComparable /** * Collection of drawings. * - * @var BaseDrawing[] + * @var ArrayObject */ private $drawingCollection; /** * Collection of Chart objects. * - * @var Chart[] + * @var ArrayObject */ - private $chartCollection = []; + private $chartCollection; /** * Worksheet title. @@ -180,7 +180,7 @@ class Worksheet implements IComparable /** * Collection of breaks. * - * @var array + * @var int[] */ private $breaks = []; @@ -194,7 +194,7 @@ class Worksheet implements IComparable /** * Collection of protected cell ranges. * - * @var array + * @var string[] */ private $protectedCells = []; @@ -278,9 +278,9 @@ class Worksheet implements IComparable /** * Cached highest column. * - * @var string + * @var int */ - private $cachedHighestColumn = 'A'; + private $cachedHighestColumn = 1; /** * Cached highest row. @@ -313,7 +313,7 @@ class Worksheet implements IComparable /** * Tab color. * - * @var Color + * @var null|Color */ private $tabColor; @@ -383,9 +383,11 @@ class Worksheet implements IComparable { if ($this->cellCollection !== null) { $this->cellCollection->unsetWorksheetCells(); + // @phpstan-ignore-next-line $this->cellCollection = null; } // detach ourself from the workbook, so that it can then delete this worksheet successfully + // @phpstan-ignore-next-line $this->parent = null; } @@ -397,6 +399,7 @@ class Worksheet implements IComparable Calculation::getInstance($this->parent)->clearCalculationCacheForWorksheet($this->title); $this->disconnectCells(); + $this->rowDimensions = []; } /** @@ -534,7 +537,7 @@ class Worksheet implements IComparable /** * Get collection of drawings. * - * @return BaseDrawing[] + * @return ArrayObject */ public function getDrawingCollection() { @@ -544,7 +547,7 @@ class Worksheet implements IComparable /** * Get collection of charts. * - * @return Chart[] + * @return ArrayObject */ public function getChartCollection() { @@ -728,7 +731,7 @@ class Worksheet implements IComparable // loop through all cells in the worksheet foreach ($this->getCoordinates(false) as $coordinate) { - $cell = $this->getCell($coordinate, false); + $cell = $this->getCellOrNull($coordinate); if ($cell !== null && isset($autoSizes[$this->cellCollection->getCurrentColumn()])) { //Determine if cell is in merge range $isMerged = isset($isMergeCell[$this->cellCollection->getCurrentCoordinate()]); @@ -754,15 +757,17 @@ class Worksheet implements IComparable $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode() ); - $autoSizes[$this->cellCollection->getCurrentColumn()] = max( - (float) $autoSizes[$this->cellCollection->getCurrentColumn()], - (float) Shared\Font::calculateColumnWidth( - $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(), - $cellValue, - $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getAlignment()->getTextRotation(), - $this->getParent()->getDefaultStyle()->getFont() - ) - ); + if ($cellValue !== null && $cellValue !== '') { + $autoSizes[$this->cellCollection->getCurrentColumn()] = max( + (float) $autoSizes[$this->cellCollection->getCurrentColumn()], + (float) Shared\Font::calculateColumnWidth( + $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(), + $cellValue, + $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getAlignment()->getTextRotation(), + $this->getParent()->getDefaultStyle()->getFont() + ) + ); + } } } } @@ -824,7 +829,7 @@ class Worksheet implements IComparable /** * Set title. * - * @param string $pValue String containing the dimension of this worksheet + * @param string $title String containing the dimension of this worksheet * @param bool $updateFormulaCellReferences Flag indicating whether cell references in formulae should * be updated to reflect the new sheet name. * This should be left as the default true, unless you are @@ -835,10 +840,10 @@ class Worksheet implements IComparable * * @return $this */ - public function setTitle($pValue, $updateFormulaCellReferences = true, $validate = true) + public function setTitle($title, $updateFormulaCellReferences = true, $validate = true) { // Is this a 'rename' or not? - if ($this->getTitle() == $pValue) { + if ($this->getTitle() == $title) { return $this; } @@ -847,37 +852,37 @@ class Worksheet implements IComparable if ($validate) { // Syntax check - self::checkSheetTitle($pValue); + self::checkSheetTitle($title); if ($this->parent) { // Is there already such sheet name? - if ($this->parent->sheetNameExists($pValue)) { + if ($this->parent->sheetNameExists($title)) { // Use name, but append with lowest possible integer - if (Shared\StringHelper::countCharacters($pValue) > 29) { - $pValue = Shared\StringHelper::substring($pValue, 0, 29); + if (Shared\StringHelper::countCharacters($title) > 29) { + $title = Shared\StringHelper::substring($title, 0, 29); } $i = 1; - while ($this->parent->sheetNameExists($pValue . ' ' . $i)) { + while ($this->parent->sheetNameExists($title . ' ' . $i)) { ++$i; if ($i == 10) { - if (Shared\StringHelper::countCharacters($pValue) > 28) { - $pValue = Shared\StringHelper::substring($pValue, 0, 28); + if (Shared\StringHelper::countCharacters($title) > 28) { + $title = Shared\StringHelper::substring($title, 0, 28); } } elseif ($i == 100) { - if (Shared\StringHelper::countCharacters($pValue) > 27) { - $pValue = Shared\StringHelper::substring($pValue, 0, 27); + if (Shared\StringHelper::countCharacters($title) > 27) { + $title = Shared\StringHelper::substring($title, 0, 27); } } } - $pValue .= " $i"; + $title .= " $i"; } } } // Set title - $this->title = $pValue; + $this->title = $title; $this->dirty = true; if ($this->parent && $this->parent->getCalculationEngine()) { @@ -1039,7 +1044,7 @@ class Worksheet implements IComparable public function getHighestColumn($row = null) { if ($row == null) { - return $this->cachedHighestColumn; + return Coordinate::stringFromColumnIndex($this->cachedHighestColumn); } return $this->getHighestDataColumn($row); @@ -1166,50 +1171,94 @@ class Worksheet implements IComparable /** * Get cell at a specific coordinate. * - * @param string $pCoordinate Coordinate of the cell, eg: 'A1' - * @param bool $createIfNotExists Flag indicating whether a new cell should be created if it doesn't - * already exist, or a null should be returned instead + * @param string $coordinate Coordinate of the cell, eg: 'A1' * - * @return null|Cell Cell that was found/created or null + * @return Cell Cell that was found or created */ - public function getCell($pCoordinate, $createIfNotExists = true) + public function getCell(string $coordinate): Cell { - // Uppercase coordinate - $pCoordinateUpper = strtoupper($pCoordinate); + // Shortcut for increased performance for the vast majority of simple cases + if ($this->cellCollection->has($coordinate)) { + /** @var Cell $cell */ + $cell = $this->cellCollection->get($coordinate); - // Check cell collection - if ($this->cellCollection->has($pCoordinateUpper)) { - return $this->cellCollection->get($pCoordinateUpper); + return $cell; } + /** @var Worksheet $sheet */ + [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($coordinate); + $cell = $sheet->cellCollection->get($finalCoordinate); + + return $cell ?? $sheet->createNewCell($finalCoordinate); + } + + /** + * Get the correct Worksheet and coordinate from a coordinate that may + * contains reference to another sheet or a named range. + * + * @return array{0: Worksheet, 1: string} + */ + private function getWorksheetAndCoordinate(string $pCoordinate): array + { + $sheet = null; + $finalCoordinate = null; + // Worksheet reference? if (strpos($pCoordinate, '!') !== false) { $worksheetReference = self::extractSheetTitle($pCoordinate, true); - return $this->parent->getSheetByName($worksheetReference[0])->getCell(strtoupper($worksheetReference[1]), $createIfNotExists); - } + $sheet = $this->parent->getSheetByName($worksheetReference[0]); + $finalCoordinate = strtoupper($worksheetReference[1]); - // Named range? - if ( - (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $pCoordinate, $matches)) && - (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/i', $pCoordinate, $matches)) + if (!$sheet) { + throw new Exception('Sheet not found for name: ' . $worksheetReference[0]); + } + } elseif ( + !preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $pCoordinate) && + preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/i', $pCoordinate) ) { - $namedRange = DefinedName::resolveName($pCoordinate, $this); + // Named range? + $namedRange = $this->validateNamedRange($pCoordinate, true); if ($namedRange !== null) { - $pCoordinate = $namedRange->getValue(); + $sheet = $namedRange->getWorksheet(); + if (!$sheet) { + throw new Exception('Sheet not found for named range: ' . $namedRange->getName()); + } - return $namedRange->getWorksheet()->getCell($pCoordinate, $createIfNotExists); + $cellCoordinate = ltrim(substr($namedRange->getValue(), strrpos($namedRange->getValue(), '!')), '!'); + $finalCoordinate = str_replace('$', '', $cellCoordinate); } } - if (Coordinate::coordinateIsRange($pCoordinate)) { - throw new Exception('Cell coordinate can not be a range of cells.'); - } elseif (strpos($pCoordinate, '$') !== false) { + if (!$sheet || !$finalCoordinate) { + $sheet = $this; + $finalCoordinate = strtoupper($pCoordinate); + } + + if (Coordinate::coordinateIsRange($finalCoordinate)) { + throw new Exception('Cell coordinate string can not be a range of cells.'); + } elseif (strpos($finalCoordinate, '$') !== false) { throw new Exception('Cell coordinate must not be absolute.'); } - // Create new cell object, if required - return $createIfNotExists ? $this->createNewCell($pCoordinateUpper) : null; + return [$sheet, $finalCoordinate]; + } + + /** + * Get an existing cell at a specific coordinate, or null. + * + * @param string $coordinate Coordinate of the cell, eg: 'A1' + * + * @return null|Cell Cell that was found or null + */ + private function getCellOrNull($coordinate): ?Cell + { + // Check cell collection + if ($this->cellCollection->has($coordinate)) { + return $this->cellCollection->get($coordinate); + } + + return null; } /** @@ -1217,22 +1266,23 @@ class Worksheet implements IComparable * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell - * @param bool $createIfNotExists Flag indicating whether a new cell should be created if it doesn't - * already exist, or a null should be returned instead * - * @return null|Cell Cell that was found/created or null + * @return Cell Cell that was found/created or null */ - public function getCellByColumnAndRow($columnIndex, $row, $createIfNotExists = true) + public function getCellByColumnAndRow($columnIndex, $row): Cell { $columnLetter = Coordinate::stringFromColumnIndex($columnIndex); $coordinate = $columnLetter . $row; if ($this->cellCollection->has($coordinate)) { - return $this->cellCollection->get($coordinate); + /** @var Cell $cell */ + $cell = $this->cellCollection->get($coordinate); + + return $cell; } // Create new cell object, if required - return $createIfNotExists ? $this->createNewCell($coordinate) : null; + return $this->createNewCell($coordinate); } /** @@ -1249,18 +1299,19 @@ class Worksheet implements IComparable $this->cellCollectionIsSorted = false; // Coordinates - $aCoordinates = Coordinate::coordinateFromString($pCoordinate); - if (Coordinate::columnIndexFromString($this->cachedHighestColumn) < Coordinate::columnIndexFromString($aCoordinates[0])) { - $this->cachedHighestColumn = $aCoordinates[0]; + [$column, $row] = Coordinate::coordinateFromString($pCoordinate); + $aIndexes = Coordinate::indexesFromString($pCoordinate); + if ($this->cachedHighestColumn < $aIndexes[0]) { + $this->cachedHighestColumn = $aIndexes[0]; } - if ($aCoordinates[1] > $this->cachedHighestRow) { - $this->cachedHighestRow = $aCoordinates[1]; + if ($aIndexes[1] > $this->cachedHighestRow) { + $this->cachedHighestRow = $aIndexes[1]; } // Cell needs appropriate xfIndex from dimensions records // but don't create dimension records if they don't already exist - $rowDimension = $this->getRowDimension($aCoordinates[1], false); - $columnDimension = $this->getColumnDimension($aCoordinates[0], false); + $rowDimension = $this->rowDimensions[$row] ?? null; + $columnDimension = $this->columnDimensions[$column] ?? null; if ($rowDimension !== null && $rowDimension->getXfIndex() > 0) { // then there is a row dimension with explicit style, assign it to the cell @@ -1276,50 +1327,16 @@ class Worksheet implements IComparable /** * Does the cell at a specific coordinate exist? * - * @param string $pCoordinate Coordinate of the cell eg: 'A1' + * @param string $coordinate Coordinate of the cell eg: 'A1' * * @return bool */ - public function cellExists($pCoordinate) + public function cellExists($coordinate) { - // Worksheet reference? - if (strpos($pCoordinate, '!') !== false) { - $worksheetReference = self::extractSheetTitle($pCoordinate, true); + /** @var Worksheet $sheet */ + [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($coordinate); - return $this->parent->getSheetByName($worksheetReference[0])->cellExists(strtoupper($worksheetReference[1])); - } - - // Named range? - if ( - (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $pCoordinate, $matches)) && - (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/i', $pCoordinate, $matches)) - ) { - $namedRange = DefinedName::resolveName($pCoordinate, $this); - if ($namedRange !== null) { - $pCoordinate = $namedRange->getValue(); - if ($this->getHashCode() != $namedRange->getWorksheet()->getHashCode()) { - if (!$namedRange->getLocalOnly()) { - return $namedRange->getWorksheet()->cellExists($pCoordinate); - } - - throw new Exception('Named range ' . $namedRange->getName() . ' is not accessible from within sheet ' . $this->getTitle()); - } - } else { - return false; - } - } - - // Uppercase coordinate - $pCoordinate = strtoupper($pCoordinate); - - if (Coordinate::coordinateIsRange($pCoordinate)) { - throw new Exception('Cell coordinate can not be a range of cells.'); - } elseif (strpos($pCoordinate, '$') !== false) { - throw new Exception('Cell coordinate must not be absolute.'); - } - - // Cell exists? - return $this->cellCollection->has($pCoordinate); + return $sheet->cellCollection->has($finalCoordinate); } /** @@ -1339,20 +1356,11 @@ class Worksheet implements IComparable * Get row dimension at a specific row. * * @param int $pRow Numeric index of the row - * @param bool $create - * - * @return RowDimension */ - public function getRowDimension($pRow, $create = true) + public function getRowDimension(int $pRow): RowDimension { - // Found - $found = null; - // Get row dimension if (!isset($this->rowDimensions[$pRow])) { - if (!$create) { - return null; - } $this->rowDimensions[$pRow] = new RowDimension($pRow); $this->cachedHighestRow = max($this->cachedHighestRow, $pRow); @@ -1365,24 +1373,19 @@ class Worksheet implements IComparable * Get column dimension at a specific column. * * @param string $pColumn String index of the column eg: 'A' - * @param bool $create - * - * @return ColumnDimension */ - public function getColumnDimension($pColumn, $create = true) + public function getColumnDimension(string $pColumn): ColumnDimension { // Uppercase coordinate $pColumn = strtoupper($pColumn); // Fetch dimensions if (!isset($this->columnDimensions[$pColumn])) { - if (!$create) { - return null; - } $this->columnDimensions[$pColumn] = new ColumnDimension($pColumn); - if (Coordinate::columnIndexFromString($this->cachedHighestColumn) < Coordinate::columnIndexFromString($pColumn)) { - $this->cachedHighestColumn = $pColumn; + $columnIndex = Coordinate::columnIndexFromString($pColumn); + if ($this->cachedHighestColumn < $columnIndex) { + $this->cachedHighestColumn = $columnIndex; } } @@ -1393,10 +1396,8 @@ class Worksheet implements IComparable * Get column dimension at a specific column by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell - * - * @return ColumnDimension */ - public function getColumnDimensionByColumn($columnIndex) + public function getColumnDimensionByColumn(int $columnIndex): ColumnDimension { return $this->getColumnDimension(Coordinate::stringFromColumnIndex($columnIndex)); } @@ -1486,7 +1487,7 @@ class Worksheet implements IComparable * Set conditional styles. * * @param string $pCoordinate eg: 'A1' - * @param $pValue Conditional[] + * @param Conditional[] $pValue * * @return $this */ @@ -1644,7 +1645,7 @@ class Worksheet implements IComparable /** * Get breaks. * - * @return array[] + * @return int[] */ public function getBreaks() { @@ -1857,7 +1858,7 @@ class Worksheet implements IComparable /** * Get protected cells. * - * @return array[] + * @return string[] */ public function getProtectedCells() { @@ -1927,7 +1928,7 @@ class Worksheet implements IComparable /** * Get Freeze Pane. * - * @return string + * @return null|string */ public function getFreezePane() { @@ -1965,6 +1966,13 @@ class Worksheet implements IComparable return $this; } + public function setTopLeftCell(string $topLeftCell): self + { + $this->topLeftCell = $topLeftCell; + + return $this; + } + /** * Freeze Pane by using numeric cell coordinates. * @@ -1991,7 +1999,7 @@ class Worksheet implements IComparable /** * Get the default position of the right bottom pane. * - * @return int + * @return null|string */ public function getTopLeftCell() { @@ -2365,6 +2373,38 @@ class Worksheet implements IComparable return $this->setSelectedCells($pCoordinate); } + /** + * Sigh - Phpstan thinks, correctly, that preg_replace can return null. + * But Scrutinizer doesn't. Try to satisfy both. + * + * @param mixed $str + */ + private static function ensureString($str): string + { + return is_string($str) ? $str : ''; + } + + public static function pregReplace(string $pattern, string $replacement, string $subject): string + { + return self::ensureString(preg_replace($pattern, $replacement, $subject)); + } + + private function tryDefinedName(string $pCoordinate): string + { + // Uppercase coordinate + $pCoordinate = strtoupper($pCoordinate); + // Eliminate leading equal sign + $pCoordinate = self::pregReplace('/^=/', '', $pCoordinate); + $defined = $this->parent->getDefinedName($pCoordinate, $this); + if ($defined !== null) { + if ($defined->getWorksheet() === $this && !$defined->isFormula()) { + $pCoordinate = self::pregReplace('/^=/', '', $defined->getValue()); + } + } + + return $pCoordinate; + } + /** * Select a range of cells. * @@ -2374,20 +2414,23 @@ class Worksheet implements IComparable */ public function setSelectedCells($pCoordinate) { - // Uppercase coordinate - $pCoordinate = strtoupper($pCoordinate); + $originalCoordinate = $pCoordinate; + $pCoordinate = $this->tryDefinedName($pCoordinate); // Convert 'A' to 'A:A' - $pCoordinate = preg_replace('/^([A-Z]+)$/', '${1}:${1}', $pCoordinate); + $pCoordinate = self::pregReplace('/^([A-Z]+)$/', '${1}:${1}', $pCoordinate); // Convert '1' to '1:1' - $pCoordinate = preg_replace('/^(\d+)$/', '${1}:${1}', $pCoordinate); + $pCoordinate = self::pregReplace('/^(\d+)$/', '${1}:${1}', $pCoordinate); // Convert 'A:C' to 'A1:C1048576' - $pCoordinate = preg_replace('/^([A-Z]+):([A-Z]+)$/', '${1}1:${2}1048576', $pCoordinate); + $pCoordinate = self::pregReplace('/^([A-Z]+):([A-Z]+)$/', '${1}1:${2}1048576', $pCoordinate); // Convert '1:3' to 'A1:XFD3' - $pCoordinate = preg_replace('/^(\d+):(\d+)$/', 'A${1}:XFD${2}', $pCoordinate); + $pCoordinate = self::pregReplace('/^(\d+):(\d+)$/', 'A${1}:XFD${2}', $pCoordinate); + if (preg_match('/^\\$?[A-Z]{1,3}\\$?\d{1,7}(:\\$?[A-Z]{1,3}\\$?\d{1,7})?$/', $pCoordinate) !== 1) { + throw new Exception("Invalid setSelectedCells $originalCoordinate $pCoordinate"); + } if (Coordinate::coordinateIsRange($pCoordinate)) { [$first] = Coordinate::splitRange($pCoordinate); @@ -2550,10 +2593,42 @@ class Worksheet implements IComparable return $returnValue; } + private function validateNamedRange(string $definedName, bool $returnNullIfInvalid = false): ?DefinedName + { + $namedRange = DefinedName::resolveName($definedName, $this); + if ($namedRange === null) { + if ($returnNullIfInvalid) { + return null; + } + + throw new Exception('Named Range ' . $definedName . ' does not exist.'); + } + + if ($namedRange->isFormula()) { + if ($returnNullIfInvalid) { + return null; + } + + throw new Exception('Defined Named ' . $definedName . ' is a formula, not a range or cell.'); + } + + if ($namedRange->getLocalOnly() && $this->getHashCode() !== $namedRange->getWorksheet()->getHashCode()) { + if ($returnNullIfInvalid) { + return null; + } + + throw new Exception( + 'Named range ' . $definedName . ' is not accessible from within sheet ' . $this->getTitle() + ); + } + + return $namedRange; + } + /** * Create array from a range of cells. * - * @param string $pNamedRange Name of the Named Range + * @param string $definedName The Named Range that should be returned * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist * @param bool $calculateFormulas Should formulas be calculated? * @param bool $formatData Should formatting be applied to cell values? @@ -2562,17 +2637,14 @@ class Worksheet implements IComparable * * @return array */ - public function namedRangeToArray($pNamedRange, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) + public function namedRangeToArray(string $definedName, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) { - $namedRange = DefinedName::resolveName($pNamedRange, $this); - if ($namedRange !== null) { - $pWorkSheet = $namedRange->getWorksheet(); - $pCellRange = $namedRange->getValue(); + $namedRange = $this->validateNamedRange($definedName); + $workSheet = $namedRange->getWorksheet(); + $cellRange = ltrim(substr($namedRange->getValue(), strrpos($namedRange->getValue(), '!')), '!'); + $cellRange = str_replace('$', '', $cellRange); - return $pWorkSheet->rangeToArray($pCellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef); - } - - throw new Exception('Named Range ' . $pNamedRange . ' does not exist.'); + return $workSheet->rangeToArray($cellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef); } /** @@ -2652,9 +2724,9 @@ class Worksheet implements IComparable // Cache values if ($highestColumn < 1) { - $this->cachedHighestColumn = 'A'; + $this->cachedHighestColumn = 1; } else { - $this->cachedHighestColumn = Coordinate::stringFromColumnIndex($highestColumn); + $this->cachedHighestColumn = $highestColumn; } $this->cachedHighestRow = $highestRow; @@ -2880,7 +2952,6 @@ class Worksheet implements IComparable public function resetTabColor() { $this->tabColor = null; - $this->tabColor = null; return $this; } @@ -2910,6 +2981,7 @@ class Worksheet implements IComparable */ public function __clone() { + // @phpstan-ignore-next-line foreach ($this as $key => $val) { if ($key == 'parent') { continue; diff --git a/src/PhpSpreadsheet/Writer/BaseWriter.php b/src/PhpSpreadsheet/Writer/BaseWriter.php index 6e8f7495..7811a2a0 100644 --- a/src/PhpSpreadsheet/Writer/BaseWriter.php +++ b/src/PhpSpreadsheet/Writer/BaseWriter.php @@ -6,7 +6,7 @@ abstract class BaseWriter implements IWriter { /** * Write charts that are defined in the workbook? - * Identifies whether the Writer should write definitions for any charts that exist in the PhpSpreadsheet object;. + * Identifies whether the Writer should write definitions for any charts that exist in the PhpSpreadsheet object. * * @var bool */ @@ -94,6 +94,13 @@ abstract class BaseWriter implements IWriter return $this->diskCachingDirectory; } + protected function processFlags(int $flags): void + { + if (((bool) ($flags & self::SAVE_WITH_CHARTS)) === true) { + $this->setIncludeCharts(true); + } + } + /** * Open file handle. * @@ -108,7 +115,12 @@ abstract class BaseWriter implements IWriter return; } - $fileHandle = $filename ? fopen($filename, 'wb+') : false; + $mode = 'wb+'; + $scheme = parse_url($filename, PHP_URL_SCHEME); + if ($scheme === 's3') { + $mode = 'w'; + } + $fileHandle = $filename ? fopen($filename, $mode) : false; if ($fileHandle === false) { throw new Exception('Could not open file "' . $filename . '" for writing.'); } diff --git a/src/PhpSpreadsheet/Writer/Csv.php b/src/PhpSpreadsheet/Writer/Csv.php index d6d688c0..556ac2de 100644 --- a/src/PhpSpreadsheet/Writer/Csv.php +++ b/src/PhpSpreadsheet/Writer/Csv.php @@ -64,6 +64,13 @@ class Csv extends BaseWriter */ private $excelCompatibility = false; + /** + * Output encoding. + * + * @var string + */ + private $outputEncoding = ''; + /** * Create a new CSV. * @@ -79,8 +86,10 @@ class Csv extends BaseWriter * * @param resource|string $filename */ - public function save($filename): void + public function save($filename, int $flags = 0): void { + $this->processFlags($flags); + // Fetch sheet $sheet = $this->spreadsheet->getSheet($this->sheetIndex); @@ -296,6 +305,31 @@ class Csv extends BaseWriter return $this; } + /** + * Get output encoding. + * + * @return string + */ + public function getOutputEncoding() + { + return $this->outputEncoding; + } + + /** + * Set output encoding. + * + * @param string $pValue Output encoding + * + * @return $this + */ + public function setOutputEncoding($pValue) + { + $this->outputEncoding = $pValue; + + return $this; + } + + /** @var bool */ private $enclosureRequired = true; public function setEnclosureRequired(bool $value): self @@ -310,6 +344,20 @@ class Csv extends BaseWriter return $this->enclosureRequired; } + /** + * Convert boolean to TRUE/FALSE; otherwise return element cast to string. + * + * @param mixed $element + */ + private static function elementToString($element): string + { + if (is_bool($element)) { + return $element ? 'TRUE' : 'FALSE'; + } + + return (string) $element; + } + /** * Write line to CSV file. * @@ -325,6 +373,7 @@ class Csv extends BaseWriter $line = ''; foreach ($pValues as $element) { + $element = self::elementToString($element); // Add delimiter $line .= $delimiter; $delimiter = $this->delimiter; @@ -347,6 +396,9 @@ class Csv extends BaseWriter $line .= $this->lineEnding; // Write to file + if ($this->outputEncoding != '') { + $line = mb_convert_encoding($line, $this->outputEncoding); + } fwrite($pFileHandle, $line); } } diff --git a/src/PhpSpreadsheet/Writer/Html.php b/src/PhpSpreadsheet/Writer/Html.php index 340a9ba0..9f7d347b 100644 --- a/src/PhpSpreadsheet/Writer/Html.php +++ b/src/PhpSpreadsheet/Writer/Html.php @@ -9,6 +9,7 @@ use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Chart\Chart; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\RichText\Run; +use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Shared\Drawing as SharedDrawing; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Shared\Font as SharedFont; @@ -37,7 +38,7 @@ class Html extends BaseWriter /** * Sheet index to write. * - * @var int + * @var null|int */ private $sheetIndex = 0; @@ -153,8 +154,10 @@ class Html extends BaseWriter * * @param resource|string $filename */ - public function save($filename): void + public function save($filename, int $flags = 0): void { + $this->processFlags($flags); + // Open file $this->openFileHandle($filename); @@ -348,7 +351,9 @@ class Html extends BaseWriter private static function generateMeta($val, $desc) { - return $val ? (' ' . PHP_EOL) : ''; + return $val + ? (' ' . PHP_EOL) + : ''; } /** @@ -367,7 +372,7 @@ class Html extends BaseWriter $html .= ' ' . PHP_EOL; $html .= ' ' . PHP_EOL; $html .= ' ' . PHP_EOL; - $html .= ' ' . htmlspecialchars($properties->getTitle()) . '' . PHP_EOL; + $html .= ' ' . htmlspecialchars($properties->getTitle(), Settings::htmlEntityFlags()) . '' . PHP_EOL; $html .= self::generateMeta($properties->getCreator(), 'author'); $html .= self::generateMeta($properties->getTitle(), 'title'); $html .= self::generateMeta($properties->getDescription(), 'description'); @@ -453,10 +458,8 @@ class Html extends BaseWriter // Get worksheet dimension [$min, $max] = explode(':', $sheet->calculateWorksheetDataDimension()); - [$minCol, $minRow] = Coordinate::coordinateFromString($min); - $minCol = Coordinate::columnIndexFromString($minCol); - [$maxCol, $maxRow] = Coordinate::coordinateFromString($max); - $maxCol = Coordinate::columnIndexFromString($maxCol); + [$minCol, $minRow] = Coordinate::indexesFromString($min); + [$maxCol, $maxRow] = Coordinate::indexesFromString($max); [$theadStart, $theadEnd, $tbodyStart] = $this->generateSheetStarts($sheet, $minRow); @@ -548,20 +551,19 @@ class Html extends BaseWriter * Jpgraph code issuing warnings. So, don't measure * code coverage for this function till that is fixed. * - * @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet * @param int $row Row to check for charts * * @return array * * @codeCoverageIgnore */ - private function extendRowsForCharts(Worksheet $pSheet, int $row) + private function extendRowsForCharts(Worksheet $worksheet, int $row) { $rowMax = $row; $colMax = 'A'; $anyfound = false; if ($this->includeCharts) { - foreach ($pSheet->getChartCollection() as $chart) { + foreach ($worksheet->getChartCollection() as $chart) { if ($chart instanceof Chart) { $anyfound = true; $chartCoordinates = $chart->getTopLeftPosition(); @@ -580,11 +582,11 @@ class Html extends BaseWriter return [$rowMax, $colMax, $anyfound]; } - private function extendRowsForChartsAndImages(Worksheet $pSheet, int $row): string + private function extendRowsForChartsAndImages(Worksheet $worksheet, int $row): string { - [$rowMax, $colMax, $anyfound] = $this->extendRowsForCharts($pSheet, $row); + [$rowMax, $colMax, $anyfound] = $this->extendRowsForCharts($worksheet, $row); - foreach ($pSheet->getDrawingCollection() as $drawing) { + foreach ($worksheet->getDrawingCollection() as $drawing) { $anyfound = true; $imageTL = Coordinate::coordinateFromString($drawing->getCoordinates()); $imageCol = Coordinate::columnIndexFromString($imageTL[0]); @@ -607,8 +609,8 @@ class Html extends BaseWriter while ($row <= $rowMax) { $html .= ''; for ($col = 'A'; $col != $colMax; ++$col) { - $htmlx = $this->writeImageInCell($pSheet, $col . $row); - $htmlx .= $this->includeCharts ? $this->writeChartInCell($pSheet, $col . $row) : ''; + $htmlx = $this->writeImageInCell($worksheet, $col . $row); + $htmlx .= $this->includeCharts ? $this->writeChartInCell($worksheet, $col . $row) : ''; if ($htmlx) { $html .= "$htmlx"; } else { @@ -642,18 +644,18 @@ class Html extends BaseWriter /** * Generate image tag in cell. * - * @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet + * @param Worksheet $worksheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet * @param string $coordinates Cell coordinates * * @return string */ - private function writeImageInCell(Worksheet $pSheet, $coordinates) + private function writeImageInCell(Worksheet $worksheet, $coordinates) { // Construct HTML $html = ''; // Write images - foreach ($pSheet->getDrawingCollection() as $drawing) { + foreach ($worksheet->getDrawingCollection() as $drawing) { if ($drawing->getCoordinates() != $coordinates) { continue; } @@ -672,7 +674,7 @@ class Html extends BaseWriter $filename = preg_replace('@^[.]([^/])@', '$1', $filename); // Convert UTF8 data to PCDATA - $filename = htmlspecialchars($filename); + $filename = htmlspecialchars($filename, Settings::htmlEntityFlags()); $html .= PHP_EOL; $imageData = self::winFileToUrl($filename); @@ -692,18 +694,21 @@ class Html extends BaseWriter $drawing->getWidth() . 'px; height: ' . $drawing->getHeight() . 'px;" src="' . $imageData . '" alt="' . $filedesc . '" />'; } elseif ($drawing instanceof MemoryDrawing) { - ob_start(); // Let's start output buffering. - imagepng($drawing->getImageResource()); // This will normally output the image, but because of ob_start(), it won't. + $imageResource = $drawing->getImageResource(); + if ($imageResource) { + ob_start(); // Let's start output buffering. + imagepng($imageResource); // This will normally output the image, but because of ob_start(), it won't. $contents = ob_get_contents(); // Instead, output above is saved to $contents ob_end_clean(); // End the output buffer. $dataUri = 'data:image/jpeg;base64,' . base64_encode($contents); - // Because of the nature of tables, width is more important than height. - // max-width: 100% ensures that image doesnt overflow containing cell - // width: X sets width of supplied image. - // As a result, images bigger than cell will be contained and images smaller will not get stretched - $html .= '' . $filedesc . ''; + // Because of the nature of tables, width is more important than height. + // max-width: 100% ensures that image doesnt overflow containing cell + // width: X sets width of supplied image. + // As a result, images bigger than cell will be contained and images smaller will not get stretched + $html .= '' . $filedesc . ''; + } } } @@ -718,32 +723,27 @@ class Html extends BaseWriter * Jpgraph code issuing warnings. So, don't measure * code coverage for this function till that is fixed. * - * @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet - * @param string $coordinates Cell coordinates - * - * @return string - * * @codeCoverageIgnore */ - private function writeChartInCell(Worksheet $pSheet, $coordinates) + private function writeChartInCell(Worksheet $worksheet, string $coordinates): string { // Construct HTML $html = ''; // Write charts - foreach ($pSheet->getChartCollection() as $chart) { + foreach ($worksheet->getChartCollection() as $chart) { if ($chart instanceof Chart) { $chartCoordinates = $chart->getTopLeftPosition(); if ($chartCoordinates['cell'] == $coordinates) { $chartFileName = File::sysGetTempDir() . '/' . uniqid('', true) . '.png'; if (!$chart->render($chartFileName)) { - return; + return ''; } $html .= PHP_EOL; $imageDetails = getimagesize($chartFileName); $filedesc = $chart->getTitle(); - $filedesc = $filedesc ? self::getChartCaption($filedesc->getCaption()) : ''; + $filedesc = $filedesc ? $filedesc->getCaptionText() : ''; $filedesc = $filedesc ? htmlspecialchars($filedesc, ENT_QUOTES) : 'Embedded chart'; if ($fp = fopen($chartFileName, 'rb', 0)) { $picture = fread($fp, filesize($chartFileName)); @@ -764,27 +764,6 @@ class Html extends BaseWriter return $html; } - /** - * Extend Row if chart is placed after nominal end of row. - * This code should be exercised by sample: - * Chart/32_Chart_read_write_PDF.php. - * However, that test is suppressed due to out-of-date - * Jpgraph code issuing warnings. So, don't measure - * code coverage for this function till that is fixed. - * Caption is described in documentation as fixed, - * but in 32_Chart it is somehow an array of RichText. - * - * @param mixed $cap - * - * @return string - * - * @codeCoverageIgnore - */ - private static function getChartCaption($cap) - { - return is_array($cap) ? implode(' ', $cap) : $cap; - } - /** * Generate CSS styles. * @@ -1132,13 +1111,13 @@ class Html extends BaseWriter return $html; } - private function generateTableTagInline($pSheet, $id) + private function generateTableTagInline(Worksheet $worksheet, $id) { $style = isset($this->cssStyles['table']) ? $this->assembleCSS($this->cssStyles['table']) : ''; - $prntgrid = $pSheet->getPrintGridlines(); - $viewgrid = $this->isPdf ? $prntgrid : $pSheet->getShowGridlines(); + $prntgrid = $worksheet->getPrintGridlines(); + $viewgrid = $this->isPdf ? $prntgrid : $worksheet->getShowGridlines(); if ($viewgrid && $prntgrid) { $html = " " . PHP_EOL; } elseif ($viewgrid) { @@ -1152,28 +1131,28 @@ class Html extends BaseWriter return $html; } - private function generateTableTag($pSheet, $id, &$html, $sheetIndex): void + private function generateTableTag(Worksheet $worksheet, $id, &$html, $sheetIndex): void { if (!$this->useInlineCss) { - $gridlines = $pSheet->getShowGridlines() ? ' gridlines' : ''; - $gridlinesp = $pSheet->getPrintGridlines() ? ' gridlinesp' : ''; + $gridlines = $worksheet->getShowGridlines() ? ' gridlines' : ''; + $gridlinesp = $worksheet->getPrintGridlines() ? ' gridlinesp' : ''; $html .= "
" . PHP_EOL; } else { - $html .= $this->generateTableTagInline($pSheet, $id); + $html .= $this->generateTableTagInline($worksheet, $id); } } /** * Generate table header. * - * @param Worksheet $pSheet The worksheet for the table we are writing + * @param Worksheet $worksheet The worksheet for the table we are writing * @param bool $showid whether or not to add id to table tag * * @return string */ - private function generateTableHeader($pSheet, $showid = true) + private function generateTableHeader(Worksheet $worksheet, $showid = true) { - $sheetIndex = $pSheet->getParent()->getIndex($pSheet); + $sheetIndex = $worksheet->getParent()->getIndex($worksheet); // Construct HTML $html = ''; @@ -1184,10 +1163,10 @@ class Html extends BaseWriter $html .= "
\n"; } - $this->generateTableTag($pSheet, $id, $html, $sheetIndex); + $this->generateTableTag($worksheet, $id, $html, $sheetIndex); // Write
elements - $highestColumnIndex = Coordinate::columnIndexFromString($pSheet->getHighestColumn()) - 1; + $highestColumnIndex = Coordinate::columnIndexFromString($worksheet->getHighestColumn()) - 1; $i = -1; while ($i++ < $highestColumnIndex) { if (!$this->useInlineCss) { @@ -1213,17 +1192,16 @@ class Html extends BaseWriter /** * Generate row start. * - * @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet * @param int $sheetIndex Sheet index (0-based) * @param int $pRow row number * * @return string */ - private function generateRowStart(Worksheet $pSheet, $sheetIndex, $pRow) + private function generateRowStart(Worksheet $worksheet, $sheetIndex, $pRow) { $html = ''; - if (count($pSheet->getBreaks()) > 0) { - $breaks = $pSheet->getBreaks(); + if (count($worksheet->getBreaks()) > 0) { + $breaks = $worksheet->getBreaks(); // check if a break is needed before this row if (isset($breaks['A' . $pRow])) { @@ -1234,7 +1212,7 @@ class Html extends BaseWriter } // open table again:
+ etc. - $html .= $this->generateTableHeader($pSheet, false); + $html .= $this->generateTableHeader($worksheet, false); $html .= '' . PHP_EOL; } } @@ -1252,9 +1230,9 @@ class Html extends BaseWriter return $html; } - private function generateRowCellCss($pSheet, $cellAddress, $pRow, $colNum) + private function generateRowCellCss(Worksheet $worksheet, $cellAddress, $pRow, $colNum) { - $cell = ($cellAddress > '') ? $pSheet->getCell($cellAddress) : ''; + $cell = ($cellAddress > '') ? $worksheet->getCell($cellAddress) : ''; $coordinate = Coordinate::stringFromColumnIndex($colNum + 1) . ($pRow + 1); if (!$this->useInlineCss) { $cssClass = 'column' . $colNum; @@ -1298,7 +1276,7 @@ class Html extends BaseWriter // Convert UTF8 data to PCDATA $cellText = $element->getText(); - $cellData .= htmlspecialchars($cellText); + $cellData .= htmlspecialchars($cellText, Settings::htmlEntityFlags()); $cellData .= $cellEnd; @@ -1306,44 +1284,48 @@ class Html extends BaseWriter } else { // Convert UTF8 data to PCDATA $cellText = $element->getText(); - $cellData .= htmlspecialchars($cellText); + $cellData .= htmlspecialchars($cellText, Settings::htmlEntityFlags()); } } } - private function generateRowCellDataValue($pSheet, $cell, &$cellData): void + private function generateRowCellDataValue(Worksheet $worksheet, $cell, &$cellData): void { if ($cell->getValue() instanceof RichText) { $this->generateRowCellDataValueRich($cell, $cellData); } else { $origData = $this->preCalculateFormulas ? $cell->getCalculatedValue() : $cell->getValue(); - $cellData = NumberFormat::toFormattedString( - $origData, - $pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode(), - [$this, 'formatColor'] - ); - if ($cellData === $origData) { - $cellData = htmlspecialchars($cellData); + $formatCode = $worksheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode(); + if ($formatCode) { + $cellData = NumberFormat::toFormattedString( + $origData, + $formatCode, + [$this, 'formatColor'] + ); } - if ($pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSuperscript()) { + + if ($cellData === $origData) { + $cellData = htmlspecialchars($cellData ?? '', Settings::htmlEntityFlags()); + } + if ($worksheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSuperscript()) { $cellData = '' . $cellData . ''; - } elseif ($pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSubscript()) { + } elseif ($worksheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSubscript()) { $cellData = '' . $cellData . ''; } } } - private function generateRowCellData($pSheet, $cell, &$cssClass, $cellType) + private function generateRowCellData(Worksheet $worksheet, $cell, &$cssClass, $cellType) { $cellData = ' '; if ($cell instanceof Cell) { $cellData = ''; // Don't know what this does, and no test cases. //if ($cell->getParent() === null) { - // $cell->attach($pSheet); + // $cell->attach($worksheet); //} // Value - $this->generateRowCellDataValue($pSheet, $cell, $cellData); + $this->generateRowCellDataValue($worksheet, $cell, $cellData); // Converts the cell content so that spaces occuring at beginning of each new line are replaced by   // Example: " Hello\n to the world" is converted to "  Hello\n to the world" @@ -1368,7 +1350,7 @@ class Html extends BaseWriter } // General horizontal alignment: Actual horizontal alignment depends on dataType - $sharedStyle = $pSheet->getParent()->getCellXfByIndex($cell->getXfIndex()); + $sharedStyle = $worksheet->getParent()->getCellXfByIndex($cell->getXfIndex()); if ( $sharedStyle->getAlignment()->getHorizontal() == Alignment::HORIZONTAL_GENERAL && isset($this->cssStyles['.' . $cell->getDataType()]['text-align']) @@ -1386,9 +1368,9 @@ class Html extends BaseWriter return $cellData; } - private function generateRowIncludeCharts($pSheet, $coordinate) + private function generateRowIncludeCharts(Worksheet $worksheet, $coordinate) { - return $this->includeCharts ? $this->writeChartInCell($pSheet, $coordinate) : ''; + return $this->includeCharts ? $this->writeChartInCell($worksheet, $coordinate) : ''; } private function generateRowSpans($html, $rowSpan, $colSpan) @@ -1399,12 +1381,12 @@ class Html extends BaseWriter return $html; } - private function generateRowWriteCell(&$html, $pSheet, $coordinate, $cellType, $cellData, $colSpan, $rowSpan, $cssClass, $colNum, $sheetIndex, $pRow): void + private function generateRowWriteCell(&$html, Worksheet $worksheet, $coordinate, $cellType, $cellData, $colSpan, $rowSpan, $cssClass, $colNum, $sheetIndex, $pRow): void { // Image? - $htmlx = $this->writeImageInCell($pSheet, $coordinate); + $htmlx = $this->writeImageInCell($worksheet, $coordinate); // Chart? - $htmlx .= $this->generateRowIncludeCharts($pSheet, $coordinate); + $htmlx .= $this->generateRowIncludeCharts($worksheet, $coordinate); // Column start $html .= ' <' . $cellType; if (!$this->useInlineCss && !$this->isPdf) { @@ -1450,7 +1432,7 @@ class Html extends BaseWriter $html .= '>'; $html .= $htmlx; - $html .= $this->writeComment($pSheet, $coordinate); + $html .= $this->writeComment($worksheet, $coordinate); // Cell data $html .= $cellData; @@ -1462,44 +1444,43 @@ class Html extends BaseWriter /** * Generate row. * - * @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet * @param array $pValues Array containing cells in a row * @param int $pRow Row number (0-based) * @param string $cellType eg: 'td' * * @return string */ - private function generateRow(Worksheet $pSheet, array $pValues, $pRow, $cellType) + private function generateRow(Worksheet $worksheet, array $pValues, $pRow, $cellType) { // Sheet index - $sheetIndex = $pSheet->getParent()->getIndex($pSheet); - $html = $this->generateRowStart($pSheet, $sheetIndex, $pRow); + $sheetIndex = $worksheet->getParent()->getIndex($worksheet); + $html = $this->generateRowStart($worksheet, $sheetIndex, $pRow); // Write cells $colNum = 0; foreach ($pValues as $cellAddress) { - [$cell, $cssClass, $coordinate] = $this->generateRowCellCss($pSheet, $cellAddress, $pRow, $colNum); + [$cell, $cssClass, $coordinate] = $this->generateRowCellCss($worksheet, $cellAddress, $pRow, $colNum); $colSpan = 1; $rowSpan = 1; // Cell Data - $cellData = $this->generateRowCellData($pSheet, $cell, $cssClass, $cellType); + $cellData = $this->generateRowCellData($worksheet, $cell, $cssClass, $cellType); // Hyperlink? - if ($pSheet->hyperlinkExists($coordinate) && !$pSheet->getHyperlink($coordinate)->isInternal()) { - $cellData = '' . $cellData . ''; + if ($worksheet->hyperlinkExists($coordinate) && !$worksheet->getHyperlink($coordinate)->isInternal()) { + $cellData = '' . $cellData . ''; } // Should the cell be written or is it swallowed by a rowspan or colspan? - $writeCell = !(isset($this->isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum]) - && $this->isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum]); + $writeCell = !(isset($this->isSpannedCell[$worksheet->getParent()->getIndex($worksheet)][$pRow + 1][$colNum]) + && $this->isSpannedCell[$worksheet->getParent()->getIndex($worksheet)][$pRow + 1][$colNum]); // Colspan and Rowspan $colspan = 1; $rowspan = 1; - if (isset($this->isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])) { - $spans = $this->isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum]; + if (isset($this->isBaseCell[$worksheet->getParent()->getIndex($worksheet)][$pRow + 1][$colNum])) { + $spans = $this->isBaseCell[$worksheet->getParent()->getIndex($worksheet)][$pRow + 1][$colNum]; $rowSpan = $spans['rowspan']; $colSpan = $spans['colspan']; @@ -1507,13 +1488,13 @@ class Html extends BaseWriter // relies on !important for non-none border declarations in createCSSStyleBorder $endCellCoord = Coordinate::stringFromColumnIndex($colNum + $colSpan) . ($pRow + $rowSpan); if (!$this->useInlineCss) { - $cssClass .= ' style' . $pSheet->getCell($endCellCoord)->getXfIndex(); + $cssClass .= ' style' . $worksheet->getCell($endCellCoord)->getXfIndex(); } } // Write if ($writeCell) { - $this->generateRowWriteCell($html, $pSheet, $coordinate, $cellType, $cellData, $colSpan, $rowSpan, $cssClass, $colNum, $sheetIndex, $pRow); + $this->generateRowWriteCell($html, $worksheet, $coordinate, $cellType, $cellData, $colSpan, $rowSpan, $cssClass, $colNum, $sheetIndex, $pRow); } // Next column @@ -1668,7 +1649,7 @@ class Html extends BaseWriter } // convert to PCDATA - $value = htmlspecialchars($pValue); + $value = htmlspecialchars($pValue, Settings::htmlEntityFlags()); // color span tag if ($color !== null) { @@ -1703,11 +1684,11 @@ class Html extends BaseWriter $first = $cells[0]; $last = $cells[1]; - [$fc, $fr] = Coordinate::coordinateFromString($first); - $fc = Coordinate::columnIndexFromString($fc) - 1; + [$fc, $fr] = Coordinate::indexesFromString($first); + $fc = $fc - 1; - [$lc, $lr] = Coordinate::coordinateFromString($last); - $lc = Coordinate::columnIndexFromString($lc) - 1; + [$lc, $lr] = Coordinate::indexesFromString($last); + $lc = $lc - 1; // loop through the individual cells in the individual merge $r = $fr - 1; @@ -1785,12 +1766,12 @@ class Html extends BaseWriter * * @return string */ - private function writeComment(Worksheet $pSheet, $coordinate) + private function writeComment(Worksheet $worksheet, $coordinate) { $result = ''; - if (!$this->isPdf && isset($pSheet->getComments()[$coordinate])) { + if (!$this->isPdf && isset($worksheet->getComments()[$coordinate])) { $sanitizer = new HTMLPurifier(); - $sanitizedString = $sanitizer->purify($pSheet->getComment($coordinate)->getText()->getPlainText()); + $sanitizedString = $sanitizer->purify($worksheet->getComment($coordinate)->getText()->getPlainText()); if ($sanitizedString !== '') { $result .= ''; $result .= '
' . nl2br($sanitizedString) . '
'; @@ -1826,17 +1807,17 @@ class Html extends BaseWriter // Loop all sheets $sheetId = 0; - foreach ($sheets as $pSheet) { + foreach ($sheets as $worksheet) { $htmlPage .= "@page page$sheetId { "; - $left = StringHelper::formatNumber($pSheet->getPageMargins()->getLeft()) . 'in; '; + $left = StringHelper::formatNumber($worksheet->getPageMargins()->getLeft()) . 'in; '; $htmlPage .= 'margin-left: ' . $left; - $right = StringHelper::FormatNumber($pSheet->getPageMargins()->getRight()) . 'in; '; + $right = StringHelper::FormatNumber($worksheet->getPageMargins()->getRight()) . 'in; '; $htmlPage .= 'margin-right: ' . $right; - $top = StringHelper::FormatNumber($pSheet->getPageMargins()->getTop()) . 'in; '; + $top = StringHelper::FormatNumber($worksheet->getPageMargins()->getTop()) . 'in; '; $htmlPage .= 'margin-top: ' . $top; - $bottom = StringHelper::FormatNumber($pSheet->getPageMargins()->getBottom()) . 'in; '; + $bottom = StringHelper::FormatNumber($worksheet->getPageMargins()->getBottom()) . 'in; '; $htmlPage .= 'margin-bottom: ' . $bottom; - $orientation = $pSheet->getPageSetup()->getOrientation(); + $orientation = $worksheet->getPageSetup()->getOrientation(); if ($orientation === \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE) { $htmlPage .= 'size: landscape; '; } elseif ($orientation === \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_PORTRAIT) { diff --git a/src/PhpSpreadsheet/Writer/IWriter.php b/src/PhpSpreadsheet/Writer/IWriter.php index ac2972bc..b0a62726 100644 --- a/src/PhpSpreadsheet/Writer/IWriter.php +++ b/src/PhpSpreadsheet/Writer/IWriter.php @@ -6,6 +6,8 @@ use PhpOffice\PhpSpreadsheet\Spreadsheet; interface IWriter { + public const SAVE_WITH_CHARTS = 1; + /** * IWriter constructor. * @@ -61,7 +63,7 @@ interface IWriter * * @param resource|string $filename Name of the file to save */ - public function save($filename); + public function save($filename, int $flags = 0): void; /** * Get use disk caching where possible? diff --git a/src/PhpSpreadsheet/Writer/Ods.php b/src/PhpSpreadsheet/Writer/Ods.php index 61a91c1e..decd82bc 100644 --- a/src/PhpSpreadsheet/Writer/Ods.php +++ b/src/PhpSpreadsheet/Writer/Ods.php @@ -2,7 +2,6 @@ namespace PhpOffice\PhpSpreadsheet\Writer; -use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; use PhpOffice\PhpSpreadsheet\Writer\Ods\Content; @@ -18,13 +17,6 @@ use ZipStream\ZipStream; class Ods extends BaseWriter { - /** - * Private writer parts. - * - * @var Ods\WriterPart[] - */ - private $writerParts = []; - /** * Private PhpSpreadsheet. * @@ -32,6 +24,41 @@ class Ods extends BaseWriter */ private $spreadSheet; + /** + * @var Content + */ + private $writerPartContent; + + /** + * @var Meta + */ + private $writerPartMeta; + + /** + * @var MetaInf + */ + private $writerPartMetaInf; + + /** + * @var Mimetype + */ + private $writerPartMimetype; + + /** + * @var Settings + */ + private $writerPartSettings; + + /** + * @var Styles + */ + private $writerPartStyles; + + /** + * @var Thumbnails + */ + private $writerPartThumbnails; + /** * Create a new Ods. */ @@ -39,35 +66,48 @@ class Ods extends BaseWriter { $this->setSpreadsheet($spreadsheet); - $writerPartsArray = [ - 'content' => Content::class, - 'meta' => Meta::class, - 'meta_inf' => MetaInf::class, - 'mimetype' => Mimetype::class, - 'settings' => Settings::class, - 'styles' => Styles::class, - 'thumbnails' => Thumbnails::class, - ]; - - foreach ($writerPartsArray as $writer => $class) { - $this->writerParts[$writer] = new $class($this); - } + $this->writerPartContent = new Content($this); + $this->writerPartMeta = new Meta($this); + $this->writerPartMetaInf = new MetaInf($this); + $this->writerPartMimetype = new Mimetype($this); + $this->writerPartSettings = new Settings($this); + $this->writerPartStyles = new Styles($this); + $this->writerPartThumbnails = new Thumbnails($this); } - /** - * Get writer part. - * - * @param string $pPartName Writer part name - * - * @return null|Ods\WriterPart - */ - public function getWriterPart($pPartName) + public function getWriterPartContent(): Content { - if ($pPartName != '' && isset($this->writerParts[strtolower($pPartName)])) { - return $this->writerParts[strtolower($pPartName)]; - } + return $this->writerPartContent; + } - return null; + public function getWriterPartMeta(): Meta + { + return $this->writerPartMeta; + } + + public function getWriterPartMetaInf(): MetaInf + { + return $this->writerPartMetaInf; + } + + public function getWriterPartMimetype(): Mimetype + { + return $this->writerPartMimetype; + } + + public function getWriterPartSettings(): Settings + { + return $this->writerPartSettings; + } + + public function getWriterPartStyles(): Styles + { + return $this->writerPartStyles; + } + + public function getWriterPartThumbnails(): Thumbnails + { + return $this->writerPartThumbnails; } /** @@ -75,12 +115,14 @@ class Ods extends BaseWriter * * @param resource|string $filename */ - public function save($filename): void + public function save($filename, int $flags = 0): void { if (!$this->spreadSheet) { throw new WriterException('PhpSpreadsheet object unassigned.'); } + $this->processFlags($flags); + // garbage collect $this->spreadSheet->garbageCollect(); @@ -88,13 +130,13 @@ class Ods extends BaseWriter $zip = $this->createZip(); - $zip->addFile('META-INF/manifest.xml', $this->getWriterPart('meta_inf')->writeManifest()); - $zip->addFile('Thumbnails/thumbnail.png', $this->getWriterPart('thumbnails')->writeThumbnail()); - $zip->addFile('content.xml', $this->getWriterPart('content')->write()); - $zip->addFile('meta.xml', $this->getWriterPart('meta')->write()); - $zip->addFile('mimetype', $this->getWriterPart('mimetype')->write()); - $zip->addFile('settings.xml', $this->getWriterPart('settings')->write()); - $zip->addFile('styles.xml', $this->getWriterPart('styles')->write()); + $zip->addFile('META-INF/manifest.xml', $this->getWriterPartMetaInf()->write()); + $zip->addFile('Thumbnails/thumbnail.png', $this->getWriterPartthumbnails()->write()); + $zip->addFile('content.xml', $this->getWriterPartcontent()->write()); + $zip->addFile('meta.xml', $this->getWriterPartmeta()->write()); + $zip->addFile('mimetype', $this->getWriterPartmimetype()->write()); + $zip->addFile('settings.xml', $this->getWriterPartsettings()->write()); + $zip->addFile('styles.xml', $this->getWriterPartstyles()->write()); // Close file try { diff --git a/src/PhpSpreadsheet/Writer/Ods/AutoFilters.php b/src/PhpSpreadsheet/Writer/Ods/AutoFilters.php new file mode 100644 index 00000000..cf0450f1 --- /dev/null +++ b/src/PhpSpreadsheet/Writer/Ods/AutoFilters.php @@ -0,0 +1,63 @@ +objWriter = $objWriter; + $this->spreadsheet = $spreadsheet; + } + + public function write(): void + { + $wrapperWritten = false; + $sheetCount = $this->spreadsheet->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + $worksheet = $this->spreadsheet->getSheet($i); + $autofilter = $worksheet->getAutoFilter(); + if ($autofilter !== null && !empty($autofilter->getRange())) { + if ($wrapperWritten === false) { + $this->objWriter->startElement('table:database-ranges'); + $wrapperWritten = true; + } + $this->objWriter->startElement('table:database-range'); + $this->objWriter->writeAttribute('table:orientation', 'column'); + $this->objWriter->writeAttribute('table:display-filter-buttons', 'true'); + $this->objWriter->writeAttribute( + 'table:target-range-address', + $this->formatRange($worksheet, $autofilter) + ); + $this->objWriter->endElement(); + } + } + + if ($wrapperWritten === true) { + $this->objWriter->endElement(); + } + } + + protected function formatRange(Worksheet $worksheet, Autofilter $autofilter): string + { + $title = $worksheet->getTitle(); + $range = $autofilter->getRange(); + + return "'{$title}'.{$range}"; + } +} diff --git a/src/PhpSpreadsheet/Writer/Ods/Cell/Style.php b/src/PhpSpreadsheet/Writer/Ods/Cell/Style.php new file mode 100644 index 00000000..f8aae20c --- /dev/null +++ b/src/PhpSpreadsheet/Writer/Ods/Cell/Style.php @@ -0,0 +1,178 @@ +writer = $writer; + } + + private function mapHorizontalAlignment(string $horizontalAlignment): string + { + switch ($horizontalAlignment) { + case Alignment::HORIZONTAL_CENTER: + case Alignment::HORIZONTAL_CENTER_CONTINUOUS: + case Alignment::HORIZONTAL_DISTRIBUTED: + return 'center'; + case Alignment::HORIZONTAL_RIGHT: + return 'end'; + case Alignment::HORIZONTAL_FILL: + case Alignment::HORIZONTAL_JUSTIFY: + return 'justify'; + } + + return 'start'; + } + + private function mapVerticalAlignment(string $verticalAlignment): string + { + switch ($verticalAlignment) { + case Alignment::VERTICAL_TOP: + return 'top'; + case Alignment::VERTICAL_CENTER: + return 'middle'; + case Alignment::VERTICAL_DISTRIBUTED: + case Alignment::VERTICAL_JUSTIFY: + return 'automatic'; + } + + return 'bottom'; + } + + private function writeFillStyle(Fill $fill): void + { + switch ($fill->getFillType()) { + case Fill::FILL_SOLID: + $this->writer->writeAttribute('fo:background-color', sprintf( + '#%s', + strtolower($fill->getStartColor()->getRGB()) + )); + + break; + case Fill::FILL_GRADIENT_LINEAR: + case Fill::FILL_GRADIENT_PATH: + /// TODO :: To be implemented + break; + case Fill::FILL_NONE: + default: + } + } + + private function writeCellProperties(CellStyle $style): void + { + // Align + $hAlign = $style->getAlignment()->getHorizontal(); + $vAlign = $style->getAlignment()->getVertical(); + $wrap = $style->getAlignment()->getWrapText(); + + $this->writer->startElement('style:table-cell-properties'); + if (!empty($vAlign) || $wrap) { + if (!empty($vAlign)) { + $vAlign = $this->mapVerticalAlignment($vAlign); + $this->writer->writeAttribute('style:vertical-align', $vAlign); + } + if ($wrap) { + $this->writer->writeAttribute('fo:wrap-option', 'wrap'); + } + } + $this->writer->writeAttribute('style:rotation-align', 'none'); + + // Fill + if ($fill = $style->getFill()) { + $this->writeFillStyle($fill); + } + + $this->writer->endElement(); + + if (!empty($hAlign)) { + $hAlign = $this->mapHorizontalAlignment($hAlign); + $this->writer->startElement('style:paragraph-properties'); + $this->writer->writeAttribute('fo:text-align', $hAlign); + $this->writer->endElement(); + } + } + + protected function mapUnderlineStyle(Font $font): string + { + switch ($font->getUnderline()) { + case Font::UNDERLINE_DOUBLE: + case Font::UNDERLINE_DOUBLEACCOUNTING: + return'double'; + case Font::UNDERLINE_SINGLE: + case Font::UNDERLINE_SINGLEACCOUNTING: + return'single'; + } + + return 'none'; + } + + protected function writeTextProperties(CellStyle $style): void + { + // Font + $this->writer->startElement('style:text-properties'); + + $font = $style->getFont(); + + if ($font->getBold()) { + $this->writer->writeAttribute('fo:font-weight', 'bold'); + $this->writer->writeAttribute('style:font-weight-complex', 'bold'); + $this->writer->writeAttribute('style:font-weight-asian', 'bold'); + } + + if ($font->getItalic()) { + $this->writer->writeAttribute('fo:font-style', 'italic'); + } + + if ($color = $font->getColor()) { + $this->writer->writeAttribute('fo:color', sprintf('#%s', $color->getRGB())); + } + + if ($family = $font->getName()) { + $this->writer->writeAttribute('fo:font-family', $family); + } + + if ($size = $font->getSize()) { + $this->writer->writeAttribute('fo:font-size', sprintf('%.1Fpt', $size)); + } + + if ($font->getUnderline() && $font->getUnderline() !== Font::UNDERLINE_NONE) { + $this->writer->writeAttribute('style:text-underline-style', 'solid'); + $this->writer->writeAttribute('style:text-underline-width', 'auto'); + $this->writer->writeAttribute('style:text-underline-color', 'font-color'); + + $underline = $this->mapUnderlineStyle($font); + $this->writer->writeAttribute('style:text-underline-type', $underline); + } + + $this->writer->endElement(); // Close style:text-properties + } + + public function write(CellStyle $style): void + { + $this->writer->startElement('style:style'); + $this->writer->writeAttribute('style:name', self::CELL_STYLE_PREFIX . $style->getIndex()); + $this->writer->writeAttribute('style:family', 'table-cell'); + $this->writer->writeAttribute('style:parent-style-name', 'Default'); + + // Alignment, fill colour, etc + $this->writeCellProperties($style); + + // style:text-properties + $this->writeTextProperties($style); + + // End + $this->writer->endElement(); // Close style:style + } +} diff --git a/src/PhpSpreadsheet/Writer/Ods/Content.php b/src/PhpSpreadsheet/Writer/Ods/Content.php index 96e66850..a589e549 100644 --- a/src/PhpSpreadsheet/Writer/Ods/Content.php +++ b/src/PhpSpreadsheet/Writer/Ods/Content.php @@ -7,13 +7,12 @@ use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; -use PhpOffice\PhpSpreadsheet\Style\Fill; -use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Worksheet\Row; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use PhpOffice\PhpSpreadsheet\Writer\Exception; use PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Writer\Ods\Cell\Comment; +use PhpOffice\PhpSpreadsheet\Writer\Ods\Cell\Style; /** * @author Alexander Pervakov @@ -22,7 +21,6 @@ class Content extends WriterPart { const NUMBER_COLS_REPEATED_MAX = 1024; const NUMBER_ROWS_REPEATED_MAX = 1048576; - const CELL_STYLE_PREFIX = 'ce'; private $formulaConvertor; @@ -41,7 +39,7 @@ class Content extends WriterPart * * @return string XML Output */ - public function write() + public function write(): string { $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { @@ -103,6 +101,7 @@ class Content extends WriterPart $this->writeSheets($objWriter); + (new AutoFilters($objWriter, $this->getParentWriter()->getSpreadsheet()))->write(); // Defined names (ranges and formulae) (new NamedExpressions($objWriter, $this->getParentWriter()->getSpreadsheet(), $this->formulaConvertor))->write(); @@ -185,7 +184,7 @@ class Content extends WriterPart // Style XF $style = $cell->getXfIndex(); if ($style !== null) { - $objWriter->writeAttribute('table:style-name', self::CELL_STYLE_PREFIX . $style); + $objWriter->writeAttribute('table:style-name', Style::CELL_STYLE_PREFIX . $style); } switch ($cell->getDataType()) { @@ -196,7 +195,10 @@ class Content extends WriterPart break; case DataType::TYPE_ERROR: - throw new Exception('Writing of error not implemented yet.'); + $objWriter->writeAttribute('table:formula', 'of:=#NULL!'); + $objWriter->writeAttribute('office:value-type', 'string'); + $objWriter->writeAttribute('office:string-value', ''); + $objWriter->writeElement('text:p', '#NULL!'); break; case DataType::TYPE_FORMULA: @@ -217,10 +219,6 @@ class Content extends WriterPart $objWriter->writeAttribute('office:value', $formulaValue); $objWriter->writeElement('text:p', $formulaValue); - break; - case DataType::TYPE_INLINE: - throw new Exception('Writing of inline not implemented yet.'); - break; case DataType::TYPE_NUMERIC: $objWriter->writeAttribute('office:value-type', 'float'); @@ -228,6 +226,8 @@ class Content extends WriterPart $objWriter->writeElement('text:p', $cell->getValue()); break; + case DataType::TYPE_INLINE: + // break intentionally omitted case DataType::TYPE_STRING: $objWriter->writeAttribute('office:value-type', 'string'); $objWriter->writeElement('text:p', $cell->getValue()); @@ -274,89 +274,9 @@ class Content extends WriterPart */ private function writeXfStyles(XMLWriter $writer, Spreadsheet $spreadsheet): void { + $styleWriter = new Style($writer); foreach ($spreadsheet->getCellXfCollection() as $style) { - $writer->startElement('style:style'); - $writer->writeAttribute('style:name', self::CELL_STYLE_PREFIX . $style->getIndex()); - $writer->writeAttribute('style:family', 'table-cell'); - $writer->writeAttribute('style:parent-style-name', 'Default'); - - // style:text-properties - - // Font - $writer->startElement('style:text-properties'); - - $font = $style->getFont(); - - if ($font->getBold()) { - $writer->writeAttribute('fo:font-weight', 'bold'); - $writer->writeAttribute('style:font-weight-complex', 'bold'); - $writer->writeAttribute('style:font-weight-asian', 'bold'); - } - - if ($font->getItalic()) { - $writer->writeAttribute('fo:font-style', 'italic'); - } - - if ($color = $font->getColor()) { - $writer->writeAttribute('fo:color', sprintf('#%s', $color->getRGB())); - } - - if ($family = $font->getName()) { - $writer->writeAttribute('fo:font-family', $family); - } - - if ($size = $font->getSize()) { - $writer->writeAttribute('fo:font-size', sprintf('%.1Fpt', $size)); - } - - if ($font->getUnderline() && $font->getUnderline() != Font::UNDERLINE_NONE) { - $writer->writeAttribute('style:text-underline-style', 'solid'); - $writer->writeAttribute('style:text-underline-width', 'auto'); - $writer->writeAttribute('style:text-underline-color', 'font-color'); - - switch ($font->getUnderline()) { - case Font::UNDERLINE_DOUBLE: - $writer->writeAttribute('style:text-underline-type', 'double'); - - break; - case Font::UNDERLINE_SINGLE: - $writer->writeAttribute('style:text-underline-type', 'single'); - - break; - } - } - - $writer->endElement(); // Close style:text-properties - - // style:table-cell-properties - - $writer->startElement('style:table-cell-properties'); - $writer->writeAttribute('style:rotation-align', 'none'); - - // Fill - if ($fill = $style->getFill()) { - switch ($fill->getFillType()) { - case Fill::FILL_SOLID: - $writer->writeAttribute('fo:background-color', sprintf( - '#%s', - strtolower($fill->getStartColor()->getRGB()) - )); - - break; - case Fill::FILL_GRADIENT_LINEAR: - case Fill::FILL_GRADIENT_PATH: - /// TODO :: To be implemented - break; - case Fill::FILL_NONE: - default: - } - } - - $writer->endElement(); // Close style:table-cell-properties - - // End - - $writer->endElement(); // Close style:style + $styleWriter->write($style); } } @@ -374,7 +294,7 @@ class Content extends WriterPart $start = Coordinate::coordinateFromString($startCell); $end = Coordinate::coordinateFromString($endCell); $columnSpan = Coordinate::columnIndexFromString($end[0]) - Coordinate::columnIndexFromString($start[0]) + 1; - $rowSpan = $end[1] - $start[1] + 1; + $rowSpan = ((int) $end[1]) - ((int) $start[1]) + 1; $objWriter->writeAttribute('table:number-columns-spanned', $columnSpan); $objWriter->writeAttribute('table:number-rows-spanned', $rowSpan); diff --git a/src/PhpSpreadsheet/Writer/Ods/Meta.php b/src/PhpSpreadsheet/Writer/Ods/Meta.php index 365221f7..16f7c8b5 100644 --- a/src/PhpSpreadsheet/Writer/Ods/Meta.php +++ b/src/PhpSpreadsheet/Writer/Ods/Meta.php @@ -2,6 +2,8 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Ods; +use PhpOffice\PhpSpreadsheet\Document\Properties; +use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; @@ -10,15 +12,11 @@ class Meta extends WriterPart /** * Write meta.xml to XML format. * - * @param Spreadsheet $spreadsheet - * * @return string XML Output */ - public function write(?Spreadsheet $spreadsheet = null) + public function write(): string { - if (!$spreadsheet) { - $spreadsheet = $this->getParentWriter()->getSpreadsheet(); - } + $spreadsheet = $this->getParentWriter()->getSpreadsheet(); $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { @@ -45,15 +43,24 @@ class Meta extends WriterPart $objWriter->writeElement('meta:initial-creator', $spreadsheet->getProperties()->getCreator()); $objWriter->writeElement('dc:creator', $spreadsheet->getProperties()->getCreator()); - $objWriter->writeElement('meta:creation-date', date(DATE_W3C, $spreadsheet->getProperties()->getCreated())); - $objWriter->writeElement('dc:date', date(DATE_W3C, $spreadsheet->getProperties()->getCreated())); + $created = $spreadsheet->getProperties()->getCreated(); + $date = Date::dateTimeFromTimestamp("$created"); + $date->setTimeZone(Date::getDefaultOrLocalTimeZone()); + $objWriter->writeElement('meta:creation-date', $date->format(DATE_W3C)); + $created = $spreadsheet->getProperties()->getModified(); + $date = Date::dateTimeFromTimestamp("$created"); + $date->setTimeZone(Date::getDefaultOrLocalTimeZone()); + $objWriter->writeElement('dc:date', $date->format(DATE_W3C)); $objWriter->writeElement('dc:title', $spreadsheet->getProperties()->getTitle()); $objWriter->writeElement('dc:description', $spreadsheet->getProperties()->getDescription()); $objWriter->writeElement('dc:subject', $spreadsheet->getProperties()->getSubject()); - $keywords = explode(' ', $spreadsheet->getProperties()->getKeywords()); - foreach ($keywords as $keyword) { - $objWriter->writeElement('meta:keyword', $keyword); - } + $objWriter->writeElement('meta:keyword', $spreadsheet->getProperties()->getKeywords()); + // Don't know if this changed over time, but the keywords are all + // in a single declaration now. + //$keywords = explode(' ', $spreadsheet->getProperties()->getKeywords()); + //foreach ($keywords as $keyword) { + // $objWriter->writeElement('meta:keyword', $keyword); + //} // $objWriter->startElement('meta:user-defined'); @@ -66,10 +73,50 @@ class Meta extends WriterPart $objWriter->writeRaw($spreadsheet->getProperties()->getCategory()); $objWriter->endElement(); + self::writeDocPropsCustom($objWriter, $spreadsheet); + $objWriter->endElement(); $objWriter->endElement(); return $objWriter->getData(); } + + private static function writeDocPropsCustom(XMLWriter $objWriter, Spreadsheet $spreadsheet): void + { + $customPropertyList = $spreadsheet->getProperties()->getCustomProperties(); + foreach ($customPropertyList as $key => $customProperty) { + $propertyValue = $spreadsheet->getProperties()->getCustomPropertyValue($customProperty); + $propertyType = $spreadsheet->getProperties()->getCustomPropertyType($customProperty); + + $objWriter->startElement('meta:user-defined'); + $objWriter->writeAttribute('meta:name', $customProperty); + + switch ($propertyType) { + case Properties::PROPERTY_TYPE_INTEGER: + case Properties::PROPERTY_TYPE_FLOAT: + $objWriter->writeAttribute('meta:value-type', 'float'); + $objWriter->writeRawData($propertyValue); + + break; + case Properties::PROPERTY_TYPE_BOOLEAN: + $objWriter->writeAttribute('meta:value-type', 'boolean'); + $objWriter->writeRawData($propertyValue ? 'true' : 'false'); + + break; + case Properties::PROPERTY_TYPE_DATE: + $objWriter->writeAttribute('meta:value-type', 'date'); + $dtobj = Date::dateTimeFromTimestamp($propertyValue ?? 0); + $objWriter->writeRawData($dtobj->format(DATE_W3C)); + + break; + default: + $objWriter->writeRawData($propertyValue); + + break; + } + + $objWriter->endElement(); + } + } } diff --git a/src/PhpSpreadsheet/Writer/Ods/MetaInf.php b/src/PhpSpreadsheet/Writer/Ods/MetaInf.php index c9085cf8..f3f0d5fc 100644 --- a/src/PhpSpreadsheet/Writer/Ods/MetaInf.php +++ b/src/PhpSpreadsheet/Writer/Ods/MetaInf.php @@ -11,7 +11,7 @@ class MetaInf extends WriterPart * * @return string XML Output */ - public function writeManifest() + public function write(): string { $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { diff --git a/src/PhpSpreadsheet/Writer/Ods/Mimetype.php b/src/PhpSpreadsheet/Writer/Ods/Mimetype.php index 4aac3685..e109e6e7 100644 --- a/src/PhpSpreadsheet/Writer/Ods/Mimetype.php +++ b/src/PhpSpreadsheet/Writer/Ods/Mimetype.php @@ -2,18 +2,14 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Ods; -use PhpOffice\PhpSpreadsheet\Spreadsheet; - class Mimetype extends WriterPart { /** * Write mimetype to plain text format. * - * @param Spreadsheet $spreadsheet - * * @return string XML Output */ - public function write(?Spreadsheet $spreadsheet = null) + public function write(): string { return 'application/vnd.oasis.opendocument.spreadsheet'; } diff --git a/src/PhpSpreadsheet/Writer/Ods/NamedExpressions.php b/src/PhpSpreadsheet/Writer/Ods/NamedExpressions.php index 9edc5c64..e309dab1 100644 --- a/src/PhpSpreadsheet/Writer/Ods/NamedExpressions.php +++ b/src/PhpSpreadsheet/Writer/Ods/NamedExpressions.php @@ -10,24 +10,29 @@ use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class NamedExpressions { + /** @var XMLWriter */ private $objWriter; + /** @var Spreadsheet */ private $spreadsheet; + /** @var Formula */ private $formulaConvertor; - public function __construct(XMLWriter $objWriter, Spreadsheet $spreadsheet, $formulaConvertor) + public function __construct(XMLWriter $objWriter, Spreadsheet $spreadsheet, Formula $formulaConvertor) { $this->objWriter = $objWriter; $this->spreadsheet = $spreadsheet; $this->formulaConvertor = $formulaConvertor; } - public function write(): void + public function write(): string { $this->objWriter->startElement('table:named-expressions'); $this->writeExpressions(); $this->objWriter->endElement(); + + return ''; } private function writeExpressions(): void @@ -49,23 +54,29 @@ class NamedExpressions private function writeNamedFormula(DefinedName $definedName, Worksheet $defaultWorksheet): void { + $title = ($definedName->getWorksheet() !== null) ? $definedName->getWorksheet()->getTitle() : $defaultWorksheet->getTitle(); $this->objWriter->writeAttribute('table:name', $definedName->getName()); $this->objWriter->writeAttribute( 'table:expression', - $this->formulaConvertor->convertFormula($definedName->getValue(), $definedName->getWorksheet()->getTitle()) + $this->formulaConvertor->convertFormula($definedName->getValue(), $title) ); $this->objWriter->writeAttribute('table:base-cell-address', $this->convertAddress( $definedName, - "'" . (($definedName->getWorksheet() !== null) ? $definedName->getWorksheet()->getTitle() : $defaultWorksheet->getTitle()) . "'!\$A\$1" + "'" . $title . "'!\$A\$1" )); } private function writeNamedRange(DefinedName $definedName): void { + $baseCell = '$A$1'; + $ws = $definedName->getWorksheet(); + if ($ws !== null) { + $baseCell = "'" . $ws->getTitle() . "'!$baseCell"; + } $this->objWriter->writeAttribute('table:name', $definedName->getName()); $this->objWriter->writeAttribute('table:base-cell-address', $this->convertAddress( $definedName, - "'" . $definedName->getWorksheet()->getTitle() . "'!\$A\$1" + $baseCell )); $this->objWriter->writeAttribute('table:cell-range-address', $this->convertAddress($definedName, $definedName->getValue())); } @@ -98,7 +109,10 @@ class NamedExpressions if (empty($worksheet)) { if (($offset === 0) || ($address[$offset - 1] !== ':')) { // We need a worksheet - $worksheet = $definedName->getWorksheet()->getTitle(); + $ws = $definedName->getWorksheet(); + if ($ws !== null) { + $worksheet = $ws->getTitle(); + } } } else { $worksheet = str_replace("''", "'", trim($worksheet, "'")); diff --git a/src/PhpSpreadsheet/Writer/Ods/Settings.php b/src/PhpSpreadsheet/Writer/Ods/Settings.php index d458e8c2..047bd410 100644 --- a/src/PhpSpreadsheet/Writer/Ods/Settings.php +++ b/src/PhpSpreadsheet/Writer/Ods/Settings.php @@ -2,21 +2,18 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Ods; +use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; -use PhpOffice\PhpSpreadsheet\Spreadsheet; class Settings extends WriterPart { /** * Write settings.xml to XML format. * - * @param Spreadsheet $spreadsheet - * * @return string XML Output */ - public function write(?Spreadsheet $spreadsheet = null) + public function write(): string { - $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { @@ -39,13 +36,52 @@ class Settings extends WriterPart $objWriter->writeAttribute('config:name', 'ooo:view-settings'); $objWriter->startElement('config:config-item-map-indexed'); $objWriter->writeAttribute('config:name', 'Views'); - $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->startElement('config:config-item-map-entry'); + $spreadsheet = $this->getParentWriter()->getSpreadsheet(); + + $objWriter->startElement('config:config-item'); + $objWriter->writeAttribute('config:name', 'ViewId'); + $objWriter->writeAttribute('config:type', 'string'); + $objWriter->text('view1'); + $objWriter->endElement(); // ViewId + $objWriter->startElement('config:config-item-map-named'); + $objWriter->writeAttribute('config:name', 'Tables'); + foreach ($spreadsheet->getWorksheetIterator() as $ws) { + $objWriter->startElement('config:config-item-map-entry'); + $objWriter->writeAttribute('config:name', $ws->getTitle()); + $selected = $ws->getSelectedCells(); + if (preg_match('/^([a-z]+)([0-9]+)/i', $selected, $matches) === 1) { + $colSel = Coordinate::columnIndexFromString($matches[1]) - 1; + $rowSel = (int) $matches[2] - 1; + $objWriter->startElement('config:config-item'); + $objWriter->writeAttribute('config:name', 'CursorPositionX'); + $objWriter->writeAttribute('config:type', 'int'); + $objWriter->text($colSel); + $objWriter->endElement(); + $objWriter->startElement('config:config-item'); + $objWriter->writeAttribute('config:name', 'CursorPositionY'); + $objWriter->writeAttribute('config:type', 'int'); + $objWriter->text($rowSel); + $objWriter->endElement(); + } + $objWriter->endElement(); // config:config-item-map-entry + } + $objWriter->endElement(); // config:config-item-map-named + $wstitle = $spreadsheet->getActiveSheet()->getTitle(); + $objWriter->startElement('config:config-item'); + $objWriter->writeAttribute('config:name', 'ActiveTable'); + $objWriter->writeAttribute('config:type', 'string'); + $objWriter->text($wstitle); + $objWriter->endElement(); // config:config-item ActiveTable + + $objWriter->endElement(); // config:config-item-map-entry + $objWriter->endElement(); // config:config-item-map-indexed Views + $objWriter->endElement(); // config:config-item-set ooo:view-settings $objWriter->startElement('config:config-item-set'); $objWriter->writeAttribute('config:name', 'ooo:configuration-settings'); - $objWriter->endElement(); - $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // config:config-item-set ooo:configuration-settings + $objWriter->endElement(); // office:settings + $objWriter->endElement(); // office:document-settings return $objWriter->getData(); } diff --git a/src/PhpSpreadsheet/Writer/Ods/Styles.php b/src/PhpSpreadsheet/Writer/Ods/Styles.php index 7ba7eba7..448b1eff 100644 --- a/src/PhpSpreadsheet/Writer/Ods/Styles.php +++ b/src/PhpSpreadsheet/Writer/Ods/Styles.php @@ -3,18 +3,15 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; -use PhpOffice\PhpSpreadsheet\Spreadsheet; class Styles extends WriterPart { /** * Write styles.xml to XML format. * - * @param Spreadsheet $spreadsheet - * * @return string XML Output */ - public function write(?Spreadsheet $spreadsheet = null) + public function write(): string { $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { diff --git a/src/PhpSpreadsheet/Writer/Ods/Thumbnails.php b/src/PhpSpreadsheet/Writer/Ods/Thumbnails.php index dfab0654..db9579d0 100644 --- a/src/PhpSpreadsheet/Writer/Ods/Thumbnails.php +++ b/src/PhpSpreadsheet/Writer/Ods/Thumbnails.php @@ -2,18 +2,14 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Ods; -use PhpOffice\PhpSpreadsheet\Spreadsheet; - class Thumbnails extends WriterPart { /** * Write Thumbnails/thumbnail.png to PNG format. * - * @param Spreadsheet $spreadsheet - * * @return string XML Output */ - public function writeThumbnail(?Spreadsheet $spreadsheet = null) + public function write(): string { return ''; } diff --git a/src/PhpSpreadsheet/Writer/Ods/WriterPart.php b/src/PhpSpreadsheet/Writer/Ods/WriterPart.php index 1982c450..17d5d169 100644 --- a/src/PhpSpreadsheet/Writer/Ods/WriterPart.php +++ b/src/PhpSpreadsheet/Writer/Ods/WriterPart.php @@ -30,4 +30,6 @@ abstract class WriterPart { $this->parentWriter = $writer; } + + abstract public function write(): string; } diff --git a/src/PhpSpreadsheet/Writer/Pdf.php b/src/PhpSpreadsheet/Writer/Pdf.php index d1ac69fa..c419e1e2 100644 --- a/src/PhpSpreadsheet/Writer/Pdf.php +++ b/src/PhpSpreadsheet/Writer/Pdf.php @@ -165,7 +165,7 @@ abstract class Pdf extends Html /** * Set Paper Size. * - * @param string $paperSize Paper size see PageSetup::PAPERSIZE_* + * @param int $paperSize Paper size see PageSetup::PAPERSIZE_* * * @return self */ diff --git a/src/PhpSpreadsheet/Writer/Pdf/Dompdf.php b/src/PhpSpreadsheet/Writer/Pdf/Dompdf.php index 51b0e1f1..e49c22c7 100644 --- a/src/PhpSpreadsheet/Writer/Pdf/Dompdf.php +++ b/src/PhpSpreadsheet/Writer/Pdf/Dompdf.php @@ -22,7 +22,7 @@ class Dompdf extends Pdf * * @param string $filename Name of the file to save as */ - public function save($filename): void + public function save($filename, int $flags = 0): void { $fileHandle = parent::prepareForSave($filename); @@ -59,7 +59,7 @@ class Dompdf extends Pdf // Create PDF $pdf = $this->createExternalWriterInstance(); - $pdf->setPaper(strtolower($paperSize), $orientation); + $pdf->setPaper($paperSize, $orientation); $pdf->loadHtml($this->generateHTMLAll()); $pdf->render(); diff --git a/src/PhpSpreadsheet/Writer/Pdf/Mpdf.php b/src/PhpSpreadsheet/Writer/Pdf/Mpdf.php index bbc35e15..8d0eda91 100644 --- a/src/PhpSpreadsheet/Writer/Pdf/Mpdf.php +++ b/src/PhpSpreadsheet/Writer/Pdf/Mpdf.php @@ -24,7 +24,7 @@ class Mpdf extends Pdf * * @param string $filename Name of the file to save as */ - public function save($filename): void + public function save($filename, int $flags = 0): void { $fileHandle = parent::prepareForSave($filename); @@ -64,7 +64,7 @@ class Mpdf extends Pdf $config = ['tempDir' => $this->tempDir . '/mpdf']; $pdf = $this->createExternalWriterInstance($config); $ortmp = $orientation; - $pdf->_setPageSize(strtoupper($paperSize), $ortmp); + $pdf->_setPageSize($paperSize, $ortmp); $pdf->DefOrientation = $orientation; $pdf->AddPageByArray([ 'orientation' => $orientation, diff --git a/src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php b/src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php index 770c2248..6ed16a5d 100644 --- a/src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php +++ b/src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php @@ -24,7 +24,7 @@ class Tcpdf extends Pdf * * @param string $orientation Page orientation * @param string $unit Unit measure - * @param string $paperSize Paper size + * @param array|string $paperSize Paper size * * @return \TCPDF implementation */ @@ -38,7 +38,7 @@ class Tcpdf extends Pdf * * @param string $filename Name of the file to save as */ - public function save($filename): void + public function save($filename, int $flags = 0): void { $fileHandle = parent::prepareForSave($filename); diff --git a/src/PhpSpreadsheet/Writer/Xls.php b/src/PhpSpreadsheet/Writer/Xls.php index 741aee74..3a04a749 100644 --- a/src/PhpSpreadsheet/Writer/Xls.php +++ b/src/PhpSpreadsheet/Writer/Xls.php @@ -23,6 +23,9 @@ use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\Drawing; use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; +use PhpOffice\PhpSpreadsheet\Writer\Xls\Parser; +use PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook; +use PhpOffice\PhpSpreadsheet\Writer\Xls\Worksheet; class Xls extends BaseWriter { @@ -64,7 +67,7 @@ class Xls extends BaseWriter /** * Formula parser. * - * @var \PhpOffice\PhpSpreadsheet\Writer\Xls\Parser + * @var Parser */ private $parser; @@ -78,24 +81,24 @@ class Xls extends BaseWriter /** * Basic OLE object summary information. * - * @var array + * @var string */ private $summaryInformation; /** * Extended OLE object document summary information. * - * @var array + * @var string */ private $documentSummaryInformation; /** - * @var \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook + * @var Workbook */ private $writerWorkbook; /** - * @var \PhpOffice\PhpSpreadsheet\Writer\Xls\Worksheet[] + * @var Worksheet[] */ private $writerWorksheets; @@ -116,8 +119,10 @@ class Xls extends BaseWriter * * @param resource|string $filename */ - public function save($filename): void + public function save($filename, int $flags = 0): void { + $this->processFlags($flags); + // garbage collect $this->spreadsheet->garbageCollect(); @@ -216,7 +221,8 @@ class Xls extends BaseWriter $arrRootData[] = $OLE_DocumentSummaryInformation; } - $root = new Root(time(), time(), $arrRootData); + $time = $this->spreadsheet->getProperties()->getModified(); + $root = new Root($time, $time, $arrRootData); // save the OLE file $this->openFileHandle($filename); $root->save($this->fileHandle); @@ -388,7 +394,7 @@ class Xls extends BaseWriter } } - private function processMemoryDrawing(BstoreContainer &$bstoreContainer, BaseDrawing $drawing, string $renderingFunctionx): void + private function processMemoryDrawing(BstoreContainer &$bstoreContainer, MemoryDrawing $drawing, string $renderingFunctionx): void { switch ($renderingFunctionx) { case MemoryDrawing::RENDERING_JPEG: @@ -418,8 +424,9 @@ class Xls extends BaseWriter $bstoreContainer->addBSE($BSE); } - private function processDrawing(BstoreContainer &$bstoreContainer, BaseDrawing $drawing): void + private function processDrawing(BstoreContainer &$bstoreContainer, Drawing $drawing): void { + $blipType = null; $blipData = ''; $filename = $drawing->getPath(); @@ -723,6 +730,7 @@ class Xls extends BaseWriter } elseif ($dataProp['type']['data'] == 0x1E) { // null-terminated string prepended by dword string length // Null-terminated string $dataProp['data']['data'] .= chr(0); + // @phpstan-ignore-next-line ++$dataProp['data']['length']; // Complete the string with null string for being a %4 $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4) == 4 ? 0 : (4 - $dataProp['data']['length'] % 4)); @@ -740,6 +748,7 @@ class Xls extends BaseWriter } else { $dataSection_Content .= $dataProp['data']['data']; + // @phpstan-ignore-next-line $dataSection_Content_Offset += 4 + $dataProp['data']['length']; } } @@ -759,7 +768,10 @@ class Xls extends BaseWriter return $data; } - private function writeSummaryPropOle(int $dataProp, int &$dataSection_NumProps, array &$dataSection, int $sumdata, int $typdata): void + /** + * @param float|int $dataProp + */ + private function writeSummaryPropOle($dataProp, int &$dataSection_NumProps, array &$dataSection, int $sumdata, int $typdata): void { if ($dataProp) { $dataSection[] = [ diff --git a/src/PhpSpreadsheet/Writer/Xls/BIFFwriter.php b/src/PhpSpreadsheet/Writer/Xls/BIFFwriter.php index 84e27d0d..4a7e0656 100644 --- a/src/PhpSpreadsheet/Writer/Xls/BIFFwriter.php +++ b/src/PhpSpreadsheet/Writer/Xls/BIFFwriter.php @@ -49,7 +49,7 @@ class BIFFwriter /** * The string containing the data of the BIFF stream. * - * @var string + * @var null|string */ public $_data; diff --git a/src/PhpSpreadsheet/Writer/Xls/CellDataValidation.php b/src/PhpSpreadsheet/Writer/Xls/CellDataValidation.php new file mode 100644 index 00000000..7e9b3cfa --- /dev/null +++ b/src/PhpSpreadsheet/Writer/Xls/CellDataValidation.php @@ -0,0 +1,78 @@ + + */ + protected static $validationTypeMap = [ + DataValidation::TYPE_NONE => 0x00, + DataValidation::TYPE_WHOLE => 0x01, + DataValidation::TYPE_DECIMAL => 0x02, + DataValidation::TYPE_LIST => 0x03, + DataValidation::TYPE_DATE => 0x04, + DataValidation::TYPE_TIME => 0x05, + DataValidation::TYPE_TEXTLENGTH => 0x06, + DataValidation::TYPE_CUSTOM => 0x07, + ]; + + /** + * @var array + */ + protected static $errorStyleMap = [ + DataValidation::STYLE_STOP => 0x00, + DataValidation::STYLE_WARNING => 0x01, + DataValidation::STYLE_INFORMATION => 0x02, + ]; + + /** + * @var array + */ + protected static $operatorMap = [ + DataValidation::OPERATOR_BETWEEN => 0x00, + DataValidation::OPERATOR_NOTBETWEEN => 0x01, + DataValidation::OPERATOR_EQUAL => 0x02, + DataValidation::OPERATOR_NOTEQUAL => 0x03, + DataValidation::OPERATOR_GREATERTHAN => 0x04, + DataValidation::OPERATOR_LESSTHAN => 0x05, + DataValidation::OPERATOR_GREATERTHANOREQUAL => 0x06, + DataValidation::OPERATOR_LESSTHANOREQUAL => 0x07, + ]; + + public static function type(DataValidation $dataValidation): int + { + $validationType = $dataValidation->getType(); + + if (is_string($validationType) && array_key_exists($validationType, self::$validationTypeMap)) { + return self::$validationTypeMap[$validationType]; + } + + return self::$validationTypeMap[DataValidation::TYPE_NONE]; + } + + public static function errorStyle(DataValidation $dataValidation): int + { + $errorStyle = $dataValidation->getErrorStyle(); + + if (is_string($errorStyle) && array_key_exists($errorStyle, self::$errorStyleMap)) { + return self::$errorStyleMap[$errorStyle]; + } + + return self::$errorStyleMap[DataValidation::STYLE_STOP]; + } + + public static function operator(DataValidation $dataValidation): int + { + $operator = $dataValidation->getOperator(); + + if (is_string($operator) && array_key_exists($operator, self::$operatorMap)) { + return self::$operatorMap[$operator]; + } + + return self::$operatorMap[DataValidation::OPERATOR_BETWEEN]; + } +} diff --git a/src/PhpSpreadsheet/Writer/Xls/ErrorCode.php b/src/PhpSpreadsheet/Writer/Xls/ErrorCode.php new file mode 100644 index 00000000..7a864f50 --- /dev/null +++ b/src/PhpSpreadsheet/Writer/Xls/ErrorCode.php @@ -0,0 +1,28 @@ + + */ + protected static $errorCodeMap = [ + '#NULL!' => 0x00, + '#DIV/0!' => 0x07, + '#VALUE!' => 0x0F, + '#REF!' => 0x17, + '#NAME?' => 0x1D, + '#NUM!' => 0x24, + '#N/A' => 0x2A, + ]; + + public static function error(string $errorCode): int + { + if (array_key_exists($errorCode, self::$errorCodeMap)) { + return self::$errorCodeMap[$errorCode]; + } + + return 0; + } +} diff --git a/src/PhpSpreadsheet/Writer/Xls/Escher.php b/src/PhpSpreadsheet/Writer/Xls/Escher.php index 1ee2e904..e42139b3 100644 --- a/src/PhpSpreadsheet/Writer/Xls/Escher.php +++ b/src/PhpSpreadsheet/Writer/Xls/Escher.php @@ -420,8 +420,8 @@ class Escher $recType = 0xF010; // start coordinates - [$column, $row] = Coordinate::coordinateFromString($this->object->getStartCoordinates()); - $c1 = Coordinate::columnIndexFromString($column) - 1; + [$column, $row] = Coordinate::indexesFromString($this->object->getStartCoordinates()); + $c1 = $column - 1; $r1 = $row - 1; // start offsetX @@ -431,8 +431,8 @@ class Escher $startOffsetY = $this->object->getStartOffsetY(); // end coordinates - [$column, $row] = Coordinate::coordinateFromString($this->object->getEndCoordinates()); - $c2 = Coordinate::columnIndexFromString($column) - 1; + [$column, $row] = Coordinate::indexesFromString($this->object->getEndCoordinates()); + $c2 = $column - 1; $r2 = $row - 1; // end offsetX diff --git a/src/PhpSpreadsheet/Writer/Xls/Font.php b/src/PhpSpreadsheet/Writer/Xls/Font.php index 9cb31ead..1266cf24 100644 --- a/src/PhpSpreadsheet/Writer/Xls/Font.php +++ b/src/PhpSpreadsheet/Writer/Xls/Font.php @@ -119,7 +119,7 @@ class Font /** * Map of BIFF2-BIFF8 codes for underline styles. * - * @var array of int + * @var int[] */ private static $mapUnderline = [ \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_NONE => 0x00, diff --git a/src/PhpSpreadsheet/Writer/Xls/Parser.php b/src/PhpSpreadsheet/Writer/Xls/Parser.php index f89957a4..4033fd53 100644 --- a/src/PhpSpreadsheet/Writer/Xls/Parser.php +++ b/src/PhpSpreadsheet/Writer/Xls/Parser.php @@ -527,11 +527,11 @@ class Parser } elseif (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $token) && $this->spreadsheet->getDefinedName($token) !== null) { return $this->convertDefinedName($token); // commented so argument number can be processed correctly. See toReversePolish(). - /*elseif (preg_match("/[A-Z0-9\xc0-\xdc\.]+/", $token)) - { - return($this->convertFunction($token, $this->_func_args)); - }*/ - // if it's an argument, ignore the token (the argument remains) + /*elseif (preg_match("/[A-Z0-9\xc0-\xdc\.]+/", $token)) + { + return($this->convertFunction($token, $this->_func_args)); + }*/ + // if it's an argument, ignore the token (the argument remains) } elseif ($token == 'arg') { return ''; } @@ -597,10 +597,9 @@ class Parser if ($args >= 0) { return pack('Cv', $this->ptg['ptgFuncV'], $this->functions[$token][0]); } + // Variable number of args eg. SUM($i, $j, $k, ..). - if ($args == -1) { - return pack('CCv', $this->ptg['ptgFuncVarV'], $num_args, $this->functions[$token][0]); - } + return pack('CCv', $this->ptg['ptgFuncVarV'], $num_args, $this->functions[$token][0]); } /** @@ -747,7 +746,7 @@ class Parser return pack('C', 0xFF); } - private function convertDefinedName(string $name): void + private function convertDefinedName(string $name): string { if (strlen($name) > 255) { throw new WriterException('Defined Name is too long'); @@ -764,7 +763,8 @@ class Parser $ptgRef = pack('Cvxx', $this->ptg['ptgName'], $nameReference); throw new WriterException('Cannot yet write formulae with defined names to Xls'); -// return $ptgRef; + + return $ptgRef; } /** @@ -851,10 +851,10 @@ class Parser * called by the addWorksheet() method of the * \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook class. * - * @see \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook::addWorksheet() - * * @param string $name The name of the worksheet being added * @param int $index The index of the worksheet being added + * + * @see \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook::addWorksheet() */ public function setExtSheet($name, $index): void { @@ -968,6 +968,7 @@ class Parser */ private function advance() { + $token = ''; $i = $this->currentCharacter; $formula_length = strlen($this->formula); // eat up white spaces @@ -1148,10 +1149,6 @@ class Parser $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgNE', $result, $result2); - } elseif ($this->currentToken == '&') { - $this->advance(); - $result2 = $this->expression(); - $result = $this->createTree('ptgConcat', $result, $result2); } return $result; @@ -1202,6 +1199,11 @@ class Parser return $this->createTree('ptgUplus', $result2, ''); } $result = $this->term(); + while ($this->currentToken === '&') { + $this->advance(); + $result2 = $this->expression(); + $result = $this->createTree('ptgConcat', $result, $result2); + } while ( ($this->currentToken == '+') || ($this->currentToken == '-') || @@ -1229,9 +1231,9 @@ class Parser * This function just introduces a ptgParen element in the tree, so that Excel * doesn't get confused when working with a parenthesized formula afterwards. * - * @see fact() - * * @return array The parsed ptg'd tree + * + * @see fact() */ private function parenthesizedExpression() { @@ -1473,6 +1475,7 @@ class Parser } else { $left_tree = ''; } + // add it's left subtree and return. return $left_tree . $this->convertFunction($tree['value'], $tree['right']); } diff --git a/src/PhpSpreadsheet/Writer/Xls/Style/CellAlignment.php b/src/PhpSpreadsheet/Writer/Xls/Style/CellAlignment.php new file mode 100644 index 00000000..711d88d2 --- /dev/null +++ b/src/PhpSpreadsheet/Writer/Xls/Style/CellAlignment.php @@ -0,0 +1,59 @@ + + */ + private static $horizontalMap = [ + Alignment::HORIZONTAL_GENERAL => 0, + Alignment::HORIZONTAL_LEFT => 1, + Alignment::HORIZONTAL_RIGHT => 3, + Alignment::HORIZONTAL_CENTER => 2, + Alignment::HORIZONTAL_CENTER_CONTINUOUS => 6, + Alignment::HORIZONTAL_JUSTIFY => 5, + ]; + + /** + * @var array + */ + private static $verticalMap = [ + Alignment::VERTICAL_BOTTOM => 2, + Alignment::VERTICAL_TOP => 0, + Alignment::VERTICAL_CENTER => 1, + Alignment::VERTICAL_JUSTIFY => 3, + ]; + + public static function horizontal(Alignment $alignment): int + { + $horizontalAlignment = $alignment->getHorizontal(); + + if (is_string($horizontalAlignment) && array_key_exists($horizontalAlignment, self::$horizontalMap)) { + return self::$horizontalMap[$horizontalAlignment]; + } + + return self::$horizontalMap[Alignment::HORIZONTAL_GENERAL]; + } + + public static function wrap(Alignment $alignment): int + { + $wrap = $alignment->getWrapText(); + + return ($wrap === true) ? 1 : 0; + } + + public static function vertical(Alignment $alignment): int + { + $verticalAlignment = $alignment->getVertical(); + + if (is_string($verticalAlignment) && array_key_exists($verticalAlignment, self::$verticalMap)) { + return self::$verticalMap[$verticalAlignment]; + } + + return self::$verticalMap[Alignment::VERTICAL_BOTTOM]; + } +} diff --git a/src/PhpSpreadsheet/Writer/Xls/Style/CellBorder.php b/src/PhpSpreadsheet/Writer/Xls/Style/CellBorder.php new file mode 100644 index 00000000..8d47d6aa --- /dev/null +++ b/src/PhpSpreadsheet/Writer/Xls/Style/CellBorder.php @@ -0,0 +1,39 @@ + + */ + protected static $styleMap = [ + Border::BORDER_NONE => 0x00, + Border::BORDER_THIN => 0x01, + Border::BORDER_MEDIUM => 0x02, + Border::BORDER_DASHED => 0x03, + Border::BORDER_DOTTED => 0x04, + Border::BORDER_THICK => 0x05, + Border::BORDER_DOUBLE => 0x06, + Border::BORDER_HAIR => 0x07, + Border::BORDER_MEDIUMDASHED => 0x08, + Border::BORDER_DASHDOT => 0x09, + Border::BORDER_MEDIUMDASHDOT => 0x0A, + Border::BORDER_DASHDOTDOT => 0x0B, + Border::BORDER_MEDIUMDASHDOTDOT => 0x0C, + Border::BORDER_SLANTDASHDOT => 0x0D, + ]; + + public static function style(Border $border): int + { + $borderStyle = $border->getBorderStyle(); + + if (is_string($borderStyle) && array_key_exists($borderStyle, self::$styleMap)) { + return self::$styleMap[$borderStyle]; + } + + return self::$styleMap[Border::BORDER_NONE]; + } +} diff --git a/src/PhpSpreadsheet/Writer/Xls/Style/CellFill.php b/src/PhpSpreadsheet/Writer/Xls/Style/CellFill.php new file mode 100644 index 00000000..f5a8c470 --- /dev/null +++ b/src/PhpSpreadsheet/Writer/Xls/Style/CellFill.php @@ -0,0 +1,46 @@ + + */ + protected static $fillStyleMap = [ + Fill::FILL_NONE => 0x00, + Fill::FILL_SOLID => 0x01, + Fill::FILL_PATTERN_MEDIUMGRAY => 0x02, + Fill::FILL_PATTERN_DARKGRAY => 0x03, + Fill::FILL_PATTERN_LIGHTGRAY => 0x04, + Fill::FILL_PATTERN_DARKHORIZONTAL => 0x05, + Fill::FILL_PATTERN_DARKVERTICAL => 0x06, + Fill::FILL_PATTERN_DARKDOWN => 0x07, + Fill::FILL_PATTERN_DARKUP => 0x08, + Fill::FILL_PATTERN_DARKGRID => 0x09, + Fill::FILL_PATTERN_DARKTRELLIS => 0x0A, + Fill::FILL_PATTERN_LIGHTHORIZONTAL => 0x0B, + Fill::FILL_PATTERN_LIGHTVERTICAL => 0x0C, + Fill::FILL_PATTERN_LIGHTDOWN => 0x0D, + Fill::FILL_PATTERN_LIGHTUP => 0x0E, + Fill::FILL_PATTERN_LIGHTGRID => 0x0F, + Fill::FILL_PATTERN_LIGHTTRELLIS => 0x10, + Fill::FILL_PATTERN_GRAY125 => 0x11, + Fill::FILL_PATTERN_GRAY0625 => 0x12, + Fill::FILL_GRADIENT_LINEAR => 0x00, // does not exist in BIFF8 + Fill::FILL_GRADIENT_PATH => 0x00, // does not exist in BIFF8 + ]; + + public static function style(Fill $fill): int + { + $fillStyle = $fill->getFillType(); + + if (is_string($fillStyle) && array_key_exists($fillStyle, self::$fillStyleMap)) { + return self::$fillStyleMap[$fillStyle]; + } + + return self::$fillStyleMap[Fill::FILL_NONE]; + } +} diff --git a/src/PhpSpreadsheet/Writer/Xls/Style/ColorMap.php b/src/PhpSpreadsheet/Writer/Xls/Style/ColorMap.php new file mode 100644 index 00000000..caf85c04 --- /dev/null +++ b/src/PhpSpreadsheet/Writer/Xls/Style/ColorMap.php @@ -0,0 +1,90 @@ + + */ + private static $colorMap = [ + '#000000' => 0x08, + '#FFFFFF' => 0x09, + '#FF0000' => 0x0A, + '#00FF00' => 0x0B, + '#0000FF' => 0x0C, + '#FFFF00' => 0x0D, + '#FF00FF' => 0x0E, + '#00FFFF' => 0x0F, + '#800000' => 0x10, + '#008000' => 0x11, + '#000080' => 0x12, + '#808000' => 0x13, + '#800080' => 0x14, + '#008080' => 0x15, + '#C0C0C0' => 0x16, + '#808080' => 0x17, + '#9999FF' => 0x18, + '#993366' => 0x19, + '#FFFFCC' => 0x1A, + '#CCFFFF' => 0x1B, + '#660066' => 0x1C, + '#FF8080' => 0x1D, + '#0066CC' => 0x1E, + '#CCCCFF' => 0x1F, + // '#000080' => 0x20, + // '#FF00FF' => 0x21, + // '#FFFF00' => 0x22, + // '#00FFFF' => 0x23, + // '#800080' => 0x24, + // '#800000' => 0x25, + // '#008080' => 0x26, + // '#0000FF' => 0x27, + '#00CCFF' => 0x28, + // '#CCFFFF' => 0x29, + '#CCFFCC' => 0x2A, + '#FFFF99' => 0x2B, + '#99CCFF' => 0x2C, + '#FF99CC' => 0x2D, + '#CC99FF' => 0x2E, + '#FFCC99' => 0x2F, + '#3366FF' => 0x30, + '#33CCCC' => 0x31, + '#99CC00' => 0x32, + '#FFCC00' => 0x33, + '#FF9900' => 0x34, + '#FF6600' => 0x35, + '#666699' => 0x36, + '#969696' => 0x37, + '#003366' => 0x38, + '#339966' => 0x39, + '#003300' => 0x3A, + '#333300' => 0x3B, + '#993300' => 0x3C, + // '#993366' => 0x3D, + '#333399' => 0x3E, + '#333333' => 0x3F, + ]; + + public static function lookup(Color $color, int $defaultIndex = 0x00): int + { + $colorRgb = $color->getRGB(); + if (is_string($colorRgb) && array_key_exists("#{$colorRgb}", self::$colorMap)) { + return self::$colorMap["#{$colorRgb}"]; + } + +// TODO Try and map RGB value to nearest colour within the define pallette +// $red = Color::getRed($colorRgb, false); +// $green = Color::getGreen($colorRgb, false); +// $blue = Color::getBlue($colorRgb, false); + +// $paletteSpace = 3; +// $newColor = ($red * $paletteSpace / 256) * ($paletteSpace * $paletteSpace) + +// ($green * $paletteSpace / 256) * $paletteSpace + +// ($blue * $paletteSpace / 256); + + return $defaultIndex; + } +} diff --git a/src/PhpSpreadsheet/Writer/Xls/Workbook.php b/src/PhpSpreadsheet/Writer/Xls/Workbook.php index f752bce6..6956a261 100644 --- a/src/PhpSpreadsheet/Writer/Xls/Workbook.php +++ b/src/PhpSpreadsheet/Writer/Xls/Workbook.php @@ -551,8 +551,8 @@ class Workbook extends BIFFwriter $newRange = ''; if (empty($worksheet)) { if (($offset === 0) || ($definedRange[$offset - 1] !== ':')) { - // We need a worksheet - $worksheet = $pDefinedName->getWorksheet()->getTitle(); + // We should have a worksheet + $worksheet = $pDefinedName->getWorksheet() ? $pDefinedName->getWorksheet()->getTitle() : null; } } else { $worksheet = str_replace("''", "'", trim($worksheet, "'")); @@ -600,7 +600,11 @@ class Workbook extends BIFFwriter } if ($definedName->getLocalOnly()) { - // local scope + /** + * local scope. + * + * @phpstan-ignore-next-line + */ $scope = $this->spreadsheet->getIndex($definedName->getScope()) + 1; } else { // global scope @@ -678,13 +682,13 @@ class Workbook extends BIFFwriter $formulaData = ''; for ($j = 0; $j < $countPrintArea; ++$j) { $printAreaRect = $printArea[$j]; // e.g. A3:J6 - $printAreaRect[0] = Coordinate::coordinateFromString($printAreaRect[0]); - $printAreaRect[1] = Coordinate::coordinateFromString($printAreaRect[1]); + $printAreaRect[0] = Coordinate::indexesFromString($printAreaRect[0]); + $printAreaRect[1] = Coordinate::indexesFromString($printAreaRect[1]); $print_rowmin = $printAreaRect[0][1] - 1; $print_rowmax = $printAreaRect[1][1] - 1; - $print_colmin = Coordinate::columnIndexFromString($printAreaRect[0][0]) - 1; - $print_colmax = Coordinate::columnIndexFromString($printAreaRect[1][0]) - 1; + $print_colmin = $printAreaRect[0][0] - 1; + $print_colmax = $printAreaRect[1][0] - 1; // construct formula data manually because parser does not recognize absolute 3d cell references $formulaData .= pack('Cvvvvv', 0x3B, $i, $print_rowmin, $print_rowmax, $print_colmin, $print_colmax); @@ -756,8 +760,8 @@ class Workbook extends BIFFwriter * Write a short NAME record. * * @param string $name - * @param string $sheetIndex 1-based sheet index the defined name applies to. 0 = global - * @param integer[][] $rangeBounds range boundaries + * @param int $sheetIndex 1-based sheet index the defined name applies to. 0 = global + * @param int[][] $rangeBounds range boundaries * @param bool $isHidden * * @return string Complete binary record data @@ -839,10 +843,9 @@ class Workbook extends BIFFwriter /** * Writes Excel BIFF BOUNDSHEET record. * - * @param Worksheet $sheet Worksheet name * @param int $offset Location of worksheet BOF */ - private function writeBoundSheet($sheet, $offset): void + private function writeBoundSheet(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $sheet, $offset): void { $sheetname = $sheet->getTitle(); $record = 0x0085; // Record identifier diff --git a/src/PhpSpreadsheet/Writer/Xls/Worksheet.php b/src/PhpSpreadsheet/Writer/Xls/Worksheet.php index a793128a..e8377ee9 100644 --- a/src/PhpSpreadsheet/Writer/Xls/Worksheet.php +++ b/src/PhpSpreadsheet/Writer/Xls/Worksheet.php @@ -5,17 +5,14 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use GdImage; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; -use PhpOffice\PhpSpreadsheet\Cell\DataValidation; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\RichText\Run; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Shared\Xls; -use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\Conditional; -use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Protection; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; use PhpOffice\PhpSpreadsheet\Worksheet\SheetView; @@ -95,7 +92,7 @@ class Worksheet extends BIFFwriter /** * Whether to use outline. * - * @var int + * @var bool */ private $outlineOn; @@ -217,8 +214,8 @@ class Worksheet extends BIFFwriter * * @param int $str_total Total number of strings * @param int $str_unique Total number of unique strings - * @param array &$str_table String Table - * @param array &$colors Colour Table + * @param array $str_table String Table + * @param array $colors Colour Table * @param Parser $parser The formula parser created for the Workbook * @param bool $preCalculateFormulas Flag indicating whether formulas should be calculated or just written * @param \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $phpSheet The worksheet to write @@ -244,10 +241,10 @@ class Worksheet extends BIFFwriter $this->printHeaders = 0; - $this->outlineStyle = 0; - $this->outlineBelow = 1; - $this->outlineRight = 1; - $this->outlineOn = 1; + $this->outlineStyle = false; + $this->outlineBelow = true; + $this->outlineRight = true; + $this->outlineOn = true; $this->fontHashIndex = []; @@ -259,12 +256,12 @@ class Worksheet extends BIFFwriter $maxC = $this->phpSheet->getHighestColumn(); // Determine lowest and highest column and row + $this->firstRowIndex = $minR; $this->lastRowIndex = ($maxR > 65535) ? 65535 : $maxR; $this->firstColumnIndex = Coordinate::columnIndexFromString($minC); $this->lastColumnIndex = Coordinate::columnIndexFromString($maxC); -// if ($this->firstColumnIndex > 255) $this->firstColumnIndex = 255; if ($this->lastColumnIndex > 255) { $this->lastColumnIndex = 255; } @@ -393,7 +390,13 @@ class Worksheet extends BIFFwriter // Row dimensions foreach ($phpSheet->getRowDimensions() as $rowDimension) { $xfIndex = $rowDimension->getXfIndex() + 15; // there are 15 cellXfs - $this->writeRow($rowDimension->getRowIndex() - 1, $rowDimension->getRowHeight(), $xfIndex, ($rowDimension->getVisible() ? '0' : '1'), $rowDimension->getOutlineLevel()); + $this->writeRow( + $rowDimension->getRowIndex() - 1, + (int) $rowDimension->getRowHeight(), + $xfIndex, + !$rowDimension->getVisible(), + $rowDimension->getOutlineLevel() + ); } // Write Cells @@ -413,7 +416,6 @@ class Worksheet extends BIFFwriter $cVal = $cell->getValue(); if ($cVal instanceof RichText) { $arrcRun = []; - $str_len = StringHelper::countCharacters($cVal->getPlainText(), 'UTF-8'); $str_pos = 0; $elements = $cVal->getRichTextElements(); foreach ($elements as $element) { @@ -476,7 +478,7 @@ class Worksheet extends BIFFwriter break; case DataType::TYPE_ERROR: - $this->writeBoolErr($row, $column, self::mapErrorCode($cVal), 1, $xfIndex); + $this->writeBoolErr($row, $column, ErrorCode::error($cVal), 1, $xfIndex); break; } @@ -512,7 +514,7 @@ class Worksheet extends BIFFwriter // Hyperlinks foreach ($phpSheet->getHyperLinkCollection() as $coordinate => $hyperlink) { - [$column, $row] = Coordinate::coordinateFromString($coordinate); + [$column, $row] = Coordinate::indexesFromString($coordinate); $url = $hyperlink->getUrl(); @@ -526,7 +528,7 @@ class Worksheet extends BIFFwriter $url = 'external:' . $url; } - $this->writeUrl($row - 1, Coordinate::columnIndexFromString($column) - 1, $url); + $this->writeUrl($row - 1, $column - 1, $url); } $this->writeDataValidity(); @@ -539,16 +541,21 @@ class Worksheet extends BIFFwriter $arrConditionalStyles = $phpSheet->getConditionalStylesCollection(); if (!empty($arrConditionalStyles)) { $arrConditional = []; - // @TODO CFRule & CFHeader - // Write CFHEADER record - $this->writeCFHeader(); + + $cfHeaderWritten = false; // Write ConditionalFormattingTable records foreach ($arrConditionalStyles as $cellCoordinate => $conditionalStyles) { foreach ($conditionalStyles as $conditional) { + /** @var Conditional $conditional */ if ( - $conditional->getConditionType() == Conditional::CONDITION_EXPRESSION - || $conditional->getConditionType() == Conditional::CONDITION_CELLIS + $conditional->getConditionType() == Conditional::CONDITION_EXPRESSION || + $conditional->getConditionType() == Conditional::CONDITION_CELLIS ) { + // Write CFHEADER record (only if there are Conditional Styles that we are able to write) + if ($cfHeaderWritten === false) { + $this->writeCFHeader(); + $cfHeaderWritten = true; + } if (!isset($arrConditional[$conditional->getHashCode()])) { // This hash code has been handled $arrConditional[$conditional->getHashCode()] = true; @@ -587,22 +594,20 @@ class Worksheet extends BIFFwriter $lastCell = $explodes[1]; } - $firstCellCoordinates = Coordinate::coordinateFromString($firstCell); // e.g. [0, 1] - $lastCellCoordinates = Coordinate::coordinateFromString($lastCell); // e.g. [1, 6] + $firstCellCoordinates = Coordinate::indexesFromString($firstCell); // e.g. [0, 1] + $lastCellCoordinates = Coordinate::indexesFromString($lastCell); // e.g. [1, 6] - return pack('vvvv', $firstCellCoordinates[1] - 1, $lastCellCoordinates[1] - 1, Coordinate::columnIndexFromString($firstCellCoordinates[0]) - 1, Coordinate::columnIndexFromString($lastCellCoordinates[0]) - 1); + return pack('vvvv', $firstCellCoordinates[1] - 1, $lastCellCoordinates[1] - 1, $firstCellCoordinates[0] - 1, $lastCellCoordinates[0] - 1); } /** - * Retrieves data from memory in one chunk, or from disk in $buffer + * Retrieves data from memory in one chunk, or from disk * sized chunks. * * @return string The data */ public function getData() { - $buffer = 4096; - // Return data stored in memory if (isset($this->_data)) { $tmp = $this->_data; @@ -612,7 +617,7 @@ class Worksheet extends BIFFwriter } // No data to return - return false; + return ''; } /** @@ -640,11 +645,6 @@ class Worksheet extends BIFFwriter $this->outlineBelow = $symbols_below; $this->outlineRight = $symbols_right; $this->outlineStyle = $auto_style; - - // Ensure this is a boolean vale for Window2 - if ($this->outlineOn) { - $this->outlineOn = 1; - } } /** @@ -843,7 +843,7 @@ class Worksheet extends BIFFwriter $errorCodes = DataType::getErrorCodes(); if (isset($errorCodes[$calculatedValue])) { // Error value - $num = pack('CCCvCv', 0x02, 0x00, self::mapErrorCode($calculatedValue), 0x00, 0x00, 0xFFFF); + $num = pack('CCCvCv', 0x02, 0x00, ErrorCode::error($calculatedValue), 0x00, 0x00, 0xFFFF); } elseif ($calculatedValue === '') { // Empty string (and BIFF8) $num = pack('CCCvCv', 0x03, 0x00, 0x00, 0x00, 0x00, 0xFFFF); @@ -875,7 +875,7 @@ class Worksheet extends BIFFwriter // Parse the formula using the parser in Parser.php try { - $error = $this->parser->parse($formula); + $this->parser->parse($formula); $formula = $this->parser->toReversePolish(); $formlen = strlen($formula); // Length of the binary string @@ -926,20 +926,14 @@ class Worksheet extends BIFFwriter * The hyperlink can be to a http, ftp, mail, internal sheet (not yet), or external * directory url. * - * Returns 0 : normal termination - * -2 : row or column out of range - * -3 : long string truncated to 255 chars - * * @param int $row Row * @param int $col Column * @param string $url URL string - * - * @return int */ - private function writeUrl($row, $col, $url) + private function writeUrl($row, $col, $url): void { // Add start row and col to arg list - return $this->writeUrlRange($row, $col, $row, $col, $url); + $this->writeUrlRange($row, $col, $row, $col, $url); } /** @@ -954,21 +948,19 @@ class Worksheet extends BIFFwriter * @param int $col2 End column * @param string $url URL string * - * @return int - * * @see writeUrl() */ - public function writeUrlRange($row1, $col1, $row2, $col2, $url) + private function writeUrlRange($row1, $col1, $row2, $col2, $url): void { // Check for internal/external sheet links or default to web link if (preg_match('[^internal:]', $url)) { - return $this->writeUrlInternal($row1, $col1, $row2, $col2, $url); + $this->writeUrlInternal($row1, $col1, $row2, $col2, $url); } if (preg_match('[^external:]', $url)) { - return $this->writeUrlExternal($row1, $col1, $row2, $col2, $url); + $this->writeUrlExternal($row1, $col1, $row2, $col2, $url); } - return $this->writeUrlWeb($row1, $col1, $row2, $col2, $url); + $this->writeUrlWeb($row1, $col1, $row2, $col2, $url); } /** @@ -982,14 +974,11 @@ class Worksheet extends BIFFwriter * @param int $col2 End column * @param string $url URL string * - * @return int - * * @see writeUrl() */ - public function writeUrlWeb($row1, $col1, $row2, $col2, $url) + public function writeUrlWeb($row1, $col1, $row2, $col2, $url): void { $record = 0x01B8; // Record identifier - $length = 0x00000; // Bytes to follow // Pack the undocumented parts of the hyperlink stream $unknown1 = pack('H*', 'D0C9EA79F9BACE118C8200AA004BA90B02000000'); @@ -1014,8 +1003,6 @@ class Worksheet extends BIFFwriter // Write the packed data $this->append($header . $data . $unknown1 . $options . $unknown2 . $url_len . $url); - - return 0; } /** @@ -1027,14 +1014,11 @@ class Worksheet extends BIFFwriter * @param int $col2 End column * @param string $url URL string * - * @return int - * * @see writeUrl() */ - public function writeUrlInternal($row1, $col1, $row2, $col2, $url) + private function writeUrlInternal($row1, $col1, $row2, $col2, $url): void { $record = 0x01B8; // Record identifier - $length = 0x00000; // Bytes to follow // Strip URL type $url = preg_replace('/^internal:/', '', $url); @@ -1063,8 +1047,6 @@ class Worksheet extends BIFFwriter // Write the packed data $this->append($header . $data . $unknown1 . $options . $url_len . $url); - - return 0; } /** @@ -1080,16 +1062,14 @@ class Worksheet extends BIFFwriter * @param int $col2 End column * @param string $url URL string * - * @return int - * * @see writeUrl() */ - public function writeUrlExternal($row1, $col1, $row2, $col2, $url) + private function writeUrlExternal($row1, $col1, $row2, $col2, $url): void { // Network drives are different. We will handle them separately // MS/Novell network drives and shares start with \\ if (preg_match('[^external:\\\\]', $url)) { - return; //($this->writeUrlExternal_net($row1, $col1, $row2, $col2, $url, $str, $format)); + return; } $record = 0x01B8; // Record identifier @@ -1165,8 +1145,6 @@ class Worksheet extends BIFFwriter // Write the packed data $this->append($header . $data); - - return 0; } /** @@ -1196,7 +1174,7 @@ class Worksheet extends BIFFwriter } // Use writeRow($row, null, $XF) to set XF format without setting height - if ($height != null) { + if ($height !== null) { $miyRw = $height * 20; // row height } else { $miyRw = 0xff; // default row height is 256 @@ -1209,7 +1187,7 @@ class Worksheet extends BIFFwriter // collapsed. The zero height flag, 0x20, is used to collapse a row. $grbit |= $level; - if ($hidden) { + if ($hidden === true) { $grbit |= 0x0030; } if ($height !== null) { @@ -1344,32 +1322,13 @@ class Worksheet extends BIFFwriter */ private function writeColinfo($col_array): void { - if (isset($col_array[0])) { - $colFirst = $col_array[0]; - } - if (isset($col_array[1])) { - $colLast = $col_array[1]; - } - if (isset($col_array[2])) { - $coldx = $col_array[2]; - } else { - $coldx = 8.43; - } - if (isset($col_array[3])) { - $xfIndex = $col_array[3]; - } else { - $xfIndex = 15; - } - if (isset($col_array[4])) { - $grbit = $col_array[4]; - } else { - $grbit = 0; - } - if (isset($col_array[5])) { - $level = $col_array[5]; - } else { - $level = 0; - } + $colFirst = $col_array[0] ?? null; + $colLast = $col_array[1] ?? null; + $coldx = $col_array[2] ?? 8.43; + $xfIndex = $col_array[3] ?? 15; + $grbit = $col_array[4] ?? 0; + $level = $col_array[5] ?? 0; + $record = 0x007D; // Record identifier $length = 0x000C; // Number of bytes to follow @@ -1425,13 +1384,6 @@ class Worksheet extends BIFFwriter $irefAct = 0; // Active cell ref $cref = 1; // Number of refs - if (!isset($rwLast)) { - $rwLast = $rwFirst; // Last row in reference - } - if (!isset($colLast)) { - $colLast = $colFirst; // Last col in reference - } - // Swap last row/col for first row/col as necessary if ($rwFirst > $rwLast) { [$rwFirst, $rwLast] = [$rwLast, $rwFirst]; @@ -1481,10 +1433,10 @@ class Worksheet extends BIFFwriter // extract the row and column indexes $range = Coordinate::splitRange($mergeCell); [$first, $last] = $range[0]; - [$firstColumn, $firstRow] = Coordinate::coordinateFromString($first); - [$lastColumn, $lastRow] = Coordinate::coordinateFromString($last); + [$firstColumn, $firstRow] = Coordinate::indexesFromString($first); + [$lastColumn, $lastRow] = Coordinate::indexesFromString($last); - $recordData .= pack('vvvv', $firstRow - 1, $lastRow - 1, Coordinate::columnIndexFromString($firstColumn) - 1, Coordinate::columnIndexFromString($lastColumn) - 1); + $recordData .= pack('vvvv', $firstRow - 1, $lastRow - 1, $firstColumn - 1, $lastColumn - 1); // flush record if we have reached limit for number of merged cells, or reached final merged cell if ($j == $maxCountMergeCellsPerRecord || $i == $countMergeCells) { @@ -1574,7 +1526,7 @@ class Worksheet extends BIFFwriter /** * Write BIFF record RANGEPROTECTION. * - * Openoffice.org's Documentaion of the Microsoft Excel File Format uses term RANGEPROTECTION for these records + * Openoffice.org's Documentation of the Microsoft Excel File Format uses term RANGEPROTECTION for these records * Microsoft Office Excel 97-2007 Binary File Format Specification uses term FEAT for these records */ private function writeRangeProtection(): void @@ -1627,76 +1579,37 @@ class Worksheet extends BIFFwriter */ private function writePanes(): void { - $panes = []; - if ($this->phpSheet->getFreezePane()) { - [$column, $row] = Coordinate::coordinateFromString($this->phpSheet->getFreezePane()); - $panes[0] = Coordinate::columnIndexFromString($column) - 1; - $panes[1] = $row - 1; - - [$leftMostColumn, $topRow] = Coordinate::coordinateFromString($this->phpSheet->getTopLeftCell()); - //Coordinates are zero-based in xls files - $panes[2] = $topRow - 1; - $panes[3] = Coordinate::columnIndexFromString($leftMostColumn) - 1; - } else { + if (!$this->phpSheet->getFreezePane()) { // thaw panes return; } - $x = $panes[0] ?? null; - $y = $panes[1] ?? null; - $rwTop = $panes[2] ?? null; - $colLeft = $panes[3] ?? null; - if (count($panes) > 4) { // if Active pane was received - $pnnAct = $panes[4]; - } else { - $pnnAct = null; - } + [$column, $row] = Coordinate::indexesFromString($this->phpSheet->getFreezePane() ?? ''); + $x = $column - 1; + $y = $row - 1; + + [$leftMostColumn, $topRow] = Coordinate::indexesFromString($this->phpSheet->getTopLeftCell()); + //Coordinates are zero-based in xls files + $rwTop = $topRow - 1; + $colLeft = $leftMostColumn - 1; + $record = 0x0041; // Record identifier $length = 0x000A; // Number of bytes to follow - // Code specific to frozen or thawed panes. - if ($this->phpSheet->getFreezePane()) { - // Set default values for $rwTop and $colLeft - if (!isset($rwTop)) { - $rwTop = $y; - } - if (!isset($colLeft)) { - $colLeft = $x; - } - } else { - // Set default values for $rwTop and $colLeft - if (!isset($rwTop)) { - $rwTop = 0; - } - if (!isset($colLeft)) { - $colLeft = 0; - } - - // Convert Excel's row and column units to the internal units. - // The default row height is 12.75 - // The default column width is 8.43 - // The following slope and intersection values were interpolated. - // - $y = 20 * $y + 255; - $x = 113.879 * $x + 390; - } - // Determine which pane should be active. There is also the undocumented // option to override this should it be necessary: may be removed later. - // - if (!isset($pnnAct)) { - if ($x != 0 && $y != 0) { - $pnnAct = 0; // Bottom right - } - if ($x != 0 && $y == 0) { - $pnnAct = 1; // Top right - } - if ($x == 0 && $y != 0) { - $pnnAct = 2; // Bottom left - } - if ($x == 0 && $y == 0) { - $pnnAct = 3; // Top left - } + $pnnAct = null; + if ($x != 0 && $y != 0) { + $pnnAct = 0; // Bottom right + } + if ($x != 0 && $y == 0) { + $pnnAct = 1; // Top right + } + if ($x == 0 && $y != 0) { + $pnnAct = 2; // Bottom left + } + if ($x == 0 && $y == 0) { + $pnnAct = 3; // Top left } $this->activePane = $pnnAct; // Used in writeSelection @@ -1715,9 +1628,7 @@ class Worksheet extends BIFFwriter $length = 0x0022; // Number of bytes to follow $iPaperSize = $this->phpSheet->getPageSetup()->getPaperSize(); // Paper size - - $iScale = $this->phpSheet->getPageSetup()->getScale() ? - $this->phpSheet->getPageSetup()->getScale() : 100; // Print scaling factor + $iScale = $this->phpSheet->getPageSetup()->getScale() ?: 100; // Print scaling factor $iPageStart = 0x01; // Starting page number $iFitWidth = (int) $this->phpSheet->getPageSetup()->getFitToWidth(); // Fit to number of pages wide @@ -2227,7 +2138,7 @@ class Worksheet extends BIFFwriter private function writePassword(): void { // Exit unless sheet protection and password have been specified - if (!$this->phpSheet->getProtection()->getSheet() || !$this->phpSheet->getProtection()->getPassword()) { + if (!$this->phpSheet->getProtection()->getSheet() || !$this->phpSheet->getProtection()->getPassword() || $this->phpSheet->getProtection()->getAlgorithm() !== '') { return; } @@ -2255,7 +2166,9 @@ class Worksheet extends BIFFwriter */ public function insertBitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, $scale_y = 1): void { - $bitmap_array = (is_resource($bitmap) || $bitmap instanceof GdImage ? $this->processBitmapGd($bitmap) : $this->processBitmap($bitmap)); + $bitmap_array = (is_resource($bitmap) || $bitmap instanceof GdImage + ? $this->processBitmapGd($bitmap) + : $this->processBitmap($bitmap)); [$width, $height, $size, $data] = $bitmap_array; // Scale the frame of the image. @@ -2724,67 +2637,16 @@ class Worksheet extends BIFFwriter $record = 0x01BE; // Record identifier foreach ($dataValidationCollection as $cellCoordinate => $dataValidation) { - // initialize record data - $data = ''; - // options $options = 0x00000000; // data type - $type = 0x00; - switch ($dataValidation->getType()) { - case DataValidation::TYPE_NONE: - $type = 0x00; - - break; - case DataValidation::TYPE_WHOLE: - $type = 0x01; - - break; - case DataValidation::TYPE_DECIMAL: - $type = 0x02; - - break; - case DataValidation::TYPE_LIST: - $type = 0x03; - - break; - case DataValidation::TYPE_DATE: - $type = 0x04; - - break; - case DataValidation::TYPE_TIME: - $type = 0x05; - - break; - case DataValidation::TYPE_TEXTLENGTH: - $type = 0x06; - - break; - case DataValidation::TYPE_CUSTOM: - $type = 0x07; - - break; - } + $type = CellDataValidation::type($dataValidation); $options |= $type << 0; // error style - $errorStyle = 0x00; - switch ($dataValidation->getErrorStyle()) { - case DataValidation::STYLE_STOP: - $errorStyle = 0x00; - - break; - case DataValidation::STYLE_WARNING: - $errorStyle = 0x01; - - break; - case DataValidation::STYLE_INFORMATION: - $errorStyle = 0x02; - - break; - } + $errorStyle = CellDataValidation::errorStyle($dataValidation); $options |= $errorStyle << 4; @@ -2806,41 +2668,7 @@ class Worksheet extends BIFFwriter $options |= $dataValidation->getShowErrorMessage() << 19; // condition operator - $operator = 0x00; - switch ($dataValidation->getOperator()) { - case DataValidation::OPERATOR_BETWEEN: - $operator = 0x00; - - break; - case DataValidation::OPERATOR_NOTBETWEEN: - $operator = 0x01; - - break; - case DataValidation::OPERATOR_EQUAL: - $operator = 0x02; - - break; - case DataValidation::OPERATOR_NOTEQUAL: - $operator = 0x03; - - break; - case DataValidation::OPERATOR_GREATERTHAN: - $operator = 0x04; - - break; - case DataValidation::OPERATOR_LESSTHAN: - $operator = 0x05; - - break; - case DataValidation::OPERATOR_GREATERTHANOREQUAL: - $operator = 0x06; - - break; - case DataValidation::OPERATOR_LESSTHANOREQUAL: - $operator = 0x07; - - break; - } + $operator = CellDataValidation::operator($dataValidation); $options |= $operator << 20; @@ -2910,35 +2738,6 @@ class Worksheet extends BIFFwriter } } - /** - * Map Error code. - * - * @param string $errorCode - * - * @return int - */ - private static function mapErrorCode($errorCode) - { - switch ($errorCode) { - case '#NULL!': - return 0x00; - case '#DIV/0!': - return 0x07; - case '#VALUE!': - return 0x0F; - case '#REF!': - return 0x17; - case '#NAME?': - return 0x1D; - case '#NUM!': - return 0x24; - case '#N/A': - return 0x2A; - } - - return 0; - } - /** * Write PLV Record. */ @@ -2976,9 +2775,9 @@ class Worksheet extends BIFFwriter private function writeCFRule(Conditional $conditional): void { $record = 0x01B1; // Record identifier + $type = null; // Type of the CF + $operatorType = null; // Comparison operator - // $type : Type of the CF - // $operatorType : Comparison operator if ($conditional->getConditionType() == Conditional::CONDITION_EXPRESSION) { $type = 0x02; $operatorType = 0x00; @@ -3045,12 +2844,12 @@ class Worksheet extends BIFFwriter // $flags : Option flags // Alignment - $bAlignHz = ($conditional->getStyle()->getAlignment()->getHorizontal() == null ? 1 : 0); - $bAlignVt = ($conditional->getStyle()->getAlignment()->getVertical() == null ? 1 : 0); - $bAlignWrapTx = ($conditional->getStyle()->getAlignment()->getWrapText() == false ? 1 : 0); - $bTxRotation = ($conditional->getStyle()->getAlignment()->getTextRotation() == null ? 1 : 0); - $bIndent = ($conditional->getStyle()->getAlignment()->getIndent() == 0 ? 1 : 0); - $bShrinkToFit = ($conditional->getStyle()->getAlignment()->getShrinkToFit() == false ? 1 : 0); + $bAlignHz = ($conditional->getStyle()->getAlignment()->getHorizontal() === null ? 1 : 0); + $bAlignVt = ($conditional->getStyle()->getAlignment()->getVertical() === null ? 1 : 0); + $bAlignWrapTx = ($conditional->getStyle()->getAlignment()->getWrapText() === false ? 1 : 0); + $bTxRotation = ($conditional->getStyle()->getAlignment()->getTextRotation() === null ? 1 : 0); + $bIndent = ($conditional->getStyle()->getAlignment()->getIndent() === 0 ? 1 : 0); + $bShrinkToFit = ($conditional->getStyle()->getAlignment()->getShrinkToFit() === false ? 1 : 0); if ($bAlignHz == 0 || $bAlignVt == 0 || $bAlignWrapTx == 0 || $bTxRotation == 0 || $bIndent == 0 || $bShrinkToFit == 0) { $bFormatAlign = 1; } else { @@ -3079,7 +2878,7 @@ class Worksheet extends BIFFwriter $bFormatBorder = 0; } // Pattern - $bFillStyle = ($conditional->getStyle()->getFill()->getFillType() == null ? 0 : 1); + $bFillStyle = ($conditional->getStyle()->getFill()->getFillType() === null ? 0 : 1); $bFillColor = ($conditional->getStyle()->getFill()->getStartColor()->getARGB() == null ? 0 : 1); $bFillColorBg = ($conditional->getStyle()->getFill()->getEndColor()->getARGB() == null ? 0 : 1); if ($bFillStyle == 0 || $bFillColor == 0 || $bFillColorBg == 0) { @@ -3089,14 +2888,14 @@ class Worksheet extends BIFFwriter } // Font if ( - $conditional->getStyle()->getFont()->getName() != null - || $conditional->getStyle()->getFont()->getSize() != null - || $conditional->getStyle()->getFont()->getBold() != null - || $conditional->getStyle()->getFont()->getItalic() != null - || $conditional->getStyle()->getFont()->getSuperscript() != null - || $conditional->getStyle()->getFont()->getSubscript() != null - || $conditional->getStyle()->getFont()->getUnderline() != null - || $conditional->getStyle()->getFont()->getStrikethrough() != null + $conditional->getStyle()->getFont()->getName() !== null + || $conditional->getStyle()->getFont()->getSize() !== null + || $conditional->getStyle()->getFont()->getBold() !== null + || $conditional->getStyle()->getFont()->getItalic() !== null + || $conditional->getStyle()->getFont()->getSuperscript() !== null + || $conditional->getStyle()->getFont()->getSubscript() !== null + || $conditional->getStyle()->getFont()->getUnderline() !== null + || $conditional->getStyle()->getFont()->getStrikethrough() !== null || $conditional->getStyle()->getFont()->getColor()->getARGB() != null ) { $bFormatFont = 1; @@ -3143,17 +2942,22 @@ class Worksheet extends BIFFwriter // Text direction $flags |= (1 == 0 ? 0x80000000 : 0); + $dataBlockFont = null; + $dataBlockAlign = null; + $dataBlockBorder = null; + $dataBlockFill = null; + // Data Blocks if ($bFormatFont == 1) { // Font Name - if ($conditional->getStyle()->getFont()->getName() == null) { + if ($conditional->getStyle()->getFont()->getName() === null) { $dataBlockFont = pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000); $dataBlockFont .= pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000); } else { $dataBlockFont = StringHelper::UTF8toBIFF8UnicodeLong($conditional->getStyle()->getFont()->getName()); } // Font Size - if ($conditional->getStyle()->getFont()->getSize() == null) { + if ($conditional->getStyle()->getFont()->getSize() === null) { $dataBlockFont .= pack('V', 20 * 11); } else { $dataBlockFont .= pack('V', 20 * $conditional->getStyle()->getFont()->getSize()); @@ -3161,16 +2965,16 @@ class Worksheet extends BIFFwriter // Font Options $dataBlockFont .= pack('V', 0); // Font weight - if ($conditional->getStyle()->getFont()->getBold() == true) { + if ($conditional->getStyle()->getFont()->getBold() === true) { $dataBlockFont .= pack('v', 0x02BC); } else { $dataBlockFont .= pack('v', 0x0190); } // Escapement type - if ($conditional->getStyle()->getFont()->getSubscript() == true) { + if ($conditional->getStyle()->getFont()->getSubscript() === true) { $dataBlockFont .= pack('v', 0x02); $fontEscapement = 0; - } elseif ($conditional->getStyle()->getFont()->getSuperscript() == true) { + } elseif ($conditional->getStyle()->getFont()->getSuperscript() === true) { $dataBlockFont .= pack('v', 0x01); $fontEscapement = 0; } else { @@ -3213,242 +3017,14 @@ class Worksheet extends BIFFwriter // Not used (3) $dataBlockFont .= pack('vC', 0x0000, 0x00); // Font color index - switch ($conditional->getStyle()->getFont()->getColor()->getRGB()) { - case '000000': - $colorIdx = 0x08; + $colorIdx = Style\ColorMap::lookup($conditional->getStyle()->getFont()->getColor(), 0x00); - break; - case 'FFFFFF': - $colorIdx = 0x09; - - break; - case 'FF0000': - $colorIdx = 0x0A; - - break; - case '00FF00': - $colorIdx = 0x0B; - - break; - case '0000FF': - $colorIdx = 0x0C; - - break; - case 'FFFF00': - $colorIdx = 0x0D; - - break; - case 'FF00FF': - $colorIdx = 0x0E; - - break; - case '00FFFF': - $colorIdx = 0x0F; - - break; - case '800000': - $colorIdx = 0x10; - - break; - case '008000': - $colorIdx = 0x11; - - break; - case '000080': - $colorIdx = 0x12; - - break; - case '808000': - $colorIdx = 0x13; - - break; - case '800080': - $colorIdx = 0x14; - - break; - case '008080': - $colorIdx = 0x15; - - break; - case 'C0C0C0': - $colorIdx = 0x16; - - break; - case '808080': - $colorIdx = 0x17; - - break; - case '9999FF': - $colorIdx = 0x18; - - break; - case '993366': - $colorIdx = 0x19; - - break; - case 'FFFFCC': - $colorIdx = 0x1A; - - break; - case 'CCFFFF': - $colorIdx = 0x1B; - - break; - case '660066': - $colorIdx = 0x1C; - - break; - case 'FF8080': - $colorIdx = 0x1D; - - break; - case '0066CC': - $colorIdx = 0x1E; - - break; - case 'CCCCFF': - $colorIdx = 0x1F; - - break; - case '000080': - $colorIdx = 0x20; - - break; - case 'FF00FF': - $colorIdx = 0x21; - - break; - case 'FFFF00': - $colorIdx = 0x22; - - break; - case '00FFFF': - $colorIdx = 0x23; - - break; - case '800080': - $colorIdx = 0x24; - - break; - case '800000': - $colorIdx = 0x25; - - break; - case '008080': - $colorIdx = 0x26; - - break; - case '0000FF': - $colorIdx = 0x27; - - break; - case '00CCFF': - $colorIdx = 0x28; - - break; - case 'CCFFFF': - $colorIdx = 0x29; - - break; - case 'CCFFCC': - $colorIdx = 0x2A; - - break; - case 'FFFF99': - $colorIdx = 0x2B; - - break; - case '99CCFF': - $colorIdx = 0x2C; - - break; - case 'FF99CC': - $colorIdx = 0x2D; - - break; - case 'CC99FF': - $colorIdx = 0x2E; - - break; - case 'FFCC99': - $colorIdx = 0x2F; - - break; - case '3366FF': - $colorIdx = 0x30; - - break; - case '33CCCC': - $colorIdx = 0x31; - - break; - case '99CC00': - $colorIdx = 0x32; - - break; - case 'FFCC00': - $colorIdx = 0x33; - - break; - case 'FF9900': - $colorIdx = 0x34; - - break; - case 'FF6600': - $colorIdx = 0x35; - - break; - case '666699': - $colorIdx = 0x36; - - break; - case '969696': - $colorIdx = 0x37; - - break; - case '003366': - $colorIdx = 0x38; - - break; - case '339966': - $colorIdx = 0x39; - - break; - case '003300': - $colorIdx = 0x3A; - - break; - case '333300': - $colorIdx = 0x3B; - - break; - case '993300': - $colorIdx = 0x3C; - - break; - case '993366': - $colorIdx = 0x3D; - - break; - case '333399': - $colorIdx = 0x3E; - - break; - case '333333': - $colorIdx = 0x3F; - - break; - default: - $colorIdx = 0x00; - - break; - } $dataBlockFont .= pack('V', $colorIdx); // Not used (4) $dataBlockFont .= pack('V', 0x00000000); // Options flags for modified font attributes $optionsFlags = 0; - $optionsFlagsBold = ($conditional->getStyle()->getFont()->getBold() == null ? 1 : 0); + $optionsFlagsBold = ($conditional->getStyle()->getFont()->getBold() === null ? 1 : 0); $optionsFlags |= (1 == $optionsFlagsBold ? 0x00000002 : 0); $optionsFlags |= (1 == 1 ? 0x00000008 : 0); $optionsFlags |= (1 == 1 ? 0x00000010 : 0); @@ -3468,58 +3044,11 @@ class Worksheet extends BIFFwriter // Always $dataBlockFont .= pack('v', 0x0001); } - if ($bFormatAlign == 1) { - $blockAlign = 0; + if ($bFormatAlign === 1) { // Alignment and text break - switch ($conditional->getStyle()->getAlignment()->getHorizontal()) { - case Alignment::HORIZONTAL_GENERAL: - $blockAlign = 0; - - break; - case Alignment::HORIZONTAL_LEFT: - $blockAlign = 1; - - break; - case Alignment::HORIZONTAL_RIGHT: - $blockAlign = 3; - - break; - case Alignment::HORIZONTAL_CENTER: - $blockAlign = 2; - - break; - case Alignment::HORIZONTAL_CENTER_CONTINUOUS: - $blockAlign = 6; - - break; - case Alignment::HORIZONTAL_JUSTIFY: - $blockAlign = 5; - - break; - } - if ($conditional->getStyle()->getAlignment()->getWrapText() == true) { - $blockAlign |= 1 << 3; - } else { - $blockAlign |= 0 << 3; - } - switch ($conditional->getStyle()->getAlignment()->getVertical()) { - case Alignment::VERTICAL_BOTTOM: - $blockAlign = 2 << 4; - - break; - case Alignment::VERTICAL_TOP: - $blockAlign = 0 << 4; - - break; - case Alignment::VERTICAL_CENTER: - $blockAlign = 1 << 4; - - break; - case Alignment::VERTICAL_JUSTIFY: - $blockAlign = 3 << 4; - - break; - } + $blockAlign = Style\CellAlignment::horizontal($conditional->getStyle()->getAlignment()); + $blockAlign |= Style\CellAlignment::wrap($conditional->getStyle()->getAlignment()) << 3; + $blockAlign |= Style\CellAlignment::vertical($conditional->getStyle()->getAlignment()) << 4; $blockAlign |= 0 << 7; // Text rotation angle @@ -3527,7 +3056,7 @@ class Worksheet extends BIFFwriter // Indentation $blockIndent = $conditional->getStyle()->getAlignment()->getIndent(); - if ($conditional->getStyle()->getAlignment()->getShrinkToFit() == true) { + if ($conditional->getStyle()->getAlignment()->getShrinkToFit() === true) { $blockIndent |= 1 << 4; } else { $blockIndent |= 0 << 4; @@ -3539,240 +3068,11 @@ class Worksheet extends BIFFwriter $dataBlockAlign = pack('CCvvv', $blockAlign, $blockRotation, $blockIndent, $blockIndentRelative, 0x0000); } - if ($bFormatBorder == 1) { - $blockLineStyle = 0; - switch ($conditional->getStyle()->getBorders()->getLeft()->getBorderStyle()) { - case Border::BORDER_NONE: - $blockLineStyle |= 0x00; - - break; - case Border::BORDER_THIN: - $blockLineStyle |= 0x01; - - break; - case Border::BORDER_MEDIUM: - $blockLineStyle |= 0x02; - - break; - case Border::BORDER_DASHED: - $blockLineStyle |= 0x03; - - break; - case Border::BORDER_DOTTED: - $blockLineStyle |= 0x04; - - break; - case Border::BORDER_THICK: - $blockLineStyle |= 0x05; - - break; - case Border::BORDER_DOUBLE: - $blockLineStyle |= 0x06; - - break; - case Border::BORDER_HAIR: - $blockLineStyle |= 0x07; - - break; - case Border::BORDER_MEDIUMDASHED: - $blockLineStyle |= 0x08; - - break; - case Border::BORDER_DASHDOT: - $blockLineStyle |= 0x09; - - break; - case Border::BORDER_MEDIUMDASHDOT: - $blockLineStyle |= 0x0A; - - break; - case Border::BORDER_DASHDOTDOT: - $blockLineStyle |= 0x0B; - - break; - case Border::BORDER_MEDIUMDASHDOTDOT: - $blockLineStyle |= 0x0C; - - break; - case Border::BORDER_SLANTDASHDOT: - $blockLineStyle |= 0x0D; - - break; - } - switch ($conditional->getStyle()->getBorders()->getRight()->getBorderStyle()) { - case Border::BORDER_NONE: - $blockLineStyle |= 0x00 << 4; - - break; - case Border::BORDER_THIN: - $blockLineStyle |= 0x01 << 4; - - break; - case Border::BORDER_MEDIUM: - $blockLineStyle |= 0x02 << 4; - - break; - case Border::BORDER_DASHED: - $blockLineStyle |= 0x03 << 4; - - break; - case Border::BORDER_DOTTED: - $blockLineStyle |= 0x04 << 4; - - break; - case Border::BORDER_THICK: - $blockLineStyle |= 0x05 << 4; - - break; - case Border::BORDER_DOUBLE: - $blockLineStyle |= 0x06 << 4; - - break; - case Border::BORDER_HAIR: - $blockLineStyle |= 0x07 << 4; - - break; - case Border::BORDER_MEDIUMDASHED: - $blockLineStyle |= 0x08 << 4; - - break; - case Border::BORDER_DASHDOT: - $blockLineStyle |= 0x09 << 4; - - break; - case Border::BORDER_MEDIUMDASHDOT: - $blockLineStyle |= 0x0A << 4; - - break; - case Border::BORDER_DASHDOTDOT: - $blockLineStyle |= 0x0B << 4; - - break; - case Border::BORDER_MEDIUMDASHDOTDOT: - $blockLineStyle |= 0x0C << 4; - - break; - case Border::BORDER_SLANTDASHDOT: - $blockLineStyle |= 0x0D << 4; - - break; - } - switch ($conditional->getStyle()->getBorders()->getTop()->getBorderStyle()) { - case Border::BORDER_NONE: - $blockLineStyle |= 0x00 << 8; - - break; - case Border::BORDER_THIN: - $blockLineStyle |= 0x01 << 8; - - break; - case Border::BORDER_MEDIUM: - $blockLineStyle |= 0x02 << 8; - - break; - case Border::BORDER_DASHED: - $blockLineStyle |= 0x03 << 8; - - break; - case Border::BORDER_DOTTED: - $blockLineStyle |= 0x04 << 8; - - break; - case Border::BORDER_THICK: - $blockLineStyle |= 0x05 << 8; - - break; - case Border::BORDER_DOUBLE: - $blockLineStyle |= 0x06 << 8; - - break; - case Border::BORDER_HAIR: - $blockLineStyle |= 0x07 << 8; - - break; - case Border::BORDER_MEDIUMDASHED: - $blockLineStyle |= 0x08 << 8; - - break; - case Border::BORDER_DASHDOT: - $blockLineStyle |= 0x09 << 8; - - break; - case Border::BORDER_MEDIUMDASHDOT: - $blockLineStyle |= 0x0A << 8; - - break; - case Border::BORDER_DASHDOTDOT: - $blockLineStyle |= 0x0B << 8; - - break; - case Border::BORDER_MEDIUMDASHDOTDOT: - $blockLineStyle |= 0x0C << 8; - - break; - case Border::BORDER_SLANTDASHDOT: - $blockLineStyle |= 0x0D << 8; - - break; - } - switch ($conditional->getStyle()->getBorders()->getBottom()->getBorderStyle()) { - case Border::BORDER_NONE: - $blockLineStyle |= 0x00 << 12; - - break; - case Border::BORDER_THIN: - $blockLineStyle |= 0x01 << 12; - - break; - case Border::BORDER_MEDIUM: - $blockLineStyle |= 0x02 << 12; - - break; - case Border::BORDER_DASHED: - $blockLineStyle |= 0x03 << 12; - - break; - case Border::BORDER_DOTTED: - $blockLineStyle |= 0x04 << 12; - - break; - case Border::BORDER_THICK: - $blockLineStyle |= 0x05 << 12; - - break; - case Border::BORDER_DOUBLE: - $blockLineStyle |= 0x06 << 12; - - break; - case Border::BORDER_HAIR: - $blockLineStyle |= 0x07 << 12; - - break; - case Border::BORDER_MEDIUMDASHED: - $blockLineStyle |= 0x08 << 12; - - break; - case Border::BORDER_DASHDOT: - $blockLineStyle |= 0x09 << 12; - - break; - case Border::BORDER_MEDIUMDASHDOT: - $blockLineStyle |= 0x0A << 12; - - break; - case Border::BORDER_DASHDOTDOT: - $blockLineStyle |= 0x0B << 12; - - break; - case Border::BORDER_MEDIUMDASHDOTDOT: - $blockLineStyle |= 0x0C << 12; - - break; - case Border::BORDER_SLANTDASHDOT: - $blockLineStyle |= 0x0D << 12; - - break; - } + if ($bFormatBorder === 1) { + $blockLineStyle = Style\CellBorder::style($conditional->getStyle()->getBorders()->getLeft()); + $blockLineStyle |= Style\CellBorder::style($conditional->getStyle()->getBorders()->getRight()) << 4; + $blockLineStyle |= Style\CellBorder::style($conditional->getStyle()->getBorders()->getTop()) << 8; + $blockLineStyle |= Style\CellBorder::style($conditional->getStyle()->getBorders()->getBottom()) << 12; // TODO writeCFRule() => $blockLineStyle => Index Color for left line // TODO writeCFRule() => $blockLineStyle => Index Color for right line @@ -3782,649 +3082,36 @@ class Worksheet extends BIFFwriter // TODO writeCFRule() => $blockColor => Index Color for top line // TODO writeCFRule() => $blockColor => Index Color for bottom line // TODO writeCFRule() => $blockColor => Index Color for diagonal line - switch ($conditional->getStyle()->getBorders()->getDiagonal()->getBorderStyle()) { - case Border::BORDER_NONE: - $blockColor |= 0x00 << 21; - - break; - case Border::BORDER_THIN: - $blockColor |= 0x01 << 21; - - break; - case Border::BORDER_MEDIUM: - $blockColor |= 0x02 << 21; - - break; - case Border::BORDER_DASHED: - $blockColor |= 0x03 << 21; - - break; - case Border::BORDER_DOTTED: - $blockColor |= 0x04 << 21; - - break; - case Border::BORDER_THICK: - $blockColor |= 0x05 << 21; - - break; - case Border::BORDER_DOUBLE: - $blockColor |= 0x06 << 21; - - break; - case Border::BORDER_HAIR: - $blockColor |= 0x07 << 21; - - break; - case Border::BORDER_MEDIUMDASHED: - $blockColor |= 0x08 << 21; - - break; - case Border::BORDER_DASHDOT: - $blockColor |= 0x09 << 21; - - break; - case Border::BORDER_MEDIUMDASHDOT: - $blockColor |= 0x0A << 21; - - break; - case Border::BORDER_DASHDOTDOT: - $blockColor |= 0x0B << 21; - - break; - case Border::BORDER_MEDIUMDASHDOTDOT: - $blockColor |= 0x0C << 21; - - break; - case Border::BORDER_SLANTDASHDOT: - $blockColor |= 0x0D << 21; - - break; - } + $blockColor |= Style\CellBorder::style($conditional->getStyle()->getBorders()->getDiagonal()) << 21; $dataBlockBorder = pack('vv', $blockLineStyle, $blockColor); } - if ($bFormatFill == 1) { - // Fill Patern Style - $blockFillPatternStyle = 0; - switch ($conditional->getStyle()->getFill()->getFillType()) { - case Fill::FILL_NONE: - $blockFillPatternStyle = 0x00; + if ($bFormatFill === 1) { + // Fill Pattern Style + $blockFillPatternStyle = Style\CellFill::style($conditional->getStyle()->getFill()); + // Background Color + $colorIdxBg = Style\ColorMap::lookup($conditional->getStyle()->getFill()->getStartColor(), 0x41); + // Foreground Color + $colorIdxFg = Style\ColorMap::lookup($conditional->getStyle()->getFill()->getEndColor(), 0x40); - break; - case Fill::FILL_SOLID: - $blockFillPatternStyle = 0x01; - - break; - case Fill::FILL_PATTERN_MEDIUMGRAY: - $blockFillPatternStyle = 0x02; - - break; - case Fill::FILL_PATTERN_DARKGRAY: - $blockFillPatternStyle = 0x03; - - break; - case Fill::FILL_PATTERN_LIGHTGRAY: - $blockFillPatternStyle = 0x04; - - break; - case Fill::FILL_PATTERN_DARKHORIZONTAL: - $blockFillPatternStyle = 0x05; - - break; - case Fill::FILL_PATTERN_DARKVERTICAL: - $blockFillPatternStyle = 0x06; - - break; - case Fill::FILL_PATTERN_DARKDOWN: - $blockFillPatternStyle = 0x07; - - break; - case Fill::FILL_PATTERN_DARKUP: - $blockFillPatternStyle = 0x08; - - break; - case Fill::FILL_PATTERN_DARKGRID: - $blockFillPatternStyle = 0x09; - - break; - case Fill::FILL_PATTERN_DARKTRELLIS: - $blockFillPatternStyle = 0x0A; - - break; - case Fill::FILL_PATTERN_LIGHTHORIZONTAL: - $blockFillPatternStyle = 0x0B; - - break; - case Fill::FILL_PATTERN_LIGHTVERTICAL: - $blockFillPatternStyle = 0x0C; - - break; - case Fill::FILL_PATTERN_LIGHTDOWN: - $blockFillPatternStyle = 0x0D; - - break; - case Fill::FILL_PATTERN_LIGHTUP: - $blockFillPatternStyle = 0x0E; - - break; - case Fill::FILL_PATTERN_LIGHTGRID: - $blockFillPatternStyle = 0x0F; - - break; - case Fill::FILL_PATTERN_LIGHTTRELLIS: - $blockFillPatternStyle = 0x10; - - break; - case Fill::FILL_PATTERN_GRAY125: - $blockFillPatternStyle = 0x11; - - break; - case Fill::FILL_PATTERN_GRAY0625: - $blockFillPatternStyle = 0x12; - - break; - case Fill::FILL_GRADIENT_LINEAR: - $blockFillPatternStyle = 0x00; - - break; // does not exist in BIFF8 - case Fill::FILL_GRADIENT_PATH: - $blockFillPatternStyle = 0x00; - - break; // does not exist in BIFF8 - default: - $blockFillPatternStyle = 0x00; - - break; - } - // Color - switch ($conditional->getStyle()->getFill()->getStartColor()->getRGB()) { - case '000000': - $colorIdxBg = 0x08; - - break; - case 'FFFFFF': - $colorIdxBg = 0x09; - - break; - case 'FF0000': - $colorIdxBg = 0x0A; - - break; - case '00FF00': - $colorIdxBg = 0x0B; - - break; - case '0000FF': - $colorIdxBg = 0x0C; - - break; - case 'FFFF00': - $colorIdxBg = 0x0D; - - break; - case 'FF00FF': - $colorIdxBg = 0x0E; - - break; - case '00FFFF': - $colorIdxBg = 0x0F; - - break; - case '800000': - $colorIdxBg = 0x10; - - break; - case '008000': - $colorIdxBg = 0x11; - - break; - case '000080': - $colorIdxBg = 0x12; - - break; - case '808000': - $colorIdxBg = 0x13; - - break; - case '800080': - $colorIdxBg = 0x14; - - break; - case '008080': - $colorIdxBg = 0x15; - - break; - case 'C0C0C0': - $colorIdxBg = 0x16; - - break; - case '808080': - $colorIdxBg = 0x17; - - break; - case '9999FF': - $colorIdxBg = 0x18; - - break; - case '993366': - $colorIdxBg = 0x19; - - break; - case 'FFFFCC': - $colorIdxBg = 0x1A; - - break; - case 'CCFFFF': - $colorIdxBg = 0x1B; - - break; - case '660066': - $colorIdxBg = 0x1C; - - break; - case 'FF8080': - $colorIdxBg = 0x1D; - - break; - case '0066CC': - $colorIdxBg = 0x1E; - - break; - case 'CCCCFF': - $colorIdxBg = 0x1F; - - break; - case '000080': - $colorIdxBg = 0x20; - - break; - case 'FF00FF': - $colorIdxBg = 0x21; - - break; - case 'FFFF00': - $colorIdxBg = 0x22; - - break; - case '00FFFF': - $colorIdxBg = 0x23; - - break; - case '800080': - $colorIdxBg = 0x24; - - break; - case '800000': - $colorIdxBg = 0x25; - - break; - case '008080': - $colorIdxBg = 0x26; - - break; - case '0000FF': - $colorIdxBg = 0x27; - - break; - case '00CCFF': - $colorIdxBg = 0x28; - - break; - case 'CCFFFF': - $colorIdxBg = 0x29; - - break; - case 'CCFFCC': - $colorIdxBg = 0x2A; - - break; - case 'FFFF99': - $colorIdxBg = 0x2B; - - break; - case '99CCFF': - $colorIdxBg = 0x2C; - - break; - case 'FF99CC': - $colorIdxBg = 0x2D; - - break; - case 'CC99FF': - $colorIdxBg = 0x2E; - - break; - case 'FFCC99': - $colorIdxBg = 0x2F; - - break; - case '3366FF': - $colorIdxBg = 0x30; - - break; - case '33CCCC': - $colorIdxBg = 0x31; - - break; - case '99CC00': - $colorIdxBg = 0x32; - - break; - case 'FFCC00': - $colorIdxBg = 0x33; - - break; - case 'FF9900': - $colorIdxBg = 0x34; - - break; - case 'FF6600': - $colorIdxBg = 0x35; - - break; - case '666699': - $colorIdxBg = 0x36; - - break; - case '969696': - $colorIdxBg = 0x37; - - break; - case '003366': - $colorIdxBg = 0x38; - - break; - case '339966': - $colorIdxBg = 0x39; - - break; - case '003300': - $colorIdxBg = 0x3A; - - break; - case '333300': - $colorIdxBg = 0x3B; - - break; - case '993300': - $colorIdxBg = 0x3C; - - break; - case '993366': - $colorIdxBg = 0x3D; - - break; - case '333399': - $colorIdxBg = 0x3E; - - break; - case '333333': - $colorIdxBg = 0x3F; - - break; - default: - $colorIdxBg = 0x41; - - break; - } - // Fg Color - switch ($conditional->getStyle()->getFill()->getEndColor()->getRGB()) { - case '000000': - $colorIdxFg = 0x08; - - break; - case 'FFFFFF': - $colorIdxFg = 0x09; - - break; - case 'FF0000': - $colorIdxFg = 0x0A; - - break; - case '00FF00': - $colorIdxFg = 0x0B; - - break; - case '0000FF': - $colorIdxFg = 0x0C; - - break; - case 'FFFF00': - $colorIdxFg = 0x0D; - - break; - case 'FF00FF': - $colorIdxFg = 0x0E; - - break; - case '00FFFF': - $colorIdxFg = 0x0F; - - break; - case '800000': - $colorIdxFg = 0x10; - - break; - case '008000': - $colorIdxFg = 0x11; - - break; - case '000080': - $colorIdxFg = 0x12; - - break; - case '808000': - $colorIdxFg = 0x13; - - break; - case '800080': - $colorIdxFg = 0x14; - - break; - case '008080': - $colorIdxFg = 0x15; - - break; - case 'C0C0C0': - $colorIdxFg = 0x16; - - break; - case '808080': - $colorIdxFg = 0x17; - - break; - case '9999FF': - $colorIdxFg = 0x18; - - break; - case '993366': - $colorIdxFg = 0x19; - - break; - case 'FFFFCC': - $colorIdxFg = 0x1A; - - break; - case 'CCFFFF': - $colorIdxFg = 0x1B; - - break; - case '660066': - $colorIdxFg = 0x1C; - - break; - case 'FF8080': - $colorIdxFg = 0x1D; - - break; - case '0066CC': - $colorIdxFg = 0x1E; - - break; - case 'CCCCFF': - $colorIdxFg = 0x1F; - - break; - case '000080': - $colorIdxFg = 0x20; - - break; - case 'FF00FF': - $colorIdxFg = 0x21; - - break; - case 'FFFF00': - $colorIdxFg = 0x22; - - break; - case '00FFFF': - $colorIdxFg = 0x23; - - break; - case '800080': - $colorIdxFg = 0x24; - - break; - case '800000': - $colorIdxFg = 0x25; - - break; - case '008080': - $colorIdxFg = 0x26; - - break; - case '0000FF': - $colorIdxFg = 0x27; - - break; - case '00CCFF': - $colorIdxFg = 0x28; - - break; - case 'CCFFFF': - $colorIdxFg = 0x29; - - break; - case 'CCFFCC': - $colorIdxFg = 0x2A; - - break; - case 'FFFF99': - $colorIdxFg = 0x2B; - - break; - case '99CCFF': - $colorIdxFg = 0x2C; - - break; - case 'FF99CC': - $colorIdxFg = 0x2D; - - break; - case 'CC99FF': - $colorIdxFg = 0x2E; - - break; - case 'FFCC99': - $colorIdxFg = 0x2F; - - break; - case '3366FF': - $colorIdxFg = 0x30; - - break; - case '33CCCC': - $colorIdxFg = 0x31; - - break; - case '99CC00': - $colorIdxFg = 0x32; - - break; - case 'FFCC00': - $colorIdxFg = 0x33; - - break; - case 'FF9900': - $colorIdxFg = 0x34; - - break; - case 'FF6600': - $colorIdxFg = 0x35; - - break; - case '666699': - $colorIdxFg = 0x36; - - break; - case '969696': - $colorIdxFg = 0x37; - - break; - case '003366': - $colorIdxFg = 0x38; - - break; - case '339966': - $colorIdxFg = 0x39; - - break; - case '003300': - $colorIdxFg = 0x3A; - - break; - case '333300': - $colorIdxFg = 0x3B; - - break; - case '993300': - $colorIdxFg = 0x3C; - - break; - case '993366': - $colorIdxFg = 0x3D; - - break; - case '333399': - $colorIdxFg = 0x3E; - - break; - case '333333': - $colorIdxFg = 0x3F; - - break; - default: - $colorIdxFg = 0x40; - - break; - } $dataBlockFill = pack('v', $blockFillPatternStyle); $dataBlockFill .= pack('v', $colorIdxFg | ($colorIdxBg << 7)); } - if ($bFormatProt == 1) { - $dataBlockProtection = 0; - if ($conditional->getStyle()->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED) { - $dataBlockProtection = 1; - } - if ($conditional->getStyle()->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED) { - $dataBlockProtection = 1 << 1; - } - } $data = pack('CCvvVv', $type, $operatorType, $szValue1, $szValue2, $flags, 0x0000); - if ($bFormatFont == 1) { // Block Formatting : OK + if ($bFormatFont === 1) { // Block Formatting : OK $data .= $dataBlockFont; } - if ($bFormatAlign == 1) { + if ($bFormatAlign === 1) { $data .= $dataBlockAlign; } - if ($bFormatBorder == 1) { + if ($bFormatBorder === 1) { $data .= $dataBlockBorder; } - if ($bFormatFill == 1) { // Block Formatting : OK + if ($bFormatFill === 1) { // Block Formatting : OK $data .= $dataBlockFill; } if ($bFormatProt == 1) { - $data .= $dataBlockProtection; + $data .= $this->getDataBlockProtection($conditional); } if ($operand1 !== null) { $data .= $operand1; @@ -4452,28 +3139,25 @@ class Worksheet extends BIFFwriter foreach ($this->phpSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { foreach ($conditionalStyles as $conditional) { if ( - $conditional->getConditionType() == Conditional::CONDITION_EXPRESSION - || $conditional->getConditionType() == Conditional::CONDITION_CELLIS + $conditional->getConditionType() == Conditional::CONDITION_EXPRESSION || + $conditional->getConditionType() == Conditional::CONDITION_CELLIS ) { if (!in_array($conditional->getHashCode(), $arrConditional)) { $arrConditional[] = $conditional->getHashCode(); } // Cells - $arrCoord = Coordinate::coordinateFromString($cellCoordinate); - if (!is_numeric($arrCoord[0])) { - $arrCoord[0] = Coordinate::columnIndexFromString($arrCoord[0]); + $rangeCoordinates = Coordinate::rangeBoundaries($cellCoordinate); + if ($numColumnMin === null || ($numColumnMin > $rangeCoordinates[0][0])) { + $numColumnMin = $rangeCoordinates[0][0]; } - if ($numColumnMin === null || ($numColumnMin > $arrCoord[0])) { - $numColumnMin = $arrCoord[0]; + if ($numColumnMax === null || ($numColumnMax < $rangeCoordinates[1][0])) { + $numColumnMax = $rangeCoordinates[1][0]; } - if ($numColumnMax === null || ($numColumnMax < $arrCoord[0])) { - $numColumnMax = $arrCoord[0]; + if ($numRowMin === null || ($numRowMin > $rangeCoordinates[0][1])) { + $numRowMin = (int) $rangeCoordinates[0][1]; } - if ($numRowMin === null || ($numRowMin > $arrCoord[1])) { - $numRowMin = $arrCoord[1]; - } - if ($numRowMax === null || ($numRowMax < $arrCoord[1])) { - $numRowMax = $arrCoord[1]; + if ($numRowMax === null || ($numRowMax < $rangeCoordinates[1][1])) { + $numRowMax = (int) $rangeCoordinates[1][1]; } } } @@ -4488,4 +3172,17 @@ class Worksheet extends BIFFwriter $data .= $cellRange; $this->append($header . $data); } + + private function getDataBlockProtection(Conditional $conditional): int + { + $dataBlockProtection = 0; + if ($conditional->getStyle()->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED) { + $dataBlockProtection = 1; + } + if ($conditional->getStyle()->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED) { + $dataBlockProtection = 1 << 1; + } + + return $dataBlockProtection; + } } diff --git a/src/PhpSpreadsheet/Writer/Xls/Xf.php b/src/PhpSpreadsheet/Writer/Xls/Xf.php index 3e8169b3..b2dbc67a 100644 --- a/src/PhpSpreadsheet/Writer/Xls/Xf.php +++ b/src/PhpSpreadsheet/Writer/Xls/Xf.php @@ -3,11 +3,12 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use PhpOffice\PhpSpreadsheet\Style\Alignment; -use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Borders; -use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Protection; use PhpOffice\PhpSpreadsheet\Style\Style; +use PhpOffice\PhpSpreadsheet\Writer\Xls\Style\CellAlignment; +use PhpOffice\PhpSpreadsheet\Writer\Xls\Style\CellBorder; +use PhpOffice\PhpSpreadsheet\Writer\Xls\Style\CellFill; // Original file header of PEAR::Spreadsheet_Excel_Writer_Format (used as the base for this class): // ----------------------------------------------------------------------------------------- @@ -115,6 +116,21 @@ class Xf */ private $rightBorderColor; + /** + * @var int + */ + private $diag; + + /** + * @var int + */ + private $diagColor; + + /** + * @var Style + */ + private $style; + /** * Constructor. * @@ -132,14 +148,14 @@ class Xf $this->foregroundColor = 0x40; $this->backgroundColor = 0x41; - $this->_diag = 0; + $this->diag = 0; $this->bottomBorderColor = 0x40; $this->topBorderColor = 0x40; $this->leftBorderColor = 0x40; $this->rightBorderColor = 0x40; - $this->_diag_color = 0x40; - $this->_style = $style; + $this->diagColor = 0x40; + $this->style = $style; } /** @@ -153,39 +169,39 @@ class Xf if ($this->isStyleXf) { $style = 0xFFF5; } else { - $style = self::mapLocked($this->_style->getProtection()->getLocked()); - $style |= self::mapHidden($this->_style->getProtection()->getHidden()) << 1; + $style = self::mapLocked($this->style->getProtection()->getLocked()); + $style |= self::mapHidden($this->style->getProtection()->getHidden()) << 1; } // Flags to indicate if attributes have been set. $atr_num = ($this->numberFormatIndex != 0) ? 1 : 0; $atr_fnt = ($this->fontIndex != 0) ? 1 : 0; - $atr_alc = ((int) $this->_style->getAlignment()->getWrapText()) ? 1 : 0; - $atr_bdr = (self::mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) || - self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) || - self::mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) || - self::mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle())) ? 1 : 0; - $atr_pat = (($this->foregroundColor != 0x40) || - ($this->backgroundColor != 0x41) || - self::mapFillType($this->_style->getFill()->getFillType())) ? 1 : 0; - $atr_prot = self::mapLocked($this->_style->getProtection()->getLocked()) - | self::mapHidden($this->_style->getProtection()->getHidden()); + $atr_alc = ((int) $this->style->getAlignment()->getWrapText()) ? 1 : 0; + $atr_bdr = (CellBorder::style($this->style->getBorders()->getBottom()) || + CellBorder::style($this->style->getBorders()->getTop()) || + CellBorder::style($this->style->getBorders()->getLeft()) || + CellBorder::style($this->style->getBorders()->getRight())) ? 1 : 0; + $atr_pat = ($this->foregroundColor != 0x40) ? 1 : 0; + $atr_pat = ($this->backgroundColor != 0x41) ? 1 : $atr_pat; + $atr_pat = CellFill::style($this->style->getFill()) ? 1 : $atr_pat; + $atr_prot = self::mapLocked($this->style->getProtection()->getLocked()) + | self::mapHidden($this->style->getProtection()->getHidden()); // Zero the default border colour if the border has not been set. - if (self::mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) == 0) { + if (CellBorder::style($this->style->getBorders()->getBottom()) == 0) { $this->bottomBorderColor = 0; } - if (self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) == 0) { + if (CellBorder::style($this->style->getBorders()->getTop()) == 0) { $this->topBorderColor = 0; } - if (self::mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) == 0) { + if (CellBorder::style($this->style->getBorders()->getRight()) == 0) { $this->rightBorderColor = 0; } - if (self::mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) == 0) { + if (CellBorder::style($this->style->getBorders()->getLeft()) == 0) { $this->leftBorderColor = 0; } - if (self::mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) == 0) { - $this->_diag_color = 0; + if (CellBorder::style($this->style->getBorders()->getDiagonal()) == 0) { + $this->diagColor = 0; } $record = 0x00E0; // Record identifier @@ -194,9 +210,10 @@ class Xf $ifnt = $this->fontIndex; // Index to FONT record $ifmt = $this->numberFormatIndex; // Index to FORMAT record - $align = $this->mapHAlign($this->_style->getAlignment()->getHorizontal()); // Alignment - $align |= (int) $this->_style->getAlignment()->getWrapText() << 3; - $align |= self::mapVAlign($this->_style->getAlignment()->getVertical()) << 4; + // Alignment + $align = CellAlignment::horizontal($this->style->getAlignment()); + $align |= CellAlignment::wrap($this->style->getAlignment()) << 3; + $align |= CellAlignment::vertical($this->style->getAlignment()) << 4; $align |= $this->textJustLast << 7; $used_attrib = $atr_num << 2; @@ -209,35 +226,35 @@ class Xf $icv = $this->foregroundColor; // fg and bg pattern colors $icv |= $this->backgroundColor << 7; - $border1 = self::mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()); // Border line style and color - $border1 |= self::mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) << 4; - $border1 |= self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) << 8; - $border1 |= self::mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) << 12; + $border1 = CellBorder::style($this->style->getBorders()->getLeft()); // Border line style and color + $border1 |= CellBorder::style($this->style->getBorders()->getRight()) << 4; + $border1 |= CellBorder::style($this->style->getBorders()->getTop()) << 8; + $border1 |= CellBorder::style($this->style->getBorders()->getBottom()) << 12; $border1 |= $this->leftBorderColor << 16; $border1 |= $this->rightBorderColor << 23; - $diagonalDirection = $this->_style->getBorders()->getDiagonalDirection(); + $diagonalDirection = $this->style->getBorders()->getDiagonalDirection(); $diag_tl_to_rb = $diagonalDirection == Borders::DIAGONAL_BOTH - || $diagonalDirection == Borders::DIAGONAL_DOWN; + || $diagonalDirection == Borders::DIAGONAL_DOWN; $diag_tr_to_lb = $diagonalDirection == Borders::DIAGONAL_BOTH - || $diagonalDirection == Borders::DIAGONAL_UP; + || $diagonalDirection == Borders::DIAGONAL_UP; $border1 |= $diag_tl_to_rb << 30; $border1 |= $diag_tr_to_lb << 31; $border2 = $this->topBorderColor; // Border color $border2 |= $this->bottomBorderColor << 7; - $border2 |= $this->_diag_color << 14; - $border2 |= self::mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) << 21; - $border2 |= self::mapFillType($this->_style->getFill()->getFillType()) << 26; + $border2 |= $this->diagColor << 14; + $border2 |= CellBorder::style($this->style->getBorders()->getDiagonal()) << 21; + $border2 |= CellFill::style($this->style->getFill()) << 26; $header = pack('vv', $record, $length); //BIFF8 options: identation, shrinkToFit and text direction - $biff8_options = $this->_style->getAlignment()->getIndent(); - $biff8_options |= (int) $this->_style->getAlignment()->getShrinkToFit() << 4; + $biff8_options = $this->style->getAlignment()->getIndent(); + $biff8_options |= (int) $this->style->getAlignment()->getShrinkToFit() << 4; $data = pack('vvvC', $ifnt, $ifmt, $style, $align); - $data .= pack('CCC', self::mapTextRotation($this->_style->getAlignment()->getTextRotation()), $biff8_options, $used_attrib); + $data .= pack('CCC', self::mapTextRotation($this->style->getAlignment()->getTextRotation()), $biff8_options, $used_attrib); $data .= pack('VVv', $border1, $border2, $icv); return $header . $data; @@ -300,7 +317,7 @@ class Xf */ public function setDiagColor($colorIndex): void { - $this->_diag_color = $colorIndex; + $this->diagColor = $colorIndex; } /** @@ -344,148 +361,6 @@ class Xf $this->fontIndex = $value; } - /** - * Map of BIFF2-BIFF8 codes for border styles. - * - * @var array of int - */ - private static $mapBorderStyles = [ - Border::BORDER_NONE => 0x00, - Border::BORDER_THIN => 0x01, - Border::BORDER_MEDIUM => 0x02, - Border::BORDER_DASHED => 0x03, - Border::BORDER_DOTTED => 0x04, - Border::BORDER_THICK => 0x05, - Border::BORDER_DOUBLE => 0x06, - Border::BORDER_HAIR => 0x07, - Border::BORDER_MEDIUMDASHED => 0x08, - Border::BORDER_DASHDOT => 0x09, - Border::BORDER_MEDIUMDASHDOT => 0x0A, - Border::BORDER_DASHDOTDOT => 0x0B, - Border::BORDER_MEDIUMDASHDOTDOT => 0x0C, - Border::BORDER_SLANTDASHDOT => 0x0D, - ]; - - /** - * Map border style. - * - * @param string $borderStyle - * - * @return int - */ - private static function mapBorderStyle($borderStyle) - { - if (isset(self::$mapBorderStyles[$borderStyle])) { - return self::$mapBorderStyles[$borderStyle]; - } - - return 0x00; - } - - /** - * Map of BIFF2-BIFF8 codes for fill types. - * - * @var array of int - */ - private static $mapFillTypes = [ - Fill::FILL_NONE => 0x00, - Fill::FILL_SOLID => 0x01, - Fill::FILL_PATTERN_MEDIUMGRAY => 0x02, - Fill::FILL_PATTERN_DARKGRAY => 0x03, - Fill::FILL_PATTERN_LIGHTGRAY => 0x04, - Fill::FILL_PATTERN_DARKHORIZONTAL => 0x05, - Fill::FILL_PATTERN_DARKVERTICAL => 0x06, - Fill::FILL_PATTERN_DARKDOWN => 0x07, - Fill::FILL_PATTERN_DARKUP => 0x08, - Fill::FILL_PATTERN_DARKGRID => 0x09, - Fill::FILL_PATTERN_DARKTRELLIS => 0x0A, - Fill::FILL_PATTERN_LIGHTHORIZONTAL => 0x0B, - Fill::FILL_PATTERN_LIGHTVERTICAL => 0x0C, - Fill::FILL_PATTERN_LIGHTDOWN => 0x0D, - Fill::FILL_PATTERN_LIGHTUP => 0x0E, - Fill::FILL_PATTERN_LIGHTGRID => 0x0F, - Fill::FILL_PATTERN_LIGHTTRELLIS => 0x10, - Fill::FILL_PATTERN_GRAY125 => 0x11, - Fill::FILL_PATTERN_GRAY0625 => 0x12, - Fill::FILL_GRADIENT_LINEAR => 0x00, // does not exist in BIFF8 - Fill::FILL_GRADIENT_PATH => 0x00, // does not exist in BIFF8 - ]; - - /** - * Map fill type. - * - * @param string $fillType - * - * @return int - */ - private static function mapFillType($fillType) - { - if (isset(self::$mapFillTypes[$fillType])) { - return self::$mapFillTypes[$fillType]; - } - - return 0x00; - } - - /** - * Map of BIFF2-BIFF8 codes for horizontal alignment. - * - * @var array of int - */ - private static $mapHAlignments = [ - Alignment::HORIZONTAL_GENERAL => 0, - Alignment::HORIZONTAL_LEFT => 1, - Alignment::HORIZONTAL_CENTER => 2, - Alignment::HORIZONTAL_RIGHT => 3, - Alignment::HORIZONTAL_FILL => 4, - Alignment::HORIZONTAL_JUSTIFY => 5, - Alignment::HORIZONTAL_CENTER_CONTINUOUS => 6, - ]; - - /** - * Map to BIFF2-BIFF8 codes for horizontal alignment. - * - * @param string $hAlign - * - * @return int - */ - private function mapHAlign($hAlign) - { - if (isset(self::$mapHAlignments[$hAlign])) { - return self::$mapHAlignments[$hAlign]; - } - - return 0; - } - - /** - * Map of BIFF2-BIFF8 codes for vertical alignment. - * - * @var array of int - */ - private static $mapVAlignments = [ - Alignment::VERTICAL_TOP => 0, - Alignment::VERTICAL_CENTER => 1, - Alignment::VERTICAL_BOTTOM => 2, - Alignment::VERTICAL_JUSTIFY => 3, - ]; - - /** - * Map to BIFF2-BIFF8 codes for vertical alignment. - * - * @param string $vAlign - * - * @return int - */ - private static function mapVAlign($vAlign) - { - if (isset(self::$mapVAlignments[$vAlign])) { - return self::$mapVAlignments[$vAlign]; - } - - return 2; - } - /** * Map to BIFF8 codes for text rotation angle. * @@ -497,15 +372,22 @@ class Xf { if ($textRotation >= 0) { return $textRotation; - } elseif ($textRotation == -165) { - return 255; - } elseif ($textRotation < 0) { - return 90 - $textRotation; } + if ($textRotation == Alignment::TEXTROTATION_STACK_PHPSPREADSHEET) { + return Alignment::TEXTROTATION_STACK_EXCEL; + } + + return 90 - $textRotation; } + private const LOCK_ARRAY = [ + Protection::PROTECTION_INHERIT => 1, + Protection::PROTECTION_PROTECTED => 1, + Protection::PROTECTION_UNPROTECTED => 0, + ]; + /** - * Map locked. + * Map locked values. * * @param string $locked * @@ -513,18 +395,15 @@ class Xf */ private static function mapLocked($locked) { - switch ($locked) { - case Protection::PROTECTION_INHERIT: - return 1; - case Protection::PROTECTION_PROTECTED: - return 1; - case Protection::PROTECTION_UNPROTECTED: - return 0; - default: - return 1; - } + return array_key_exists($locked, self::LOCK_ARRAY) ? self::LOCK_ARRAY[$locked] : 1; } + private const HIDDEN_ARRAY = [ + Protection::PROTECTION_INHERIT => 0, + Protection::PROTECTION_PROTECTED => 1, + Protection::PROTECTION_UNPROTECTED => 0, + ]; + /** * Map hidden. * @@ -534,15 +413,6 @@ class Xf */ private static function mapHidden($hidden) { - switch ($hidden) { - case Protection::PROTECTION_INHERIT: - return 0; - case Protection::PROTECTION_PROTECTED: - return 1; - case Protection::PROTECTION_UNPROTECTED: - return 0; - default: - return 0; - } + return array_key_exists($hidden, self::HIDDEN_ARRAY) ? self::HIDDEN_ARRAY[$hidden] : 0; } } diff --git a/src/PhpSpreadsheet/Writer/Xlsx.php b/src/PhpSpreadsheet/Writer/Xlsx.php index 104e6041..befc9cef 100644 --- a/src/PhpSpreadsheet/Writer/Xlsx.php +++ b/src/PhpSpreadsheet/Writer/Xlsx.php @@ -5,8 +5,13 @@ namespace PhpOffice\PhpSpreadsheet\Writer; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\HashTable; -use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Spreadsheet; +use PhpOffice\PhpSpreadsheet\Style\Borders; +use PhpOffice\PhpSpreadsheet\Style\Conditional; +use PhpOffice\PhpSpreadsheet\Style\Fill; +use PhpOffice\PhpSpreadsheet\Style\Font; +use PhpOffice\PhpSpreadsheet\Style\NumberFormat; +use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\Drawing as WorksheetDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; @@ -37,13 +42,6 @@ class Xlsx extends BaseWriter */ private $office2003compatibility = false; - /** - * Private writer parts. - * - * @var Xlsx\WriterPart[] - */ - private $writerParts = []; - /** * Private Spreadsheet. * @@ -61,49 +59,49 @@ class Xlsx extends BaseWriter /** * Private unique Conditional HashTable. * - * @var HashTable + * @var HashTable */ private $stylesConditionalHashTable; /** * Private unique Style HashTable. * - * @var HashTable + * @var HashTable<\PhpOffice\PhpSpreadsheet\Style\Style> */ private $styleHashTable; /** * Private unique Fill HashTable. * - * @var HashTable + * @var HashTable */ private $fillHashTable; /** * Private unique \PhpOffice\PhpSpreadsheet\Style\Font HashTable. * - * @var HashTable + * @var HashTable */ private $fontHashTable; /** * Private unique Borders HashTable. * - * @var HashTable + * @var HashTable */ private $bordersHashTable; /** * Private unique NumberFormat HashTable. * - * @var HashTable + * @var HashTable */ private $numFmtHashTable; /** * Private unique \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\BaseDrawing HashTable. * - * @var HashTable + * @var HashTable */ private $drawingHashTable; @@ -114,6 +112,71 @@ class Xlsx extends BaseWriter */ private $zip; + /** + * @var Chart + */ + private $writerPartChart; + + /** + * @var Comments + */ + private $writerPartComments; + + /** + * @var ContentTypes + */ + private $writerPartContentTypes; + + /** + * @var DocProps + */ + private $writerPartDocProps; + + /** + * @var Drawing + */ + private $writerPartDrawing; + + /** + * @var Rels + */ + private $writerPartRels; + + /** + * @var RelsRibbon + */ + private $writerPartRelsRibbon; + + /** + * @var RelsVBA + */ + private $writerPartRelsVBA; + + /** + * @var StringTable + */ + private $writerPartStringTable; + + /** + * @var Style + */ + private $writerPartStyle; + + /** + * @var Theme + */ + private $writerPartTheme; + + /** + * @var Workbook + */ + private $writerPartWorkbook; + + /** + * @var Worksheet + */ + private $writerPartWorksheet; + /** * Create a new Xlsx Writer. */ @@ -122,53 +185,100 @@ class Xlsx extends BaseWriter // Assign PhpSpreadsheet $this->setSpreadsheet($spreadsheet); - $writerPartsArray = [ - 'stringtable' => StringTable::class, - 'contenttypes' => ContentTypes::class, - 'docprops' => DocProps::class, - 'rels' => Rels::class, - 'theme' => Theme::class, - 'style' => Style::class, - 'workbook' => Workbook::class, - 'worksheet' => Worksheet::class, - 'drawing' => Drawing::class, - 'comments' => Comments::class, - 'chart' => Chart::class, - 'relsvba' => RelsVBA::class, - 'relsribbonobjects' => RelsRibbon::class, - ]; - - // Initialise writer parts - // and Assign their parent IWriters - foreach ($writerPartsArray as $writer => $class) { - $this->writerParts[$writer] = new $class($this); - } - - $hashTablesArray = ['stylesConditionalHashTable', 'fillHashTable', 'fontHashTable', - 'bordersHashTable', 'numFmtHashTable', 'drawingHashTable', - 'styleHashTable', - ]; + $this->writerPartChart = new Chart($this); + $this->writerPartComments = new Comments($this); + $this->writerPartContentTypes = new ContentTypes($this); + $this->writerPartDocProps = new DocProps($this); + $this->writerPartDrawing = new Drawing($this); + $this->writerPartRels = new Rels($this); + $this->writerPartRelsRibbon = new RelsRibbon($this); + $this->writerPartRelsVBA = new RelsVBA($this); + $this->writerPartStringTable = new StringTable($this); + $this->writerPartStyle = new Style($this); + $this->writerPartTheme = new Theme($this); + $this->writerPartWorkbook = new Workbook($this); + $this->writerPartWorksheet = new Worksheet($this); // Set HashTable variables - foreach ($hashTablesArray as $tableName) { - $this->$tableName = new HashTable(); - } + // @phpstan-ignore-next-line + $this->bordersHashTable = new HashTable(); + // @phpstan-ignore-next-line + $this->drawingHashTable = new HashTable(); + // @phpstan-ignore-next-line + $this->fillHashTable = new HashTable(); + // @phpstan-ignore-next-line + $this->fontHashTable = new HashTable(); + // @phpstan-ignore-next-line + $this->numFmtHashTable = new HashTable(); + // @phpstan-ignore-next-line + $this->styleHashTable = new HashTable(); + // @phpstan-ignore-next-line + $this->stylesConditionalHashTable = new HashTable(); } - /** - * Get writer part. - * - * @param string $pPartName Writer part name - * - * @return \PhpOffice\PhpSpreadsheet\Writer\Xlsx\WriterPart - */ - public function getWriterPart($pPartName) + public function getWriterPartChart(): Chart { - if ($pPartName != '' && isset($this->writerParts[strtolower($pPartName)])) { - return $this->writerParts[strtolower($pPartName)]; - } + return $this->writerPartChart; + } - return null; + public function getWriterPartComments(): Comments + { + return $this->writerPartComments; + } + + public function getWriterPartContentTypes(): ContentTypes + { + return $this->writerPartContentTypes; + } + + public function getWriterPartDocProps(): DocProps + { + return $this->writerPartDocProps; + } + + public function getWriterPartDrawing(): Drawing + { + return $this->writerPartDrawing; + } + + public function getWriterPartRels(): Rels + { + return $this->writerPartRels; + } + + public function getWriterPartRelsRibbon(): RelsRibbon + { + return $this->writerPartRelsRibbon; + } + + public function getWriterPartRelsVBA(): RelsVBA + { + return $this->writerPartRelsVBA; + } + + public function getWriterPartStringTable(): StringTable + { + return $this->writerPartStringTable; + } + + public function getWriterPartStyle(): Style + { + return $this->writerPartStyle; + } + + public function getWriterPartTheme(): Theme + { + return $this->writerPartTheme; + } + + public function getWriterPartWorkbook(): Workbook + { + return $this->writerPartWorkbook; + } + + public function getWriterPartWorksheet(): Worksheet + { + return $this->writerPartWorksheet; } /** @@ -176,14 +286,14 @@ class Xlsx extends BaseWriter * * @param resource|string $filename */ - public function save($filename): void + public function save($filename, int $flags = 0): void { + $this->processFlags($flags); + // garbage collect $this->pathNames = []; $this->spreadSheet->garbageCollect(); - $this->openFileHandle($filename); - $saveDebugLog = Calculation::getInstance($this->spreadSheet)->getDebugLog()->getWriteDebugLog(); Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog(false); $saveDateReturnType = Functions::getReturnDateType(); @@ -192,91 +302,86 @@ class Xlsx extends BaseWriter // Create string lookup table $this->stringTable = []; for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { - $this->stringTable = $this->getWriterPart('StringTable')->createStringTable($this->spreadSheet->getSheet($i), $this->stringTable); + $this->stringTable = $this->getWriterPartStringTable()->createStringTable($this->spreadSheet->getSheet($i), $this->stringTable); } // Create styles dictionaries - $this->styleHashTable->addFromSource($this->getWriterPart('Style')->allStyles($this->spreadSheet)); - $this->stylesConditionalHashTable->addFromSource($this->getWriterPart('Style')->allConditionalStyles($this->spreadSheet)); - $this->fillHashTable->addFromSource($this->getWriterPart('Style')->allFills($this->spreadSheet)); - $this->fontHashTable->addFromSource($this->getWriterPart('Style')->allFonts($this->spreadSheet)); - $this->bordersHashTable->addFromSource($this->getWriterPart('Style')->allBorders($this->spreadSheet)); - $this->numFmtHashTable->addFromSource($this->getWriterPart('Style')->allNumberFormats($this->spreadSheet)); + $this->styleHashTable->addFromSource($this->getWriterPartStyle()->allStyles($this->spreadSheet)); + $this->stylesConditionalHashTable->addFromSource($this->getWriterPartStyle()->allConditionalStyles($this->spreadSheet)); + $this->fillHashTable->addFromSource($this->getWriterPartStyle()->allFills($this->spreadSheet)); + $this->fontHashTable->addFromSource($this->getWriterPartStyle()->allFonts($this->spreadSheet)); + $this->bordersHashTable->addFromSource($this->getWriterPartStyle()->allBorders($this->spreadSheet)); + $this->numFmtHashTable->addFromSource($this->getWriterPartStyle()->allNumberFormats($this->spreadSheet)); // Create drawing dictionary - $this->drawingHashTable->addFromSource($this->getWriterPart('Drawing')->allDrawings($this->spreadSheet)); - - $options = new Archive(); - $options->setEnableZip64(false); - $options->setOutputStream($this->fileHandle); - - $this->zip = new ZipStream(null, $options); + $this->drawingHashTable->addFromSource($this->getWriterPartDrawing()->allDrawings($this->spreadSheet)); + $zipContent = []; // Add [Content_Types].xml to ZIP file - $this->addZipFile('[Content_Types].xml', $this->getWriterPart('ContentTypes')->writeContentTypes($this->spreadSheet, $this->includeCharts)); + $zipContent['[Content_Types].xml'] = $this->getWriterPartContentTypes()->writeContentTypes($this->spreadSheet, $this->includeCharts); //if hasMacros, add the vbaProject.bin file, Certificate file(if exists) if ($this->spreadSheet->hasMacros()) { $macrosCode = $this->spreadSheet->getMacrosCode(); if ($macrosCode !== null) { // we have the code ? - $this->addZipFile('xl/vbaProject.bin', $macrosCode); //allways in 'xl', allways named vbaProject.bin + $zipContent['xl/vbaProject.bin'] = $macrosCode; //allways in 'xl', allways named vbaProject.bin if ($this->spreadSheet->hasMacrosCertificate()) { //signed macros ? // Yes : add the certificate file and the related rels file - $this->addZipFile('xl/vbaProjectSignature.bin', $this->spreadSheet->getMacrosCertificate()); - $this->addZipFile('xl/_rels/vbaProject.bin.rels', $this->getWriterPart('RelsVBA')->writeVBARelationships($this->spreadSheet)); + $zipContent['xl/vbaProjectSignature.bin'] = $this->spreadSheet->getMacrosCertificate(); + $zipContent['xl/_rels/vbaProject.bin.rels'] = $this->getWriterPartRelsVBA()->writeVBARelationships($this->spreadSheet); } } } //a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels) if ($this->spreadSheet->hasRibbon()) { $tmpRibbonTarget = $this->spreadSheet->getRibbonXMLData('target'); - $this->addZipFile($tmpRibbonTarget, $this->spreadSheet->getRibbonXMLData('data')); + $zipContent[$tmpRibbonTarget] = $this->spreadSheet->getRibbonXMLData('data'); if ($this->spreadSheet->hasRibbonBinObjects()) { $tmpRootPath = dirname($tmpRibbonTarget) . '/'; $ribbonBinObjects = $this->spreadSheet->getRibbonBinObjects('data'); //the files to write foreach ($ribbonBinObjects as $aPath => $aContent) { - $this->addZipFile($tmpRootPath . $aPath, $aContent); + $zipContent[$tmpRootPath . $aPath] = $aContent; } //the rels for files - $this->addZipFile($tmpRootPath . '_rels/' . basename($tmpRibbonTarget) . '.rels', $this->getWriterPart('RelsRibbonObjects')->writeRibbonRelationships($this->spreadSheet)); + $zipContent[$tmpRootPath . '_rels/' . basename($tmpRibbonTarget) . '.rels'] = $this->getWriterPartRelsRibbon()->writeRibbonRelationships($this->spreadSheet); } } // Add relationships to ZIP file - $this->addZipFile('_rels/.rels', $this->getWriterPart('Rels')->writeRelationships($this->spreadSheet)); - $this->addZipFile('xl/_rels/workbook.xml.rels', $this->getWriterPart('Rels')->writeWorkbookRelationships($this->spreadSheet)); + $zipContent['_rels/.rels'] = $this->getWriterPartRels()->writeRelationships($this->spreadSheet); + $zipContent['xl/_rels/workbook.xml.rels'] = $this->getWriterPartRels()->writeWorkbookRelationships($this->spreadSheet); // Add document properties to ZIP file - $this->addZipFile('docProps/app.xml', $this->getWriterPart('DocProps')->writeDocPropsApp($this->spreadSheet)); - $this->addZipFile('docProps/core.xml', $this->getWriterPart('DocProps')->writeDocPropsCore($this->spreadSheet)); - $customPropertiesPart = $this->getWriterPart('DocProps')->writeDocPropsCustom($this->spreadSheet); + $zipContent['docProps/app.xml'] = $this->getWriterPartDocProps()->writeDocPropsApp($this->spreadSheet); + $zipContent['docProps/core.xml'] = $this->getWriterPartDocProps()->writeDocPropsCore($this->spreadSheet); + $customPropertiesPart = $this->getWriterPartDocProps()->writeDocPropsCustom($this->spreadSheet); if ($customPropertiesPart !== null) { - $this->addZipFile('docProps/custom.xml', $customPropertiesPart); + $zipContent['docProps/custom.xml'] = $customPropertiesPart; } // Add theme to ZIP file - $this->addZipFile('xl/theme/theme1.xml', $this->getWriterPart('Theme')->writeTheme($this->spreadSheet)); + $zipContent['xl/theme/theme1.xml'] = $this->getWriterPartTheme()->writeTheme($this->spreadSheet); // Add string table to ZIP file - $this->addZipFile('xl/sharedStrings.xml', $this->getWriterPart('StringTable')->writeStringTable($this->stringTable)); + $zipContent['xl/sharedStrings.xml'] = $this->getWriterPartStringTable()->writeStringTable($this->stringTable); // Add styles to ZIP file - $this->addZipFile('xl/styles.xml', $this->getWriterPart('Style')->writeStyles($this->spreadSheet)); + $zipContent['xl/styles.xml'] = $this->getWriterPartStyle()->writeStyles($this->spreadSheet); // Add workbook to ZIP file - $this->addZipFile('xl/workbook.xml', $this->getWriterPart('Workbook')->writeWorkbook($this->spreadSheet, $this->preCalculateFormulas)); + $zipContent['xl/workbook.xml'] = $this->getWriterPartWorkbook()->writeWorkbook($this->spreadSheet, $this->preCalculateFormulas); $chartCount = 0; // Add worksheets for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { - $this->addZipFile('xl/worksheets/sheet' . ($i + 1) . '.xml', $this->getWriterPart('Worksheet')->writeWorksheet($this->spreadSheet->getSheet($i), $this->stringTable, $this->includeCharts)); + $zipContent['xl/worksheets/sheet' . ($i + 1) . '.xml'] = $this->getWriterPartWorksheet()->writeWorksheet($this->spreadSheet->getSheet($i), $this->stringTable, $this->includeCharts); if ($this->includeCharts) { $charts = $this->spreadSheet->getSheet($i)->getChartCollection(); if (count($charts) > 0) { foreach ($charts as $chart) { - $this->addZipFile('xl/charts/chart' . ($chartCount + 1) . '.xml', $this->getWriterPart('Chart')->writeChart($chart, $this->preCalculateFormulas)); + $zipContent['xl/charts/chart' . ($chartCount + 1) . '.xml'] = $this->getWriterPartChart()->writeChart($chart, $this->preCalculateFormulas); ++$chartCount; } } @@ -287,19 +392,19 @@ class Xlsx extends BaseWriter // Add worksheet relationships (drawings, ...) for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { // Add relationships - $this->addZipFile('xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeWorksheetRelationships($this->spreadSheet->getSheet($i), ($i + 1), $this->includeCharts)); + $zipContent['xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels'] = $this->getWriterPartRels()->writeWorksheetRelationships($this->spreadSheet->getSheet($i), ($i + 1), $this->includeCharts); // Add unparsedLoadedData $sheetCodeName = $this->spreadSheet->getSheet($i)->getCodeName(); $unparsedLoadedData = $this->spreadSheet->getUnparsedLoadedData(); if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'])) { foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'] as $ctrlProp) { - $this->addZipFile($ctrlProp['filePath'], $ctrlProp['content']); + $zipContent[$ctrlProp['filePath']] = $ctrlProp['content']; } } if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'])) { foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'] as $ctrlProp) { - $this->addZipFile($ctrlProp['filePath'], $ctrlProp['content']); + $zipContent[$ctrlProp['filePath']] = $ctrlProp['content']; } } @@ -312,13 +417,13 @@ class Xlsx extends BaseWriter // Add drawing and image relationship parts if (($drawingCount > 0) || ($chartCount > 0)) { // Drawing relationships - $this->addZipFile('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->spreadSheet->getSheet($i), $chartRef1, $this->includeCharts)); + $zipContent['xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels'] = $this->getWriterPartRels()->writeDrawingRelationships($this->spreadSheet->getSheet($i), $chartRef1, $this->includeCharts); // Drawings - $this->addZipFile('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts)); + $zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = $this->getWriterPartDrawing()->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts); } elseif (isset($unparsedLoadedData['sheets'][$sheetCodeName]['drawingAlternateContents'])) { // Drawings - $this->addZipFile('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts)); + $zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = $this->getWriterPartDrawing()->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts); } // Add unparsed drawings @@ -327,7 +432,7 @@ class Xlsx extends BaseWriter $drawingFile = array_search($relId, $unparsedLoadedData['sheets'][$sheetCodeName]['drawingOriginalIds']); if ($drawingFile !== false) { $drawingFile = ltrim($drawingFile, '.'); - $this->addZipFile('xl' . $drawingFile, $drawingXml); + $zipContent['xl' . $drawingFile] = $drawingXml; } } } @@ -335,30 +440,30 @@ class Xlsx extends BaseWriter // Add comment relationship parts if (count($this->spreadSheet->getSheet($i)->getComments()) > 0) { // VML Comments - $this->addZipFile('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->spreadSheet->getSheet($i))); + $zipContent['xl/drawings/vmlDrawing' . ($i + 1) . '.vml'] = $this->getWriterPartComments()->writeVMLComments($this->spreadSheet->getSheet($i)); // Comments - $this->addZipFile('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->spreadSheet->getSheet($i))); + $zipContent['xl/comments' . ($i + 1) . '.xml'] = $this->getWriterPartComments()->writeComments($this->spreadSheet->getSheet($i)); } // Add unparsed relationship parts if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['vmlDrawings'])) { foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['vmlDrawings'] as $vmlDrawing) { - $this->addZipFile($vmlDrawing['filePath'], $vmlDrawing['content']); + $zipContent[$vmlDrawing['filePath']] = $vmlDrawing['content']; } } // Add header/footer relationship parts if (count($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) { // VML Drawings - $this->addZipFile('xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml', $this->getWriterPart('Drawing')->writeVMLHeaderFooterImages($this->spreadSheet->getSheet($i))); + $zipContent['xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml'] = $this->getWriterPartDrawing()->writeVMLHeaderFooterImages($this->spreadSheet->getSheet($i)); // VML Drawing relationships - $this->addZipFile('xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels', $this->getWriterPart('Rels')->writeHeaderFooterDrawingRelationships($this->spreadSheet->getSheet($i))); + $zipContent['xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels'] = $this->getWriterPartRels()->writeHeaderFooterDrawingRelationships($this->spreadSheet->getSheet($i)); // Media foreach ($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) { - $this->addZipFile('xl/media/' . $image->getIndexedFilename(), file_get_contents($image->getPath())); + $zipContent['xl/media/' . $image->getIndexedFilename()] = file_get_contents($image->getPath()); } } } @@ -381,7 +486,7 @@ class Xlsx extends BaseWriter $imageContents = file_get_contents($imagePath); } - $this->addZipFile('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents); + $zipContent['xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename())] = $imageContents; } elseif ($this->getDrawingHashTable()->getByIndex($i) instanceof MemoryDrawing) { ob_start(); call_user_func( @@ -391,13 +496,23 @@ class Xlsx extends BaseWriter $imageContents = ob_get_contents(); ob_end_clean(); - $this->addZipFile('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents); + $zipContent['xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename())] = $imageContents; } } Functions::setReturnDateType($saveDateReturnType); Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); + $this->openFileHandle($filename); + + $options = new Archive(); + $options->setEnableZip64(false); + $options->setOutputStream($this->fileHandle); + + $this->zip = new ZipStream(null, $options); + + $this->addZipFiles($zipContent); + // Close file try { $this->zip->finish(); @@ -445,7 +560,7 @@ class Xlsx extends BaseWriter /** * Get Style HashTable. * - * @return HashTable + * @return HashTable<\PhpOffice\PhpSpreadsheet\Style\Style> */ public function getStyleHashTable() { @@ -455,7 +570,7 @@ class Xlsx extends BaseWriter /** * Get Conditional HashTable. * - * @return HashTable + * @return HashTable */ public function getStylesConditionalHashTable() { @@ -465,7 +580,7 @@ class Xlsx extends BaseWriter /** * Get Fill HashTable. * - * @return HashTable + * @return HashTable */ public function getFillHashTable() { @@ -475,7 +590,7 @@ class Xlsx extends BaseWriter /** * Get \PhpOffice\PhpSpreadsheet\Style\Font HashTable. * - * @return HashTable + * @return HashTable */ public function getFontHashTable() { @@ -485,7 +600,7 @@ class Xlsx extends BaseWriter /** * Get Borders HashTable. * - * @return HashTable + * @return HashTable */ public function getBordersHashTable() { @@ -495,7 +610,7 @@ class Xlsx extends BaseWriter /** * Get NumberFormat HashTable. * - * @return HashTable + * @return HashTable */ public function getNumFmtHashTable() { @@ -505,7 +620,7 @@ class Xlsx extends BaseWriter /** * Get \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\BaseDrawing HashTable. * - * @return HashTable + * @return HashTable */ public function getDrawingHashTable() { @@ -545,4 +660,11 @@ class Xlsx extends BaseWriter $this->zip->addFile($path, $content); } } + + private function addZipFiles(array $zipContent): void + { + foreach ($zipContent as $path => $content) { + $this->addZipFile($path, $content); + } + } } diff --git a/src/PhpSpreadsheet/Writer/Xlsx/Chart.php b/src/PhpSpreadsheet/Writer/Xlsx/Chart.php index 583b262c..e65f6e34 100644 --- a/src/PhpSpreadsheet/Writer/Xlsx/Chart.php +++ b/src/PhpSpreadsheet/Writer/Xlsx/Chart.php @@ -129,7 +129,7 @@ class Chart extends WriterPart if ((is_array($caption)) && (count($caption) > 0)) { $caption = $caption[0]; } - $this->getParentWriter()->getWriterPart('stringtable')->writeRichTextForCharts($objWriter, $caption, 'a'); + $this->getParentWriter()->getWriterPartstringtable()->writeRichTextForCharts($objWriter, $caption, 'a'); $objWriter->endElement(); $objWriter->endElement(); @@ -202,7 +202,7 @@ class Chart extends WriterPart * @param Axis $xAxis * @param Axis $yAxis */ - private function writePlotArea(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pSheet, PlotArea $plotArea, ?Title $xAxisLabel = null, ?Title $yAxisLabel = null, ?Axis $xAxis = null, ?Axis $yAxis = null, ?GridLines $majorGridlines = null, ?GridLines $minorGridlines = null): void + private function writePlotArea(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet, PlotArea $plotArea, ?Title $xAxisLabel = null, ?Title $yAxisLabel = null, ?Axis $xAxis = null, ?Axis $yAxis = null, ?GridLines $majorGridlines = null, ?GridLines $minorGridlines = null): void { if ($plotArea === null) { return; @@ -219,10 +219,12 @@ class Chart extends WriterPart $chartTypes = self::getChartType($plotArea); $catIsMultiLevelSeries = $valIsMultiLevelSeries = false; $plotGroupingType = ''; + $chartType = null; foreach ($chartTypes as $chartType) { $objWriter->startElement('c:' . $chartType); $groupCount = $plotArea->getPlotGroupCount(); + $plotGroup = null; for ($i = 0; $i < $groupCount; ++$i) { $plotGroup = $plotArea->getPlotGroupByIndex($i); $groupType = $plotGroup->getPlotType(); @@ -244,7 +246,7 @@ class Chart extends WriterPart $this->writeDataLabels($objWriter, $layout); - if ($chartType === DataSeries::TYPE_LINECHART) { + if ($chartType === DataSeries::TYPE_LINECHART && $plotGroup) { // Line only, Line3D can't be smoothed $objWriter->startElement('c:smooth'); $objWriter->writeAttribute('val', (int) $plotGroup->getSmoothLine()); @@ -316,10 +318,10 @@ class Chart extends WriterPart if ($chartType === DataSeries::TYPE_BUBBLECHART) { $this->writeValueAxis($objWriter, $xAxisLabel, $chartType, $id1, $id2, $catIsMultiLevelSeries, $xAxis, $majorGridlines, $minorGridlines); } else { - $this->writeCategoryAxis($objWriter, $xAxisLabel, $id1, $id2, $catIsMultiLevelSeries, $yAxis); + $this->writeCategoryAxis($objWriter, $xAxisLabel, $id1, $id2, $catIsMultiLevelSeries, $xAxis); } - $this->writeValueAxis($objWriter, $yAxisLabel, $chartType, $id1, $id2, $valIsMultiLevelSeries, $xAxis, $majorGridlines, $minorGridlines); + $this->writeValueAxis($objWriter, $yAxisLabel, $chartType, $id1, $id2, $valIsMultiLevelSeries, $yAxis, $majorGridlines, $minorGridlines); } $objWriter->endElement(); @@ -1038,9 +1040,9 @@ class Chart extends WriterPart * @param DataSeries $plotGroup * @param string $groupType Type of plot for dataseries * @param XMLWriter $objWriter XML Writer - * @param bool &$catIsMultiLevelSeries Is category a multi-series category - * @param bool &$valIsMultiLevelSeries Is value set a multi-series set - * @param string &$plotGroupingType Type of grouping for multi-series values + * @param bool $catIsMultiLevelSeries Is category a multi-series category + * @param bool $valIsMultiLevelSeries Is value set a multi-series set + * @param string $plotGroupingType Type of grouping for multi-series values */ private function writePlotGroup($plotGroup, $groupType, $objWriter, &$catIsMultiLevelSeries, &$valIsMultiLevelSeries, &$plotGroupingType): void { @@ -1079,6 +1081,7 @@ class Chart extends WriterPart } } + $plotSeriesIdx = 0; foreach ($plotSeriesOrder as $plotSeriesIdx => $plotSeriesRef) { $objWriter->startElement('c:ser'); diff --git a/src/PhpSpreadsheet/Writer/Xlsx/Comments.php b/src/PhpSpreadsheet/Writer/Xlsx/Comments.php index 73c4308b..51f4248c 100644 --- a/src/PhpSpreadsheet/Writer/Xlsx/Comments.php +++ b/src/PhpSpreadsheet/Writer/Xlsx/Comments.php @@ -79,7 +79,7 @@ class Comments extends WriterPart // text $objWriter->startElement('text'); - $this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $pComment->getText()); + $this->getParentWriter()->getWriterPartstringtable()->writeRichText($objWriter, $pComment->getText()); $objWriter->endElement(); $objWriter->endElement(); @@ -165,8 +165,7 @@ class Comments extends WriterPart private function writeVMLComment(XMLWriter $objWriter, $pCellReference, Comment $pComment): void { // Metadata - [$column, $row] = Coordinate::coordinateFromString($pCellReference); - $column = Coordinate::columnIndexFromString($column); + [$column, $row] = Coordinate::indexesFromString($pCellReference); $id = 1024 + $column + $row; $id = substr($id, 0, 4); diff --git a/src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php b/src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php index 8c3da827..1fef0901 100644 --- a/src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php +++ b/src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php @@ -2,6 +2,7 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; +use Exception; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\DefinedName; @@ -11,8 +12,10 @@ use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class DefinedNames { + /** @var XMLWriter */ private $objWriter; + /** @var Spreadsheet */ private $spreadsheet; public function __construct(XMLWriter $objWriter, Spreadsheet $spreadsheet) @@ -66,12 +69,128 @@ class DefinedNames private function writeDefinedName(DefinedName $pDefinedName): void { // definedName for named range + $local = -1; + if ($pDefinedName->getLocalOnly() && $pDefinedName->getScope() !== null) { + try { + $local = $pDefinedName->getScope()->getParent()->getIndex($pDefinedName->getScope()); + } catch (Exception $e) { + // See issue 2266 - deleting sheet which contains + // defined names will cause Exception above. + return; + } + } $this->objWriter->startElement('definedName'); $this->objWriter->writeAttribute('name', $pDefinedName->getName()); - if ($pDefinedName->getLocalOnly() && $pDefinedName->getScope() !== null) { - $this->objWriter->writeAttribute('localSheetId', $pDefinedName->getScope()->getParent()->getIndex($pDefinedName->getScope())); + if ($local >= 0) { + $this->objWriter->writeAttribute( + 'localSheetId', + "$local" + ); } + $definedRange = $this->getDefinedRange($pDefinedName); + + $this->objWriter->writeRawData($definedRange); + + $this->objWriter->endElement(); + } + + /** + * Write Defined Name for autoFilter. + */ + private function writeNamedRangeForAutofilter(Worksheet $worksheet, int $worksheetId = 0): void + { + // NamedRange for autoFilter + $autoFilterRange = $worksheet->getAutoFilter()->getRange(); + if (!empty($autoFilterRange)) { + $this->objWriter->startElement('definedName'); + $this->objWriter->writeAttribute('name', '_xlnm._FilterDatabase'); + $this->objWriter->writeAttribute('localSheetId', "$worksheetId"); + $this->objWriter->writeAttribute('hidden', '1'); + + // Create absolute coordinate and write as raw text + $range = Coordinate::splitRange($autoFilterRange); + $range = $range[0]; + // Strip any worksheet ref so we can make the cell ref absolute + [, $range[0]] = Worksheet::extractSheetTitle($range[0], true); + + $range[0] = Coordinate::absoluteCoordinate($range[0]); + $range[1] = Coordinate::absoluteCoordinate($range[1]); + $range = implode(':', $range); + + $this->objWriter->writeRawData('\'' . str_replace("'", "''", $worksheet->getTitle() ?? '') . '\'!' . $range); + + $this->objWriter->endElement(); + } + } + + /** + * Write Defined Name for PrintTitles. + */ + private function writeNamedRangeForPrintTitles(Worksheet $worksheet, int $worksheetId = 0): void + { + // NamedRange for PrintTitles + if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet() || $worksheet->getPageSetup()->isRowsToRepeatAtTopSet()) { + $this->objWriter->startElement('definedName'); + $this->objWriter->writeAttribute('name', '_xlnm.Print_Titles'); + $this->objWriter->writeAttribute('localSheetId', "$worksheetId"); + + // Setting string + $settingString = ''; + + // Columns to repeat + if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { + $repeat = $worksheet->getPageSetup()->getColumnsToRepeatAtLeft(); + + $settingString .= '\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1]; + } + + // Rows to repeat + if ($worksheet->getPageSetup()->isRowsToRepeatAtTopSet()) { + if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { + $settingString .= ','; + } + + $repeat = $worksheet->getPageSetup()->getRowsToRepeatAtTop(); + + $settingString .= '\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1]; + } + + $this->objWriter->writeRawData($settingString); + + $this->objWriter->endElement(); + } + } + + /** + * Write Defined Name for PrintTitles. + */ + private function writeNamedRangeForPrintArea(Worksheet $worksheet, int $worksheetId = 0): void + { + // NamedRange for PrintArea + if ($worksheet->getPageSetup()->isPrintAreaSet()) { + $this->objWriter->startElement('definedName'); + $this->objWriter->writeAttribute('name', '_xlnm.Print_Area'); + $this->objWriter->writeAttribute('localSheetId', "$worksheetId"); + + // Print area + $printArea = Coordinate::splitRange($worksheet->getPageSetup()->getPrintArea()); + + $chunks = []; + foreach ($printArea as $printAreaRect) { + $printAreaRect[0] = Coordinate::absoluteReference($printAreaRect[0]); + $printAreaRect[1] = Coordinate::absoluteReference($printAreaRect[1]); + $chunks[] = '\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!' . implode(':', $printAreaRect); + } + + $this->objWriter->writeRawData(implode(',', $chunks)); + + $this->objWriter->endElement(); + } + } + + private function getDefinedRange(DefinedName $pDefinedName): string + { $definedRange = $pDefinedName->getValue(); $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui', @@ -99,21 +218,17 @@ class DefinedNames if (empty($worksheet)) { if (($offset === 0) || ($definedRange[$offset - 1] !== ':')) { // We should have a worksheet - $worksheet = $pDefinedName->getWorksheet()->getTitle(); + $ws = $pDefinedName->getWorksheet(); + $worksheet = ($ws === null) ? null : $ws->getTitle(); } } else { $worksheet = str_replace("''", "'", trim($worksheet, "'")); } + if (!empty($worksheet)) { $newRange = "'" . str_replace("'", "''", $worksheet) . "'!"; } - - if (!empty($column)) { - $newRange .= $column; - } - if (!empty($row)) { - $newRange .= $row; - } + $newRange = "{$newRange}{$column}{$row}"; $definedRange = substr($definedRange, 0, $offset) . $newRange . substr($definedRange, $offset + $length); } @@ -122,102 +237,6 @@ class DefinedNames $definedRange = substr($definedRange, 1); } - $this->objWriter->writeRawData($definedRange); - - $this->objWriter->endElement(); - } - - /** - * Write Defined Name for autoFilter. - */ - private function writeNamedRangeForAutofilter(Worksheet $pSheet, int $pSheetId = 0): void - { - // NamedRange for autoFilter - $autoFilterRange = $pSheet->getAutoFilter()->getRange(); - if (!empty($autoFilterRange)) { - $this->objWriter->startElement('definedName'); - $this->objWriter->writeAttribute('name', '_xlnm._FilterDatabase'); - $this->objWriter->writeAttribute('localSheetId', $pSheetId); - $this->objWriter->writeAttribute('hidden', '1'); - - // Create absolute coordinate and write as raw text - $range = Coordinate::splitRange($autoFilterRange); - $range = $range[0]; - // Strip any worksheet ref so we can make the cell ref absolute - [$ws, $range[0]] = Worksheet::extractSheetTitle($range[0], true); - - $range[0] = Coordinate::absoluteCoordinate($range[0]); - $range[1] = Coordinate::absoluteCoordinate($range[1]); - $range = implode(':', $range); - - $this->objWriter->writeRawData('\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . $range); - - $this->objWriter->endElement(); - } - } - - /** - * Write Defined Name for PrintTitles. - */ - private function writeNamedRangeForPrintTitles(Worksheet $pSheet, int $pSheetId = 0): void - { - // NamedRange for PrintTitles - if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet() || $pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) { - $this->objWriter->startElement('definedName'); - $this->objWriter->writeAttribute('name', '_xlnm.Print_Titles'); - $this->objWriter->writeAttribute('localSheetId', $pSheetId); - - // Setting string - $settingString = ''; - - // Columns to repeat - if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { - $repeat = $pSheet->getPageSetup()->getColumnsToRepeatAtLeft(); - - $settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1]; - } - - // Rows to repeat - if ($pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) { - if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { - $settingString .= ','; - } - - $repeat = $pSheet->getPageSetup()->getRowsToRepeatAtTop(); - - $settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1]; - } - - $this->objWriter->writeRawData($settingString); - - $this->objWriter->endElement(); - } - } - - /** - * Write Defined Name for PrintTitles. - */ - private function writeNamedRangeForPrintArea(Worksheet $pSheet, int $pSheetId = 0): void - { - // NamedRange for PrintArea - if ($pSheet->getPageSetup()->isPrintAreaSet()) { - $this->objWriter->startElement('definedName'); - $this->objWriter->writeAttribute('name', '_xlnm.Print_Area'); - $this->objWriter->writeAttribute('localSheetId', $pSheetId); - - // Print area - $printArea = Coordinate::splitRange($pSheet->getPageSetup()->getPrintArea()); - - $chunks = []; - foreach ($printArea as $printAreaRect) { - $printAreaRect[0] = Coordinate::absoluteReference($printAreaRect[0]); - $printAreaRect[1] = Coordinate::absoluteReference($printAreaRect[1]); - $chunks[] = '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . implode(':', $printAreaRect); - } - - $this->objWriter->writeRawData(implode(',', $chunks)); - - $this->objWriter->endElement(); - } + return $definedRange; } } diff --git a/src/PhpSpreadsheet/Writer/Xlsx/DocProps.php b/src/PhpSpreadsheet/Writer/Xlsx/DocProps.php index bcbc2379..43ce442f 100644 --- a/src/PhpSpreadsheet/Writer/Xlsx/DocProps.php +++ b/src/PhpSpreadsheet/Writer/Xlsx/DocProps.php @@ -2,6 +2,8 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; +use PhpOffice\PhpSpreadsheet\Document\Properties; +use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; @@ -137,13 +139,17 @@ class DocProps extends WriterPart // dcterms:created $objWriter->startElement('dcterms:created'); $objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF'); - $objWriter->writeRawData(date(DATE_W3C, $spreadsheet->getProperties()->getCreated())); + $created = $spreadsheet->getProperties()->getCreated(); + $date = Date::dateTimeFromTimestamp("$created"); + $objWriter->writeRawData($date->format(DATE_W3C)); $objWriter->endElement(); // dcterms:modified $objWriter->startElement('dcterms:modified'); $objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF'); - $objWriter->writeRawData(date(DATE_W3C, $spreadsheet->getProperties()->getModified())); + $created = $spreadsheet->getProperties()->getModified(); + $date = Date::dateTimeFromTimestamp("$created"); + $objWriter->writeRawData($date->format(DATE_W3C)); $objWriter->endElement(); // dc:title @@ -170,13 +176,13 @@ class DocProps extends WriterPart /** * Write docProps/custom.xml to XML format. * - * @return string XML Output + * @return null|string XML Output */ public function writeDocPropsCustom(Spreadsheet $spreadsheet) { $customPropertyList = $spreadsheet->getProperties()->getCustomProperties(); if (empty($customPropertyList)) { - return; + return null; } // Create XML writer @@ -205,21 +211,22 @@ class DocProps extends WriterPart $objWriter->writeAttribute('name', $customProperty); switch ($propertyType) { - case 'i': + case Properties::PROPERTY_TYPE_INTEGER: $objWriter->writeElement('vt:i4', $propertyValue); break; - case 'f': + case Properties::PROPERTY_TYPE_FLOAT: $objWriter->writeElement('vt:r8', $propertyValue); break; - case 'b': + case Properties::PROPERTY_TYPE_BOOLEAN: $objWriter->writeElement('vt:bool', ($propertyValue) ? 'true' : 'false'); break; - case 'd': + case Properties::PROPERTY_TYPE_DATE: $objWriter->startElement('vt:filetime'); - $objWriter->writeRawData(date(DATE_W3C, $propertyValue)); + $date = Date::dateTimeFromTimestamp("$propertyValue"); + $objWriter->writeRawData($date->format(DATE_W3C)); $objWriter->endElement(); break; diff --git a/src/PhpSpreadsheet/Writer/Xlsx/Drawing.php b/src/PhpSpreadsheet/Writer/Xlsx/Drawing.php index 1713b982..a4b09d39 100644 --- a/src/PhpSpreadsheet/Writer/Xlsx/Drawing.php +++ b/src/PhpSpreadsheet/Writer/Xlsx/Drawing.php @@ -84,22 +84,22 @@ class Drawing extends WriterPart public function writeChart(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Chart\Chart $pChart, $pRelationId = -1): void { $tl = $pChart->getTopLeftPosition(); - $tl['colRow'] = Coordinate::coordinateFromString($tl['cell']); + $tlColRow = Coordinate::indexesFromString($tl['cell']); $br = $pChart->getBottomRightPosition(); - $br['colRow'] = Coordinate::coordinateFromString($br['cell']); + $brColRow = Coordinate::indexesFromString($br['cell']); $objWriter->startElement('xdr:twoCellAnchor'); $objWriter->startElement('xdr:from'); - $objWriter->writeElement('xdr:col', Coordinate::columnIndexFromString($tl['colRow'][0]) - 1); + $objWriter->writeElement('xdr:col', $tlColRow[0] - 1); $objWriter->writeElement('xdr:colOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($tl['xOffset'])); - $objWriter->writeElement('xdr:row', $tl['colRow'][1] - 1); + $objWriter->writeElement('xdr:row', $tlColRow[1] - 1); $objWriter->writeElement('xdr:rowOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($tl['yOffset'])); $objWriter->endElement(); $objWriter->startElement('xdr:to'); - $objWriter->writeElement('xdr:col', Coordinate::columnIndexFromString($br['colRow'][0]) - 1); + $objWriter->writeElement('xdr:col', $brColRow[0] - 1); $objWriter->writeElement('xdr:colOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($br['xOffset'])); - $objWriter->writeElement('xdr:row', $br['colRow'][1] - 1); + $objWriter->writeElement('xdr:row', $brColRow[1] - 1); $objWriter->writeElement('xdr:rowOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($br['yOffset'])); $objWriter->endElement(); @@ -158,8 +158,7 @@ class Drawing extends WriterPart // xdr:oneCellAnchor $objWriter->startElement('xdr:oneCellAnchor'); // Image location - $aCoordinates = Coordinate::coordinateFromString($pDrawing->getCoordinates()); - $aCoordinates[0] = Coordinate::columnIndexFromString($aCoordinates[0]); + $aCoordinates = Coordinate::indexesFromString($pDrawing->getCoordinates()); // xdr:from $objWriter->startElement('xdr:from'); @@ -433,7 +432,7 @@ class Drawing extends WriterPart { // Calculate object id preg_match('{(\d+)}', md5($pReference), $m); - $id = 1500 + (substr($m[1], 0, 2) * 1); + $id = 1500 + ((int) substr($m[1], 0, 2) * 1); // Calculate offset $width = $pImage->getWidth(); diff --git a/src/PhpSpreadsheet/Writer/Xlsx/Rels.php b/src/PhpSpreadsheet/Writer/Xlsx/Rels.php index 79841404..a67d3ef8 100644 --- a/src/PhpSpreadsheet/Writer/Xlsx/Rels.php +++ b/src/PhpSpreadsheet/Writer/Xlsx/Rels.php @@ -291,7 +291,7 @@ class Rels extends WriterPart /** * Write drawing relationships to XML format. * - * @param int &$chartRef Chart ID + * @param int $chartRef Chart ID * @param bool $includeCharts Flag indicating if we should write charts * * @return string XML Output @@ -425,9 +425,7 @@ class Rels extends WriterPart } /** - * @param $objWriter * @param \PhpOffice\PhpSpreadsheet\Worksheet\Drawing $drawing - * @param $i * * @return int */ diff --git a/src/PhpSpreadsheet/Writer/Xlsx/StringTable.php b/src/PhpSpreadsheet/Writer/Xlsx/StringTable.php index b0f7d6d4..755e04d3 100644 --- a/src/PhpSpreadsheet/Writer/Xlsx/StringTable.php +++ b/src/PhpSpreadsheet/Writer/Xlsx/StringTable.php @@ -14,12 +14,12 @@ class StringTable extends WriterPart /** * Create worksheet stringtable. * - * @param Worksheet $pSheet Worksheet - * @param string[] $pExistingTable Existing table to eventually merge with + * @param Worksheet $worksheet Worksheet + * @param string[] $existingTable Existing table to eventually merge with * * @return string[] String table for worksheet */ - public function createStringTable(Worksheet $pSheet, $pExistingTable = null) + public function createStringTable(Worksheet $worksheet, $existingTable = null) { // Create string lookup table $aStringTable = []; @@ -27,23 +27,23 @@ class StringTable extends WriterPart $aFlippedStringTable = null; // For faster lookup // Is an existing table given? - if (($pExistingTable !== null) && is_array($pExistingTable)) { - $aStringTable = $pExistingTable; + if (($existingTable !== null) && is_array($existingTable)) { + $aStringTable = $existingTable; } // Fill index array $aFlippedStringTable = $this->flipStringTable($aStringTable); // Loop through cells - foreach ($pSheet->getCoordinates() as $coordinate) { - $cell = $pSheet->getCell($coordinate); + foreach ($worksheet->getCoordinates() as $coordinate) { + $cell = $worksheet->getCell($coordinate); $cellValue = $cell->getValue(); if ( !is_object($cellValue) && ($cellValue !== null) && $cellValue !== '' && - !isset($aFlippedStringTable[$cellValue]) && - ($cell->getDataType() == DataType::TYPE_STRING || $cell->getDataType() == DataType::TYPE_STRING2 || $cell->getDataType() == DataType::TYPE_NULL) + ($cell->getDataType() == DataType::TYPE_STRING || $cell->getDataType() == DataType::TYPE_STRING2 || $cell->getDataType() == DataType::TYPE_NULL) && + !isset($aFlippedStringTable[$cellValue]) ) { $aStringTable[] = $cellValue; $aFlippedStringTable[$cellValue] = true; diff --git a/src/PhpSpreadsheet/Writer/Xlsx/Theme.php b/src/PhpSpreadsheet/Writer/Xlsx/Theme.php index 3a47be7f..99177292 100644 --- a/src/PhpSpreadsheet/Writer/Xlsx/Theme.php +++ b/src/PhpSpreadsheet/Writer/Xlsx/Theme.php @@ -10,7 +10,7 @@ class Theme extends WriterPart /** * Map of Major fonts to write. * - * @var array of string + * @var string[] */ private static $majorFonts = [ 'Jpan' => 'MS Pゴシック', @@ -48,7 +48,7 @@ class Theme extends WriterPart /** * Map of Minor fonts to write. * - * @var array of string + * @var string[] */ private static $minorFonts = [ 'Jpan' => 'MS Pゴシック', @@ -86,7 +86,7 @@ class Theme extends WriterPart /** * Map of core colours. * - * @var array of string + * @var string[] */ private static $colourScheme = [ 'dk2' => '1F497D', @@ -784,13 +784,9 @@ class Theme extends WriterPart /** * Write fonts to XML format. * - * @param XMLWriter $objWriter - * @param string $latinFont - * @param array of string $fontSet - * - * @return string XML Output + * @param string[] $fontSet */ - private function writeFonts($objWriter, $latinFont, $fontSet) + private function writeFonts(XMLWriter $objWriter, string $latinFont, array $fontSet): void { // a:latin $objWriter->startElement('a:latin'); @@ -817,12 +813,8 @@ class Theme extends WriterPart /** * Write colour scheme to XML format. - * - * @param XMLWriter $objWriter - * - * @return string XML Output */ - private function writeColourScheme($objWriter) + private function writeColourScheme(XMLWriter $objWriter): void { foreach (self::$colourScheme as $colourName => $colourValue) { $objWriter->startElement('a:' . $colourName); diff --git a/src/PhpSpreadsheet/Writer/Xlsx/Workbook.php b/src/PhpSpreadsheet/Writer/Xlsx/Workbook.php index 0a20ea9d..20ca1aa4 100644 --- a/src/PhpSpreadsheet/Writer/Xlsx/Workbook.php +++ b/src/PhpSpreadsheet/Writer/Xlsx/Workbook.php @@ -201,22 +201,22 @@ class Workbook extends WriterPart * Write sheet. * * @param XMLWriter $objWriter XML Writer - * @param string $pSheetname Sheet name - * @param int $pSheetId Sheet id - * @param int $pRelId Relationship ID + * @param string $worksheetName Sheet name + * @param int $worksheetId Sheet id + * @param int $relId Relationship ID * @param string $sheetState Sheet state (visible, hidden, veryHidden) */ - private function writeSheet(XMLWriter $objWriter, $pSheetname, $pSheetId = 1, $pRelId = 1, $sheetState = 'visible'): void + private function writeSheet(XMLWriter $objWriter, $worksheetName, $worksheetId = 1, $relId = 1, $sheetState = 'visible'): void { - if ($pSheetname != '') { + if ($worksheetName != '') { // Write sheet $objWriter->startElement('sheet'); - $objWriter->writeAttribute('name', $pSheetname); - $objWriter->writeAttribute('sheetId', $pSheetId); + $objWriter->writeAttribute('name', $worksheetName); + $objWriter->writeAttribute('sheetId', $worksheetId); if ($sheetState !== 'visible' && $sheetState != '') { $objWriter->writeAttribute('state', $sheetState); } - $objWriter->writeAttribute('r:id', 'rId' . $pRelId); + $objWriter->writeAttribute('r:id', 'rId' . $relId); $objWriter->endElement(); } else { throw new WriterException('Invalid parameters passed.'); diff --git a/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php b/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php index 8faa7ae2..72b13fc5 100644 --- a/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php +++ b/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php @@ -5,9 +5,12 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\RichText\RichText; +use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Style\Conditional; +use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalDataBar; +use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalFormattingRuleExtension; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule; use PhpOffice\PhpSpreadsheet\Worksheet\SheetView; @@ -23,7 +26,7 @@ class Worksheet extends WriterPart * * @return string XML Output */ - public function writeWorksheet(PhpspreadsheetWorksheet $pSheet, $pStringTable = null, $includeCharts = false) + public function writeWorksheet(PhpspreadsheetWorksheet $worksheet, $pStringTable = null, $includeCharts = false) { // Create XML writer $objWriter = null; @@ -44,75 +47,82 @@ class Worksheet extends WriterPart $objWriter->writeAttribute('xmlns:xdr', 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing'); $objWriter->writeAttribute('xmlns:x14', 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main'); + $objWriter->writeAttribute('xmlns:xm', 'http://schemas.microsoft.com/office/excel/2006/main'); $objWriter->writeAttribute('xmlns:mc', 'http://schemas.openxmlformats.org/markup-compatibility/2006'); $objWriter->writeAttribute('mc:Ignorable', 'x14ac'); $objWriter->writeAttribute('xmlns:x14ac', 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac'); // sheetPr - $this->writeSheetPr($objWriter, $pSheet); + $this->writeSheetPr($objWriter, $worksheet); // Dimension - $this->writeDimension($objWriter, $pSheet); + $this->writeDimension($objWriter, $worksheet); // sheetViews - $this->writeSheetViews($objWriter, $pSheet); + $this->writeSheetViews($objWriter, $worksheet); // sheetFormatPr - $this->writeSheetFormatPr($objWriter, $pSheet); + $this->writeSheetFormatPr($objWriter, $worksheet); // cols - $this->writeCols($objWriter, $pSheet); + $this->writeCols($objWriter, $worksheet); // sheetData - $this->writeSheetData($objWriter, $pSheet, $pStringTable); + $this->writeSheetData($objWriter, $worksheet, $pStringTable); // sheetProtection - $this->writeSheetProtection($objWriter, $pSheet); + $this->writeSheetProtection($objWriter, $worksheet); // protectedRanges - $this->writeProtectedRanges($objWriter, $pSheet); + $this->writeProtectedRanges($objWriter, $worksheet); // autoFilter - $this->writeAutoFilter($objWriter, $pSheet); + $this->writeAutoFilter($objWriter, $worksheet); // mergeCells - $this->writeMergeCells($objWriter, $pSheet); + $this->writeMergeCells($objWriter, $worksheet); // conditionalFormatting - $this->writeConditionalFormatting($objWriter, $pSheet); + $this->writeConditionalFormatting($objWriter, $worksheet); // dataValidations - $this->writeDataValidations($objWriter, $pSheet); + $this->writeDataValidations($objWriter, $worksheet); // hyperlinks - $this->writeHyperlinks($objWriter, $pSheet); + $this->writeHyperlinks($objWriter, $worksheet); // Print options - $this->writePrintOptions($objWriter, $pSheet); + $this->writePrintOptions($objWriter, $worksheet); // Page margins - $this->writePageMargins($objWriter, $pSheet); + $this->writePageMargins($objWriter, $worksheet); // Page setup - $this->writePageSetup($objWriter, $pSheet); + $this->writePageSetup($objWriter, $worksheet); // Header / footer - $this->writeHeaderFooter($objWriter, $pSheet); + $this->writeHeaderFooter($objWriter, $worksheet); // Breaks - $this->writeBreaks($objWriter, $pSheet); + $this->writeBreaks($objWriter, $worksheet); // Drawings and/or Charts - $this->writeDrawings($objWriter, $pSheet, $includeCharts); + $this->writeDrawings($objWriter, $worksheet, $includeCharts); // LegacyDrawing - $this->writeLegacyDrawing($objWriter, $pSheet); + $this->writeLegacyDrawing($objWriter, $worksheet); // LegacyDrawingHF - $this->writeLegacyDrawingHF($objWriter, $pSheet); + $this->writeLegacyDrawingHF($objWriter, $worksheet); // AlternateContent - $this->writeAlternateContent($objWriter, $pSheet); + $this->writeAlternateContent($objWriter, $worksheet); + + // ConditionalFormattingRuleExtensionList + // (Must be inserted last. Not insert last, an Excel parse error will occur) + $this->writeExtLst($objWriter, $worksheet); + // dataValidations + $this->writeDataValidations($objWriter, $worksheet); $objWriter->endElement(); @@ -124,40 +134,40 @@ class Worksheet extends WriterPart * Write SheetPr. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet + * @param PhpspreadsheetWorksheet $worksheet Worksheet */ - private function writeSheetPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void + private function writeSheetPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // sheetPr $objWriter->startElement('sheetPr'); - if ($pSheet->getParent()->hasMacros()) { + if ($worksheet->getParent()->hasMacros()) { //if the workbook have macros, we need to have codeName for the sheet - if (!$pSheet->hasCodeName()) { - $pSheet->setCodeName($pSheet->getTitle()); + if (!$worksheet->hasCodeName()) { + $worksheet->setCodeName($worksheet->getTitle()); } - $objWriter->writeAttribute('codeName', $pSheet->getCodeName()); + self::writeAttributeNotNull($objWriter, 'codeName', $worksheet->getCodeName()); } - $autoFilterRange = $pSheet->getAutoFilter()->getRange(); + $autoFilterRange = $worksheet->getAutoFilter()->getRange(); if (!empty($autoFilterRange)) { $objWriter->writeAttribute('filterMode', 1); - $pSheet->getAutoFilter()->showHideRows(); + $worksheet->getAutoFilter()->showHideRows(); } // tabColor - if ($pSheet->isTabColorSet()) { + if ($worksheet->isTabColorSet()) { $objWriter->startElement('tabColor'); - $objWriter->writeAttribute('rgb', $pSheet->getTabColor()->getARGB()); + $objWriter->writeAttribute('rgb', $worksheet->getTabColor()->getARGB()); $objWriter->endElement(); } // outlinePr $objWriter->startElement('outlinePr'); - $objWriter->writeAttribute('summaryBelow', ($pSheet->getShowSummaryBelow() ? '1' : '0')); - $objWriter->writeAttribute('summaryRight', ($pSheet->getShowSummaryRight() ? '1' : '0')); + $objWriter->writeAttribute('summaryBelow', ($worksheet->getShowSummaryBelow() ? '1' : '0')); + $objWriter->writeAttribute('summaryRight', ($worksheet->getShowSummaryRight() ? '1' : '0')); $objWriter->endElement(); // pageSetUpPr - if ($pSheet->getPageSetup()->getFitToPage()) { + if ($worksheet->getPageSetup()->getFitToPage()) { $objWriter->startElement('pageSetUpPr'); $objWriter->writeAttribute('fitToPage', '1'); $objWriter->endElement(); @@ -170,13 +180,12 @@ class Worksheet extends WriterPart * Write Dimension. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeDimension(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void + private function writeDimension(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // dimension $objWriter->startElement('dimension'); - $objWriter->writeAttribute('ref', $pSheet->calculateWorksheetDimension()); + $objWriter->writeAttribute('ref', $worksheet->calculateWorksheetDimension()); $objWriter->endElement(); } @@ -184,16 +193,15 @@ class Worksheet extends WriterPart * Write SheetViews. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeSheetViews(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void + private function writeSheetViews(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // sheetViews $objWriter->startElement('sheetViews'); // Sheet selected? $sheetSelected = false; - if ($this->getParentWriter()->getSpreadsheet()->getIndex($pSheet) == $this->getParentWriter()->getSpreadsheet()->getActiveSheetIndex()) { + if ($this->getParentWriter()->getSpreadsheet()->getIndex($worksheet) == $this->getParentWriter()->getSpreadsheet()->getActiveSheetIndex()) { $sheetSelected = true; } @@ -203,55 +211,54 @@ class Worksheet extends WriterPart $objWriter->writeAttribute('workbookViewId', '0'); // Zoom scales - if ($pSheet->getSheetView()->getZoomScale() != 100) { - $objWriter->writeAttribute('zoomScale', $pSheet->getSheetView()->getZoomScale()); + if ($worksheet->getSheetView()->getZoomScale() != 100) { + $objWriter->writeAttribute('zoomScale', $worksheet->getSheetView()->getZoomScale()); } - if ($pSheet->getSheetView()->getZoomScaleNormal() != 100) { - $objWriter->writeAttribute('zoomScaleNormal', $pSheet->getSheetView()->getZoomScaleNormal()); + if ($worksheet->getSheetView()->getZoomScaleNormal() != 100) { + $objWriter->writeAttribute('zoomScaleNormal', $worksheet->getSheetView()->getZoomScaleNormal()); } // Show zeros (Excel also writes this attribute only if set to false) - if ($pSheet->getSheetView()->getShowZeros() === false) { + if ($worksheet->getSheetView()->getShowZeros() === false) { $objWriter->writeAttribute('showZeros', 0); } // View Layout Type - if ($pSheet->getSheetView()->getView() !== SheetView::SHEETVIEW_NORMAL) { - $objWriter->writeAttribute('view', $pSheet->getSheetView()->getView()); + if ($worksheet->getSheetView()->getView() !== SheetView::SHEETVIEW_NORMAL) { + $objWriter->writeAttribute('view', $worksheet->getSheetView()->getView()); } // Gridlines - if ($pSheet->getShowGridlines()) { + if ($worksheet->getShowGridlines()) { $objWriter->writeAttribute('showGridLines', 'true'); } else { $objWriter->writeAttribute('showGridLines', 'false'); } // Row and column headers - if ($pSheet->getShowRowColHeaders()) { + if ($worksheet->getShowRowColHeaders()) { $objWriter->writeAttribute('showRowColHeaders', '1'); } else { $objWriter->writeAttribute('showRowColHeaders', '0'); } // Right-to-left - if ($pSheet->getRightToLeft()) { + if ($worksheet->getRightToLeft()) { $objWriter->writeAttribute('rightToLeft', 'true'); } - $activeCell = $pSheet->getActiveCell(); - $sqref = $pSheet->getSelectedCells(); + $topLeftCell = $worksheet->getTopLeftCell(); + $activeCell = $worksheet->getActiveCell(); + $sqref = $worksheet->getSelectedCells(); // Pane $pane = ''; - if ($pSheet->getFreezePane()) { - [$xSplit, $ySplit] = Coordinate::coordinateFromString($pSheet->getFreezePane()); + if ($worksheet->getFreezePane()) { + [$xSplit, $ySplit] = Coordinate::coordinateFromString($worksheet->getFreezePane() ?? ''); $xSplit = Coordinate::columnIndexFromString($xSplit); --$xSplit; --$ySplit; - $topLeftCell = $pSheet->getTopLeftCell(); - // pane $pane = 'topRight'; $objWriter->startElement('pane'); @@ -262,7 +269,7 @@ class Worksheet extends WriterPart $objWriter->writeAttribute('ySplit', $ySplit); $pane = ($xSplit > 0) ? 'bottomRight' : 'bottomLeft'; } - $objWriter->writeAttribute('topLeftCell', $topLeftCell); + self::writeAttributeNotNull($objWriter, 'topLeftCell', $topLeftCell); $objWriter->writeAttribute('activePane', $pane); $objWriter->writeAttribute('state', 'frozen'); $objWriter->endElement(); @@ -276,6 +283,8 @@ class Worksheet extends WriterPart $objWriter->writeAttribute('pane', 'bottomLeft'); $objWriter->endElement(); } + } else { + self::writeAttributeNotNull($objWriter, 'topLeftCell', $topLeftCell); } // Selection @@ -298,37 +307,36 @@ class Worksheet extends WriterPart * Write SheetFormatPr. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeSheetFormatPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void + private function writeSheetFormatPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // sheetFormatPr $objWriter->startElement('sheetFormatPr'); // Default row height - if ($pSheet->getDefaultRowDimension()->getRowHeight() >= 0) { + if ($worksheet->getDefaultRowDimension()->getRowHeight() >= 0) { $objWriter->writeAttribute('customHeight', 'true'); - $objWriter->writeAttribute('defaultRowHeight', StringHelper::formatNumber($pSheet->getDefaultRowDimension()->getRowHeight())); + $objWriter->writeAttribute('defaultRowHeight', StringHelper::formatNumber($worksheet->getDefaultRowDimension()->getRowHeight())); } else { $objWriter->writeAttribute('defaultRowHeight', '14.4'); } // Set Zero Height row if ( - (string) $pSheet->getDefaultRowDimension()->getZeroHeight() === '1' || - strtolower((string) $pSheet->getDefaultRowDimension()->getZeroHeight()) == 'true' + (string) $worksheet->getDefaultRowDimension()->getZeroHeight() === '1' || + strtolower((string) $worksheet->getDefaultRowDimension()->getZeroHeight()) == 'true' ) { $objWriter->writeAttribute('zeroHeight', '1'); } // Default column width - if ($pSheet->getDefaultColumnDimension()->getWidth() >= 0) { - $objWriter->writeAttribute('defaultColWidth', StringHelper::formatNumber($pSheet->getDefaultColumnDimension()->getWidth())); + if ($worksheet->getDefaultColumnDimension()->getWidth() >= 0) { + $objWriter->writeAttribute('defaultColWidth', StringHelper::formatNumber($worksheet->getDefaultColumnDimension()->getWidth())); } // Outline level - row $outlineLevelRow = 0; - foreach ($pSheet->getRowDimensions() as $dimension) { + foreach ($worksheet->getRowDimensions() as $dimension) { if ($dimension->getOutlineLevel() > $outlineLevelRow) { $outlineLevelRow = $dimension->getOutlineLevel(); } @@ -337,7 +345,7 @@ class Worksheet extends WriterPart // Outline level - column $outlineLevelCol = 0; - foreach ($pSheet->getColumnDimensions() as $dimension) { + foreach ($worksheet->getColumnDimensions() as $dimension) { if ($dimension->getOutlineLevel() > $outlineLevelCol) { $outlineLevelCol = $dimension->getOutlineLevel(); } @@ -351,18 +359,18 @@ class Worksheet extends WriterPart * Write Cols. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet + * @param PhpspreadsheetWorksheet $worksheet Worksheet */ - private function writeCols(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void + private function writeCols(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // cols - if (count($pSheet->getColumnDimensions()) > 0) { + if (count($worksheet->getColumnDimensions()) > 0) { $objWriter->startElement('cols'); - $pSheet->calculateColumnWidths(); + $worksheet->calculateColumnWidths(); // Loop through column dimensions - foreach ($pSheet->getColumnDimensions() as $colDimension) { + foreach ($worksheet->getColumnDimensions() as $colDimension) { // col $objWriter->startElement('col'); $objWriter->writeAttribute('min', Coordinate::columnIndexFromString($colDimension->getColumnIndex())); @@ -387,7 +395,7 @@ class Worksheet extends WriterPart } // Custom width? - if ($colDimension->getWidth() != $pSheet->getDefaultColumnDimension()->getWidth()) { + if ($colDimension->getWidth() != $worksheet->getDefaultColumnDimension()->getWidth()) { $objWriter->writeAttribute('customWidth', 'true'); } @@ -415,14 +423,13 @@ class Worksheet extends WriterPart * Write SheetProtection. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeSheetProtection(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void + private function writeSheetProtection(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // sheetProtection $objWriter->startElement('sheetProtection'); - $protection = $pSheet->getProtection(); + $protection = $worksheet->getProtection(); if ($protection->getAlgorithm()) { $objWriter->writeAttribute('algorithmName', $protection->getAlgorithm()); @@ -459,6 +466,13 @@ class Worksheet extends WriterPart } } + private static function writeAttributeNotNull(XMLWriter $objWriter, string $attr, ?string $val): void + { + if ($val !== null) { + $objWriter->writeAttribute($attr, $val); + } + } + private static function writeElementIf(XMLWriter $objWriter, $condition, string $attr, string $val): void { if ($condition) { @@ -503,19 +517,106 @@ class Worksheet extends WriterPart } } + private static function writeExtConditionalFormattingElements(XMLWriter $objWriter, ConditionalFormattingRuleExtension $ruleExtension): void + { + $prefix = 'x14'; + $objWriter->startElementNs($prefix, 'conditionalFormatting', null); + + $objWriter->startElementNs($prefix, 'cfRule', null); + $objWriter->writeAttribute('type', $ruleExtension->getCfRule()); + $objWriter->writeAttribute('id', $ruleExtension->getId()); + $objWriter->startElementNs($prefix, 'dataBar', null); + $dataBar = $ruleExtension->getDataBarExt(); + foreach ($dataBar->getXmlAttributes() as $attrKey => $val) { + $objWriter->writeAttribute($attrKey, $val); + } + $minCfvo = $dataBar->getMinimumConditionalFormatValueObject(); + if ($minCfvo) { + $objWriter->startElementNs($prefix, 'cfvo', null); + $objWriter->writeAttribute('type', $minCfvo->getType()); + if ($minCfvo->getCellFormula()) { + $objWriter->writeElement('xm:f', $minCfvo->getCellFormula()); + } + $objWriter->endElement(); //end cfvo + } + + $maxCfvo = $dataBar->getMaximumConditionalFormatValueObject(); + if ($maxCfvo) { + $objWriter->startElementNs($prefix, 'cfvo', null); + $objWriter->writeAttribute('type', $maxCfvo->getType()); + if ($maxCfvo->getCellFormula()) { + $objWriter->writeElement('xm:f', $maxCfvo->getCellFormula()); + } + $objWriter->endElement(); //end cfvo + } + + foreach ($dataBar->getXmlElements() as $elmKey => $elmAttr) { + $objWriter->startElementNs($prefix, $elmKey, null); + foreach ($elmAttr as $attrKey => $attrVal) { + $objWriter->writeAttribute($attrKey, $attrVal); + } + $objWriter->endElement(); //end elmKey + } + $objWriter->endElement(); //end dataBar + $objWriter->endElement(); //end cfRule + $objWriter->writeElement('xm:sqref', $ruleExtension->getSqref()); + $objWriter->endElement(); //end conditionalFormatting + } + + private static function writeDataBarElements(XMLWriter $objWriter, $dataBar): void + { + /** @var ConditionalDataBar $dataBar */ + if ($dataBar) { + $objWriter->startElement('dataBar'); + self::writeAttributeIf($objWriter, null !== $dataBar->getShowValue(), 'showValue', $dataBar->getShowValue() ? '1' : '0'); + + $minCfvo = $dataBar->getMinimumConditionalFormatValueObject(); + if ($minCfvo) { + $objWriter->startElement('cfvo'); + self::writeAttributeIf($objWriter, $minCfvo->getType(), 'type', (string) $minCfvo->getType()); + self::writeAttributeIf($objWriter, $minCfvo->getValue(), 'val', (string) $minCfvo->getValue()); + $objWriter->endElement(); + } + $maxCfvo = $dataBar->getMaximumConditionalFormatValueObject(); + if ($maxCfvo) { + $objWriter->startElement('cfvo'); + self::writeAttributeIf($objWriter, $maxCfvo->getType(), 'type', (string) $maxCfvo->getType()); + self::writeAttributeIf($objWriter, $maxCfvo->getValue(), 'val', (string) $maxCfvo->getValue()); + $objWriter->endElement(); + } + if ($dataBar->getColor()) { + $objWriter->startElement('color'); + $objWriter->writeAttribute('rgb', $dataBar->getColor()); + $objWriter->endElement(); + } + $objWriter->endElement(); // end dataBar + + if ($dataBar->getConditionalFormattingRuleExt()) { + $objWriter->startElement('extLst'); + $extension = $dataBar->getConditionalFormattingRuleExt(); + $objWriter->startElement('ext'); + $objWriter->writeAttribute('uri', '{B025F937-C7B1-47D3-B67F-A62EFF666E3E}'); + $objWriter->startElementNs('x14', 'id', null); + $objWriter->text($extension->getId()); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); //end extLst + } + } + } + /** * Write ConditionalFormatting. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeConditionalFormatting(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void + private function writeConditionalFormatting(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // Conditional id $id = 1; // Loop through styles in the current worksheet - foreach ($pSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { + foreach ($worksheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { foreach ($conditionalStyles as $conditional) { // WHY was this again? // if ($this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()) == '') { @@ -529,26 +630,40 @@ class Worksheet extends WriterPart // cfRule $objWriter->startElement('cfRule'); $objWriter->writeAttribute('type', $conditional->getConditionType()); - $objWriter->writeAttribute('dxfId', $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode())); + self::writeAttributeIf( + $objWriter, + ($conditional->getConditionType() != Conditional::CONDITION_DATABAR), + 'dxfId', + (string) $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()) + ); $objWriter->writeAttribute('priority', $id++); self::writeAttributeif( $objWriter, - ($conditional->getConditionType() == Conditional::CONDITION_CELLIS || $conditional->getConditionType() == Conditional::CONDITION_CONTAINSTEXT) - && $conditional->getOperatorType() != Conditional::OPERATOR_NONE, + ( + $conditional->getConditionType() === Conditional::CONDITION_CELLIS + || $conditional->getConditionType() === Conditional::CONDITION_CONTAINSTEXT + || $conditional->getConditionType() === Conditional::CONDITION_NOTCONTAINSTEXT + ) && $conditional->getOperatorType() !== Conditional::OPERATOR_NONE, 'operator', $conditional->getOperatorType() ); self::writeAttributeIf($objWriter, $conditional->getStopIfTrue(), 'stopIfTrue', '1'); - if ($conditional->getConditionType() == Conditional::CONDITION_CONTAINSTEXT) { + if ( + $conditional->getConditionType() === Conditional::CONDITION_CONTAINSTEXT + || $conditional->getConditionType() === Conditional::CONDITION_NOTCONTAINSTEXT + ) { self::writeTextCondElements($objWriter, $conditional, $cellCoordinate); } else { self::writeOtherCondElements($objWriter, $conditional, $cellCoordinate); } - $objWriter->endElement(); + // + self::writeDataBarElements($objWriter, $conditional->getDataBar()); + + $objWriter->endElement(); //end cfRule $objWriter->endElement(); } @@ -560,21 +675,25 @@ class Worksheet extends WriterPart * Write DataValidations. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeDataValidations(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void + private function writeDataValidations(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // Datavalidation collection - $dataValidationCollection = $pSheet->getDataValidationCollection(); + $dataValidationCollection = $worksheet->getDataValidationCollection(); // Write data validations? if (!empty($dataValidationCollection)) { $dataValidationCollection = Coordinate::mergeRangesInCollection($dataValidationCollection); - $objWriter->startElement('dataValidations'); + $objWriter->startElement('extLst'); + $objWriter->startElement('ext'); + $objWriter->writeAttribute('uri', '{CCE6A557-97BC-4b89-ADB6-D9C93CAAB3DF}'); + $objWriter->writeAttribute('xmlns:x14', 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main'); + $objWriter->startElement('x14:dataValidations'); $objWriter->writeAttribute('count', count($dataValidationCollection)); + $objWriter->writeAttribute('xmlns:xm', 'http://schemas.microsoft.com/office/excel/2006/main'); foreach ($dataValidationCollection as $coordinate => $dv) { - $objWriter->startElement('dataValidation'); + $objWriter->startElement('x14:dataValidation'); if ($dv->getType() != '') { $objWriter->writeAttribute('type', $dv->getType()); @@ -589,6 +708,7 @@ class Worksheet extends WriterPart } $objWriter->writeAttribute('allowBlank', ($dv->getAllowBlank() ? '1' : '0')); + // showDropDown is really hideDropDown Excel renders as true = hide, false = show $objWriter->writeAttribute('showDropDown', (!$dv->getShowDropDown() ? '1' : '0')); $objWriter->writeAttribute('showInputMessage', ($dv->getShowInputMessage() ? '1' : '0')); $objWriter->writeAttribute('showErrorMessage', ($dv->getShowErrorMessage() ? '1' : '0')); @@ -606,19 +726,24 @@ class Worksheet extends WriterPart $objWriter->writeAttribute('prompt', $dv->getPrompt()); } - $objWriter->writeAttribute('sqref', $coordinate); - if ($dv->getFormula1() !== '') { - $objWriter->writeElement('formula1', $dv->getFormula1()); + $objWriter->startElement('x14:formula1'); + $objWriter->writeElement('xm:f', $dv->getFormula1()); + $objWriter->endElement(); } if ($dv->getFormula2() !== '') { - $objWriter->writeElement('formula2', $dv->getFormula2()); + $objWriter->startElement('x14:formula2'); + $objWriter->writeElement('xm:f', $dv->getFormula2()); + $objWriter->endElement(); } + $objWriter->writeElement('xm:sqref', $dv->getSqref() ?? $coordinate); $objWriter->endElement(); } - $objWriter->endElement(); + $objWriter->endElement(); // dataValidations + $objWriter->endElement(); // ext + $objWriter->endElement(); // extLst } } @@ -626,12 +751,11 @@ class Worksheet extends WriterPart * Write Hyperlinks. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeHyperlinks(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void + private function writeHyperlinks(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // Hyperlink collection - $hyperlinkCollection = $pSheet->getHyperlinkCollection(); + $hyperlinkCollection = $worksheet->getHyperlinkCollection(); // Relation ID $relationId = 1; @@ -667,16 +791,15 @@ class Worksheet extends WriterPart * Write ProtectedRanges. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeProtectedRanges(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void + private function writeProtectedRanges(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { - if (count($pSheet->getProtectedCells()) > 0) { + if (count($worksheet->getProtectedCells()) > 0) { // protectedRanges $objWriter->startElement('protectedRanges'); // Loop protectedRanges - foreach ($pSheet->getProtectedCells() as $protectedCell => $passwordHash) { + foreach ($worksheet->getProtectedCells() as $protectedCell => $passwordHash) { // protectedRange $objWriter->startElement('protectedRange'); $objWriter->writeAttribute('name', 'p' . md5($protectedCell)); @@ -695,16 +818,15 @@ class Worksheet extends WriterPart * Write MergeCells. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeMergeCells(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void + private function writeMergeCells(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { - if (count($pSheet->getMergeCells()) > 0) { + if (count($worksheet->getMergeCells()) > 0) { // mergeCells $objWriter->startElement('mergeCells'); // Loop mergeCells - foreach ($pSheet->getMergeCells() as $mergeCell) { + foreach ($worksheet->getMergeCells() as $mergeCell) { // mergeCell $objWriter->startElement('mergeCell'); $objWriter->writeAttribute('ref', $mergeCell); @@ -719,21 +841,20 @@ class Worksheet extends WriterPart * Write PrintOptions. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writePrintOptions(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void + private function writePrintOptions(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // printOptions $objWriter->startElement('printOptions'); - $objWriter->writeAttribute('gridLines', ($pSheet->getPrintGridlines() ? 'true' : 'false')); + $objWriter->writeAttribute('gridLines', ($worksheet->getPrintGridlines() ? 'true' : 'false')); $objWriter->writeAttribute('gridLinesSet', 'true'); - if ($pSheet->getPageSetup()->getHorizontalCentered()) { + if ($worksheet->getPageSetup()->getHorizontalCentered()) { $objWriter->writeAttribute('horizontalCentered', 'true'); } - if ($pSheet->getPageSetup()->getVerticalCentered()) { + if ($worksheet->getPageSetup()->getVerticalCentered()) { $objWriter->writeAttribute('verticalCentered', 'true'); } @@ -744,18 +865,17 @@ class Worksheet extends WriterPart * Write PageMargins. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writePageMargins(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void + private function writePageMargins(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // pageMargins $objWriter->startElement('pageMargins'); - $objWriter->writeAttribute('left', StringHelper::formatNumber($pSheet->getPageMargins()->getLeft())); - $objWriter->writeAttribute('right', StringHelper::formatNumber($pSheet->getPageMargins()->getRight())); - $objWriter->writeAttribute('top', StringHelper::formatNumber($pSheet->getPageMargins()->getTop())); - $objWriter->writeAttribute('bottom', StringHelper::formatNumber($pSheet->getPageMargins()->getBottom())); - $objWriter->writeAttribute('header', StringHelper::formatNumber($pSheet->getPageMargins()->getHeader())); - $objWriter->writeAttribute('footer', StringHelper::formatNumber($pSheet->getPageMargins()->getFooter())); + $objWriter->writeAttribute('left', StringHelper::formatNumber($worksheet->getPageMargins()->getLeft())); + $objWriter->writeAttribute('right', StringHelper::formatNumber($worksheet->getPageMargins()->getRight())); + $objWriter->writeAttribute('top', StringHelper::formatNumber($worksheet->getPageMargins()->getTop())); + $objWriter->writeAttribute('bottom', StringHelper::formatNumber($worksheet->getPageMargins()->getBottom())); + $objWriter->writeAttribute('header', StringHelper::formatNumber($worksheet->getPageMargins()->getHeader())); + $objWriter->writeAttribute('footer', StringHelper::formatNumber($worksheet->getPageMargins()->getFooter())); $objWriter->endElement(); } @@ -763,11 +883,11 @@ class Worksheet extends WriterPart * Write AutoFilter. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet + * @param PhpspreadsheetWorksheet $worksheet Worksheet */ - private function writeAutoFilter(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void + private function writeAutoFilter(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { - $autoFilterRange = $pSheet->getAutoFilter()->getRange(); + $autoFilterRange = $worksheet->getAutoFilter()->getRange(); if (!empty($autoFilterRange)) { // autoFilter $objWriter->startElement('autoFilter'); @@ -781,13 +901,13 @@ class Worksheet extends WriterPart $objWriter->writeAttribute('ref', str_replace('$', '', $range)); - $columns = $pSheet->getAutoFilter()->getColumns(); + $columns = $worksheet->getAutoFilter()->getColumns(); if (count($columns) > 0) { foreach ($columns as $columnID => $column) { $rules = $column->getRules(); if (count($rules) > 0) { $objWriter->startElement('filterColumn'); - $objWriter->writeAttribute('colId', $pSheet->getAutoFilter()->getColumnOffset($columnID)); + $objWriter->writeAttribute('colId', $worksheet->getAutoFilter()->getColumnOffset($columnID)); $objWriter->startElement($column->getFilterType()); if ($column->getJoin() == Column::AUTOFILTER_COLUMN_JOIN_AND) { @@ -807,15 +927,18 @@ class Worksheet extends WriterPart $objWriter->writeAttribute('type', $rule->getGrouping()); $val = $column->getAttribute('val'); if ($val !== null) { - $objWriter->writeAttribute('val', $val); + $objWriter->writeAttribute('val', "$val"); } $maxVal = $column->getAttribute('maxVal'); if ($maxVal !== null) { - $objWriter->writeAttribute('maxVal', $maxVal); + $objWriter->writeAttribute('maxVal', "$maxVal"); } } elseif ($rule->getRuleType() === Rule::AUTOFILTER_RULETYPE_TOPTENFILTER) { // Top 10 Filter Rule - $objWriter->writeAttribute('val', $rule->getValue()); + $ruleValue = $rule->getValue(); + if (!is_array($ruleValue)) { + $objWriter->writeAttribute('val', "$ruleValue"); + } $objWriter->writeAttribute('percent', (($rule->getOperator() === Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) ? '1' : '0')); $objWriter->writeAttribute('top', (($rule->getGrouping() === Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) ? '1' : '0')); } else { @@ -827,14 +950,18 @@ class Worksheet extends WriterPart } if ($rule->getRuleType() === Rule::AUTOFILTER_RULETYPE_DATEGROUP) { // Date Group filters - foreach ($rule->getValue() as $key => $value) { - if ($value > '') { - $objWriter->writeAttribute($key, $value); + $ruleValue = $rule->getValue(); + if (is_array($ruleValue)) { + foreach ($ruleValue as $key => $value) { + $objWriter->writeAttribute($key, "$value"); } } $objWriter->writeAttribute('dateTimeGrouping', $rule->getGrouping()); } else { - $objWriter->writeAttribute('val', $rule->getValue()); + $ruleValue = $rule->getValue(); + if (!is_array($ruleValue)) { + $objWriter->writeAttribute('val', "$ruleValue"); + } } $objWriter->endElement(); @@ -855,37 +982,37 @@ class Worksheet extends WriterPart * Write PageSetup. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet + * @param PhpspreadsheetWorksheet $worksheet Worksheet */ - private function writePageSetup(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void + private function writePageSetup(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // pageSetup $objWriter->startElement('pageSetup'); - $objWriter->writeAttribute('paperSize', $pSheet->getPageSetup()->getPaperSize()); - $objWriter->writeAttribute('orientation', $pSheet->getPageSetup()->getOrientation()); + $objWriter->writeAttribute('paperSize', $worksheet->getPageSetup()->getPaperSize()); + $objWriter->writeAttribute('orientation', $worksheet->getPageSetup()->getOrientation()); - if ($pSheet->getPageSetup()->getScale() !== null) { - $objWriter->writeAttribute('scale', $pSheet->getPageSetup()->getScale()); + if ($worksheet->getPageSetup()->getScale() !== null) { + $objWriter->writeAttribute('scale', $worksheet->getPageSetup()->getScale()); } - if ($pSheet->getPageSetup()->getFitToHeight() !== null) { - $objWriter->writeAttribute('fitToHeight', $pSheet->getPageSetup()->getFitToHeight()); + if ($worksheet->getPageSetup()->getFitToHeight() !== null) { + $objWriter->writeAttribute('fitToHeight', $worksheet->getPageSetup()->getFitToHeight()); } else { $objWriter->writeAttribute('fitToHeight', '0'); } - if ($pSheet->getPageSetup()->getFitToWidth() !== null) { - $objWriter->writeAttribute('fitToWidth', $pSheet->getPageSetup()->getFitToWidth()); + if ($worksheet->getPageSetup()->getFitToWidth() !== null) { + $objWriter->writeAttribute('fitToWidth', $worksheet->getPageSetup()->getFitToWidth()); } else { $objWriter->writeAttribute('fitToWidth', '0'); } - if ($pSheet->getPageSetup()->getFirstPageNumber() !== null) { - $objWriter->writeAttribute('firstPageNumber', $pSheet->getPageSetup()->getFirstPageNumber()); + if ($worksheet->getPageSetup()->getFirstPageNumber() !== null) { + $objWriter->writeAttribute('firstPageNumber', $worksheet->getPageSetup()->getFirstPageNumber()); $objWriter->writeAttribute('useFirstPageNumber', '1'); } - $objWriter->writeAttribute('pageOrder', $pSheet->getPageSetup()->getPageOrder()); + $objWriter->writeAttribute('pageOrder', $worksheet->getPageSetup()->getPageOrder()); - $getUnparsedLoadedData = $pSheet->getParent()->getUnparsedLoadedData(); - if (isset($getUnparsedLoadedData['sheets'][$pSheet->getCodeName()]['pageSetupRelId'])) { - $objWriter->writeAttribute('r:id', $getUnparsedLoadedData['sheets'][$pSheet->getCodeName()]['pageSetupRelId']); + $getUnparsedLoadedData = $worksheet->getParent()->getUnparsedLoadedData(); + if (isset($getUnparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId'])) { + $objWriter->writeAttribute('r:id', $getUnparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId']); } $objWriter->endElement(); @@ -895,23 +1022,23 @@ class Worksheet extends WriterPart * Write Header / Footer. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet + * @param PhpspreadsheetWorksheet $worksheet Worksheet */ - private function writeHeaderFooter(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void + private function writeHeaderFooter(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // headerFooter $objWriter->startElement('headerFooter'); - $objWriter->writeAttribute('differentOddEven', ($pSheet->getHeaderFooter()->getDifferentOddEven() ? 'true' : 'false')); - $objWriter->writeAttribute('differentFirst', ($pSheet->getHeaderFooter()->getDifferentFirst() ? 'true' : 'false')); - $objWriter->writeAttribute('scaleWithDoc', ($pSheet->getHeaderFooter()->getScaleWithDocument() ? 'true' : 'false')); - $objWriter->writeAttribute('alignWithMargins', ($pSheet->getHeaderFooter()->getAlignWithMargins() ? 'true' : 'false')); + $objWriter->writeAttribute('differentOddEven', ($worksheet->getHeaderFooter()->getDifferentOddEven() ? 'true' : 'false')); + $objWriter->writeAttribute('differentFirst', ($worksheet->getHeaderFooter()->getDifferentFirst() ? 'true' : 'false')); + $objWriter->writeAttribute('scaleWithDoc', ($worksheet->getHeaderFooter()->getScaleWithDocument() ? 'true' : 'false')); + $objWriter->writeAttribute('alignWithMargins', ($worksheet->getHeaderFooter()->getAlignWithMargins() ? 'true' : 'false')); - $objWriter->writeElement('oddHeader', $pSheet->getHeaderFooter()->getOddHeader()); - $objWriter->writeElement('oddFooter', $pSheet->getHeaderFooter()->getOddFooter()); - $objWriter->writeElement('evenHeader', $pSheet->getHeaderFooter()->getEvenHeader()); - $objWriter->writeElement('evenFooter', $pSheet->getHeaderFooter()->getEvenFooter()); - $objWriter->writeElement('firstHeader', $pSheet->getHeaderFooter()->getFirstHeader()); - $objWriter->writeElement('firstFooter', $pSheet->getHeaderFooter()->getFirstFooter()); + $objWriter->writeElement('oddHeader', $worksheet->getHeaderFooter()->getOddHeader()); + $objWriter->writeElement('oddFooter', $worksheet->getHeaderFooter()->getOddFooter()); + $objWriter->writeElement('evenHeader', $worksheet->getHeaderFooter()->getEvenHeader()); + $objWriter->writeElement('evenFooter', $worksheet->getHeaderFooter()->getEvenFooter()); + $objWriter->writeElement('firstHeader', $worksheet->getHeaderFooter()->getFirstHeader()); + $objWriter->writeElement('firstFooter', $worksheet->getHeaderFooter()->getFirstFooter()); $objWriter->endElement(); } @@ -919,14 +1046,14 @@ class Worksheet extends WriterPart * Write Breaks. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet + * @param PhpspreadsheetWorksheet $worksheet Worksheet */ - private function writeBreaks(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void + private function writeBreaks(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // Get row and column breaks $aRowBreaks = []; $aColumnBreaks = []; - foreach ($pSheet->getBreaks() as $cell => $breakType) { + foreach ($worksheet->getBreaks() as $cell => $breakType) { if ($breakType == PhpspreadsheetWorksheet::BREAK_ROW) { $aRowBreaks[] = $cell; } elseif ($breakType == PhpspreadsheetWorksheet::BREAK_COLUMN) { @@ -975,26 +1102,26 @@ class Worksheet extends WriterPart * Write SheetData. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet + * @param PhpspreadsheetWorksheet $worksheet Worksheet * @param string[] $pStringTable String table */ - private function writeSheetData(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet, array $pStringTable): void + private function writeSheetData(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, array $pStringTable): void { // Flipped stringtable, for faster index searching - $aFlippedStringTable = $this->getParentWriter()->getWriterPart('stringtable')->flipStringTable($pStringTable); + $aFlippedStringTable = $this->getParentWriter()->getWriterPartstringtable()->flipStringTable($pStringTable); // sheetData $objWriter->startElement('sheetData'); // Get column count - $colCount = Coordinate::columnIndexFromString($pSheet->getHighestColumn()); + $colCount = Coordinate::columnIndexFromString($worksheet->getHighestColumn()); // Highest row number - $highestRow = $pSheet->getHighestRow(); + $highestRow = $worksheet->getHighestRow(); // Loop through cells $cellsByRow = []; - foreach ($pSheet->getCoordinates() as $coordinate) { + foreach ($worksheet->getCoordinates() as $coordinate) { $cellAddress = Coordinate::coordinateFromString($coordinate); $cellsByRow[$cellAddress[1]][] = $coordinate; } @@ -1002,7 +1129,7 @@ class Worksheet extends WriterPart $currentRow = 0; while ($currentRow++ < $highestRow) { // Get row dimension - $rowDimension = $pSheet->getRowDimension($currentRow); + $rowDimension = $worksheet->getRowDimension($currentRow); // Write current row? $writeCurrentRow = isset($cellsByRow[$currentRow]) || $rowDimension->getRowHeight() >= 0 || $rowDimension->getVisible() == false || $rowDimension->getCollapsed() == true || $rowDimension->getOutlineLevel() > 0 || $rowDimension->getXfIndex() !== null; @@ -1044,7 +1171,7 @@ class Worksheet extends WriterPart if (isset($cellsByRow[$currentRow])) { foreach ($cellsByRow[$currentRow] as $cellAddress) { // Write cell - $this->writeCell($objWriter, $pSheet, $cellAddress, $aFlippedStringTable); + $this->writeCell($objWriter, $worksheet, $cellAddress, $aFlippedStringTable); } } @@ -1063,10 +1190,13 @@ class Worksheet extends WriterPart { $objWriter->writeAttribute('t', $mappedType); if (!$cellValue instanceof RichText) { - $objWriter->writeElement('t', StringHelper::controlCharacterPHP2OOXML(htmlspecialchars($cellValue))); + $objWriter->writeElement( + 't', + StringHelper::controlCharacterPHP2OOXML(htmlspecialchars($cellValue, Settings::htmlEntityFlags())) + ); } elseif ($cellValue instanceof RichText) { $objWriter->startElement('is'); - $this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $cellValue); + $this->getParentWriter()->getWriterPartstringtable()->writeRichText($objWriter, $cellValue); $objWriter->endElement(); } } @@ -1125,8 +1255,10 @@ class Worksheet extends WriterPart return; } $objWriter->writeAttribute('t', 'str'); + $calculatedValue = StringHelper::controlCharacterPHP2OOXML($calculatedValue); } elseif (is_bool($calculatedValue)) { $objWriter->writeAttribute('t', 'b'); + $calculatedValue = (int) $calculatedValue; } // array values are not yet supported //$attributes = $pCell->getFormulaAttributes(); @@ -1146,7 +1278,7 @@ class Worksheet extends WriterPart $objWriter, $this->getParentWriter()->getOffice2003Compatibility() === false, 'v', - ($this->getParentWriter()->getPreCalculateFormulas() && !is_array($calculatedValue) && substr($calculatedValue, 0, 1) !== '#') + ($this->getParentWriter()->getPreCalculateFormulas() && !is_array($calculatedValue) && substr($calculatedValue ?? '', 0, 1) !== '#') ? StringHelper::formatNumber($calculatedValue) : '0' ); } @@ -1155,14 +1287,14 @@ class Worksheet extends WriterPart * Write Cell. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet + * @param PhpspreadsheetWorksheet $worksheet Worksheet * @param string $pCellAddress Cell Address * @param string[] $pFlippedStringTable String table (flipped), for faster index searching */ - private function writeCell(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet, string $pCellAddress, array $pFlippedStringTable): void + private function writeCell(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, string $pCellAddress, array $pFlippedStringTable): void { // Cell - $pCell = $pSheet->getCell($pCellAddress); + $pCell = $worksheet->getCell($pCellAddress); $objWriter->startElement('c'); $objWriter->writeAttribute('r', $pCellAddress); @@ -1210,15 +1342,15 @@ class Worksheet extends WriterPart * Write Drawings. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet + * @param PhpspreadsheetWorksheet $worksheet Worksheet * @param bool $includeCharts Flag indicating if we should include drawing details for charts */ - private function writeDrawings(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet, $includeCharts = false): void + private function writeDrawings(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, $includeCharts = false): void { - $unparsedLoadedData = $pSheet->getParent()->getUnparsedLoadedData(); - $hasUnparsedDrawing = isset($unparsedLoadedData['sheets'][$pSheet->getCodeName()]['drawingOriginalIds']); - $chartCount = ($includeCharts) ? $pSheet->getChartCollection()->count() : 0; - if ($chartCount == 0 && $pSheet->getDrawingCollection()->count() == 0 && !$hasUnparsedDrawing) { + $unparsedLoadedData = $worksheet->getParent()->getUnparsedLoadedData(); + $hasUnparsedDrawing = isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds']); + $chartCount = ($includeCharts) ? $worksheet->getChartCollection()->count() : 0; + if ($chartCount == 0 && $worksheet->getDrawingCollection()->count() == 0 && !$hasUnparsedDrawing) { return; } @@ -1226,8 +1358,8 @@ class Worksheet extends WriterPart $objWriter->startElement('drawing'); $rId = 'rId1'; - if (isset($unparsedLoadedData['sheets'][$pSheet->getCodeName()]['drawingOriginalIds'])) { - $drawingOriginalIds = $unparsedLoadedData['sheets'][$pSheet->getCodeName()]['drawingOriginalIds']; + if (isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds'])) { + $drawingOriginalIds = $unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds']; // take first. In future can be overriten // (! synchronize with \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Rels::writeWorksheetRelationships) $rId = reset($drawingOriginalIds); @@ -1241,12 +1373,12 @@ class Worksheet extends WriterPart * Write LegacyDrawing. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet + * @param PhpspreadsheetWorksheet $worksheet Worksheet */ - private function writeLegacyDrawing(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void + private function writeLegacyDrawing(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // If sheet contains comments, add the relationships - if (count($pSheet->getComments()) > 0) { + if (count($worksheet->getComments()) > 0) { $objWriter->startElement('legacyDrawing'); $objWriter->writeAttribute('r:id', 'rId_comments_vml1'); $objWriter->endElement(); @@ -1257,26 +1389,61 @@ class Worksheet extends WriterPart * Write LegacyDrawingHF. * * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet + * @param PhpspreadsheetWorksheet $worksheet Worksheet */ - private function writeLegacyDrawingHF(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void + private function writeLegacyDrawingHF(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // If sheet contains images, add the relationships - if (count($pSheet->getHeaderFooter()->getImages()) > 0) { + if (count($worksheet->getHeaderFooter()->getImages()) > 0) { $objWriter->startElement('legacyDrawingHF'); $objWriter->writeAttribute('r:id', 'rId_headerfooter_vml1'); $objWriter->endElement(); } } - private function writeAlternateContent(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void + private function writeAlternateContent(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { - if (empty($pSheet->getParent()->getUnparsedLoadedData()['sheets'][$pSheet->getCodeName()]['AlternateContents'])) { + if (empty($worksheet->getParent()->getUnparsedLoadedData()['sheets'][$worksheet->getCodeName()]['AlternateContents'])) { return; } - foreach ($pSheet->getParent()->getUnparsedLoadedData()['sheets'][$pSheet->getCodeName()]['AlternateContents'] as $alternateContent) { + foreach ($worksheet->getParent()->getUnparsedLoadedData()['sheets'][$worksheet->getCodeName()]['AlternateContents'] as $alternateContent) { $objWriter->writeRaw($alternateContent); } } + + /** + * write + * only implementation conditionalFormattings. + * + * @url https://docs.microsoft.com/en-us/openspecs/office_standards/ms-xlsx/07d607af-5618-4ca2-b683-6a78dc0d9627 + */ + private function writeExtLst(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void + { + $conditionalFormattingRuleExtList = []; + foreach ($worksheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { + /** @var Conditional $conditional */ + foreach ($conditionalStyles as $conditional) { + $dataBar = $conditional->getDataBar(); + // @phpstan-ignore-next-line + if ($dataBar && $dataBar->getConditionalFormattingRuleExt()) { + $conditionalFormattingRuleExtList[] = $dataBar->getConditionalFormattingRuleExt(); + } + } + } + + if (count($conditionalFormattingRuleExtList) > 0) { + $conditionalFormattingRuleExtNsPrefix = 'x14'; + $objWriter->startElement('extLst'); + $objWriter->startElement('ext'); + $objWriter->writeAttribute('uri', '{78C0D931-6437-407d-A8EE-F0AAD7539E65}'); + $objWriter->startElementNs($conditionalFormattingRuleExtNsPrefix, 'conditionalFormattings', null); + foreach ($conditionalFormattingRuleExtList as $extension) { + self::writeExtConditionalFormattingElements($objWriter, $extension); + } + $objWriter->endElement(); //end conditionalFormattings + $objWriter->endElement(); //end ext + $objWriter->endElement(); //end extLst + } + } } diff --git a/src/PhpSpreadsheet/Writer/Xlsx/Xlfn.php b/src/PhpSpreadsheet/Writer/Xlsx/Xlfn.php index 8f7c07e8..c88ef245 100644 --- a/src/PhpSpreadsheet/Writer/Xlsx/Xlfn.php +++ b/src/PhpSpreadsheet/Writer/Xlsx/Xlfn.php @@ -10,6 +10,7 @@ class Xlfn . '|beta[.]inv' . '|binom[.]dist' . '|binom[.]inv' + . '|ceiling[.]precise' . '|chisq[.]dist' . '|chisq[.]dist[.]rt' . '|chisq[.]inv' @@ -27,6 +28,7 @@ class Xlfn . '|f[.]inv' . '|f[.]inv[.]rt' . '|f[.]test' + . '|floor[.]precise' . '|gamma[.]dist' . '|gamma[.]inv' . '|gammaln[.]precise' @@ -138,6 +140,11 @@ class Xlfn . '|unique' . '|xlookup' . '|xmatch' + . '|arraytotext' + . '|call' + . '|let' + . '|register[.]id' + . '|valuetotext' . ')(?=\\s*[(])/i'; /** diff --git a/tests/PhpSpreadsheetTests/Calculation/CalculationTest.php b/tests/PhpSpreadsheetTests/Calculation/CalculationTest.php index 8e339207..296a3b0f 100644 --- a/tests/PhpSpreadsheetTests/Calculation/CalculationTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/CalculationTest.php @@ -4,13 +4,20 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PHPUnit\Framework\TestCase; class CalculationTest extends TestCase { + /** + * @var string + */ private $compatibilityMode; + /** + * @var string + */ private $locale; protected function setUp(): void @@ -46,7 +53,7 @@ class CalculationTest extends TestCase self::assertEquals($expectedResultOpenOffice, $resultOpenOffice, 'should be OpenOffice compatible'); } - public function providerBinaryComparisonOperation() + public function providerBinaryComparisonOperation(): array { return require 'tests/data/CalculationBinaryComparisonOperation.php'; } @@ -63,7 +70,7 @@ class CalculationTest extends TestCase self::assertIsCallable($functionCall); } - public function providerGetFunctions() + public function providerGetFunctions(): array { return Calculation::getInstance()->getFunctions(); } @@ -88,7 +95,13 @@ class CalculationTest extends TestCase self::assertTrue($calculation->setLocale($locale)); } - public function providerCanLoadAllSupportedLocales() + public function testInvalidLocaleReturnsFalse(): void + { + $calculation = Calculation::getInstance(); + self::assertFalse($calculation->setLocale('xx')); + } + + public function providerCanLoadAllSupportedLocales(): array { return [ ['bg'], @@ -102,7 +115,7 @@ class CalculationTest extends TestCase ['hu'], ['it'], ['nl'], - ['no'], + ['nb'], ['pl'], ['pt'], ['pt_br'], @@ -117,11 +130,13 @@ class CalculationTest extends TestCase $calculation = Calculation::getInstance(); $tree = $calculation->parseFormula('=_xlfn.ISFORMULA(A1)'); + self::assertIsArray($tree); self::assertCount(3, $tree); $function = $tree[2]; self::assertEquals('Function', $function['type']); $tree = $calculation->parseFormula('=_xlfn.STDEV.S(A1:B2)'); + self::assertIsArray($tree); self::assertCount(5, $tree); $function = $tree[4]; self::assertEquals('Function', $function['type']); @@ -159,6 +174,14 @@ class CalculationTest extends TestCase $cell->getStyle()->setQuotePrefix(true); self::assertEquals("=cmd|'/C calc'!A0", $cell->getCalculatedValue()); + + $cell2 = $workSheet->getCell('A2'); + $cell2->setValueExplicit('ABC', DataType::TYPE_FORMULA); + self::assertEquals('ABC', $cell2->getCalculatedValue()); + + $cell3 = $workSheet->getCell('A3'); + $cell3->setValueExplicit('=', DataType::TYPE_FORMULA); + self::assertEquals('', $cell3->getCalculatedValue()); } public function testCellWithDdeExpresion(): void @@ -196,6 +219,7 @@ class CalculationTest extends TestCase // Very simple formula $formula = '=IF(A1="please +",B1)'; $tokens = $calculation->parseFormula($formula); + self::assertIsArray($tokens); $foundEqualAssociatedToStoreKey = false; $foundConditionalOnB1 = false; @@ -225,6 +249,7 @@ class CalculationTest extends TestCase // Internal operation $formula = '=IF(A1="please +",SUM(B1:B3))+IF(A2="please *",PRODUCT(C1:C3), C1)'; $tokens = $calculation->parseFormula($formula); + self::assertIsArray($tokens); $plusGotTagged = false; $productFunctionCorrectlyTagged = false; @@ -254,6 +279,7 @@ class CalculationTest extends TestCase $formula = '=IF(A1="please +",SUM(B1:B3),1+IF(NOT(A2="please *"),C2-C1,PRODUCT(C1:C3)))'; $tokens = $calculation->parseFormula($formula); + self::assertIsArray($tokens); $plusCorrectlyTagged = false; $productFunctionCorrectlyTagged = false; @@ -298,6 +324,8 @@ class CalculationTest extends TestCase $formula = '=IF(A1="flag",IF(A2<10, 0) + IF(A3<10000, 0))'; $tokens = $calculation->parseFormula($formula); + self::assertIsArray($tokens); + $properlyTaggedPlus = false; foreach ($tokens as $token) { $isPlus = $token['value'] === '+'; @@ -310,8 +338,8 @@ class CalculationTest extends TestCase } /** - * @param $expectedResult - * @param $dataArray + * @param mixed $expectedResult + * @param mixed $dataArray * @param string $formula * @param string $cellCoordinates where to put the formula * @param string[] $shouldBeSetInCacheCells coordinates of cells that must @@ -358,7 +386,7 @@ class CalculationTest extends TestCase self::assertEquals($expectedResult, $calculated); } - public function dataProviderBranchPruningFullExecution() + public function dataProviderBranchPruningFullExecution(): array { return require 'tests/data/Calculation/Calculation.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/DefinedNameConfusedForCellTest.php b/tests/PhpSpreadsheetTests/Calculation/DefinedNameConfusedForCellTest.php index 76886c23..6f97f9c8 100644 --- a/tests/PhpSpreadsheetTests/Calculation/DefinedNameConfusedForCellTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/DefinedNameConfusedForCellTest.php @@ -2,20 +2,23 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation; +use PhpOffice\PhpSpreadsheet\IOFactory; +use PhpOffice\PhpSpreadsheet\NamedRange; use PhpOffice\PhpSpreadsheet\Shared\File; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PHPUnit\Framework\TestCase; class DefinedNameConfusedForCellTest extends TestCase { public function testDefinedName(): void { - $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet(); + $obj = new Spreadsheet(); $sheet0 = $obj->setActiveSheetIndex(0); $sheet0->setCellValue('A1', 2); - $obj->addNamedRange(new \PhpOffice\PhpSpreadsheet\NamedRange('A1A', $sheet0, 'A1')); + $obj->addNamedRange(new NamedRange('A1A', $sheet0, 'A1')); $sheet0->setCellValue('B1', '=2*A1A'); - $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($obj, 'Xlsx'); - $filename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); + $writer = IOFactory::createWriter($obj, 'Xlsx'); + $filename = File::temporaryFilename(); $writer->save($filename); self::assertTrue(true); unlink($filename); diff --git a/tests/PhpSpreadsheetTests/Calculation/Engine/RangeTest.php b/tests/PhpSpreadsheetTests/Calculation/Engine/RangeTest.php index 4f1ff397..c27d16af 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Engine/RangeTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Engine/RangeTest.php @@ -9,7 +9,10 @@ use PHPUnit\Framework\TestCase; class RangeTest extends TestCase { - protected $spreadSheet; + /** + * @var Spreadsheet + */ + private $spreadSheet; protected function setUp(): void { @@ -40,7 +43,7 @@ class RangeTest extends TestCase self::assertSame($expectedResult, $actualRresult); } - public function providerRangeEvaluation() + public function providerRangeEvaluation(): array { return[ ['=SUM(A1:B3,A1:C2)', 48], @@ -88,7 +91,7 @@ class RangeTest extends TestCase self::assertSame($expectedResult, $sumRresult); } - public function providerNamedRangeEvaluation() + public function providerNamedRangeEvaluation(): array { return[ ['$A$1:$B$3', '$A$1:$C$2', '=SUM(GROUP1,GROUP2)', 48], @@ -123,7 +126,7 @@ class RangeTest extends TestCase self::assertSame($expectedResult, $sumRresult); } - public function providerUTF8NamedRangeEvaluation() + public function providerUTF8NamedRangeEvaluation(): array { return[ [['Γειά', 'σου', 'Κόσμε'], ['$A$1', '$B$1:$B$2', '$C$1:$C$3'], '=SUM(Γειά,σου,Κόσμε)', 26], @@ -151,7 +154,7 @@ class RangeTest extends TestCase self::assertSame($expectedCount, $actualCount); } - public function providerCompositeNamedRangeEvaluation() + public function providerCompositeNamedRangeEvaluation(): array { return[ // Calculation engine doesn't yet handle union ranges with overlap diff --git a/tests/PhpSpreadsheetTests/Calculation/FinancialTest.php b/tests/PhpSpreadsheetTests/Calculation/FinancialTest.php deleted file mode 100644 index e80ef35b..00000000 --- a/tests/PhpSpreadsheetTests/Calculation/FinancialTest.php +++ /dev/null @@ -1,628 +0,0 @@ - 0.999999 && $frac < 1.000001) { - $result = $expectedResult; - } - } - } - self::assertEquals($expectedResult, $result, $message); - } - - public function providerXIRR() - { - return require 'tests/data/Calculation/Financial/XIRR.php'; - } - - /** - * @dataProvider providerXNPV - * - * @param mixed $expectedResult - * @param mixed $message - */ - public function testXNPV($expectedResult, $message, ...$args): void - { - $result = Financial::XNPV(...$args); - if (is_numeric($result) && is_numeric($expectedResult)) { - if ($expectedResult != 0) { - $frac = $result / $expectedResult; - if ($frac > 0.999999 && $frac < 1.000001) { - $result = $expectedResult; - } - } - } - self::assertEquals($expectedResult, $result, $message); - } - - public function providerXNPV() - { - return require 'tests/data/Calculation/Financial/XNPV.php'; - } - - /** - * @dataProvider providerPDURATION - * - * @param mixed $expectedResult - */ - public function testPDURATION($expectedResult, array $args): void - { - $result = Financial::PDURATION(...$args); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); - } - - public function providerPDURATION() - { - return require 'tests/data/Calculation/Financial/PDURATION.php'; - } - - /** - * @dataProvider providerRRI - * - * @param mixed $expectedResult - */ - public function testRRI($expectedResult, array $args): void - { - $result = Financial::RRI(...$args); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); - } - - public function providerRRI() - { - return require 'tests/data/Calculation/Financial/RRI.php'; - } - - /** - * @dataProvider providerSLN - * - * @param mixed $expectedResult - */ - public function testSLN($expectedResult, array $args): void - { - $result = Financial::SLN(...$args); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); - } - - public function providerSLN() - { - return require 'tests/data/Calculation/Financial/SLN.php'; - } - - /** - * @dataProvider providerSYD - * - * @param mixed $expectedResult - */ - public function testSYD($expectedResult, array $args): void - { - $result = Financial::SYD(...$args); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); - } - - public function providerSYD() - { - return require 'tests/data/Calculation/Financial/SYD.php'; - } -} diff --git a/tests/PhpSpreadsheetTests/Calculation/FormulaAsStringTest.php b/tests/PhpSpreadsheetTests/Calculation/FormulaAsStringTest.php index 9afe5570..27c746b4 100644 --- a/tests/PhpSpreadsheetTests/Calculation/FormulaAsStringTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/FormulaAsStringTest.php @@ -39,7 +39,7 @@ class FormulaAsStringTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerFunctionsAsString() + public function providerFunctionsAsString(): array { return require 'tests/data/Calculation/FunctionsAsString.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DAverageTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DAverageTest.php new file mode 100644 index 00000000..2d8fb9f9 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DAverageTest.php @@ -0,0 +1,110 @@ +database1(), + 'Yield', + [ + ['Tree', 'Height'], + ['=Apple', '>10'], + ], + ], + [ + 13, + $this->database1(), + 3, + $this->database1(), + ], + [ + 268333.333333333333, + $this->database2(), + 'Sales', + [ + ['Quarter', 'Sales Rep.'], + ['>1', 'Tina'], + ], + ], + [ + 372500, + $this->database2(), + 'Sales', + [ + ['Quarter', 'Area'], + ['1', 'South'], + ], + ], + [ + null, + $this->database1(), + null, + $this->database1(), + ], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DCountATest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DCountATest.php new file mode 100644 index 00000000..2f7cad14 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DCountATest.php @@ -0,0 +1,103 @@ +database1(), + 'Profit', + [ + ['Tree', 'Height', 'Height'], + ['=Apple', '>10', '<16'], + ], + ], + [ + 2, + $this->database2(), + 'Score', + [ + ['Subject', 'Gender'], + ['Science', 'Male'], + ], + ], + [ + 1, + $this->database2(), + 'Score', + [ + ['Subject', 'Gender'], + ['Math', 'Female'], + ], + ], + [ + 3, + $this->database2(), + 'Score', + [ + ['Subject', 'Score'], + ['English', '>60%'], + ], + ], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DCountTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DCountTest.php new file mode 100644 index 00000000..3f9d9966 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DCountTest.php @@ -0,0 +1,136 @@ +database1(), + 'Age', + [ + ['Tree', 'Height', 'Height'], + ['=Apple', '>10', '<16'], + ], + ], + [ + 1, + $this->database2(), + 'Score', + [ + ['Subject', 'Gender'], + ['Science', 'Male'], + ], + ], + [ + 1, + $this->database2(), + 'Score', + [ + ['Subject', 'Gender'], + ['Math', 'Female'], + ], + ], + [ + 3, + $this->database2(), + null, + [ + ['Subject', 'Score'], + ['English', '>63%'], + ], + ], + [ + 3, + $this->database3(), + 'Value', + [ + ['Status'], + [true], + ], + ], + [ + 5, + $this->database3(), + 'Value', + [ + ['Status'], + ['<>true'], + ], + ], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DGetTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DGetTest.php new file mode 100644 index 00000000..7853e0b6 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DGetTest.php @@ -0,0 +1,115 @@ +database1(), + 'Yield', + [ + ['Tree'], + ['=Apple'], + ['=Pear'], + ], + ], + [ + 10, + $this->database1(), + 'Yield', + [ + ['Tree', 'Height', 'Height'], + ['=Apple', '>10', '<16'], + ['=Pear', '>12', null], + ], + ], + [ + 188000, + $this->database2(), + 'Sales', + [ + ['Sales Rep.', 'Quarter'], + ['Tina', 4], + ], + ], + [ + Functions::NAN(), + $this->database2(), + 'Sales', + [ + ['Area', 'Quarter'], + ['South', 4], + ], + ], + [ + null, + $this->database1(), + null, + $this->database1(), + ], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DMaxTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DMaxTest.php new file mode 100644 index 00000000..94ac0425 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DMaxTest.php @@ -0,0 +1,105 @@ +database1(), + 'Profit', + [ + ['Tree', 'Height', 'Height'], + ['=Apple', '>10', '<16'], + ['=Pear', null, null], + ], + ], + [ + 340000, + $this->database2(), + 'Sales', + [ + ['Quarter', 'Area'], + [2, 'North'], + ], + ], + [ + 460000, + $this->database2(), + 'Sales', + [ + ['Sales Rep.', 'Quarter'], + ['Carol', '>1'], + ], + ], + [ + null, + $this->database1(), + null, + $this->database1(), + ], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DMinTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DMinTest.php new file mode 100644 index 00000000..a02ad2e1 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DMinTest.php @@ -0,0 +1,101 @@ +database1(), + 'Profit', + [ + ['Tree', 'Height', 'Height'], + ['=Apple', '>10', '<16'], + ['=Pear', '>12', null], + ], + ], + [ + 0.48, + $this->database2(), + 'Score', + [ + ['Subject', 'Age'], + ['Science', '>8'], + ], + ], + [ + 0.55, + $this->database2(), + 'Score', + [ + ['Subject', 'Gender'], + ['Math', 'Male'], + ], + ], + [ + null, + $this->database1(), + null, + $this->database1(), + ], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DProductTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DProductTest.php new file mode 100644 index 00000000..14962558 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DProductTest.php @@ -0,0 +1,102 @@ +database1(), + 'Yield', + [ + ['Tree', 'Height', 'Height'], + ['=Apple', '>10', '<16'], + ['=Pear', null, null], + ], + ], + [ + 36, + $this->database2(), + 'Score', + [ + ['Name', 'Date'], + ['Gary', '05-Jan-2017'], + ], + ], + [ + 8, + $this->database2(), + 'Score', + [ + ['Test', 'Date'], + ['Test1', '<05-Jan-2017'], + ], + ], + [ + null, + $this->database1(), + null, + $this->database1(), + ], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DStDevPTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DStDevPTest.php new file mode 100644 index 00000000..669a694b --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DStDevPTest.php @@ -0,0 +1,101 @@ +database1(), + 'Yield', + [ + ['Tree'], + ['=Apple'], + ['=Pear'], + ], + ], + [ + 0.085244745684, + $this->database2(), + 'Score', + [ + ['Subject', 'Gender'], + ['English', 'Male'], + ], + ], + [ + 0.160623784042, + $this->database2(), + 'Score', + [ + ['Subject', 'Age'], + ['Math', '>8'], + ], + ], + [ + null, + $this->database1(), + null, + $this->database1(), + ], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DStDevTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DStDevTest.php new file mode 100644 index 00000000..a7975a11 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DStDevTest.php @@ -0,0 +1,101 @@ +database1(), + 'Yield', + [ + ['Tree'], + ['=Apple'], + ['=Pear'], + ], + ], + [ + 0.104403065089, + $this->database2(), + 'Score', + [ + ['Subject', 'Gender'], + ['English', 'Male'], + ], + ], + [ + 0.196723155729, + $this->database2(), + 'Score', + [ + ['Subject', 'Age'], + ['Math', '>8'], + ], + ], + [ + null, + $this->database1(), + null, + $this->database1(), + ], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DSumTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DSumTest.php new file mode 100644 index 00000000..55edffe0 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DSumTest.php @@ -0,0 +1,123 @@ +database1(), + 'Profit', + [ + ['Tree'], + ['=Apple'], + ], + ], + [ + 248, + $this->database1(), + 'Profit', + [ + ['Tree', 'Height', 'Height'], + ['=Apple', '>10', '<16'], + ['=Pear', null, null], + ], + ], + [ + 1210000, + $this->database2(), + 'Sales', + [ + ['Quarter', 'Area'], + ['>2', 'North'], + ], + ], + [ + 710000, + $this->database2(), + 'Sales', + [ + ['Quarter', 'Sales Rep.'], + ['3', 'C*'], + ], + ], + [ + 705000, + $this->database2(), + 'Sales', + [ + ['Quarter', 'Sales Rep.'], + ['3', '<>C*'], + ], + ], + [ + null, + $this->database1(), + null, + $this->database1(), + ], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DVarPTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DVarPTest.php new file mode 100644 index 00000000..60612db5 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DVarPTest.php @@ -0,0 +1,101 @@ +database1(), + 'Yield', + [ + ['Tree'], + ['=Apple'], + ['=Pear'], + ], + ], + [ + 0.025622222222, + $this->database2(), + 'Score', + [ + ['Subject', 'Gender'], + ['Math', 'Male'], + ], + ], + [ + 0.011622222222, + $this->database2(), + 'Score', + [ + ['Subject', 'Age'], + ['Science', '>8'], + ], + ], + [ + null, + $this->database1(), + null, + $this->database1(), + ], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DVarTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DVarTest.php new file mode 100644 index 00000000..0015b7fb --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Database/DVarTest.php @@ -0,0 +1,101 @@ +database1(), + 'Yield', + [ + ['Tree'], + ['=Apple'], + ['=Pear'], + ], + ], + [ + 0.038433333333, + $this->database2(), + 'Score', + [ + ['Subject', 'Gender'], + ['Math', 'Male'], + ], + ], + [ + 0.017433333333, + $this->database2(), + 'Score', + [ + ['Subject', 'Age'], + ['Science', '>8'], + ], + ], + [ + null, + $this->database1(), + null, + $this->database1(), + ], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/AllSetupTeardown.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/AllSetupTeardown.php new file mode 100644 index 00000000..9fb5dfa5 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/AllSetupTeardown.php @@ -0,0 +1,107 @@ +compatibilityMode = Functions::getCompatibilityMode(); + $this->excelCalendar = Date::getExcelCalendar(); + $this->returnDateType = Functions::getReturnDateType(); + } + + protected function tearDown(): void + { + Date::setExcelCalendar($this->excelCalendar); + Functions::setCompatibilityMode($this->compatibilityMode); + Functions::setReturnDateType($this->returnDateType); + $this->sheet = null; + if ($this->spreadsheet !== null) { + $this->spreadsheet->disconnectWorksheets(); + $this->spreadsheet = null; + } + } + + protected static function setMac1904(): void + { + Date::setExcelCalendar(Date::CALENDAR_MAC_1904); + } + + protected static function setUnixReturn(): void + { + Functions::setReturnDateType(Functions::RETURNDATE_UNIX_TIMESTAMP); + } + + protected static function setObjectReturn(): void + { + Functions::setReturnDateType(Functions::RETURNDATE_PHP_DATETIME_OBJECT); + } + + protected static function setOpenOffice(): void + { + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + } + + /** + * @param mixed $expectedResult + */ + protected function mightHaveException($expectedResult): void + { + if ($expectedResult === 'exception') { + $this->expectException(CalcException::class); + } + } + + protected function getSpreadsheet(): Spreadsheet + { + if ($this->spreadsheet !== null) { + return $this->spreadsheet; + } + $this->spreadsheet = new Spreadsheet(); + + return $this->spreadsheet; + } + + protected function getSheet(): Worksheet + { + if ($this->sheet !== null) { + return $this->sheet; + } + $this->sheet = $this->getSpreadsheet()->getActiveSheet(); + + return $this->sheet; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/DateDifTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/DateDifTest.php index db8e29a1..d7d69376 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/DateDifTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/DateDifTest.php @@ -2,35 +2,23 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; - -class DateDifTest extends TestCase +class DateDifTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - /** * @dataProvider providerDATEDIF * * @param mixed $expectedResult - * @param $startDate - * @param $endDate - * @param $unit */ - public function testDATEDIF($expectedResult, $startDate, $endDate, $unit): void + public function testDATEDIF($expectedResult, string $formula): void { - $result = DateTime::DATEDIF($startDate, $endDate, $unit); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('B1')->setValue('1954-11-23'); + $sheet->getCell('A1')->setValue("=DATEDIF($formula)"); + self::assertSame($expectedResult, $sheet->getCell('A1')->getCalculatedValue()); } - public function providerDATEDIF() + public function providerDATEDIF(): array { return require 'tests/data/Calculation/DateTime/DATEDIF.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/DateTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/DateTest.php index 48f7cfd7..5e884707 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/DateTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/DateTest.php @@ -2,53 +2,42 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; +use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Date; -class DateTest extends TestCase +class DateTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - /** * @dataProvider providerDATE * * @param mixed $expectedResult - * @param $year - * @param $month - * @param $day */ - public function testDATE($expectedResult, $year, $month, $day): void + public function testDATE($expectedResult, string $formula): void { - $result = DateTime::DATE($year, $month, $day); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('B1')->setValue('1954-11-23'); + $sheet->getCell('A1')->setValue("=DATE($formula)"); + self::assertEquals($expectedResult, $sheet->getCell('A1')->getCalculatedValue()); } - public function providerDATE() + public function providerDATE(): array { return require 'tests/data/Calculation/DateTime/DATE.php'; } public function testDATEtoUnixTimestamp(): void { - Functions::setReturnDateType(Functions::RETURNDATE_UNIX_TIMESTAMP); + self::setUnixReturn(); - $result = DateTime::DATE(2012, 1, 31); + $result = Date::fromYMD(2012, 1, 31); // 32-bit safe self::assertEquals(1327968000, $result); - self::assertEqualsWithDelta(1327968000, $result, 1E-8); } public function testDATEtoDateTimeObject(): void { - Functions::setReturnDateType(Functions::RETURNDATE_PHP_DATETIME_OBJECT); + self::setObjectReturn(); - $result = DateTime::DATE(2012, 1, 31); + $result = Date::fromYMD(2012, 1, 31); // Must return an object... self::assertIsObject($result); // ... of the correct type @@ -59,17 +48,12 @@ class DateTest extends TestCase public function testDATEwith1904Calendar(): void { - Date::setExcelCalendar(Date::CALENDAR_MAC_1904); + self::setMac1904(); - $result = DateTime::DATE(1918, 11, 11); + $result = Date::fromYMD(1918, 11, 11); self::assertEquals($result, 5428); - } - public function testDATEwith1904CalendarError(): void - { - Date::setExcelCalendar(Date::CALENDAR_MAC_1904); - - $result = DateTime::DATE(1901, 1, 31); + $result = Date::fromYMD(1901, 1, 31); self::assertEquals($result, '#NUM!'); } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/DateValueTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/DateValueTest.php index 51e4f7c0..521bde1f 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/DateValueTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/DateValueTest.php @@ -2,52 +2,60 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; +use DateTimeImmutable; use DateTimeInterface; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; +use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\DateValue; -class DateValueTest extends TestCase +class DateValueTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - /** * @dataProvider providerDATEVALUE * * @param mixed $expectedResult - * @param $dateValue */ - public function testDATEVALUE($expectedResult, $dateValue): void + public function testDATEVALUE($expectedResult, string $dateValue): void { - $result = DateTime::DATEVALUE($dateValue); + $this->getSheet()->getCell('B1')->setValue('1954-07-20'); + // Loop to avoid extraordinarily rare edge case where first calculation + // and second do not take place on same day. + $row = 0; + do { + ++$row; + $dtStart = new DateTimeImmutable(); + $startDay = $dtStart->format('d'); + if (is_string($expectedResult)) { + $replYMD = str_replace('Y', date('Y'), $expectedResult); + if ($replYMD !== $expectedResult) { + $expectedResult = DateValue::fromString($replYMD); + } + } + $this->getSheet()->getCell("A$row")->setValue("=DATEVALUE($dateValue)"); + $result = $this->getSheet()->getCell("A$row")->getCalculatedValue(); + $dtEnd = new DateTimeImmutable(); + $endDay = $dtEnd->format('d'); + } while ($startDay !== $endDay); self::assertEqualsWithDelta($expectedResult, $result, 1E-8); } - public function providerDATEVALUE() + public function providerDATEVALUE(): array { return require 'tests/data/Calculation/DateTime/DATEVALUE.php'; } public function testDATEVALUEtoUnixTimestamp(): void { - Functions::setReturnDateType(Functions::RETURNDATE_UNIX_TIMESTAMP); + self::setUnixReturn(); - $result = DateTime::DATEVALUE('2012-1-31'); + $result = DateValue::fromString('2012-1-31'); self::assertEquals(1327968000, $result); self::assertEqualsWithDelta(1327968000, $result, 1E-8); } public function testDATEVALUEtoDateTimeObject(): void { - Functions::setReturnDateType(Functions::RETURNDATE_PHP_DATETIME_OBJECT); + self::setObjectReturn(); - $result = DateTime::DATEVALUE('2012-1-31'); + $result = DateValue::fromString('2012-1-31'); // Must return an object... self::assertIsObject($result); // ... of the correct type @@ -55,4 +63,13 @@ class DateValueTest extends TestCase // ... with the correct value self::assertEquals($result->format('d-M-Y'), '31-Jan-2012'); } + + public function testDATEVALUEwith1904Calendar(): void + { + self::setMac1904(); + self::assertEquals(5428, DateValue::fromString('1918-11-11')); + self::assertEquals(0, DateValue::fromString('1904-01-01')); + self::assertEquals('#VALUE!', DateValue::fromString('1903-12-31')); + self::assertEquals('#VALUE!', DateValue::fromString('1900-02-29')); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/DayTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/DayTest.php index 482e068d..af196050 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/DayTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/DayTest.php @@ -2,56 +2,43 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; - -class DayTest extends TestCase +class DayTest extends AllSetupTeardown { - private $compatibilityMode; - - private $returnDateType; - - private $excelCalendar; - - protected function setUp(): void - { - $this->compatibilityMode = Functions::getCompatibilityMode(); - $this->returnDateType = Functions::getReturnDateType(); - $this->excelCalendar = Date::getExcelCalendar(); - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - - protected function tearDown(): void - { - Functions::setCompatibilityMode($this->compatibilityMode); - Functions::setReturnDateType($this->returnDateType); - Date::setExcelCalendar($this->excelCalendar); - } - /** * @dataProvider providerDAY * * @param mixed $expectedResultExcel - * @param mixed $expectedResultOpenOffice - * @param $dateTimeValue */ - public function testDAY($expectedResultExcel, $expectedResultOpenOffice, $dateTimeValue): void + public function testDAY($expectedResultExcel, string $dateTimeValue): void { - $resultExcel = DateTime::DAYOFMONTH($dateTimeValue); - self::assertEqualsWithDelta($expectedResultExcel, $resultExcel, 1E-8); - - Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); - - $resultOpenOffice = DateTime::DAYOFMONTH($dateTimeValue); - self::assertEqualsWithDelta($expectedResultOpenOffice, $resultOpenOffice, 1E-8); + $this->mightHaveException($expectedResultExcel); + $sheet = $this->getSheet(); + $sheet->getCell('B1')->setValue('1954-11-23'); + $sheet->getCell('A1')->setValue("=DAY($dateTimeValue)"); + self::assertSame($expectedResultExcel, $sheet->getCell('A1')->getCalculatedValue()); } - public function providerDAY() + public function providerDAY(): array { return require 'tests/data/Calculation/DateTime/DAY.php'; } + + /** + * @dataProvider providerDAYOpenOffice + * + * @param mixed $expectedResultOpenOffice + */ + public function testDAYOpenOffice($expectedResultOpenOffice, string $dateTimeValue): void + { + self::setOpenOffice(); + $this->mightHaveException($expectedResultOpenOffice); + $sheet = $this->getSheet(); + $sheet->getCell('A2')->setValue("=DAY($dateTimeValue)"); + self::assertSame($expectedResultOpenOffice, $sheet->getCell('A2')->getCalculatedValue()); + } + + public function providerDAYOpenOffice(): array + { + return require 'tests/data/Calculation/DateTime/DAYOpenOffice.php'; + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/Days360Test.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/Days360Test.php index 47449e0d..5a3e235d 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/Days360Test.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/Days360Test.php @@ -2,35 +2,24 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; - -class Days360Test extends TestCase +class Days360Test extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - /** * @dataProvider providerDAYS360 * * @param mixed $expectedResult - * @param $startDate - * @param $endDate - * @param $method */ - public function testDAYS360($expectedResult, $startDate, $endDate, $method): void + public function testDAYS360($expectedResult, string $formula): void { - $result = DateTime::DAYS360($startDate, $endDate, $method); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('B1')->setValue('2000-02-29'); + $sheet->getCell('C1')->setValue('2000-03-31'); + $sheet->getCell('A1')->setValue("=DAYS360($formula)"); + self::assertSame($expectedResult, $sheet->getCell('A1')->getCalculatedValue()); } - public function providerDAYS360() + public function providerDAYS360(): array { return require 'tests/data/Calculation/DateTime/DAYS360.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/DaysTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/DaysTest.php index fe31dfcc..a63e45cc 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/DaysTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/DaysTest.php @@ -2,35 +2,44 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; +use DateTime; +use DateTimeImmutable; +use Exception; +use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Days; -class DaysTest extends TestCase +class DaysTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - /** * @dataProvider providerDAYS * * @param mixed $expectedResult - * @param $endDate - * @param $startDate */ - public function testDAYS($expectedResult, $endDate, $startDate): void + public function testDAYS($expectedResult, string $formula): void { - $result = DateTime::DAYS($endDate, $startDate); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('B1')->setValue('1954-11-23'); + $sheet->getCell('C1')->setValue('1954-11-30'); + $sheet->getCell('A1')->setValue("=DAYS($formula)"); + self::assertSame($expectedResult, $sheet->getCell('A1')->getCalculatedValue()); } - public function providerDAYS() + public function providerDAYS(): array { return require 'tests/data/Calculation/DateTime/DAYS.php'; } + + public function testObject(): void + { + $obj1 = new DateTime('2000-3-31'); + $obj2 = new DateTimeImmutable('2000-2-29'); + self::assertSame(31, Days::between($obj1, $obj2)); + } + + public function testNonDateObject(): void + { + $obj1 = new Exception(); + $obj2 = new DateTimeImmutable('2000-2-29'); + self::assertSame('#VALUE!', Days::between($obj1, $obj2)); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/EDateTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/EDateTest.php index a887ba5b..22613fe5 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/EDateTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/EDateTest.php @@ -2,52 +2,43 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; +use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Month; -class EDateTest extends TestCase +class EDateTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - /** * @dataProvider providerEDATE * * @param mixed $expectedResult - * @param $dateValue - * @param $adjustmentMonths */ - public function testEDATE($expectedResult, $dateValue, $adjustmentMonths): void + public function testEDATE($expectedResult, string $formula): void { - $result = DateTime::EDATE($dateValue, $adjustmentMonths); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue("=EDATE($formula)"); + $sheet->getCell('B1')->setValue('1954-11-23'); + self::assertEquals($expectedResult, $sheet->getCell('A1')->getCalculatedValue()); } - public function providerEDATE() + public function providerEDATE(): array { return require 'tests/data/Calculation/DateTime/EDATE.php'; } public function testEDATEtoUnixTimestamp(): void { - Functions::setReturnDateType(Functions::RETURNDATE_UNIX_TIMESTAMP); + self::setUnixReturn(); - $result = DateTime::EDATE('2012-1-26', -1); + $result = Month::adjust('2012-1-26', -1); self::assertEquals(1324857600, $result); self::assertEqualsWithDelta(1324857600, $result, 1E-8); } public function testEDATEtoDateTimeObject(): void { - Functions::setReturnDateType(Functions::RETURNDATE_PHP_DATETIME_OBJECT); + self::setObjectReturn(); - $result = DateTime::EDATE('2012-1-26', -1); + $result = Month::adjust('2012-1-26', -1); // Must return an object... self::assertIsObject($result); // ... of the correct type diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/EoMonthTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/EoMonthTest.php index f9c54039..3c39fbbc 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/EoMonthTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/EoMonthTest.php @@ -2,57 +2,47 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; +use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Month; -class EoMonthTest extends TestCase +class EoMonthTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - /** * @dataProvider providerEOMONTH * * @param mixed $expectedResult - * @param $dateValue - * @param $adjustmentMonths */ - public function testEOMONTH($expectedResult, $dateValue, $adjustmentMonths): void + public function testEOMONTH($expectedResult, string $formula): void { - $result = DateTime::EOMONTH($dateValue, $adjustmentMonths); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue("=EOMONTH($formula)"); + $sheet->getCell('B1')->setValue('1954-11-23'); + self::assertEquals($expectedResult, $sheet->getCell('A1')->getCalculatedValue()); } - public function providerEOMONTH() + public function providerEOMONTH(): array { return require 'tests/data/Calculation/DateTime/EOMONTH.php'; } public function testEOMONTHtoUnixTimestamp(): void { - Functions::setReturnDateType(Functions::RETURNDATE_UNIX_TIMESTAMP); + self::setUnixReturn(); - $result = DateTime::EOMONTH('2012-1-26', -1); + $result = Month::lastDay('2012-1-26', -1); self::assertEquals(1325289600, $result); - self::assertEqualsWithDelta(1325289600, $result, 1E-8); } public function testEOMONTHtoDateTimeObject(): void { - Functions::setReturnDateType(Functions::RETURNDATE_PHP_DATETIME_OBJECT); + self::setObjectReturn(); - $result = DateTime::EOMONTH('2012-1-26', -1); + $result = Month::lastDay('2012-1-26', -1); // Must return an object... self::assertIsObject($result); // ... of the correct type self::assertTrue(is_a($result, 'DateTimeInterface')); // ... with the correct value - self::assertEquals($result->format('d-M-Y'), '31-Dec-2011'); + self::assertSame($result->format('d-M-Y'), '31-Dec-2011'); } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/HourTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/HourTest.php index 2d0cd5d1..c1e4f29c 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/HourTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/HourTest.php @@ -2,33 +2,23 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; - -class HourTest extends TestCase +class HourTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - /** * @dataProvider providerHOUR * * @param mixed $expectedResult - * @param $dateTimeValue */ - public function testHOUR($expectedResult, $dateTimeValue): void + public function testHOUR($expectedResult, string $dateTimeValue): void { - $result = DateTime::HOUROFDAY($dateTimeValue); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue("=HOUR($dateTimeValue)"); + $sheet->getCell('B1')->setValue('1954-11-23 2:23:46'); + self::assertSame($expectedResult, $sheet->getCell('A1')->getCalculatedValue()); } - public function providerHOUR() + public function providerHOUR(): array { return require 'tests/data/Calculation/DateTime/HOUR.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/IsoWeekNumTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/IsoWeekNumTest.php index 1ef0080a..29e35b38 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/IsoWeekNumTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/IsoWeekNumTest.php @@ -2,34 +2,46 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; - -class IsoWeekNumTest extends TestCase +class IsoWeekNumTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - /** * @dataProvider providerISOWEEKNUM * * @param mixed $expectedResult - * @param mixed $dateValue + * @param string $dateValue */ public function testISOWEEKNUM($expectedResult, $dateValue): void { - $result = DateTime::ISOWEEKNUM($dateValue); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue("=ISOWEEKNUM($dateValue)"); + $sheet->getCell('B1')->setValue('1954-11-23'); + self::assertSame($expectedResult, $sheet->getCell('A1')->getCalculatedValue()); } - public function providerISOWEEKNUM() + public function providerISOWEEKNUM(): array { return require 'tests/data/Calculation/DateTime/ISOWEEKNUM.php'; } + + /** + * @dataProvider providerISOWEEKNUM1904 + * + * @param mixed $expectedResult + * @param string $dateValue + */ + public function testISOWEEKNUM1904($expectedResult, $dateValue): void + { + $this->mightHaveException($expectedResult); + self::setMac1904(); + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue("=ISOWEEKNUM($dateValue)"); + $sheet->getCell('B1')->setValue('1954-11-23'); + self::assertSame($expectedResult, $sheet->getCell('A1')->getCalculatedValue()); + } + + public function providerISOWEEKNUM1904(): array + { + return require 'tests/data/Calculation/DateTime/ISOWEEKNUM1904.php'; + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/MinuteTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/MinuteTest.php index 8472c6de..b5207d7e 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/MinuteTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/MinuteTest.php @@ -2,33 +2,23 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; - -class MinuteTest extends TestCase +class MinuteTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - /** * @dataProvider providerMINUTE * * @param mixed $expectedResult - * @param $dateTimeValue */ - public function testMINUTE($expectedResult, $dateTimeValue): void + public function testMINUTE($expectedResult, string $dateTimeValue): void { - $result = DateTime::MINUTE($dateTimeValue); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue("=MINUTE($dateTimeValue)"); + $sheet->getCell('B1')->setValue('1954-11-23 2:23:46'); + self::assertSame($expectedResult, $sheet->getCell('A1')->getCalculatedValue()); } - public function providerMINUTE() + public function providerMINUTE(): array { return require 'tests/data/Calculation/DateTime/MINUTE.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/MonthTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/MonthTest.php index 62513702..30465e87 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/MonthTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/MonthTest.php @@ -2,33 +2,23 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; - -class MonthTest extends TestCase +class MonthTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - /** * @dataProvider providerMONTH * * @param mixed $expectedResult - * @param $dateTimeValue */ - public function testMONTH($expectedResult, $dateTimeValue): void + public function testMONTH($expectedResult, string $dateTimeValue): void { - $result = DateTime::MONTHOFYEAR($dateTimeValue); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue("=MONTH($dateTimeValue)"); + $sheet->getCell('B1')->setValue('1954-11-23'); + self::assertSame($expectedResult, $sheet->getCell('A1')->getCalculatedValue()); } - public function providerMONTH() + public function providerMONTH(): array { return require 'tests/data/Calculation/DateTime/MONTH.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/MovedFunctionsTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/MovedFunctionsTest.php new file mode 100644 index 00000000..d14f7d7d --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/MovedFunctionsTest.php @@ -0,0 +1,63 @@ +format('s'); + $nowResult = DateTime::DATETIMENOW(); + $todayResult = DateTime::DATENOW(); + $dtEnd = new DateTimeImmutable(); + $endSecond = $dtEnd->format('s'); + } while ($startSecond !== $endSecond); + self::assertSame(DateTime::DAYOFMONTH($nowResult), DateTime::DAYOFMONTH($todayResult)); + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/NetworkDaysTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/NetworkDaysTest.php index e366c44e..d6b1a89f 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/NetworkDaysTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/NetworkDaysTest.php @@ -2,32 +2,50 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; - -class NetworkDaysTest extends TestCase +class NetworkDaysTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - /** * @dataProvider providerNETWORKDAYS * * @param mixed $expectedResult + * @param mixed $arg1 + * @param mixed $arg2 */ - public function testNETWORKDAYS($expectedResult, ...$args): void + public function testNETWORKDAYS($expectedResult, $arg1 = 'omitted', $arg2 = 'omitted', ?array $arg3 = null): void { - $result = DateTime::NETWORKDAYS(...$args); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($arg1 !== null) { + $sheet->getCell('A1')->setValue($arg1); + } + if ($arg2 !== null) { + $sheet->getCell('A2')->setValue($arg2); + } + $dateArray = []; + if (is_array($arg3)) { + if (array_key_exists(0, $arg3) && is_array($arg3[0])) { + $dateArray = $arg3[0]; + } else { + $dateArray = $arg3; + } + } + $dateIndex = 0; + foreach ($dateArray as $date) { + ++$dateIndex; + $sheet->getCell("C$dateIndex")->setValue($date); + } + $arrayArg = $dateIndex ? ", C1:C$dateIndex" : ''; + if ($arg1 === 'omitted') { + $sheet->getCell('B1')->setValue('=NETWORKDAYS()'); + } elseif ($arg2 === 'omitted') { + $sheet->getCell('B1')->setValue('=NETWORKDAYS(A1)'); + } else { + $sheet->getCell('B1')->setValue("=NETWORKDAYS(A1, A2$arrayArg)"); + } + self::assertEquals($expectedResult, $sheet->getCell('B1')->getCalculatedValue()); } - public function providerNETWORKDAYS() + public function providerNETWORKDAYS(): array { return require 'tests/data/Calculation/DateTime/NETWORKDAYS.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/NowTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/NowTest.php new file mode 100644 index 00000000..05e9d411 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/NowTest.php @@ -0,0 +1,38 @@ +getSheet(); + $row = 0; + // Loop to avoid rare edge case where first calculation + // and second do not take place in same second. + do { + ++$row; + $dtStart = new DateTimeImmutable(); + $startSecond = $dtStart->format('s'); + $sheet->setCellValue("A$row", '=NOW()'); + // cache result for later assertions + $sheet->getCell("A$row")->getCalculatedValue(); + $dtEnd = new DateTimeImmutable(); + $endSecond = $dtEnd->format('s'); + } while ($startSecond !== $endSecond); + $sheet->setCellValue("B$row", "=YEAR(A$row)"); + $sheet->setCellValue("C$row", "=MONTH(A$row)"); + $sheet->setCellValue("D$row", "=DAY(A$row)"); + $sheet->setCellValue("E$row", "=HOUR(A$row)"); + $sheet->setCellValue("F$row", "=MINUTE(A$row)"); + $sheet->setCellValue("G$row", "=SECOND(A$row)"); + self::assertEquals($dtStart->format('Y'), $sheet->getCell("B$row")->getCalculatedValue()); + self::assertEquals($dtStart->format('m'), $sheet->getCell("C$row")->getCalculatedValue()); + self::assertEquals($dtStart->format('d'), $sheet->getCell("D$row")->getCalculatedValue()); + self::assertEquals($dtStart->format('H'), $sheet->getCell("E$row")->getCalculatedValue()); + self::assertEquals($dtStart->format('i'), $sheet->getCell("F$row")->getCalculatedValue()); + self::assertEquals($dtStart->format('s'), $sheet->getCell("G$row")->getCalculatedValue()); + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/SecondTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/SecondTest.php index bc2b0752..1a411d45 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/SecondTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/SecondTest.php @@ -2,33 +2,23 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; - -class SecondTest extends TestCase +class SecondTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - /** * @dataProvider providerSECOND * * @param mixed $expectedResult - * @param $dateTimeValue */ - public function testSECOND($expectedResult, $dateTimeValue): void + public function testSECOND($expectedResult, string $dateTimeValue): void { - $result = DateTime::SECOND($dateTimeValue); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue("=SECOND($dateTimeValue)"); + $sheet->getCell('B1')->setValue('1954-11-23 2:23:46'); + self::assertSame($expectedResult, $sheet->getCell('A1')->getCalculatedValue()); } - public function providerSECOND() + public function providerSECOND(): array { return require 'tests/data/Calculation/DateTime/SECOND.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/TimeTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/TimeTest.php index 344061d4..3ee1aa55 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/TimeTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/TimeTest.php @@ -2,49 +2,44 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; +use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Time; -class TimeTest extends TestCase +class TimeTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - /** * @dataProvider providerTIME * * @param mixed $expectedResult */ - public function testTIME($expectedResult, ...$args): void + public function testTIME($expectedResult, string $formula): void { - $result = DateTime::TIME(...$args); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('B1')->setValue('15'); + $sheet->getCell('B2')->setValue('32'); + $sheet->getCell('B3')->setValue('50'); + $sheet->getCell('A1')->setValue("=TIME($formula)"); + self::assertEqualsWithDelta($expectedResult, $sheet->getCell('A1')->getCalculatedValue(), 1E-8); } - public function providerTIME() + public function providerTIME(): array { return require 'tests/data/Calculation/DateTime/TIME.php'; } public function testTIMEtoUnixTimestamp(): void { - Functions::setReturnDateType(Functions::RETURNDATE_PHP_NUMERIC); + self::setUnixReturn(); - $result = DateTime::TIME(7, 30, 20); + $result = Time::fromHMS(7, 30, 20); self::assertEqualsWithDelta(27020, $result, 1E-8); } public function testTIMEtoDateTimeObject(): void { - Functions::setReturnDateType(Functions::RETURNDATE_PHP_OBJECT); + self::setObjectReturn(); - $result = DateTime::TIME(7, 30, 20); + $result = Time::fromHMS(7, 30, 20); // Must return an object... self::assertIsObject($result); // ... of the correct type @@ -52,4 +47,17 @@ class TimeTest extends TestCase // ... with the correct value self::assertEquals($result->format('H:i:s'), '07:30:20'); } + + public function testTIME1904(): void + { + self::setMac1904(); + $result = Time::fromHMS(0, 0, 0); + self::assertEquals(0, $result); + } + + public function testTIME1900(): void + { + $result = Time::fromHMS(0, 0, 0); + self::assertEquals(0, $result); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/TimeValueTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/TimeValueTest.php index 04b8c058..6995c312 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/TimeValueTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/TimeValueTest.php @@ -2,51 +2,45 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; +use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\TimeValue; -class TimeValueTest extends TestCase +class TimeValueTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - /** * @dataProvider providerTIMEVALUE * * @param mixed $expectedResult - * @param $timeValue + * @param mixed $timeValue */ public function testTIMEVALUE($expectedResult, $timeValue): void { - $result = DateTime::TIMEVALUE($timeValue); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('B1')->setValue('03:45:52'); + $sheet->getCell('A1')->setValue("=TIMEVALUE($timeValue)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-8); } - public function providerTIMEVALUE() + public function providerTIMEVALUE(): array { return require 'tests/data/Calculation/DateTime/TIMEVALUE.php'; } public function testTIMEVALUEtoUnixTimestamp(): void { - Functions::setReturnDateType(Functions::RETURNDATE_UNIX_TIMESTAMP); + self::setUnixReturn(); - $result = DateTime::TIMEVALUE('7:30:20'); + $result = TimeValue::fromString('7:30:20'); self::assertEquals(23420, $result); self::assertEqualsWithDelta(23420, $result, 1E-8); } public function testTIMEVALUEtoDateTimeObject(): void { - Functions::setReturnDateType(Functions::RETURNDATE_PHP_DATETIME_OBJECT); + self::setObjectReturn(); - $result = DateTime::TIMEVALUE('7:30:20'); + $result = TimeValue::fromString('7:30:20'); // Must return an object... self::assertIsObject($result); // ... of the correct type diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/TodayTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/TodayTest.php new file mode 100644 index 00000000..518623b5 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/TodayTest.php @@ -0,0 +1,38 @@ +getSheet(); + $row = 0; + // Loop to avoid rare edge case where first calculation + // and second do not take place in same second. + do { + ++$row; + $dtStart = new DateTimeImmutable(); + $startSecond = $dtStart->format('s'); + $sheet->setCellValue("A$row", '=TODAY()'); + // cache result for later assertions + $sheet->getCell("A$row")->getCalculatedValue(); + $dtEnd = new DateTimeImmutable(); + $endSecond = $dtEnd->format('s'); + } while ($startSecond !== $endSecond); + $sheet->setCellValue("B$row", "=YEAR(A$row)"); + $sheet->setCellValue("C$row", "=MONTH(A$row)"); + $sheet->setCellValue("D$row", "=DAY(A$row)"); + $sheet->setCellValue("E$row", "=HOUR(A$row)"); + $sheet->setCellValue("F$row", "=MINUTE(A$row)"); + $sheet->setCellValue("G$row", "=SECOND(A$row)"); + self::assertSame((int) $dtStart->format('Y'), $sheet->getCell("B$row")->getCalculatedValue()); + self::assertSame((int) $dtStart->format('m'), $sheet->getCell("C$row")->getCalculatedValue()); + self::assertSame((int) $dtStart->format('d'), $sheet->getCell("D$row")->getCalculatedValue()); + self::assertSame(0, $sheet->getCell("E$row")->getCalculatedValue()); + self::assertSame(0, $sheet->getCell("F$row")->getCalculatedValue()); + self::assertSame(0, $sheet->getCell("G$row")->getCalculatedValue()); + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/WeekDayTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/WeekDayTest.php index c5b89e01..3c7f682d 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/WeekDayTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/WeekDayTest.php @@ -2,33 +2,34 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; +use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Week; -class WeekDayTest extends TestCase +class WeekDayTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - /** * @dataProvider providerWEEKDAY * * @param mixed $expectedResult */ - public function testWEEKDAY($expectedResult, ...$args): void + public function testWEEKDAY($expectedResult, string $formula): void { - $result = DateTime::WEEKDAY(...$args); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('B1')->setValue('1954-11-23'); + $sheet->getCell('A1')->setValue("=WEEKDAY($formula)"); + self::assertSame($expectedResult, $sheet->getCell('A1')->getCalculatedValue()); } - public function providerWEEKDAY() + public function providerWEEKDAY(): array { return require 'tests/data/Calculation/DateTime/WEEKDAY.php'; } + + public function testWEEKDAYwith1904Calendar(): void + { + self::setMac1904(); + self::assertEquals(7, Week::day('1904-01-02')); + self::assertEquals(6, Week::day('1904-01-01')); + self::assertEquals(6, Week::day(null)); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/WeekNumTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/WeekNumTest.php index 9d8e1eb2..caa71f17 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/WeekNumTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/WeekNumTest.php @@ -2,33 +2,44 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; - -class WeekNumTest extends TestCase +class WeekNumTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - /** * @dataProvider providerWEEKNUM * * @param mixed $expectedResult */ - public function testWEEKNUM($expectedResult, ...$args): void + public function testWEEKNUM($expectedResult, string $formula): void { - $result = DateTime::WEEKNUM(...$args); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('B1')->setValue('1954-11-23'); + $sheet->getCell('A1')->setValue("=WEEKNUM($formula)"); + self::assertSame($expectedResult, $sheet->getCell('A1')->getCalculatedValue()); } - public function providerWEEKNUM() + public function providerWEEKNUM(): array { return require 'tests/data/Calculation/DateTime/WEEKNUM.php'; } + + /** + * @dataProvider providerWEEKNUM1904 + * + * @param mixed $expectedResult + */ + public function testWEEKNUM1904($expectedResult, string $formula): void + { + $this->mightHaveException($expectedResult); + self::setMac1904(); + $sheet = $this->getSheet(); + $sheet->getCell('B1')->setValue('1954-11-23'); + $sheet->getCell('A1')->setValue("=WEEKNUM($formula)"); + self::assertSame($expectedResult, $sheet->getCell('A1')->getCalculatedValue()); + } + + public function providerWEEKNUM1904(): array + { + return require 'tests/data/Calculation/DateTime/WEEKNUM1904.php'; + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/WorkDayTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/WorkDayTest.php index 4784e463..3cfa9219 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/WorkDayTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/WorkDayTest.php @@ -2,32 +2,50 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; - -class WorkDayTest extends TestCase +class WorkDayTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - /** * @dataProvider providerWORKDAY * * @param mixed $expectedResult + * @param mixed $arg1 + * @param mixed $arg2 */ - public function testWORKDAY($expectedResult, ...$args): void + public function testWORKDAY($expectedResult, $arg1 = 'omitted', $arg2 = 'omitted', ?array $arg3 = null): void { - $result = DateTime::WORKDAY(...$args); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($arg1 !== null) { + $sheet->getCell('A1')->setValue($arg1); + } + if ($arg2 !== null) { + $sheet->getCell('A2')->setValue($arg2); + } + $dateArray = []; + if (is_array($arg3)) { + if (array_key_exists(0, $arg3) && is_array($arg3[0])) { + $dateArray = $arg3[0]; + } else { + $dateArray = $arg3; + } + } + $dateIndex = 0; + foreach ($dateArray as $date) { + ++$dateIndex; + $sheet->getCell("C$dateIndex")->setValue($date); + } + $arrayArg = $dateIndex ? ", C1:C$dateIndex" : ''; + if ($arg1 === 'omitted') { + $sheet->getCell('B1')->setValue('=WORKDAY()'); + } elseif ($arg2 === 'omitted') { + $sheet->getCell('B1')->setValue('=WORKDAY(A1)'); + } else { + $sheet->getCell('B1')->setValue("=WORKDAY(A1, A2$arrayArg)"); + } + self::assertEquals($expectedResult, $sheet->getCell('B1')->getCalculatedValue()); } - public function providerWORKDAY() + public function providerWORKDAY(): array { return require 'tests/data/Calculation/DateTime/WORKDAY.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/YearFracTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/YearFracTest.php index 05f11310..d7427bfd 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/YearFracTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/YearFracTest.php @@ -2,32 +2,42 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; - -class YearFracTest extends TestCase +class YearFracTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - /** * @dataProvider providerYEARFRAC * * @param mixed $expectedResult + * @param mixed $arg1 + * @param mixed $arg2 + * @param mixed $arg3 */ - public function testYEARFRAC($expectedResult, ...$args): void + public function testYEARFRAC($expectedResult, $arg1 = 'omitted', $arg2 = 'omitted', $arg3 = 'omitted'): void { - $result = DateTime::YEARFRAC(...$args); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($arg1 !== null) { + $sheet->getCell('A1')->setValue($arg1); + } + if ($arg2 !== null) { + $sheet->getCell('A2')->setValue($arg2); + } + if ($arg3 !== null) { + $sheet->getCell('A3')->setValue($arg3); + } + if ($arg1 === 'omitted') { + $sheet->getCell('B1')->setValue('=YEARFRAC()'); + } elseif ($arg2 === 'omitted') { + $sheet->getCell('B1')->setValue('=YEARFRAC(A1)'); + } elseif ($arg3 === 'omitted') { + $sheet->getCell('B1')->setValue('=YEARFRAC(A1, A2)'); + } else { + $sheet->getCell('B1')->setValue('=YEARFRAC(A1, A2, A3)'); + } + self::assertEqualswithDelta($expectedResult, $sheet->getCell('B1')->getCalculatedValue(), 1E-6); } - public function providerYEARFRAC() + public function providerYEARFRAC(): array { return require 'tests/data/Calculation/DateTime/YEARFRAC.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/YearTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/YearTest.php index bbdaf92a..a31ac7aa 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/YearTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/DateTime/YearTest.php @@ -2,33 +2,23 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PHPUnit\Framework\TestCase; - -class YearTest extends TestCase +class YearTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - } - /** * @dataProvider providerYEAR * * @param mixed $expectedResult - * @param $dateTimeValue */ - public function testYEAR($expectedResult, $dateTimeValue): void + public function testYEAR($expectedResult, string $dateTimeValue): void { - $result = DateTime::YEAR($dateTimeValue); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue("=YEAR($dateTimeValue)"); + $sheet->getCell('B1')->setValue('1954-11-23'); + self::assertSame($expectedResult, $sheet->getCell('A1')->getCalculatedValue()); } - public function providerYEAR() + public function providerYEAR(): array { return require 'tests/data/Calculation/DateTime/YEAR.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BesselITest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BesselITest.php index 8fff98af..d24a0208 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BesselITest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BesselITest.php @@ -8,7 +8,7 @@ use PHPUnit\Framework\TestCase; class BesselITest extends TestCase { - const BESSEL_PRECISION = 1E-8; + const BESSEL_PRECISION = 1E-9; protected function setUp(): void { @@ -26,7 +26,7 @@ class BesselITest extends TestCase self::assertEqualsWithDelta($expectedResult, $result, self::BESSEL_PRECISION); } - public function providerBESSELI() + public function providerBESSELI(): array { return require 'tests/data/Calculation/Engineering/BESSELI.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BesselJTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BesselJTest.php index d10f028f..325a0d64 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BesselJTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BesselJTest.php @@ -26,7 +26,7 @@ class BesselJTest extends TestCase self::assertEqualsWithDelta($expectedResult, $result, self::BESSEL_PRECISION); } - public function providerBESSEJ() + public function providerBESSEJ(): array { return require 'tests/data/Calculation/Engineering/BESSELJ.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BesselKTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BesselKTest.php index 27123a26..51725d38 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BesselKTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BesselKTest.php @@ -8,7 +8,7 @@ use PHPUnit\Framework\TestCase; class BesselKTest extends TestCase { - const BESSEL_PRECISION = 1E-8; + const BESSEL_PRECISION = 1E-12; protected function setUp(): void { @@ -26,7 +26,7 @@ class BesselKTest extends TestCase self::assertEqualsWithDelta($expectedResult, $result, self::BESSEL_PRECISION); } - public function providerBESSELK() + public function providerBESSELK(): array { return require 'tests/data/Calculation/Engineering/BESSELK.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BesselYTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BesselYTest.php index ab55f0ac..1e8d863f 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BesselYTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BesselYTest.php @@ -8,7 +8,7 @@ use PHPUnit\Framework\TestCase; class BesselYTest extends TestCase { - const BESSEL_PRECISION = 1E-8; + const BESSEL_PRECISION = 1E-12; protected function setUp(): void { @@ -26,7 +26,7 @@ class BesselYTest extends TestCase self::assertEqualsWithDelta($expectedResult, $result, self::BESSEL_PRECISION); } - public function providerBESSELY() + public function providerBESSELY(): array { return require 'tests/data/Calculation/Engineering/BESSELY.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Bin2DecTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Bin2DecTest.php index faba3de8..c0923d1a 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Bin2DecTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Bin2DecTest.php @@ -2,30 +2,92 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\Engineering; -use PhpOffice\PhpSpreadsheet\Calculation\Engineering; +use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PHPUnit\Framework\TestCase; class Bin2DecTest extends TestCase { + /** + * @var string + */ + private $compatibilityMode; + protected function setUp(): void { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $this->compatibilityMode = Functions::getCompatibilityMode(); + } + + protected function tearDown(): void + { + Functions::setCompatibilityMode($this->compatibilityMode); } /** * @dataProvider providerBIN2DEC * * @param mixed $expectedResult + * @param mixed $formula */ - public function testBIN2DEC($expectedResult, ...$args): void + public function testBin2Dec($expectedResult, $formula): void { - $result = Engineering::BINTODEC(...$args); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 101); + $sheet->getCell('A1')->setValue("=BIN2DEC($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerBIN2DEC() + public function providerBIN2DEC(): array { return require 'tests/data/Calculation/Engineering/BIN2DEC.php'; } + + /** + * @dataProvider providerBIN2DEC + * + * @param mixed $expectedResult + * @param mixed $formula + */ + public function testBIN2DECOds($expectedResult, $formula): void + { + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + if ($formula === 'true') { + $expectedResult = 1; + } elseif ($formula === 'false') { + $expectedResult = 0; + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 101); + $sheet->getCell('A1')->setValue("=BIN2DEC($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function testBIN2DECFrac(): void + { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_GNUMERIC); + $cell = 'G1'; + $sheet->setCellValue($cell, '=BIN2DEC(101.1)'); + self::assertEquals(5, $sheet->getCell($cell)->getCalculatedValue(), 'Gnumeric'); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + $cell = 'O1'; + $sheet->setCellValue($cell, '=BIN2DEC(101.1)'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue(), 'Ods'); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $cell = 'E1'; + $sheet->setCellValue($cell, '=BIN2DEC(101.1)'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue(), 'Excel'); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Bin2HexTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Bin2HexTest.php index 2a16d5ac..c95c375d 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Bin2HexTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Bin2HexTest.php @@ -2,30 +2,92 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\Engineering; -use PhpOffice\PhpSpreadsheet\Calculation\Engineering; +use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PHPUnit\Framework\TestCase; class Bin2HexTest extends TestCase { + /** + * @var string + */ + private $compatibilityMode; + protected function setUp(): void { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $this->compatibilityMode = Functions::getCompatibilityMode(); + } + + protected function tearDown(): void + { + Functions::setCompatibilityMode($this->compatibilityMode); } /** * @dataProvider providerBIN2HEX * * @param mixed $expectedResult + * @param mixed $formula */ - public function testBIN2HEX($expectedResult, ...$args): void + public function testBin2Hex($expectedResult, $formula): void { - $result = Engineering::BINTOHEX(...$args); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 101); + $sheet->getCell('A1')->setValue("=BIN2HEX($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerBIN2HEX() + public function providerBIN2HEX(): array { return require 'tests/data/Calculation/Engineering/BIN2HEX.php'; } + + /** + * @dataProvider providerBIN2HEX + * + * @param mixed $expectedResult + * @param mixed $formula + */ + public function testBIN2HEXOds($expectedResult, $formula): void + { + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + if ($formula === 'true') { + $expectedResult = 1; + } elseif ($formula === 'false') { + $expectedResult = 0; + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 101); + $sheet->getCell('A1')->setValue("=BIN2HEX($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function testBIN2HEXFrac(): void + { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_GNUMERIC); + $cell = 'G1'; + $sheet->setCellValue($cell, '=BIN2HEX(101.1)'); + self::assertEquals(5, $sheet->getCell($cell)->getCalculatedValue()); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + $cell = 'O1'; + $sheet->setCellValue($cell, '=BIN2HEX(101.1)'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue()); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $cell = 'E1'; + $sheet->setCellValue($cell, '=BIN2HEX(101.1)'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue()); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Bin2OctTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Bin2OctTest.php index 78db6a6e..ee54063c 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Bin2OctTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Bin2OctTest.php @@ -2,30 +2,92 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\Engineering; -use PhpOffice\PhpSpreadsheet\Calculation\Engineering; +use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PHPUnit\Framework\TestCase; class Bin2OctTest extends TestCase { + /** + * @var string + */ + private $compatibilityMode; + protected function setUp(): void { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $this->compatibilityMode = Functions::getCompatibilityMode(); + } + + protected function tearDown(): void + { + Functions::setCompatibilityMode($this->compatibilityMode); } /** * @dataProvider providerBIN2OCT * * @param mixed $expectedResult + * @param mixed $formula */ - public function testBIN2OCT($expectedResult, ...$args): void + public function testBin2Oct($expectedResult, $formula): void { - $result = Engineering::BINTOOCT(...$args); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 101); + $sheet->getCell('A1')->setValue("=BIN2OCT($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerBIN2OCT() + public function providerBIN2OCT(): array { return require 'tests/data/Calculation/Engineering/BIN2OCT.php'; } + + /** + * @dataProvider providerBIN2OCT + * + * @param mixed $expectedResult + * @param mixed $formula + */ + public function testBIN2OCTOds($expectedResult, $formula): void + { + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + if ($formula === 'true') { + $expectedResult = 1; + } elseif ($formula === 'false') { + $expectedResult = 0; + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 101); + $sheet->getCell('A1')->setValue("=BIN2OCT($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function testBIN2OCTFrac(): void + { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_GNUMERIC); + $cell = 'G1'; + $sheet->setCellValue($cell, '=BIN2OCT(101.1)'); + self::assertEquals(5, $sheet->getCell($cell)->getCalculatedValue()); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + $cell = 'O1'; + $sheet->setCellValue($cell, '=BIN2OCT(101.1)'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue()); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $cell = 'E1'; + $sheet->setCellValue($cell, '=BIN2OCT(101.1)'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue()); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BitAndTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BitAndTest.php index e73efccc..23682908 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BitAndTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BitAndTest.php @@ -2,30 +2,31 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\Engineering; -use PhpOffice\PhpSpreadsheet\Calculation\Engineering; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PHPUnit\Framework\TestCase; class BitAndTest extends TestCase { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerBITAND * * @param mixed $expectedResult - * @param mixed[] $args */ - public function testBITAND($expectedResult, array $args): void + public function testBITAND($expectedResult, string $formula): void { - $result = Engineering::BITAND(...$args); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 24); + $sheet->getCell('A1')->setValue("=BITAND($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerBITAND() + public function providerBITAND(): array { return require 'tests/data/Calculation/Engineering/BITAND.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BitLShiftTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BitLShiftTest.php index 61aa89b4..ee408497 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BitLShiftTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BitLShiftTest.php @@ -2,30 +2,31 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\Engineering; -use PhpOffice\PhpSpreadsheet\Calculation\Engineering; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PHPUnit\Framework\TestCase; class BitLShiftTest extends TestCase { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerBITLSHIFT * * @param mixed $expectedResult - * @param mixed[] $args */ - public function testBITLSHIFT($expectedResult, array $args): void + public function testBITLSHIFT($expectedResult, string $formula): void { - $result = Engineering::BITLSHIFT(...$args); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 8); + $sheet->getCell('A1')->setValue("=BITLSHIFT($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerBITLSHIFT() + public function providerBITLSHIFT(): array { return require 'tests/data/Calculation/Engineering/BITLSHIFT.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BitOrTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BitOrTest.php index 857c7466..3cc1f4bc 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BitOrTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BitOrTest.php @@ -2,30 +2,31 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\Engineering; -use PhpOffice\PhpSpreadsheet\Calculation\Engineering; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PHPUnit\Framework\TestCase; class BitOrTest extends TestCase { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerBITOR * * @param mixed $expectedResult - * @param mixed[] $args */ - public function testBITOR($expectedResult, array $args): void + public function testBITOR($expectedResult, string $formula): void { - $result = Engineering::BITOR(...$args); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 8); + $sheet->getCell('A1')->setValue("=BITOR($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerBITOR() + public function providerBITOR(): array { return require 'tests/data/Calculation/Engineering/BITOR.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BitRShiftTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BitRShiftTest.php index 26b13d07..f58d6149 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BitRShiftTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BitRShiftTest.php @@ -2,30 +2,31 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\Engineering; -use PhpOffice\PhpSpreadsheet\Calculation\Engineering; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PHPUnit\Framework\TestCase; class BitRShiftTest extends TestCase { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerBITRSHIFT * * @param mixed $expectedResult - * @param mixed[] $args */ - public function testBITRSHIFT($expectedResult, array $args): void + public function testBITRSHIFT($expectedResult, string $formula): void { - $result = Engineering::BITRSHIFT(...$args); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 8); + $sheet->getCell('A1')->setValue("=BITRSHIFT($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerBITRSHIFT() + public function providerBITRSHIFT(): array { return require 'tests/data/Calculation/Engineering/BITRSHIFT.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BitXorTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BitXorTest.php index 4415f6da..4fa302af 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BitXorTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/BitXorTest.php @@ -2,30 +2,31 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\Engineering; -use PhpOffice\PhpSpreadsheet\Calculation\Engineering; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PHPUnit\Framework\TestCase; class BitXorTest extends TestCase { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerBITXOR * * @param mixed $expectedResult - * @param mixed[] $args */ - public function testBITXOR($expectedResult, array $args): void + public function testBITXOR($expectedResult, string $formula): void { - $result = Engineering::BITXOR(...$args); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 8); + $sheet->getCell('A1')->setValue("=BITXOR($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerBITXOR() + public function providerBITXOR(): array { return require 'tests/data/Calculation/Engineering/BITXOR.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ComplexTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ComplexTest.php index 4b857e2d..f60315dc 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ComplexTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ComplexTest.php @@ -24,7 +24,7 @@ class ComplexTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerCOMPLEX() + public function providerCOMPLEX(): array { return require 'tests/data/Calculation/Engineering/COMPLEX.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ConvertUoMTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ConvertUoMTest.php index 7a18067f..87198edb 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ConvertUoMTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ConvertUoMTest.php @@ -37,6 +37,12 @@ class ConvertUoMTest extends TestCase self::assertIsArray($result); } + public function testGetBinaryConversionMultipliers(): void + { + $result = Engineering::getBinaryConversionMultipliers(); + self::assertIsArray($result); + } + /** * @dataProvider providerCONVERTUOM * @@ -48,7 +54,7 @@ class ConvertUoMTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerCONVERTUOM() + public function providerCONVERTUOM(): array { return require 'tests/data/Calculation/Engineering/CONVERTUOM.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Dec2BinTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Dec2BinTest.php index 3626ac6b..dfed3478 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Dec2BinTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Dec2BinTest.php @@ -2,30 +2,92 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\Engineering; -use PhpOffice\PhpSpreadsheet\Calculation\Engineering; +use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PHPUnit\Framework\TestCase; class Dec2BinTest extends TestCase { + /** + * @var string + */ + private $compatibilityMode; + protected function setUp(): void { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $this->compatibilityMode = Functions::getCompatibilityMode(); + } + + protected function tearDown(): void + { + Functions::setCompatibilityMode($this->compatibilityMode); } /** * @dataProvider providerDEC2BIN * * @param mixed $expectedResult + * @param mixed $formula */ - public function testDEC2BIN($expectedResult, ...$args): void + public function testDEC2BIN($expectedResult, $formula): void { - $result = Engineering::DECTOBIN(...$args); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 5); + $sheet->getCell('A1')->setValue("=DEC2BIN($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerDEC2BIN() + public function providerDEC2BIN(): array { return require 'tests/data/Calculation/Engineering/DEC2BIN.php'; } + + /** + * @dataProvider providerDEC2BIN + * + * @param mixed $expectedResult + * @param mixed $formula + */ + public function testDEC2BINOds($expectedResult, $formula): void + { + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + if ($formula === 'true') { + $expectedResult = 1; + } elseif ($formula === 'false') { + $expectedResult = 0; + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 5); + $sheet->getCell('A1')->setValue("=DEC2BIN($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function testDEC2BINFrac(): void + { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_GNUMERIC); + $cell = 'G1'; + $sheet->setCellValue($cell, '=DEC2BIN(5.1)'); + self::assertEquals(101, $sheet->getCell($cell)->getCalculatedValue(), 'Gnumeric'); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + $cell = 'O1'; + $sheet->setCellValue($cell, '=DEC2BIN(5.1)'); + self::assertEquals(101, $sheet->getCell($cell)->getCalculatedValue(), 'Ods'); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $cell = 'E1'; + $sheet->setCellValue($cell, '=DEC2BIN(5.1)'); + self::assertEquals(101, $sheet->getCell($cell)->getCalculatedValue(), 'Excel'); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Dec2HexTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Dec2HexTest.php index d191f620..ebe49464 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Dec2HexTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Dec2HexTest.php @@ -3,29 +3,99 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\Engineering; +use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PHPUnit\Framework\TestCase; class Dec2HexTest extends TestCase { + /** + * @var string + */ + private $compatibilityMode; + protected function setUp(): void { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $this->compatibilityMode = Functions::getCompatibilityMode(); + } + + protected function tearDown(): void + { + Functions::setCompatibilityMode($this->compatibilityMode); } /** * @dataProvider providerDEC2HEX * * @param mixed $expectedResult + * @param mixed $formula */ - public function testDEC2HEX($expectedResult, ...$args): void + public function testDEC2HEX($expectedResult, $formula): void { - $result = Engineering::DECTOHEX(...$args); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 17); + $sheet->getCell('A1')->setValue("=DEC2HEX($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerDEC2HEX() + public function providerDEC2HEX(): array { return require 'tests/data/Calculation/Engineering/DEC2HEX.php'; } + + /** + * @dataProvider providerDEC2HEX + * + * @param mixed $expectedResult + * @param mixed $formula + */ + public function testDEC2HEXOds($expectedResult, $formula): void + { + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + if ($formula === 'true') { + $expectedResult = 1; + } elseif ($formula === 'false') { + $expectedResult = 0; + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 17); + $sheet->getCell('A1')->setValue("=DEC2HEX($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function testDEC2HEXFrac(): void + { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_GNUMERIC); + $cell = 'G1'; + $sheet->setCellValue($cell, '=DEC2HEX(17.1)'); + self::assertEquals(11, $sheet->getCell($cell)->getCalculatedValue(), 'Gnumeric'); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + $cell = 'O1'; + $sheet->setCellValue($cell, '=DEC2HEX(17.1)'); + self::assertEquals(11, $sheet->getCell($cell)->getCalculatedValue(), 'Ods'); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $cell = 'E1'; + $sheet->setCellValue($cell, '=DEC2HEX(17.1)'); + self::assertEquals(11, $sheet->getCell($cell)->getCalculatedValue(), 'Excel'); + } + + public function test32bitHex(): void + { + self::assertEquals('A2DE246000', Engineering\ConvertDecimal::hex32bit(-400000000000, 'DE246000', true)); + self::assertEquals('7FFFFFFFFF', Engineering\ConvertDecimal::hex32bit(549755813887, 'FFFFFFFF', true)); + self::assertEquals('FFFFFFFFFF', Engineering\ConvertDecimal::hex32bit(-1, 'FFFFFFFF', true)); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Dec2OctTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Dec2OctTest.php index 61eb3dbb..093f17bc 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Dec2OctTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Dec2OctTest.php @@ -2,30 +2,92 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\Engineering; -use PhpOffice\PhpSpreadsheet\Calculation\Engineering; +use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PHPUnit\Framework\TestCase; class Dec2OctTest extends TestCase { + /** + * @var string + */ + private $compatibilityMode; + protected function setUp(): void { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $this->compatibilityMode = Functions::getCompatibilityMode(); + } + + protected function tearDown(): void + { + Functions::setCompatibilityMode($this->compatibilityMode); } /** * @dataProvider providerDEC2OCT * * @param mixed $expectedResult + * @param mixed $formula */ - public function testDEC2OCT($expectedResult, ...$args): void + public function testDEC2OCT($expectedResult, $formula): void { - $result = Engineering::DECTOOCT(...$args); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 17); + $sheet->getCell('A1')->setValue("=DEC2OCT($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerDEC2OCT() + public function providerDEC2OCT(): array { return require 'tests/data/Calculation/Engineering/DEC2OCT.php'; } + + /** + * @dataProvider providerDEC2OCT + * + * @param mixed $expectedResult + * @param mixed $formula + */ + public function testDEC2OCTOds($expectedResult, $formula): void + { + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + if ($formula === 'true') { + $expectedResult = 1; + } elseif ($formula === 'false') { + $expectedResult = 0; + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 17); + $sheet->getCell('A1')->setValue("=DEC2OCT($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function testDEC2OCTFrac(): void + { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_GNUMERIC); + $cell = 'G1'; + $sheet->setCellValue($cell, '=DEC2OCT(17.1)'); + self::assertEquals(21, $sheet->getCell($cell)->getCalculatedValue(), 'Gnumeric'); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + $cell = 'O1'; + $sheet->setCellValue($cell, '=DEC2OCT(17.1)'); + self::assertEquals(21, $sheet->getCell($cell)->getCalculatedValue(), 'Ods'); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $cell = 'E1'; + $sheet->setCellValue($cell, '=DEC2OCT(17.1)'); + self::assertEquals(21, $sheet->getCell($cell)->getCalculatedValue(), 'Excel'); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/DeltaTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/DeltaTest.php index a93d2ea6..749b33c2 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/DeltaTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/DeltaTest.php @@ -24,7 +24,7 @@ class DeltaTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerDELTA() + public function providerDELTA(): array { return require 'tests/data/Calculation/Engineering/DELTA.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ErfCTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ErfCTest.php index 09bf448e..45d5b4c8 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ErfCTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ErfCTest.php @@ -27,7 +27,7 @@ class ErfCTest extends TestCase self::assertEqualsWithDelta($expectedResult, $result, self::ERF_PRECISION); } - public function providerERFC() + public function providerERFC(): array { return require 'tests/data/Calculation/Engineering/ERFC.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ErfPreciseTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ErfPreciseTest.php index eb26ae98..952b2560 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ErfPreciseTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ErfPreciseTest.php @@ -27,7 +27,7 @@ class ErfPreciseTest extends TestCase self::assertEqualsWithDelta($expectedResult, $result, self::ERF_PRECISION); } - public function providerERFPRECISE() + public function providerERFPRECISE(): array { return require 'tests/data/Calculation/Engineering/ERFPRECISE.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ErfTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ErfTest.php index 8201edbc..9866024f 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ErfTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ErfTest.php @@ -27,7 +27,7 @@ class ErfTest extends TestCase self::assertEqualsWithDelta($expectedResult, $result, self::ERF_PRECISION); } - public function providerERF() + public function providerERF(): array { return require 'tests/data/Calculation/Engineering/ERF.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/GeStepTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/GeStepTest.php index 370c1a82..07e3a48c 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/GeStepTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/GeStepTest.php @@ -24,7 +24,7 @@ class GeStepTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerGESTEP() + public function providerGESTEP(): array { return require 'tests/data/Calculation/Engineering/GESTEP.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Hex2BinTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Hex2BinTest.php index 44d8908d..ad76716c 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Hex2BinTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Hex2BinTest.php @@ -2,30 +2,95 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\Engineering; -use PhpOffice\PhpSpreadsheet\Calculation\Engineering; +use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PHPUnit\Framework\TestCase; class Hex2BinTest extends TestCase { + /** + * @var string + */ + private $compatibilityMode; + protected function setUp(): void { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $this->compatibilityMode = Functions::getCompatibilityMode(); + } + + protected function tearDown(): void + { + Functions::setCompatibilityMode($this->compatibilityMode); } /** * @dataProvider providerHEX2BIN * * @param mixed $expectedResult + * @param mixed $formula */ - public function testHEX2BIN($expectedResult, ...$args): void + public function testHEX2BIN($expectedResult, $formula): void { - $result = Engineering::HEXTOBIN(...$args); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 'B'); + $sheet->getCell('A1')->setValue("=HEX2BIN($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerHEX2BIN() + public function providerHEX2BIN(): array { return require 'tests/data/Calculation/Engineering/HEX2BIN.php'; } + + /** + * @dataProvider providerHEX2BIN + * + * @param mixed $expectedResult + * @param mixed $formula + */ + public function testHEX2BINOds($expectedResult, $formula): void + { + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + if ($formula === 'true') { + $expectedResult = 1; + } elseif ($formula === 'false') { + $expectedResult = 0; + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 'B'); + $sheet->getCell('A1')->setValue("=HEX2BIN($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function testHEX2BINFrac(): void + { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_GNUMERIC); + $cell = 'G1'; + $sheet->setCellValue($cell, '=HEX2BIN(10.1)'); + self::assertEquals('10000', $sheet->getCell($cell)->getCalculatedValue()); + $cell = 'F21'; + $sheet->setCellValue($cell, '=HEX2BIN("A.1")'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue()); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + $cell = 'O1'; + $sheet->setCellValue($cell, '=HEX2BIN(10.1)'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue()); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $cell = 'E1'; + $sheet->setCellValue($cell, '=HEX2BIN(10.1)'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue()); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Hex2DecTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Hex2DecTest.php index b388b2b7..806ba44d 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Hex2DecTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Hex2DecTest.php @@ -2,30 +2,95 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\Engineering; -use PhpOffice\PhpSpreadsheet\Calculation\Engineering; +use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PHPUnit\Framework\TestCase; class Hex2DecTest extends TestCase { + /** + * @var string + */ + private $compatibilityMode; + protected function setUp(): void { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $this->compatibilityMode = Functions::getCompatibilityMode(); + } + + protected function tearDown(): void + { + Functions::setCompatibilityMode($this->compatibilityMode); } /** * @dataProvider providerHEX2DEC * * @param mixed $expectedResult + * @param mixed $formula */ - public function testHEX2DEC($expectedResult, ...$args): void + public function testHEX2DEC($expectedResult, $formula): void { - $result = Engineering::HEXTODEC(...$args); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 'B'); + $sheet->getCell('A1')->setValue("=HEX2DEC($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerHEX2DEC() + public function providerHEX2DEC(): array { return require 'tests/data/Calculation/Engineering/HEX2DEC.php'; } + + /** + * @dataProvider providerHEX2DEC + * + * @param mixed $expectedResult + * @param mixed $formula + */ + public function testHEX2DECOds($expectedResult, $formula): void + { + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + if ($formula === 'true') { + $expectedResult = 1; + } elseif ($formula === 'false') { + $expectedResult = 0; + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 'B'); + $sheet->getCell('A1')->setValue("=HEX2DEC($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function testHEX2DECFrac(): void + { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_GNUMERIC); + $cell = 'G1'; + $sheet->setCellValue($cell, '=HEX2DEC(10.1)'); + self::assertEquals(16, $sheet->getCell($cell)->getCalculatedValue()); + $cell = 'F21'; + $sheet->setCellValue($cell, '=HEX2DEC("A.1")'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue()); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + $cell = 'O1'; + $sheet->setCellValue($cell, '=HEX2DEC(10.1)'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue()); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $cell = 'E1'; + $sheet->setCellValue($cell, '=HEX2DEC(10.1)'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue(), 'Excel'); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Hex2OctTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Hex2OctTest.php index bc0a5cb7..41f1a8f7 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Hex2OctTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Hex2OctTest.php @@ -2,30 +2,92 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\Engineering; -use PhpOffice\PhpSpreadsheet\Calculation\Engineering; +use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PHPUnit\Framework\TestCase; class Hex2OctTest extends TestCase { + /** + * @var string + */ + private $compatibilityMode; + protected function setUp(): void { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $this->compatibilityMode = Functions::getCompatibilityMode(); + } + + protected function tearDown(): void + { + Functions::setCompatibilityMode($this->compatibilityMode); } /** * @dataProvider providerHEX2OCT * * @param mixed $expectedResult + * @param mixed $formula */ - public function testHEX2OCT($expectedResult, ...$args): void + public function testHEX2OCT($expectedResult, $formula): void { - $result = Engineering::HEXTOOCT(...$args); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 'B'); + $sheet->getCell('A1')->setValue("=HEX2OCT($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerHEX2OCT() + public function providerHEX2OCT(): array { return require 'tests/data/Calculation/Engineering/HEX2OCT.php'; } + + /** + * @dataProvider providerHEX2OCT + * + * @param mixed $expectedResult + * @param mixed $formula + */ + public function testHEX2OCTOds($expectedResult, $formula): void + { + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + if ($formula === 'true') { + $expectedResult = 1; + } elseif ($formula === 'false') { + $expectedResult = 0; + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 'B'); + $sheet->getCell('A1')->setValue("=HEX2OCT($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function testHEX2OCTFrac(): void + { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_GNUMERIC); + $cell = 'G1'; + $sheet->setCellValue($cell, '=HEX2OCT(10.1)'); + self::assertEquals(20, $sheet->getCell($cell)->getCalculatedValue()); + $cell = 'F21'; + $sheet->setCellValue($cell, '=HEX2OCT("A.1")'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue()); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + $cell = 'O1'; + $sheet->setCellValue($cell, '=HEX2OCT(10.1)'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue()); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $cell = 'E1'; + $sheet->setCellValue($cell, '=HEX2OCT(10.1)'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue(), 'Excel'); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImAbsTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImAbsTest.php index 1f1ee9dd..367cfb33 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImAbsTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImAbsTest.php @@ -27,7 +27,7 @@ class ImAbsTest extends TestCase self::assertEqualsWithDelta($expectedResult, $result, self::COMPLEX_PRECISION); } - public function providerIMABS() + public function providerIMABS(): array { return require 'tests/data/Calculation/Engineering/IMABS.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImArgumentTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImArgumentTest.php index 6f1a6485..9ff8209f 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImArgumentTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImArgumentTest.php @@ -27,7 +27,7 @@ class ImArgumentTest extends TestCase self::assertEqualsWithDelta($expectedResult, $result, self::COMPLEX_PRECISION); } - public function providerIMARGUMENT() + public function providerIMARGUMENT(): array { return require 'tests/data/Calculation/Engineering/IMARGUMENT.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImConjugateTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImConjugateTest.php index bc3a3918..d952f5df 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImConjugateTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImConjugateTest.php @@ -14,7 +14,7 @@ class ImConjugateTest extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImConjugateTest extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMCONJUGATE * @@ -42,7 +37,7 @@ class ImConjugateTest extends TestCase ); } - public function providerIMCONJUGATE() + public function providerIMCONJUGATE(): array { return require 'tests/data/Calculation/Engineering/IMCONJUGATE.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImCosTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImCosTest.php index 693f0bab..b6cb8dc2 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImCosTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImCosTest.php @@ -14,7 +14,7 @@ class ImCosTest extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImCosTest extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMCOS * @@ -42,7 +37,7 @@ class ImCosTest extends TestCase ); } - public function providerIMCOS() + public function providerIMCOS(): array { return require 'tests/data/Calculation/Engineering/IMCOS.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImCoshTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImCoshTest.php index ae035fef..0d544084 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImCoshTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImCoshTest.php @@ -14,7 +14,7 @@ class ImCoshTest extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImCoshTest extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMCOSH * @@ -42,7 +37,7 @@ class ImCoshTest extends TestCase ); } - public function providerIMCOSH() + public function providerIMCOSH(): array { return require 'tests/data/Calculation/Engineering/IMCOSH.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImCotTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImCotTest.php index 8b888b3f..69bd02ff 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImCotTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImCotTest.php @@ -14,7 +14,7 @@ class ImCotTest extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImCotTest extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMCOT * @@ -42,7 +37,7 @@ class ImCotTest extends TestCase ); } - public function providerIMCOT() + public function providerIMCOT(): array { return require 'tests/data/Calculation/Engineering/IMCOT.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImCscTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImCscTest.php index 5a08c0b6..51843f89 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImCscTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImCscTest.php @@ -14,7 +14,7 @@ class ImCscTest extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImCscTest extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMCSC * @@ -42,7 +37,7 @@ class ImCscTest extends TestCase ); } - public function providerIMCSC() + public function providerIMCSC(): array { return require 'tests/data/Calculation/Engineering/IMCSC.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImCschTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImCschTest.php index a95a4eaf..d2d7511d 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImCschTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImCschTest.php @@ -14,7 +14,7 @@ class ImCschTest extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImCschTest extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMCSCH * @@ -42,7 +37,7 @@ class ImCschTest extends TestCase ); } - public function providerIMCSCH() + public function providerIMCSCH(): array { return require 'tests/data/Calculation/Engineering/IMCSCH.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImDivTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImDivTest.php index 2bc91619..652f5ca2 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImDivTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImDivTest.php @@ -14,7 +14,7 @@ class ImDivTest extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImDivTest extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMDIV * @@ -41,7 +36,7 @@ class ImDivTest extends TestCase ); } - public function providerIMDIV() + public function providerIMDIV(): array { return require 'tests/data/Calculation/Engineering/IMDIV.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImExpTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImExpTest.php index 7debbc9c..d7be573f 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImExpTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImExpTest.php @@ -14,7 +14,7 @@ class ImExpTest extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImExpTest extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMEXP * @@ -42,7 +37,7 @@ class ImExpTest extends TestCase ); } - public function providerIMEXP() + public function providerIMEXP(): array { return require 'tests/data/Calculation/Engineering/IMEXP.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImLnTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImLnTest.php index 3e270975..4566607b 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImLnTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImLnTest.php @@ -14,7 +14,7 @@ class ImLnTest extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImLnTest extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMLN * @@ -42,7 +37,7 @@ class ImLnTest extends TestCase ); } - public function providerIMLN() + public function providerIMLN(): array { return require 'tests/data/Calculation/Engineering/IMLN.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImLog10Test.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImLog10Test.php index 2a4db7fb..0d818686 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImLog10Test.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImLog10Test.php @@ -14,7 +14,7 @@ class ImLog10Test extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImLog10Test extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMLOG10 * @@ -42,7 +37,7 @@ class ImLog10Test extends TestCase ); } - public function providerIMLOG10() + public function providerIMLOG10(): array { return require 'tests/data/Calculation/Engineering/IMLOG10.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImLog2Test.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImLog2Test.php index 53b302dd..02583448 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImLog2Test.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImLog2Test.php @@ -14,7 +14,7 @@ class ImLog2Test extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImLog2Test extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMLOG2 * @@ -42,7 +37,7 @@ class ImLog2Test extends TestCase ); } - public function providerIMLOG2() + public function providerIMLOG2(): array { return require 'tests/data/Calculation/Engineering/IMLOG2.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImPowerTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImPowerTest.php index 41e52878..18e92791 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImPowerTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImPowerTest.php @@ -14,7 +14,7 @@ class ImPowerTest extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImPowerTest extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMPOWER * @@ -41,7 +36,7 @@ class ImPowerTest extends TestCase ); } - public function providerIMPOWER() + public function providerIMPOWER(): array { return require 'tests/data/Calculation/Engineering/IMPOWER.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImProductTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImProductTest.php index 43495739..845d436f 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImProductTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImProductTest.php @@ -14,7 +14,7 @@ class ImProductTest extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImProductTest extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMPRODUCT * @@ -41,7 +36,7 @@ class ImProductTest extends TestCase ); } - public function providerIMPRODUCT() + public function providerIMPRODUCT(): array { return require 'tests/data/Calculation/Engineering/IMPRODUCT.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImRealTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImRealTest.php index 08d2feb1..790487c1 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImRealTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImRealTest.php @@ -27,7 +27,7 @@ class ImRealTest extends TestCase self::assertEqualsWithDelta($expectedResult, $result, self::COMPLEX_PRECISION); } - public function providerIMREAL() + public function providerIMREAL(): array { return require 'tests/data/Calculation/Engineering/IMREAL.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSecTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSecTest.php index e785d3ac..b750796d 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSecTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSecTest.php @@ -14,7 +14,7 @@ class ImSecTest extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImSecTest extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMSEC * @@ -42,7 +37,7 @@ class ImSecTest extends TestCase ); } - public function providerIMSEC() + public function providerIMSEC(): array { return require 'tests/data/Calculation/Engineering/IMSEC.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSechTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSechTest.php index 22cb6fae..c6477c1c 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSechTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSechTest.php @@ -14,7 +14,7 @@ class ImSechTest extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImSechTest extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMSECH * @@ -42,7 +37,7 @@ class ImSechTest extends TestCase ); } - public function providerIMSECH() + public function providerIMSECH(): array { return require 'tests/data/Calculation/Engineering/IMSECH.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSinTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSinTest.php index dd797a35..df8cb020 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSinTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSinTest.php @@ -14,7 +14,7 @@ class ImSinTest extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImSinTest extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMSIN * @@ -42,7 +37,7 @@ class ImSinTest extends TestCase ); } - public function providerIMSIN() + public function providerIMSIN(): array { return require 'tests/data/Calculation/Engineering/IMSIN.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSinhTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSinhTest.php index 4174d1c0..f8dbafb9 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSinhTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSinhTest.php @@ -14,7 +14,7 @@ class ImSinhTest extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImSinhTest extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMSINH * @@ -42,7 +37,7 @@ class ImSinhTest extends TestCase ); } - public function providerIMSINH() + public function providerIMSINH(): array { return require 'tests/data/Calculation/Engineering/IMSINH.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSqrtTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSqrtTest.php index 091b11c5..0d536f94 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSqrtTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSqrtTest.php @@ -14,7 +14,7 @@ class ImSqrtTest extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImSqrtTest extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMSQRT * @@ -42,7 +37,7 @@ class ImSqrtTest extends TestCase ); } - public function providerIMSQRT() + public function providerIMSQRT(): array { return require 'tests/data/Calculation/Engineering/IMSQRT.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSubTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSubTest.php index 79286120..edb413d5 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSubTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSubTest.php @@ -14,7 +14,7 @@ class ImSubTest extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImSubTest extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMSUB * @@ -41,7 +36,7 @@ class ImSubTest extends TestCase ); } - public function providerIMSUB() + public function providerIMSUB(): array { return require 'tests/data/Calculation/Engineering/IMSUB.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSumTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSumTest.php index 8abc3638..0620c684 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSumTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImSumTest.php @@ -14,7 +14,7 @@ class ImSumTest extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImSumTest extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMSUM * @@ -41,7 +36,7 @@ class ImSumTest extends TestCase ); } - public function providerIMSUM() + public function providerIMSUM(): array { return require 'tests/data/Calculation/Engineering/IMSUM.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImTanTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImTanTest.php index 57b23815..f1e4037e 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImTanTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImTanTest.php @@ -14,7 +14,7 @@ class ImTanTest extends TestCase /** * @var ComplexAssert */ - protected $complexAssert; + private $complexAssert; protected function setUp(): void { @@ -22,11 +22,6 @@ class ImTanTest extends TestCase $this->complexAssert = new ComplexAssert(); } - protected function tearDown(): void - { - $this->complexAssert = null; - } - /** * @dataProvider providerIMTAN * @@ -42,7 +37,7 @@ class ImTanTest extends TestCase ); } - public function providerIMTAN() + public function providerIMTAN(): array { return require 'tests/data/Calculation/Engineering/IMTAN.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImaginaryTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImaginaryTest.php index 6ad72287..1c976b05 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImaginaryTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/ImaginaryTest.php @@ -27,7 +27,7 @@ class ImaginaryTest extends TestCase self::assertEqualsWithDelta($expectedResult, $result, self::COMPLEX_PRECISION); } - public function providerIMAGINARY() + public function providerIMAGINARY(): array { return require 'tests/data/Calculation/Engineering/IMAGINARY.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/MovedBitwiseTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/MovedBitwiseTest.php new file mode 100644 index 00000000..457db0d3 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/MovedBitwiseTest.php @@ -0,0 +1,24 @@ +compatibilityMode = Functions::getCompatibilityMode(); + } + + protected function tearDown(): void + { + Functions::setCompatibilityMode($this->compatibilityMode); } /** * @dataProvider providerOCT2BIN * * @param mixed $expectedResult + * @param mixed $formula */ - public function testOCT2BIN($expectedResult, ...$args): void + public function testOCT2BIN($expectedResult, $formula): void { - $result = Engineering::OCTTOBIN(...$args); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 101); + $sheet->getCell('A1')->setValue("=OCT2BIN($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerOCT2BIN() + public function providerOCT2BIN(): array { return require 'tests/data/Calculation/Engineering/OCT2BIN.php'; } + + /** + * @dataProvider providerOCT2BIN + * + * @param mixed $expectedResult + * @param mixed $formula + */ + public function testOCT2BINOds($expectedResult, $formula): void + { + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + if ($formula === 'true') { + $expectedResult = 1; + } elseif ($formula === 'false') { + $expectedResult = 0; + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 101); + $sheet->getCell('A1')->setValue("=OCT2BIN($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function testOCT2BINFrac(): void + { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_GNUMERIC); + $cell = 'G1'; + $sheet->setCellValue($cell, '=HEX2BIN(10.1)'); + self::assertEquals('10000', $sheet->getCell($cell)->getCalculatedValue()); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + $cell = 'O1'; + $sheet->setCellValue($cell, '=OCT2BIN(10.1)'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue()); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $cell = 'E1'; + $sheet->setCellValue($cell, '=OCT2BIN(10.1)'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue()); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Oct2DecTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Oct2DecTest.php index 87e213ef..2c354046 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Oct2DecTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Oct2DecTest.php @@ -2,30 +2,92 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\Engineering; -use PhpOffice\PhpSpreadsheet\Calculation\Engineering; +use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PHPUnit\Framework\TestCase; class Oct2DecTest extends TestCase { + /** + * @var string + */ + private $compatibilityMode; + protected function setUp(): void { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $this->compatibilityMode = Functions::getCompatibilityMode(); + } + + protected function tearDown(): void + { + Functions::setCompatibilityMode($this->compatibilityMode); } /** * @dataProvider providerOCT2DEC * * @param mixed $expectedResult + * @param mixed $formula */ - public function testOCT2DEC($expectedResult, ...$args): void + public function testOCT2DEC($expectedResult, $formula): void { - $result = Engineering::OCTTODEC(...$args); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 101); + $sheet->getCell('A1')->setValue("=OCT2DEC($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerOCT2DEC() + public function providerOCT2DEC(): array { return require 'tests/data/Calculation/Engineering/OCT2DEC.php'; } + + /** + * @dataProvider providerOCT2DEC + * + * @param mixed $expectedResult + * @param mixed $formula + */ + public function testOCT2DECOds($expectedResult, $formula): void + { + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + if ($formula === 'true') { + $expectedResult = 1; + } elseif ($formula === 'false') { + $expectedResult = 0; + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 101); + $sheet->getCell('A1')->setValue("=OCT2DEC($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function testOCT2DECFrac(): void + { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_GNUMERIC); + $cell = 'G1'; + $sheet->setCellValue($cell, '=OCT2DEC(10.1)'); + self::assertEquals(8, $sheet->getCell($cell)->getCalculatedValue()); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + $cell = 'O1'; + $sheet->setCellValue($cell, '=OCT2DEC(10.1)'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue()); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $cell = 'E1'; + $sheet->setCellValue($cell, '=OCT2DEC(10.1)'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue()); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Oct2HexTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Oct2HexTest.php index e2d75a78..3f721a48 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Oct2HexTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Engineering/Oct2HexTest.php @@ -2,30 +2,92 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\Engineering; -use PhpOffice\PhpSpreadsheet\Calculation\Engineering; +use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PHPUnit\Framework\TestCase; class Oct2HexTest extends TestCase { + /** + * @var string + */ + private $compatibilityMode; + protected function setUp(): void { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $this->compatibilityMode = Functions::getCompatibilityMode(); + } + + protected function tearDown(): void + { + Functions::setCompatibilityMode($this->compatibilityMode); } /** * @dataProvider providerOCT2HEX * * @param mixed $expectedResult + * @param mixed $formula */ - public function testOCT2HEX($expectedResult, ...$args): void + public function testOCT2HEX($expectedResult, $formula): void { - $result = Engineering::OCTTOHEX(...$args); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 101); + $sheet->getCell('A1')->setValue("=OCT2HEX($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerOCT2HEX() + public function providerOCT2HEX(): array { return require 'tests/data/Calculation/Engineering/OCT2HEX.php'; } + + /** + * @dataProvider providerOCT2HEX + * + * @param mixed $expectedResult + * @param mixed $formula + */ + public function testOCT2HEXOds($expectedResult, $formula): void + { + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + if ($expectedResult === 'exception') { + $this->expectException(CalcExp::class); + } + if ($formula === 'true') { + $expectedResult = 1; + } elseif ($formula === 'false') { + $expectedResult = 0; + } + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setCellValue('A2', 101); + $sheet->getCell('A1')->setValue("=OCT2HEX($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function testOCT2HEXFrac(): void + { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_GNUMERIC); + $cell = 'G1'; + $sheet->setCellValue($cell, '=OCT2HEX(20.1)'); + self::assertEquals(10, $sheet->getCell($cell)->getCalculatedValue()); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + $cell = 'O1'; + $sheet->setCellValue($cell, '=OCT2HEX(20.1)'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue()); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $cell = 'E1'; + $sheet->setCellValue($cell, '=OCT2HEX(20.1)'); + self::assertEquals('#NUM!', $sheet->getCell($cell)->getCalculatedValue()); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Financial/AccrintMTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Financial/AccrintMTest.php index 597db5c2..fbc7a61c 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Financial/AccrintMTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Financial/AccrintMTest.php @@ -21,10 +21,10 @@ class AccrintMTest extends TestCase public function testACCRINTM($expectedResult, ...$args): void { $result = Financial::ACCRINTM(...$args); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerACCRINTM() + public function providerACCRINTM(): array { return require 'tests/data/Calculation/Financial/ACCRINTM.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Financial/AccrintTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Financial/AccrintTest.php index edb79230..74444061 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Financial/AccrintTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Financial/AccrintTest.php @@ -21,10 +21,10 @@ class AccrintTest extends TestCase public function testACCRINT($expectedResult, ...$args): void { $result = Financial::ACCRINT(...$args); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerACCRINT() + public function providerACCRINT(): array { return require 'tests/data/Calculation/Financial/ACCRINT.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Financial/AmorDegRcTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Financial/AmorDegRcTest.php new file mode 100644 index 00000000..6f69e7fb --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Financial/AmorDegRcTest.php @@ -0,0 +1,31 @@ + 0.999999 && $frac < 1.000001) { + $result = $expectedResult; + } + } + } + self::assertEquals($expectedResult, $result, $message); + } + + public function providerXNPV(): array + { + return require 'tests/data/Calculation/Financial/XNPV.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Financial/XirrTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Financial/XirrTest.php new file mode 100644 index 00000000..a6677f3f --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Financial/XirrTest.php @@ -0,0 +1,40 @@ + 0.999999 && $frac < 1.000001) { + $result = $expectedResult; + } + } + } + self::assertEquals($expectedResult, $result, $message); + } + + public function providerXIRR(): array + { + return require 'tests/data/Calculation/Financial/XIRR.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Financial/YieldDiscTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Financial/YieldDiscTest.php new file mode 100644 index 00000000..1c966d87 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Financial/YieldDiscTest.php @@ -0,0 +1,31 @@ +compatibilityMode = Functions::getCompatibilityMode(); + } + + protected function tearDown(): void + { + Functions::setCompatibilityMode($this->compatibilityMode); + $this->sheet = null; + if ($this->spreadsheet !== null) { + $this->spreadsheet->disconnectWorksheets(); + $this->spreadsheet = null; + } + } + + protected static function setOpenOffice(): void + { + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + } + + protected static function setGnumeric(): void + { + Functions::setCompatibilityMode(Functions::COMPATIBILITY_GNUMERIC); + } + + /** + * @param mixed $expectedResult + */ + protected function mightHaveException($expectedResult): void + { + if ($expectedResult === 'exception') { + $this->expectException(CalcException::class); + } + } + + /** + * @param mixed $value + */ + protected function setCell(string $cell, $value): void + { + if ($value !== null) { + if (is_string($value) && is_numeric($value)) { + $this->getSheet()->getCell($cell)->setValueExplicit($value, DataType::TYPE_STRING); + } else { + $this->getSheet()->getCell($cell)->setValue($value); + } + } + } + + protected function getSpreadsheet(): Spreadsheet + { + if ($this->spreadsheet !== null) { + return $this->spreadsheet; + } + $this->spreadsheet = new Spreadsheet(); + + return $this->spreadsheet; + } + + protected function getSheet(): Worksheet + { + if ($this->sheet !== null) { + return $this->sheet; + } + $this->sheet = $this->getSpreadsheet()->getActiveSheet(); + + return $this->sheet; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ChooseTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ChooseTest.php index 01ba6f75..857973ff 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ChooseTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ChooseTest.php @@ -24,7 +24,7 @@ class ChooseTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerCHOOSE() + public function providerCHOOSE(): array { return require 'tests/data/Calculation/LookupRef/CHOOSE.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ColumnOnSpreadsheetTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ColumnOnSpreadsheetTest.php new file mode 100644 index 00000000..0c43f00f --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ColumnOnSpreadsheetTest.php @@ -0,0 +1,57 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $this->getSpreadsheet()->addNamedRange(new NamedRange('namedrangex', $sheet, '$E$2:$E$6')); + $this->getSpreadsheet()->addNamedRange(new NamedRange('namedrangey', $sheet, '$F$2:$H$2')); + $this->getSpreadsheet()->addNamedRange(new NamedRange('namedrange3', $sheet, '$F$4:$H$4')); + + $sheet1 = $this->getSpreadsheet()->createSheet(); + $sheet1->setTitle('OtherSheet'); + + if ($cellReference === 'omitted') { + $sheet->getCell('B3')->setValue('=COLUMN()'); + } else { + $sheet->getCell('B3')->setValue("=COLUMN($cellReference)"); + } + + $result = $sheet->getCell('B3')->getCalculatedValue(); + self::assertSame($expectedResult, $result); + } + + public function providerCOLUMNonSpreadsheet(): array + { + return require 'tests/data/Calculation/LookupRef/COLUMNonSpreadsheet.php'; + } + + public function testCOLUMNLocalDefinedName(): void + { + $sheet = $this->getSheet(); + + $sheet1 = $this->getSpreadsheet()->createSheet(); + $sheet1->setTitle('OtherSheet'); + $this->getSpreadsheet()->addNamedRange(new NamedRange('newnr', $sheet1, '$F$5:$H$5', true)); // defined locally, only usable on sheet1 + + $sheet1->getCell('B3')->setValue('=COLUMN(newnr)'); + $result = $sheet1->getCell('B3')->getCalculatedValue(); + self::assertSame(6, $result); + + $sheet->getCell('B3')->setValue('=COLUMN(newnr)'); + $result = $sheet->getCell('B3')->getCalculatedValue(); + self::assertSame('#NAME?', $result); + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ColumnTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ColumnTest.php new file mode 100644 index 00000000..2dfb22d9 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ColumnTest.php @@ -0,0 +1,46 @@ +getMockBuilder(Cell::class) + ->onlyMethods(['getColumn']) + ->disableOriginalConstructor() + ->getMock(); + $cell->method('getColumn') + ->willReturn('D'); + + $result = LookupRef::COLUMN(null, $cell); + self::assertSame(4, $result); + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ColumnsOnSpreadsheetTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ColumnsOnSpreadsheetTest.php new file mode 100644 index 00000000..332b5ced --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ColumnsOnSpreadsheetTest.php @@ -0,0 +1,60 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setTitle('ThisSheet'); + $this->getSpreadsheet()->addNamedRange(new NamedRange('namedrangex', $sheet, '$E$2:$E$6')); + $this->getSpreadsheet()->addNamedRange(new NamedRange('namedrangey', $sheet, '$F$2:$H$2')); + $this->getSpreadsheet()->addNamedRange(new NamedRange('namedrange3', $sheet, '$F$4:$H$4')); + $this->getSpreadsheet()->addNamedRange(new NamedRange('namedrange5', $sheet, '$F$5:$I$5', true)); + + $sheet1 = $this->getSpreadsheet()->createSheet(); + $sheet1->setTitle('OtherSheet'); + $this->getSpreadsheet()->addNamedRange(new NamedRange('localname', $sheet1, '$F$6:$H$6', true)); + + if ($cellReference === 'omitted') { + $sheet->getCell('B3')->setValue('=COLUMNS()'); + } else { + $sheet->getCell('B3')->setValue("=COLUMNS($cellReference)"); + } + + $result = $sheet->getCell('B3')->getCalculatedValue(); + self::assertSame($expectedResult, $result); + } + + public function providerCOLUMNSonSpreadsheet(): array + { + return require 'tests/data/Calculation/LookupRef/COLUMNSonSpreadsheet.php'; + } + + public function testCOLUMNSLocalDefinedName(): void + { + $sheet = $this->getSheet(); + + $sheet1 = $this->getSpreadsheet()->createSheet(); + $sheet1->setTitle('OtherSheet'); + $this->getSpreadsheet()->addNamedRange(new NamedRange('newnr', $sheet1, '$F$5:$H$5', true)); // defined locally, only usable on sheet1 + + $sheet1->getCell('B3')->setValue('=COLUMNS(newnr)'); + $result = $sheet1->getCell('B3')->getCalculatedValue(); + self::assertSame(3, $result); + + $sheet->getCell('B3')->setValue('=COLUMNS(newnr)'); + $result = $sheet->getCell('B3')->getCalculatedValue(); + self::assertSame('#NAME?', $result); + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ColumnsTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ColumnsTest.php index a7908241..e14023cd 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ColumnsTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ColumnsTest.php @@ -24,7 +24,7 @@ class ColumnsTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerCOLUMNS() + public function providerCOLUMNS(): array { return require 'tests/data/Calculation/LookupRef/COLUMNS.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/HLookupTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/HLookupTest.php index 767b6de8..7dc5b29c 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/HLookupTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/HLookupTest.php @@ -2,30 +2,91 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\LookupRef; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\LookupRef; +use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PHPUnit\Framework\TestCase; class HLookupTest extends TestCase { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerHLOOKUP * * @param mixed $expectedResult + * @param mixed $lookup + * @param mixed $rowIndex */ - public function testHLOOKUP($expectedResult, ...$args): void + public function testHLOOKUP($expectedResult, $lookup, array $values, $rowIndex, ?bool $rangeLookup = null): void { - $result = LookupRef::HLOOKUP(...$args); - self::assertEquals($expectedResult, $result); + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $maxRow = 0; + $maxCol = 0; + $maxColLetter = 'A'; + $row = 0; + foreach ($values as $rowValues) { + ++$row; + ++$maxRow; + $col = 0; + if (!is_array($rowValues)) { + $rowValues = [$rowValues]; + } + foreach ($rowValues as $cellValue) { + ++$col; + $colLetter = Coordinate::stringFromColumnIndex($col); + if ($col > $maxCol) { + $maxCol = $col; + $maxColLetter = $colLetter; + } + if ($cellValue !== null) { + $sheet->getCell("$colLetter$row")->setValue($cellValue); + } + } + } + + $boolArg = self::parseRangeLookup($rangeLookup); + $sheet->getCell('ZZ8')->setValue($lookup); + $sheet->getCell('ZZ7')->setValue($rowIndex); + $sheet->getCell('ZZ1')->setValue("=HLOOKUP(ZZ8, A1:$maxColLetter$maxRow, ZZ7$boolArg)"); + self::assertEquals($expectedResult, $sheet->getCell('ZZ1')->getCalculatedValue()); + + $spreadsheet->disconnectWorksheets(); } - public function providerHLOOKUP() + private static function parseRangeLookup(?bool $rangeLookup): string + { + if ($rangeLookup === null) { + return ''; + } + + return $rangeLookup ? ', true' : ', false'; + } + + public function providerHLOOKUP(): array { return require 'tests/data/Calculation/LookupRef/HLOOKUP.php'; } + + public function testGrandfathered(): void + { + // Second parameter is supposed to be array of arrays. + // Some old tests called function directly using array of strings; + // ensure these work as before. + $expectedResult = '#REF!'; + $result = LookupRef::HLOOKUP( + 'Selection column', + ['Selection column', 'Value to retrieve'], + 5, + false + ); + self::assertSame($expectedResult, $result); + $expectedResult = 'Value to retrieve'; + $result = LookupRef::HLOOKUP( + 'Selection column', + ['Selection column', 'Value to retrieve'], + 2, + false + ); + self::assertSame($expectedResult, $result); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/HyperlinkTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/HyperlinkTest.php new file mode 100644 index 00000000..e71992ed --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/HyperlinkTest.php @@ -0,0 +1,51 @@ +getMockBuilder(Cell::class) + ->onlyMethods(['getHyperlink']) + ->disableOriginalConstructor() + ->getMock(); + $cell->method('getHyperlink') + ->willReturn($hyperlink); + + $result = LookupRef::HYPERLINK($linkUrl, $description, $cell); + if (!is_array($expectedResult)) { + self::assertSame($expectedResult, $result); + } else { + self::assertSame($expectedResult[1], $result); + self::assertSame($expectedResult[0], $hyperlink->getUrl()); + self::assertSame($expectedResult[1], $hyperlink->getTooltip()); + } + } + + public function providerHYPERLINK(): array + { + return require 'tests/data/Calculation/LookupRef/HYPERLINK.php'; + } + + public function testHYPERLINKwithoutCell(): void + { + $result = LookupRef::HYPERLINK('https://phpspreadsheet.readthedocs.io/en/latest/', 'Read the Docs'); + self::assertSame(Functions::REF(), $result); + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/IndexTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/IndexTest.php index 8ff66931..4de661ed 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/IndexTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/IndexTest.php @@ -21,10 +21,11 @@ class IndexTest extends TestCase public function testINDEX($expectedResult, ...$args): void { $result = LookupRef::INDEX(...$args); +// var_dump($result); self::assertEquals($expectedResult, $result); } - public function providerINDEX() + public function providerINDEX(): array { return require 'tests/data/Calculation/LookupRef/INDEX.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/IndirectTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/IndirectTest.php new file mode 100644 index 00000000..7601e336 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/IndirectTest.php @@ -0,0 +1,135 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue(100); + $sheet->getCell('A2')->setValue(200); + $sheet->getCell('A3')->setValue(300); + $sheet->getCell('A4')->setValue(400); + $sheet->getCell('A5')->setValue(500); + $sheet->setTitle('ThisSheet'); + + $sheet1 = $this->getSpreadsheet()->createSheet(); + $sheet1->getCell('A1')->setValue(10); + $sheet1->getCell('A2')->setValue(20); + $sheet1->getCell('A3')->setValue(30); + $sheet1->getCell('A4')->setValue(40); + $sheet1->getCell('A5')->setValue(50); + $sheet1->getCell('B1')->setValue(1); + $sheet1->getCell('B2')->setValue(2); + $sheet1->getCell('B3')->setValue(3); + $sheet1->getCell('B4')->setValue(4); + $sheet1->getCell('B5')->setValue(5); + $sheet1->setTitle('OtherSheet'); + $this->getSpreadsheet()->addNamedRange(new NamedRange('newnr', $sheet1, '$A$2:$A$4')); + $this->getSpreadsheet()->addNamedRange(new NamedRange('localname', $sheet1, '$B$2:$B$4', true)); + + $this->setCell('B1', $cellReference); + $this->setCell('B2', $a1); + if ($cellReference === 'omitted') { + $sheet->getCell('B3')->setValue('=SUM(INDIRECT())'); + } elseif ($a1 === 'omitted') { + $sheet->getCell('B3')->setValue('=SUM(INDIRECT(B1))'); + } else { + $sheet->getCell('B3')->setValue('=SUM(INDIRECT(B1, B2))'); + } + + $result = $sheet->getCell('B3')->getCalculatedValue(); + self::assertSame($expectedResult, $result); + } + + public function providerINDIRECT(): array + { + return require 'tests/data/Calculation/LookupRef/INDIRECT.php'; + } + + public function testINDIRECTEurUsd(): void + { + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue('EUR'); + $sheet->getCell('A2')->setValue('USD'); + $sheet->getCell('B1')->setValue(360); + $sheet->getCell('B2')->setValue(300); + + $this->getSpreadsheet()->addNamedRange(new NamedRange('EUR', $sheet, '$B$1')); + $this->getSpreadsheet()->addNamedRange(new NamedRange('USD', $sheet, '$B$2')); + + $this->setCell('E1', '=INDIRECT("USD")'); + + $result = $sheet->getCell('E1')->getCalculatedValue(); + self::assertSame(300, $result); + } + + public function testINDIRECTLeadingEquals(): void + { + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue('EUR'); + $sheet->getCell('A2')->setValue('USD'); + $sheet->getCell('B1')->setValue(360); + $sheet->getCell('B2')->setValue(300); + + $this->getSpreadsheet()->addNamedRange(new NamedRange('EUR', $sheet, '=$B$1')); + $this->getSpreadsheet()->addNamedRange(new NamedRange('USD', $sheet, '=$B$2')); + + $this->setCell('E1', '=INDIRECT("USD")'); + + $result = $sheet->getCell('E1')->getCalculatedValue(); + self::assertSame(300, $result); + } + + public function testIndirectFile1(): void + { + $reader = new ReaderXlsx(); + $file = 'tests/data/Calculation/LookupRef/IndirectDefinedName.xlsx'; + $spreadsheet = $reader->load($file); + $sheet = $spreadsheet->getActiveSheet(); + $result = $sheet->getCell('A5')->getCalculatedValue(); + self::assertSame(80, $result); + $value = $sheet->getCell('A5')->getValue(); + self::assertSame('=INDIRECT("CURRENCY_EUR")', $value); + } + + public function testIndirectFile2(): void + { + $reader = new ReaderXlsx(); + $file = 'tests/data/Calculation/LookupRef/IndirectFormulaSelection.xlsx'; + $spreadsheet = $reader->load($file); + $sheet = $spreadsheet->getActiveSheet(); + $result = $sheet->getCell('A5')->getCalculatedValue(); + self::assertSame(100, $result); + $value = $sheet->getCell('A5')->getValue(); + self::assertSame('=CURRENCY_SELECTOR', $value); + $formula = $spreadsheet->getNamedFormula('CURRENCY_SELECTOR'); + if ($formula === null) { + self::fail('Expected named formula was not defined'); + } else { + self::assertSame('INDIRECT("CURRENCY_"&Sheet1!$D$1)', $formula->getFormula()); + } + } + + public function testDeprecatedCall(): void + { + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue('A2'); + $sheet->getCell('A2')->setValue('This is it'); + $result = \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::INDIRECT('A2', $sheet->getCell('A1')); + $result = \PhpOffice\PhpSpreadsheet\Calculation\Functions::flattenSingleValue($result); + self::assertSame('This is it', $result); + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/LookupTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/LookupTest.php index d1b36e4a..73dffd3d 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/LookupTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/LookupTest.php @@ -24,7 +24,7 @@ class LookupTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerLOOKUP() + public function providerLOOKUP(): array { return require 'tests/data/Calculation/LookupRef/LOOKUP.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/MatchTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/MatchTest.php index e020d3ba..ba2dce29 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/MatchTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/MatchTest.php @@ -24,7 +24,7 @@ class MatchTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerMATCH() + public function providerMATCH(): array { return require 'tests/data/Calculation/LookupRef/MATCH.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/OffsetTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/OffsetTest.php new file mode 100644 index 00000000..31a9703a --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/OffsetTest.php @@ -0,0 +1,32 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setTitle('ThisSheet'); + $this->getSpreadsheet()->addNamedRange(new NamedRange('namedrangex', $sheet, '$E$2:$E$6')); + $this->getSpreadsheet()->addNamedRange(new NamedRange('namedrangey', $sheet, '$F$2:$H$2')); + $this->getSpreadsheet()->addNamedRange(new NamedRange('namedrange3', $sheet, '$F$4:$H$4')); + $this->getSpreadsheet()->addNamedRange(new NamedRange('namedrange5', $sheet, '$F$5:$H$5', true)); + + $sheet1 = $this->getSpreadsheet()->createSheet(); + $sheet1->setTitle('OtherSheet'); + $this->getSpreadsheet()->addNamedRange(new NamedRange('localname', $sheet1, '$F$6:$H$6', true)); + + if ($cellReference === 'omitted') { + $sheet->getCell('B3')->setValue('=ROW()'); + } else { + $sheet->getCell('B3')->setValue("=ROW($cellReference)"); + } + + $result = $sheet->getCell('B3')->getCalculatedValue(); + self::assertSame($expectedResult, $result); + } + + public function providerROWOnSpreadsheet(): array + { + return require 'tests/data/Calculation/LookupRef/ROWonSpreadsheet.php'; + } + + public function testINDIRECTLocalDefinedName(): void + { + $sheet = $this->getSheet(); + + $sheet1 = $this->getSpreadsheet()->createSheet(); + $sheet1->setTitle('OtherSheet'); + $this->getSpreadsheet()->addNamedRange(new NamedRange('newnr', $sheet1, '$F$5:$H$5', true)); // defined locally, only usable on sheet1 + + $sheet1->getCell('B3')->setValue('=ROW(newnr)'); + $result = $sheet1->getCell('B3')->getCalculatedValue(); + self::assertSame(5, $result); + + $sheet->getCell('B3')->setValue('=ROW(newnr)'); + $result = $sheet->getCell('B3')->getCalculatedValue(); + self::assertSame('#NAME?', $result); + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/RowTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/RowTest.php new file mode 100644 index 00000000..0e73e829 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/RowTest.php @@ -0,0 +1,46 @@ +getMockBuilder(Cell::class) + ->onlyMethods(['getRow']) + ->disableOriginalConstructor() + ->getMock(); + $cell->method('getRow') + ->willReturn(3); + + $result = LookupRef::ROW(null, $cell); + self::assertSame(3, $result); + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/RowsOnSpreadsheetTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/RowsOnSpreadsheetTest.php new file mode 100644 index 00000000..ce5bd5ee --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/RowsOnSpreadsheetTest.php @@ -0,0 +1,60 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setTitle('ThisSheet'); + $this->getSpreadsheet()->addNamedRange(new NamedRange('namedrangex', $sheet, '$E$2:$E$6')); + $this->getSpreadsheet()->addNamedRange(new NamedRange('namedrangey', $sheet, '$F$2:$H$2')); + $this->getSpreadsheet()->addNamedRange(new NamedRange('namedrange3', $sheet, '$F$4:$H$4')); + $this->getSpreadsheet()->addNamedRange(new NamedRange('namedrange5', $sheet, '$F$5:$H$5', true)); + + $sheet1 = $this->getSpreadsheet()->createSheet(); + $sheet1->setTitle('OtherSheet'); + $this->getSpreadsheet()->addNamedRange(new NamedRange('localname', $sheet1, '$F$6:$H$6', true)); + + if ($cellReference === 'omitted') { + $sheet->getCell('B3')->setValue('=ROWS()'); + } else { + $sheet->getCell('B3')->setValue("=ROWS($cellReference)"); + } + + $result = $sheet->getCell('B3')->getCalculatedValue(); + self::assertSame($expectedResult, $result); + } + + public function providerROWSOnSpreadsheet(): array + { + return require 'tests/data/Calculation/LookupRef/ROWSonSpreadsheet.php'; + } + + public function testRowsLocalDefinedName(): void + { + $sheet = $this->getSheet(); + + $sheet1 = $this->getSpreadsheet()->createSheet(); + $sheet1->setTitle('OtherSheet'); + $this->getSpreadsheet()->addNamedRange(new NamedRange('newnr', $sheet1, '$F$5:$H$10', true)); // defined locally, only usable on sheet1 + + $sheet1->getCell('B3')->setValue('=ROWS(newnr)'); + $result = $sheet1->getCell('B3')->getCalculatedValue(); + self::assertSame(6, $result); + + $sheet->getCell('B3')->setValue('=ROWS(newnr)'); + $result = $sheet->getCell('B3')->getCalculatedValue(); + self::assertSame('#NAME?', $result); + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/RowsTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/RowsTest.php index 62a06626..ec9b33d9 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/RowsTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/RowsTest.php @@ -24,7 +24,7 @@ class RowsTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerROWS() + public function providerROWS(): array { return require 'tests/data/Calculation/LookupRef/ROWS.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/TransposeTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/TransposeTest.php new file mode 100644 index 00000000..7654f1bd --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/TransposeTest.php @@ -0,0 +1,32 @@ +getSheet(); + $this->mightHaveException($expectedResult); + $this->setCell('A1', $number); + if ($number === 'omitted') { + $sheet->getCell('B1')->setValue('=ABS()'); + } else { + $sheet->getCell('B1')->setValue('=ABS(A1)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertSame($expectedResult, $result); + } + + public function providerAbs(): array + { + return require 'tests/data/Calculation/MathTrig/ABS.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AcosTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AcosTest.php new file mode 100644 index 00000000..4b71a541 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AcosTest.php @@ -0,0 +1,26 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('A2')->setValue(0.5); + $sheet->getCell('A1')->setValue("=ACOS($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-6); + } + + public function providerAcos(): array + { + return require 'tests/data/Calculation/MathTrig/ACOS.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AcoshTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AcoshTest.php new file mode 100644 index 00000000..c2116009 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AcoshTest.php @@ -0,0 +1,26 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('A2')->setValue('1.5'); + $sheet->getCell('A1')->setValue("=ACOSH($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-6); + } + + public function providerAcosh(): array + { + return require 'tests/data/Calculation/MathTrig/ACOSH.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AcotTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AcotTest.php index d81c3b9d..8aa5541f 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AcotTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AcotTest.php @@ -2,17 +2,8 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class AcotTest extends TestCase +class AcotTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerACOT * @@ -21,11 +12,18 @@ class AcotTest extends TestCase */ public function testACOT($expectedResult, $number): void { - $result = MathTrig::ACOT($number); - self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 2.7); + $sheet->setCellValue('A4', -3.8); + $sheet->setCellValue('A5', -5); + $sheet->getCell('A1')->setValue("=ACOT($number)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-9); } - public function providerACOT() + public function providerACOT(): array { return require 'tests/data/Calculation/MathTrig/ACOT.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AcothTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AcothTest.php index 0a3864cc..173d27b5 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AcothTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AcothTest.php @@ -2,17 +2,8 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class AcothTest extends TestCase +class AcothTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerACOTH * @@ -21,11 +12,18 @@ class AcothTest extends TestCase */ public function testACOTH($expectedResult, $number): void { - $result = MathTrig::ACOTH($number); - self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 2.7); + $sheet->setCellValue('A4', -3.8); + $sheet->setCellValue('A5', -10); + $sheet->getCell('A1')->setValue("=ACOTH($number)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-9); } - public function providerACOTH() + public function providerACOTH(): array { return require 'tests/data/Calculation/MathTrig/ACOTH.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AllSetupTeardown.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AllSetupTeardown.php new file mode 100644 index 00000000..f54ecaad --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AllSetupTeardown.php @@ -0,0 +1,97 @@ +compatibilityMode = Functions::getCompatibilityMode(); + } + + protected function tearDown(): void + { + Functions::setCompatibilityMode($this->compatibilityMode); + $this->sheet = null; + if ($this->spreadsheet !== null) { + $this->spreadsheet->disconnectWorksheets(); + $this->spreadsheet = null; + } + } + + protected static function setOpenOffice(): void + { + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + } + + protected static function setGnumeric(): void + { + Functions::setCompatibilityMode(Functions::COMPATIBILITY_GNUMERIC); + } + + /** + * @param mixed $expectedResult + */ + protected function mightHaveException($expectedResult): void + { + if ($expectedResult === 'exception') { + $this->expectException(CalcException::class); + } + } + + /** + * @param mixed $value + */ + protected function setCell(string $cell, $value): void + { + if ($value !== null) { + if (is_string($value) && is_numeric($value)) { + $this->getSheet()->getCell($cell)->setValueExplicit($value, DataType::TYPE_STRING); + } else { + $this->getSheet()->getCell($cell)->setValue($value); + } + } + } + + protected function getSpreadsheet(): Spreadsheet + { + if ($this->spreadsheet !== null) { + return $this->spreadsheet; + } + $this->spreadsheet = new Spreadsheet(); + + return $this->spreadsheet; + } + + protected function getSheet(): Worksheet + { + if ($this->sheet !== null) { + return $this->sheet; + } + $this->sheet = $this->getSpreadsheet()->getActiveSheet(); + + return $this->sheet; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/ArabicTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/ArabicTest.php index 7b3a5e15..7921e85d 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/ArabicTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/ArabicTest.php @@ -2,17 +2,8 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class ArabicTest extends TestCase +class ArabicTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerARABIC * @@ -21,11 +12,15 @@ class ArabicTest extends TestCase */ public function testARABIC($expectedResult, $romanNumeral): void { - $result = MathTrig::ARABIC($romanNumeral); - self::assertEquals($expectedResult, $result); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue($romanNumeral); + $sheet->getCell('B1')->setValue('=ARABIC(A1)'); + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertSame($expectedResult, $result); } - public function providerARABIC() + public function providerARABIC(): array { return require 'tests/data/Calculation/MathTrig/ARABIC.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AsinTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AsinTest.php new file mode 100644 index 00000000..73500d9a --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AsinTest.php @@ -0,0 +1,26 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('A2')->setValue(0.5); + $sheet->getCell('A1')->setValue("=ASIN($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-6); + } + + public function providerAsin(): array + { + return require 'tests/data/Calculation/MathTrig/ASIN.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AsinhTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AsinhTest.php new file mode 100644 index 00000000..4337a394 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AsinhTest.php @@ -0,0 +1,26 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('A2')->setValue(0.5); + $sheet->getCell('A1')->setValue("=ASINH($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-6); + } + + public function providerAsinh(): array + { + return require 'tests/data/Calculation/MathTrig/ASINH.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/Atan2Test.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/Atan2Test.php index 4edec4cb..dcf35ad1 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/Atan2Test.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/Atan2Test.php @@ -2,31 +2,25 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class Atan2Test extends TestCase +class Atan2Test extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerATAN2 * * @param mixed $expectedResult - * @param mixed $x - * @param mixed $y */ - public function testATAN2($expectedResult, $x, $y): void + public function testATAN2($expectedResult, string $formula): void { - $result = MathTrig::ATAN2($x, $y); - self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('A2')->setValue(5); + $sheet->getCell('A3')->setValue(6); + $sheet->getCell('A1')->setValue("=ATAN2($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-9); } - public function providerATAN2() + public function providerATAN2(): array { return require 'tests/data/Calculation/MathTrig/ATAN2.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AtanTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AtanTest.php new file mode 100644 index 00000000..4eefd922 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AtanTest.php @@ -0,0 +1,26 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('A2')->setValue(5); + $sheet->getCell('A1')->setValue("=ATAN($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-6); + } + + public function providerAtan(): array + { + return require 'tests/data/Calculation/MathTrig/ATAN.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AtanhTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AtanhTest.php new file mode 100644 index 00000000..d790b526 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/AtanhTest.php @@ -0,0 +1,26 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('A2')->setValue(0.8); + $sheet->getCell('A1')->setValue("=ATANH($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-6); + } + + public function providerAtanh(): array + { + return require 'tests/data/Calculation/MathTrig/ATANH.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/BaseTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/BaseTest.php index 72b52559..02f895cb 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/BaseTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/BaseTest.php @@ -2,29 +2,43 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class BaseTest extends TestCase +class BaseTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerBASE * * @param mixed $expectedResult + * @param mixed $arg1 + * @param mixed $arg2 + * @param mixed $arg3 */ - public function testBASE($expectedResult, ...$args): void + public function testBASE($expectedResult, $arg1 = 'omitted', $arg2 = 'omitted', $arg3 = 'omitted'): void { - $result = MathTrig::BASE(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($arg1 !== null) { + $sheet->getCell('A1')->setValue($arg1); + } + if ($arg2 !== null) { + $sheet->getCell('A2')->setValue($arg2); + } + if ($arg3 !== null) { + $sheet->getCell('A3')->setValue($arg3); + } + if ($arg1 === 'omitted') { + $sheet->getCell('B1')->setValue('=BASE()'); + } elseif ($arg2 === 'omitted') { + $sheet->getCell('B1')->setValue('=BASE(A1)'); + } elseif ($arg3 === 'omitted') { + $sheet->getCell('B1')->setValue('=BASE(A1, A2)'); + } else { + $sheet->getCell('B1')->setValue('=BASE(A1, A2, A3)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerBASE() + public function providerBASE(): array { return require 'tests/data/Calculation/MathTrig/BASE.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CeilingMathTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CeilingMathTest.php new file mode 100644 index 00000000..8622ad62 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CeilingMathTest.php @@ -0,0 +1,30 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 2.7); + $sheet->setCellValue('A4', -3.8); + $sheet->setCellValue('A5', -5.2); + $sheet->getCell('A1')->setValue("=CEILING.MATH($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + } + + public function providerCEILINGMATH(): array + { + return require 'tests/data/Calculation/MathTrig/CEILINGMATH.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CeilingPreciseTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CeilingPreciseTest.php new file mode 100644 index 00000000..f7b0cc28 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CeilingPreciseTest.php @@ -0,0 +1,30 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 2.7); + $sheet->setCellValue('A4', -3.8); + $sheet->setCellValue('A5', -5.2); + $sheet->getCell('A1')->setValue("=CEILING.PRECISE($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + } + + public function providerFLOORPRECISE(): array + { + return require 'tests/data/Calculation/MathTrig/CEILINGPRECISE.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CeilingTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CeilingTest.php index b60d7c30..3ac38b0d 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CeilingTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CeilingTest.php @@ -2,30 +2,56 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class CeilingTest extends TestCase +class CeilingTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerCEILING * * @param mixed $expectedResult + * @param string $formula */ - public function testCEILING($expectedResult, ...$args): void + public function testCEILING($expectedResult, $formula): void { - $result = MathTrig::CEILING(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 2.7); + $sheet->setCellValue('A4', -3.8); + $sheet->setCellValue('A5', -5.2); + $sheet->getCell('A1')->setValue("=CEILING($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerCEILING() + public function providerCEILING(): array { return require 'tests/data/Calculation/MathTrig/CEILING.php'; } + + public function testCEILINGGnumeric1Arg(): void + { + self::setGnumeric(); + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue('=CEILING(5.1)'); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta(6, $result, 1E-12); + } + + public function testCELINGOpenOffice1Arg(): void + { + self::setOpenOffice(); + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue('=CEILING(5.1)'); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta(6, $result, 1E-12); + } + + public function testCEILINGExcel1Arg(): void + { + $this->mightHaveException('exception'); + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue('=CEILING(5.1)'); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta(6, $result, 1E-12); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CombinATest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CombinATest.php new file mode 100644 index 00000000..0bc70de1 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CombinATest.php @@ -0,0 +1,33 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($numObjs !== null) { + $sheet->getCell('A1')->setValue($numObjs); + } + if ($numInSet !== null) { + $sheet->getCell('A2')->setValue($numInSet); + } + $sheet->getCell('B1')->setValue('=COMBINA(A1,A2)'); + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function providerCOMBINA(): array + { + return require 'tests/data/Calculation/MathTrig/COMBINA.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CombinTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CombinTest.php index d9156339..8680dee6 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CombinTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CombinTest.php @@ -2,29 +2,31 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class CombinTest extends TestCase +class CombinTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerCOMBIN * * @param mixed $expectedResult + * @param mixed $numObjs + * @param mixed $numInSet */ - public function testCOMBIN($expectedResult, ...$args): void + public function testCOMBIN($expectedResult, $numObjs, $numInSet): void { - $result = MathTrig::COMBIN(...$args); - self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($numObjs !== null) { + $sheet->getCell('A1')->setValue($numObjs); + } + if ($numInSet !== null) { + $sheet->getCell('A2')->setValue($numInSet); + } + $sheet->getCell('B1')->setValue('=COMBIN(A1,A2)'); + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); } - public function providerCOMBIN() + public function providerCOMBIN(): array { return require 'tests/data/Calculation/MathTrig/COMBIN.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CosTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CosTest.php new file mode 100644 index 00000000..2024c6b2 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CosTest.php @@ -0,0 +1,26 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 2); + $sheet->getCell('A1')->setValue("=COS($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-6); + } + + public function providerCos(): array + { + return require 'tests/data/Calculation/MathTrig/COS.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CoshTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CoshTest.php new file mode 100644 index 00000000..1a87f72e --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CoshTest.php @@ -0,0 +1,26 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 2); + $sheet->getCell('A1')->setValue("=COSH($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-6); + } + + public function providerCosh(): array + { + return require 'tests/data/Calculation/MathTrig/COSH.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CotTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CotTest.php index 3fee6901..db9c17d1 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CotTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CotTest.php @@ -2,17 +2,8 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class CotTest extends TestCase +class CotTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerCOT * @@ -21,11 +12,18 @@ class CotTest extends TestCase */ public function testCOT($expectedResult, $angle): void { - $result = MathTrig::COT($angle); - self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 2.7); + $sheet->setCellValue('A4', -3.8); + $sheet->setCellValue('A5', -5.2); + $sheet->getCell('A1')->setValue("=COT($angle)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-9); } - public function providerCOT() + public function providerCOT(): array { return require 'tests/data/Calculation/MathTrig/COT.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CothTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CothTest.php index e3db23d5..ed0bf13e 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CothTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CothTest.php @@ -2,17 +2,8 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class CothTest extends TestCase +class CothTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerCOTH * @@ -21,11 +12,18 @@ class CothTest extends TestCase */ public function testCOTH($expectedResult, $angle): void { - $result = MathTrig::COTH($angle); - self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 2.7); + $sheet->setCellValue('A4', -3.8); + $sheet->setCellValue('A5', -5.2); + $sheet->getCell('A1')->setValue("=COTH($angle)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-9); } - public function providerCOTH() + public function providerCOTH(): array { return require 'tests/data/Calculation/MathTrig/COTH.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CscTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CscTest.php index 675ebf57..ff4067a7 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CscTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CscTest.php @@ -2,17 +2,8 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class CscTest extends TestCase +class CscTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerCSC * @@ -21,11 +12,18 @@ class CscTest extends TestCase */ public function testCSC($expectedResult, $angle): void { - $result = MathTrig::CSC($angle); - self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 2.7); + $sheet->setCellValue('A4', -3.8); + $sheet->setCellValue('A5', -5.2); + $sheet->getCell('A1')->setValue("=CSC($angle)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-9); } - public function providerCSC() + public function providerCSC(): array { return require 'tests/data/Calculation/MathTrig/CSC.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CschTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CschTest.php index c630be2f..9f6a87e7 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CschTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/CschTest.php @@ -2,17 +2,8 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class CschTest extends TestCase +class CschTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerCSCH * @@ -21,11 +12,18 @@ class CschTest extends TestCase */ public function testCSCH($expectedResult, $angle): void { - $result = MathTrig::CSCH($angle); - self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 2.7); + $sheet->setCellValue('A4', -3.8); + $sheet->setCellValue('A5', -5.2); + $sheet->getCell('A1')->setValue("=CSCH($angle)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-9); } - public function providerCSCH() + public function providerCSCH(): array { return require 'tests/data/Calculation/MathTrig/CSCH.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/DegreesTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/DegreesTest.php new file mode 100644 index 00000000..c931be2b --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/DegreesTest.php @@ -0,0 +1,31 @@ +getSheet(); + $this->mightHaveException($expectedResult); + $this->setCell('A1', $number); + if ($number === 'omitted') { + $sheet->getCell('B1')->setValue('=DEGREES()'); + } else { + $sheet->getCell('B1')->setValue('=DEGREES(A1)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-8); + } + + public function providerDegrees(): array + { + return require 'tests/data/Calculation/MathTrig/DEGREES.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/EvenTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/EvenTest.php index 96c0b046..933737b4 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/EvenTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/EvenTest.php @@ -2,30 +2,24 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class EvenTest extends TestCase +class EvenTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerEVEN * * @param mixed $expectedResult - * @param $value + * @param mixed $value */ public function testEVEN($expectedResult, $value): void { - $result = MathTrig::EVEN($value); - self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue("=EVEN($value)"); + $sheet->getCell('A2')->setValue(3.7); + self::assertEquals($expectedResult, $sheet->getCell('A1')->getCalculatedValue()); } - public function providerEVEN() + public function providerEVEN(): array { return require 'tests/data/Calculation/MathTrig/EVEN.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/ExpTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/ExpTest.php new file mode 100644 index 00000000..c1c88bb1 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/ExpTest.php @@ -0,0 +1,33 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($number !== null) { + $sheet->getCell('A1')->setValue($number); + } + if ($number === 'omitted') { + $sheet->getCell('B1')->setValue('=EXP()'); + } else { + $sheet->getCell('B1')->setValue('=EXP(A1)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + } + + public function providerEXP(): array + { + return require 'tests/data/Calculation/MathTrig/EXP.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/FactDoubleTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/FactDoubleTest.php index f0b6b146..7a620655 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/FactDoubleTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/FactDoubleTest.php @@ -2,30 +2,25 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class FactDoubleTest extends TestCase +class FactDoubleTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerFACTDOUBLE * * @param mixed $expectedResult - * @param $value + * @param mixed $value */ public function testFACTDOUBLE($expectedResult, $value): void { - $result = MathTrig::FACTDOUBLE($value); - self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue($value); + $sheet->getCell('B1')->setValue('=FACTDOUBLE(A1)'); + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); } - public function providerFACTDOUBLE() + public function providerFACTDOUBLE(): array { return require 'tests/data/Calculation/MathTrig/FACTDOUBLE.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/FactTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/FactTest.php index f6092896..5dca45ff 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/FactTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/FactTest.php @@ -2,31 +2,60 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class FactTest extends TestCase +class FactTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerFACT * * @param mixed $expectedResult - * @param $value + * @param mixed $arg1 */ - public function testFACT($expectedResult, $value): void + public function testFACT($expectedResult, $arg1): void { - $result = MathTrig::FACT($value); - self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($arg1 !== null) { + $sheet->getCell('A1')->setValue($arg1); + } + if ($arg1 === 'omitted') { + $sheet->getCell('B1')->setValue('=FACT()'); + } else { + $sheet->getCell('B1')->setValue('=FACT(A1)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); } - public function providerFACT() + public function providerFACT(): array { return require 'tests/data/Calculation/MathTrig/FACT.php'; } + + /** + * @dataProvider providerFACTGnumeric + * + * @param mixed $expectedResult + * @param mixed $arg1 + */ + public function testFACTGnumeric($expectedResult, $arg1): void + { + $this->mightHaveException($expectedResult); + self::setGnumeric(); + $sheet = $this->getSheet(); + if ($arg1 !== null) { + $sheet->getCell('A1')->setValue($arg1); + } + if ($arg1 === 'omitted') { + $sheet->getCell('B1')->setValue('=FACT()'); + } else { + $sheet->getCell('B1')->setValue('=FACT(A1)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function providerFACTGnumeric(): array + { + return require 'tests/data/Calculation/MathTrig/FACTGNUMERIC.php'; + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/FloorMathTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/FloorMathTest.php index d7d51b59..c5235569 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/FloorMathTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/FloorMathTest.php @@ -2,29 +2,28 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class FloorMathTest extends TestCase +class FloorMathTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerFLOORMATH * * @param mixed $expectedResult + * @param string $formula */ - public function testFLOORMATH($expectedResult, ...$args): void + public function testFLOORMATH($expectedResult, $formula): void { - $result = MathTrig::FLOORMATH(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 2.7); + $sheet->setCellValue('A4', -3.8); + $sheet->setCellValue('A5', -5.2); + $sheet->getCell('A1')->setValue("=FLOOR.MATH($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerFLOORMATH() + public function providerFLOORMATH(): array { return require 'tests/data/Calculation/MathTrig/FLOORMATH.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/FloorPreciseTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/FloorPreciseTest.php index ae5a3199..7db80d7a 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/FloorPreciseTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/FloorPreciseTest.php @@ -2,29 +2,28 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class FloorPreciseTest extends TestCase +class FloorPreciseTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerFLOORPRECISE * * @param mixed $expectedResult + * @param string $formula */ - public function testFLOOR($expectedResult, ...$args): void + public function testFLOORPRECISE($expectedResult, $formula): void { - $result = MathTrig::FLOORPRECISE(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 2.7); + $sheet->setCellValue('A4', -3.8); + $sheet->setCellValue('A5', -5.2); + $sheet->getCell('A1')->setValue("=FLOOR.PRECISE($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerFLOORPRECISE() + public function providerFLOORPRECISE(): array { return require 'tests/data/Calculation/MathTrig/FLOORPRECISE.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/FloorTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/FloorTest.php index e66d97ae..a106a91d 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/FloorTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/FloorTest.php @@ -2,30 +2,56 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class FloorTest extends TestCase +class FloorTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerFLOOR * * @param mixed $expectedResult + * @param string $formula */ - public function testFLOOR($expectedResult, ...$args): void + public function testFLOOR($expectedResult, $formula): void { - $result = MathTrig::FLOOR(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 2.7); + $sheet->setCellValue('A4', -3.8); + $sheet->setCellValue('A5', -5.2); + $sheet->getCell('A1')->setValue("=FLOOR($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerFLOOR() + public function providerFLOOR(): array { return require 'tests/data/Calculation/MathTrig/FLOOR.php'; } + + public function testFLOORGnumeric1Arg(): void + { + self::setGnumeric(); + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue('=FLOOR(5.1)'); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta(5, $result, 1E-12); + } + + public function testFLOOROpenOffice1Arg(): void + { + self::setOpenOffice(); + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue('=FLOOR(5.1)'); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta(5, $result, 1E-12); + } + + public function testFLOORExcel1Arg(): void + { + $this->mightHaveException('exception'); + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue('=FLOOR(5.1)'); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta(5, $result, 1E-12); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/GcdTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/GcdTest.php index ce1aec3f..8c79e0fa 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/GcdTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/GcdTest.php @@ -2,17 +2,8 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class GcdTest extends TestCase +class GcdTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerGCD * @@ -20,11 +11,25 @@ class GcdTest extends TestCase */ public function testGCD($expectedResult, ...$args): void { - $result = MathTrig::GCD(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $row = 0; + foreach ($args as $arg) { + ++$row; + if ($arg !== null) { + $sheet->getCell("A$row")->setValue($arg); + } + } + if ($row < 1) { + $sheet->getCell('B1')->setValue('=GCD()'); + } else { + $sheet->getCell('B1')->setValue("=GCD(A1:A$row)"); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerGCD() + public function providerGCD(): array { return require 'tests/data/Calculation/MathTrig/GCD.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/IntTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/IntTest.php index f400a7fe..e121decb 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/IntTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/IntTest.php @@ -2,30 +2,28 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class IntTest extends TestCase +class IntTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerINT * * @param mixed $expectedResult - * @param $value + * @param string $formula */ - public function testINT($expectedResult, $value): void + public function testINT($expectedResult, $formula): void { - $result = MathTrig::INT($value); - self::assertEquals($expectedResult, $result); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 2.7); + $sheet->setCellValue('A4', -3.8); + $sheet->setCellValue('A5', -5.2); + $sheet->getCell('A1')->setValue("=INT($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerINT() + public function providerINT(): array { return require 'tests/data/Calculation/MathTrig/INT.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/LcmTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/LcmTest.php index 57b4a67f..ec51e3a0 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/LcmTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/LcmTest.php @@ -2,17 +2,8 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class LcmTest extends TestCase +class LcmTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerLCM * @@ -20,11 +11,18 @@ class LcmTest extends TestCase */ public function testLCM($expectedResult, ...$args): void { - $result = MathTrig::LCM(...$args); + $sheet = $this->getSheet(); + $row = 0; + foreach ($args as $arg) { + ++$row; + $sheet->getCell("A$row")->setValue($arg); + } + $sheet->getCell('B1')->setValue("=LCM(A1:A$row)"); + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerLCM() + public function providerLCM(): array { return require 'tests/data/Calculation/MathTrig/LCM.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/LnTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/LnTest.php new file mode 100644 index 00000000..991af46d --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/LnTest.php @@ -0,0 +1,33 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($number !== null) { + $sheet->getCell('A1')->setValue($number); + } + if ($number === 'omitted') { + $sheet->getCell('B1')->setValue('=LN()'); + } else { + $sheet->getCell('B1')->setValue('=LN(A1)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-6); + } + + public function providerLN(): array + { + return require 'tests/data/Calculation/MathTrig/LN.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/Log10Test.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/Log10Test.php new file mode 100644 index 00000000..be095c9b --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/Log10Test.php @@ -0,0 +1,33 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($number !== null) { + $sheet->getCell('A1')->setValue($number); + } + if ($number === 'omitted') { + $sheet->getCell('B1')->setValue('=LOG10()'); + } else { + $sheet->getCell('B1')->setValue('=LOG10(A1)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-6); + } + + public function providerLN(): array + { + return require 'tests/data/Calculation/MathTrig/LOG10.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/LogTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/LogTest.php index 184d83e6..ba1823b1 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/LogTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/LogTest.php @@ -2,29 +2,37 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class LogTest extends TestCase +class LogTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerLOG * * @param mixed $expectedResult + * @param mixed $number + * @param mixed $base */ - public function testLOG($expectedResult, ...$args): void + public function testLOG($expectedResult, $number = 'omitted', $base = 'omitted'): void { - $result = MathTrig::logBase(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($number !== null) { + $sheet->getCell('A1')->setValue($number); + } + if ($base !== null) { + $sheet->getCell('A2')->setValue($base); + } + if ($number === 'omitted') { + $sheet->getCell('B1')->setValue('=LOG()'); + } elseif ($base === 'omitted') { + $sheet->getCell('B1')->setValue('=LOG(A1)'); + } else { + $sheet->getCell('B1')->setValue('=LOG(A1,A2)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerLOG() + public function providerLOG(): array { return require 'tests/data/Calculation/MathTrig/LOG.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MInverseTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MInverseTest.php index a500c3f6..f059ab48 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MInverseTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MInverseTest.php @@ -2,30 +2,31 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; -class MInverseTest extends TestCase +class MInverseTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerMINVERSE * * @param mixed $expectedResult */ - public function testMINVERSE($expectedResult, ...$args): void + public function testMINVERSE($expectedResult, array $args): void { - $result = MathTrig::MINVERSE(...$args); + $result = MathTrig\MatrixFunctions::inverse($args); self::assertEqualsWithDelta($expectedResult, $result, 1E-8); } - public function providerMINVERSE() + public function providerMINVERSE(): array { return require 'tests/data/Calculation/MathTrig/MINVERSE.php'; } + + public function testOnSpreadsheet(): void + { + // very limited ability to test this in the absence of dynamic arrays + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue('=MINVERSE({1,2,3})'); // not square + self::assertSame('#VALUE!', $sheet->getCell('A1')->getCalculatedValue()); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MMultTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MMultTest.php index 66fa80db..7e15b94c 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MMultTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MMultTest.php @@ -2,17 +2,10 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; -class MMultTest extends TestCase +class MMultTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerMMULT * @@ -20,12 +13,31 @@ class MMultTest extends TestCase */ public function testMMULT($expectedResult, ...$args): void { - $result = MathTrig::MMULT(...$args); + $result = MathTrig\MatrixFunctions::multiply(...$args); self::assertEqualsWithDelta($expectedResult, $result, 1E-8); } - public function providerMMULT() + public function providerMMULT(): array { return require 'tests/data/Calculation/MathTrig/MMULT.php'; } + + public function testOnSpreadsheet(): void + { + // very limited ability to test this in the absence of dynamic arrays + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue('=MMULT({1,2,3}, {1,2,3})'); // incompatible dimensions + self::assertSame('#VALUE!', $sheet->getCell('A1')->getCalculatedValue()); + + $sheet->getCell('A11')->setValue('=MMULT({1, 2, 3, 4}, {5; 6; 7; 8})'); + self::assertEquals(70, $sheet->getCell('A11')->getCalculatedValue()); + $sheet->getCell('A2')->setValue(1); + $sheet->getCell('B2')->setValue(2); + $sheet->getCell('C2')->setValue(3); + $sheet->getCell('D2')->setValue(4); + $sheet->getCell('D3')->setValue(5); + $sheet->getCell('D4')->setValue(6); + $sheet->getCell('A12')->setValue('=MMULT(A2:C2,D2:D4)'); + self::assertEquals(32, $sheet->getCell('A12')->getCalculatedValue()); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MRoundTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MRoundTest.php index 32c9c355..80a3d4ba 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MRoundTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MRoundTest.php @@ -2,29 +2,28 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class MRoundTest extends TestCase +class MRoundTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerMROUND * * @param mixed $expectedResult + * @param mixed $formula */ - public function testMROUND($expectedResult, ...$args): void + public function testMROUND($expectedResult, $formula): void { - $result = MathTrig::MROUND(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 2.7); + $sheet->setCellValue('A4', -3.8); + $sheet->setCellValue('A5', -5.2); + $sheet->getCell('A1')->setValue("=MROUND($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerMROUND() + public function providerMROUND(): array { return require 'tests/data/Calculation/MathTrig/MROUND.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MUnitTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MUnitTest.php new file mode 100644 index 00000000..96ebc45b --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MUnitTest.php @@ -0,0 +1,23 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if (is_array($matrix)) { + $sheet->fromArray($matrix, null, 'A1', true); + $maxCol = $sheet->getHighestColumn(); + $maxRow = $sheet->getHighestRow(); + $sheet->getCell('Z1')->setValue("=MDETERM(A1:$maxCol$maxRow)"); + } else { + $sheet->getCell('Z1')->setValue("=MDETERM($matrix)"); + } + $result = $sheet->getCell('Z1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerMDETERM() + public function providerMDETERM(): array { return require 'tests/data/Calculation/MathTrig/MDETERM.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/ModTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/ModTest.php index 930708f5..2035d26f 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/ModTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/ModTest.php @@ -2,29 +2,37 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class ModTest extends TestCase +class ModTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerMOD * * @param mixed $expectedResult + * @param mixed $dividend + * @param mixed $divisor */ - public function testMOD($expectedResult, ...$args): void + public function testMOD($expectedResult, $dividend = 'omitted', $divisor = 'omitted'): void { - $result = MathTrig::MOD(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($dividend !== null) { + $sheet->getCell('A1')->setValue($dividend); + } + if ($divisor !== null) { + $sheet->getCell('A2')->setValue($divisor); + } + if ($dividend === 'omitted') { + $sheet->getCell('B1')->setValue('=MOD()'); + } elseif ($divisor === 'omitted') { + $sheet->getCell('B1')->setValue('=MOD(A1)'); + } else { + $sheet->getCell('B1')->setValue('=MOD(A1,A2)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerMOD() + public function providerMOD(): array { return require 'tests/data/Calculation/MathTrig/MOD.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MovedFunctionsTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MovedFunctionsTest.php new file mode 100644 index 00000000..2cca8f36 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MovedFunctionsTest.php @@ -0,0 +1,111 @@ +2')); + self::assertEquals(2, MathTrig::SUMIFS( + [[1], [1], [1]], + [['Y'], ['Y'], ['N']], + '=Y', + [['H'], ['H'], ['H']], + '=H' + )); + self::assertEquals(17, MathTrig::SUMPRODUCT([1, 2, 3], [5, 0, 4])); + self::assertEquals(21, MathTrig::SUMSQ(1, 2, 4)); + self::assertEquals(-20, MathTrig::SUMX2MY2([1, 2], [3, 4])); + self::assertEquals(30, MathTrig::SUMX2PY2([1, 2], [3, 4])); + self::assertEquals(8, MathTrig::SUMXMY2([1, 2], [3, 4])); + self::assertEquals(0, MathTrig::builtinTAN(0)); + self::assertEquals(0, MathTrig::builtinTANH(0)); + self::assertEquals(70, MathTrig::TRUNC(79.2, -1)); + self::assertEquals(1, MathTrig::returnSign(79.2)); + self::assertEquals(80, MathTrig::getEven(79.2)); + $nullVal = null; + MathTrig::nullFalseTrueToNumber($nullVal); + self::assertSame(0, $nullVal); + $nullVal = true; + MathTrig::nullFalseTrueToNumber($nullVal); + self::assertSame(1, $nullVal); + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MultinomialTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MultinomialTest.php index 93735ba9..f511792a 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MultinomialTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/MultinomialTest.php @@ -2,17 +2,8 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class MultinomialTest extends TestCase +class MultinomialTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerMULTINOMIAL * @@ -20,11 +11,23 @@ class MultinomialTest extends TestCase */ public function testMULTINOMIAL($expectedResult, ...$args): void { - $result = MathTrig::MULTINOMIAL(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $row = 0; + $excelArg = ''; + foreach ($args as $arg) { + ++$row; + $excelArg = "A1:A$row"; + if ($arg !== null) { + $sheet->getCell("A$row")->setValue($arg); + } + } + $sheet->getCell('B1')->setValue("=MULTINOMIAL($excelArg)"); + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerMULTINOMIAL() + public function providerMULTINOMIAL(): array { return require 'tests/data/Calculation/MathTrig/MULTINOMIAL.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/OddTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/OddTest.php index 6c5758c6..4f6b0cab 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/OddTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/OddTest.php @@ -2,30 +2,24 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class OddTest extends TestCase +class OddTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerODD * * @param mixed $expectedResult - * @param $value + * @param mixed $value */ public function testODD($expectedResult, $value): void { - $result = MathTrig::ODD($value); - self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue("=ODD($value)"); + $sheet->getCell('A2')->setValue(3.7); + self::assertEquals($expectedResult, $sheet->getCell('A1')->getCalculatedValue()); } - public function providerODD() + public function providerODD(): array { return require 'tests/data/Calculation/MathTrig/ODD.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/PowerTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/PowerTest.php index 6749b14a..179f7ea9 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/PowerTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/PowerTest.php @@ -2,29 +2,37 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class PowerTest extends TestCase +class PowerTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerPOWER * * @param mixed $expectedResult + * @param mixed $base + * @param mixed $exponent */ - public function testPOWER($expectedResult, ...$args): void + public function testPOWER($expectedResult, $base = 'omitted', $exponent = 'omitted'): void { - $result = MathTrig::POWER(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($base !== null) { + $sheet->getCell('A1')->setValue($base); + } + if ($exponent !== null) { + $sheet->getCell('A2')->setValue($exponent); + } + if ($base === 'omitted') { + $sheet->getCell('B1')->setValue('=POWER()'); + } elseif ($exponent === 'omitted') { + $sheet->getCell('B1')->setValue('=POWER(A1)'); + } else { + $sheet->getCell('B1')->setValue('=POWER(A1,A2)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerPOWER() + public function providerPOWER(): array { return require 'tests/data/Calculation/MathTrig/POWER.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/ProductTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/ProductTest.php index 251b783b..8ce39310 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/ProductTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/ProductTest.php @@ -2,17 +2,8 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class ProductTest extends TestCase +class ProductTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerPRODUCT * @@ -20,11 +11,18 @@ class ProductTest extends TestCase */ public function testPRODUCT($expectedResult, ...$args): void { - $result = MathTrig::PRODUCT(...$args); + $sheet = $this->getSheet(); + $row = 0; + foreach ($args as $arg) { + ++$row; + $sheet->getCell("A$row")->setValue($arg); + } + $sheet->getCell('B1')->setValue("=PRODUCT(A1:A$row)"); + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerPRODUCT() + public function providerPRODUCT(): array { return require 'tests/data/Calculation/MathTrig/PRODUCT.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/QuotientTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/QuotientTest.php index 4232729a..f5bced1e 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/QuotientTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/QuotientTest.php @@ -2,29 +2,37 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class QuotientTest extends TestCase +class QuotientTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerQUOTIENT * * @param mixed $expectedResult + * @param mixed $arg1 + * @param mixed $arg2 */ - public function testQUOTIENT($expectedResult, ...$args): void + public function testQUOTIENT($expectedResult, $arg1 = 'omitted', $arg2 = 'omitted'): void { - $result = MathTrig::QUOTIENT(...$args); - self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($arg1 !== null) { + $sheet->getCell('A1')->setValue($arg1); + } + if ($arg2 !== null) { + $sheet->getCell('A2')->setValue($arg2); + } + if ($arg1 === 'omitted') { + $sheet->getCell('B1')->setValue('=QUOTIENT()'); + } elseif ($arg2 === 'omitted') { + $sheet->getCell('B1')->setValue('=QUOTIENT(A1)'); + } else { + $sheet->getCell('B1')->setValue('=QUOTIENT(A1, A2)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertSame($expectedResult, $result); } - public function providerQUOTIENT() + public function providerQUOTIENT(): array { return require 'tests/data/Calculation/MathTrig/QUOTIENT.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RadiansTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RadiansTest.php new file mode 100644 index 00000000..82df95f4 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RadiansTest.php @@ -0,0 +1,31 @@ +getSheet(); + $this->mightHaveException($expectedResult); + $this->setCell('A1', $number); + if ($number === 'omitted') { + $sheet->getCell('B1')->setValue('=RADIANS()'); + } else { + $sheet->getCell('B1')->setValue('=RADIANS(A1)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-9); + } + + public function providerRADIANS(): array + { + return require 'tests/data/Calculation/MathTrig/RADIANS.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RandBetweenTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RandBetweenTest.php new file mode 100644 index 00000000..54d2c8d4 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RandBetweenTest.php @@ -0,0 +1,46 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $lower = (int) $min; + $upper = (int) $max; + if ($min !== null) { + $sheet->getCell('A1')->setValue($min); + } + if ($max !== null) { + $sheet->getCell('A2')->setValue($max); + } + if ($min === 'omitted') { + $sheet->getCell('B1')->setValue('=RANDBETWEEN()'); + } elseif ($max === 'omitted') { + $sheet->getCell('B1')->setValue('=RANDBETWEEN(A1)'); + } else { + $sheet->getCell('B1')->setValue('=RANDBETWEEN(A1,A2)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); + if (is_numeric($expectedResult)) { + self::assertGreaterThanOrEqual($lower, $result); + self::assertLessThanOrEqual($upper, $result); + } else { + self::assertSame($expectedResult, $result); + } + } + + public function providerRANDBETWEEN(): array + { + return require 'tests/data/Calculation/MathTrig/RANDBETWEEN.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RandTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RandTest.php new file mode 100644 index 00000000..989c4883 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RandTest.php @@ -0,0 +1,24 @@ +getSheet(); + $sheet->getCell('B1')->setValue('=RAND()'); + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertGreaterThanOrEqual(0, $result); + self::assertLessThanOrEqual(1, $result); + } + + public function testRandException(): void + { + $this->mightHaveException('exception'); + $sheet = $this->getSheet(); + $sheet->getCell('B1')->setValue('=RAND(A1)'); + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEquals(0, $result); + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RomanTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RomanTest.php index c74daa32..2690c8d2 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RomanTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RomanTest.php @@ -2,29 +2,25 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class RomanTest extends TestCase +class RomanTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerROMAN * * @param mixed $expectedResult + * @param mixed $formula */ - public function testROMAN($expectedResult, ...$args): void + public function testROMAN($expectedResult, $formula): void { - $result = MathTrig::ROMAN(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A3', 49); + $sheet->getCell('A1')->setValue("=ROMAN($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerROMAN() + public function providerROMAN(): array { return require 'tests/data/Calculation/MathTrig/ROMAN.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RoundDownTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RoundDownTest.php index 2fc211f3..7adc8258 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RoundDownTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RoundDownTest.php @@ -2,29 +2,28 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class RoundDownTest extends TestCase +class RoundDownTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** - * @dataProvider providerROUNDDOWN + * @dataProvider providerRoundDown * * @param mixed $expectedResult + * @param mixed $formula */ - public function testROUNDDOWN($expectedResult, ...$args): void + public function testRoundDown($expectedResult, $formula): void { - $result = MathTrig::ROUNDDOWN(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 2.7); + $sheet->setCellValue('A4', -3.8); + $sheet->setCellValue('A5', -5.2); + $sheet->getCell('A1')->setValue("=ROUNDDOWN($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerROUNDDOWN() + public function providerRoundDown(): array { return require 'tests/data/Calculation/MathTrig/ROUNDDOWN.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RoundTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RoundTest.php new file mode 100644 index 00000000..72f57580 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RoundTest.php @@ -0,0 +1,30 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 2.7); + $sheet->setCellValue('A4', -3.8); + $sheet->setCellValue('A5', -5.2); + $sheet->getCell('A1')->setValue("=ROUND($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + } + + public function providerRound(): array + { + return require 'tests/data/Calculation/MathTrig/ROUND.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RoundUpTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RoundUpTest.php index 825fe419..b12ddec4 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RoundUpTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/RoundUpTest.php @@ -2,29 +2,28 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class RoundUpTest extends TestCase +class RoundUpTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** - * @dataProvider providerROUNDUP + * @dataProvider providerRoundUp * * @param mixed $expectedResult + * @param mixed $formula */ - public function testROUNDUP($expectedResult, ...$args): void + public function testRoundUp($expectedResult, $formula): void { - $result = MathTrig::ROUNDUP(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 2.7); + $sheet->setCellValue('A4', -3.8); + $sheet->setCellValue('A5', -5.2); + $sheet->getCell('A1')->setValue("=ROUNDUP($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerROUNDUP() + public function providerRoundUp(): array { return require 'tests/data/Calculation/MathTrig/ROUNDUP.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SecTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SecTest.php index ad4b196c..395a2fee 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SecTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SecTest.php @@ -2,17 +2,8 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class SecTest extends TestCase +class SecTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerSEC * @@ -21,11 +12,18 @@ class SecTest extends TestCase */ public function testSEC($expectedResult, $angle): void { - $result = MathTrig::SEC($angle); - self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 2.7); + $sheet->setCellValue('A4', -3.8); + $sheet->setCellValue('A5', -5.2); + $sheet->getCell('A1')->setValue("=SEC($angle)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-9); } - public function providerSEC() + public function providerSEC(): array { return require 'tests/data/Calculation/MathTrig/SEC.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SechTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SechTest.php index b9488bda..51b5ff6e 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SechTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SechTest.php @@ -2,17 +2,8 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class SechTest extends TestCase +class SechTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerSECH * @@ -21,11 +12,18 @@ class SechTest extends TestCase */ public function testSECH($expectedResult, $angle): void { - $result = MathTrig::SECH($angle); - self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 2.7); + $sheet->setCellValue('A4', -3.8); + $sheet->setCellValue('A5', -5.2); + $sheet->getCell('A1')->setValue("=SECH($angle)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-9); } - public function providerSECH() + public function providerSECH(): array { return require 'tests/data/Calculation/MathTrig/SECH.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SeriesSumTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SeriesSumTest.php index 689336a3..df7bb213 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SeriesSumTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SeriesSumTest.php @@ -3,28 +3,43 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; -class SeriesSumTest extends TestCase +class SeriesSumTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerSERIESSUM * * @param mixed $expectedResult + * @param mixed $arg1 + * @param mixed $arg2 + * @param mixed $arg3 */ - public function testSERIESSUM($expectedResult, ...$args): void + public function testSERIESSUM($expectedResult, $arg1, $arg2, $arg3, ...$args): void { - $result = MathTrig::SERIESSUM(...$args); + $sheet = $this->getSheet(); + if ($arg1 !== null) { + $sheet->getCell('C1')->setValue($arg1); + } + if ($arg2 !== null) { + $sheet->getCell('C2')->setValue($arg2); + } + if ($arg3 !== null) { + $sheet->getCell('C3')->setValue($arg3); + } + $row = 0; + $aArgs = Functions::flattenArray($args); + foreach ($aArgs as $arg) { + ++$row; + if ($arg !== null) { + $sheet->getCell("A$row")->setValue($arg); + } + } + $sheet->getCell('B1')->setValue("=SERIESSUM(C1, C2, C3, A1:A$row)"); + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerSERIESSUM() + public function providerSERIESSUM(): array { return require 'tests/data/Calculation/MathTrig/SERIESSUM.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SignTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SignTest.php index 68f5acb9..d5f65f4a 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SignTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SignTest.php @@ -2,30 +2,27 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class SignTest extends TestCase +class SignTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerSIGN * * @param mixed $expectedResult - * @param $value + * @param mixed $value */ public function testSIGN($expectedResult, $value): void { - $result = MathTrig::SIGN($value); - self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 0); + $sheet->setCellValue('A4', -3.8); + $sheet->getCell('A1')->setValue("=SIGN($value)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); } - public function providerSIGN() + public function providerSIGN(): array { return require 'tests/data/Calculation/MathTrig/SIGN.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SinTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SinTest.php new file mode 100644 index 00000000..24f6ea78 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SinTest.php @@ -0,0 +1,26 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 2); + $sheet->getCell('A1')->setValue("=SIN($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-6); + } + + public function providerSin(): array + { + return require 'tests/data/Calculation/MathTrig/SIN.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SinhTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SinhTest.php new file mode 100644 index 00000000..d25560f5 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SinhTest.php @@ -0,0 +1,26 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 2); + $sheet->getCell('A1')->setValue("=SINH($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-6); + } + + public function providerCosh(): array + { + return require 'tests/data/Calculation/MathTrig/SINH.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SqrtPiTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SqrtPiTest.php index bb4bba4b..8dd66f5f 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SqrtPiTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SqrtPiTest.php @@ -2,30 +2,31 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class SqrtPiTest extends TestCase +class SqrtPiTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerSQRTPI * * @param mixed $expectedResult - * @param $value + * @param mixed $number */ - public function testSQRTPI($expectedResult, $value): void + public function testSQRTPI($expectedResult, $number): void { - $result = MathTrig::SQRTPI($value); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($number !== null) { + $sheet->getCell('A1')->setValue($number); + } + if ($number === 'omitted') { + $sheet->getCell('B1')->setValue('=SQRTPI()'); + } else { + $sheet->getCell('B1')->setValue('=SQRTPI(A1)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerSQRTPI() + public function providerSQRTPI(): array { return require 'tests/data/Calculation/MathTrig/SQRTPI.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SqrtTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SqrtTest.php new file mode 100644 index 00000000..733de874 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SqrtTest.php @@ -0,0 +1,31 @@ +getSheet(); + $this->mightHaveException($expectedResult); + $this->setCell('A1', $number); + if ($number === 'omitted') { + $sheet->getCell('B1')->setValue('=SQRT()'); + } else { + $sheet->getCell('B1')->setValue('=SQRT(A1)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-6); + } + + public function providerSqrt(): array + { + return require 'tests/data/Calculation/MathTrig/SQRT.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SubTotalTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SubTotalTest.php index 14865673..cf79ac0b 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SubTotalTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SubTotalTest.php @@ -2,197 +2,129 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PhpOffice\PhpSpreadsheet\Cell\Cell; -use PhpOffice\PhpSpreadsheet\Worksheet\ColumnDimension; -use PhpOffice\PhpSpreadsheet\Worksheet\RowDimension; -use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; -use PHPUnit\Framework\TestCase; - -class SubTotalTest extends TestCase +class SubTotalTest extends AllSetupTeardown { - protected function setUp(): void + /** + * @dataProvider providerSUBTOTAL + * + * @param mixed $expectedResult + * @param mixed $type expect an integer + */ + public function testSubtotal($expectedResult, $type): void { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->fromArray([[0], [1], [1], [2], [3], [5], [8], [13], [21], [34], [55], [89]], null, 'A1', true); + $maxCol = $sheet->getHighestColumn(); + $maxRow = $sheet->getHighestRow(); + $sheet->getCell('D2')->setValue("=SUBTOTAL($type, A1:$maxCol$maxRow)"); + $result = $sheet->getCell('D2')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + } + + public function providerSUBTOTAL(): array + { + return require 'tests/data/Calculation/MathTrig/SUBTOTAL.php'; } /** * @dataProvider providerSUBTOTAL * * @param mixed $expectedResult + * @param mixed $type expect an integer */ - public function testSUBTOTAL($expectedResult, ...$args): void + public function testSubtotalColumnHidden($expectedResult, $type): void { - $cell = $this->getMockBuilder(Cell::class) - ->setMethods(['getValue', 'isFormula']) - ->disableOriginalConstructor() - ->getMock(); - $cell->method('getValue') - ->willReturn(null); - $cell->method('getValue') - ->willReturn(false); - $worksheet = $this->getMockBuilder(Worksheet::class) - ->setMethods(['cellExists', 'getCell']) - ->disableOriginalConstructor() - ->getMock(); - $worksheet->method('cellExists') - ->willReturn(true); - $worksheet->method('getCell') - ->willReturn($cell); - $cellReference = $this->getMockBuilder(Cell::class) - ->setMethods(['getWorksheet']) - ->disableOriginalConstructor() - ->getMock(); - $cellReference->method('getWorksheet') - ->willReturn($worksheet); - - array_push($args, $cellReference); - $result = MathTrig::SUBTOTAL(...$args); - self::assertEqualsWithDelta($expectedResult, $result, 1E-12); - } - - public function providerSUBTOTAL() - { - return require 'tests/data/Calculation/MathTrig/SUBTOTAL.php'; - } - - protected function rowVisibility() - { - $data = [1 => false, 2 => true, 3 => false, 4 => true, 5 => false, 6 => false, 7 => false, 8 => true, 9 => false, 10 => true, 11 => true]; - foreach ($data as $k => $v) { - yield $k => $v; + // Hidden columns don't affect calculation, only hidden rows + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->fromArray([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89], null, 'A1', true); + $maxCol = $sheet->getHighestColumn(); + $maxRow = $sheet->getHighestRow(); + $hiddenColumns = [ + 'A' => false, + 'B' => true, + 'C' => false, + 'D' => true, + 'E' => false, + 'F' => false, + 'G' => false, + 'H' => true, + 'I' => false, + 'J' => true, + 'K' => true, + 'L' => false, + ]; + foreach ($hiddenColumns as $col => $hidden) { + $columnDimension = $sheet->getColumnDimension($col); + $columnDimension->setVisible($hidden); } + $sheet->getCell('D2')->setValue("=SUBTOTAL($type, A1:$maxCol$maxRow)"); + $result = $sheet->getCell('D2')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } /** - * @dataProvider providerHiddenSUBTOTAL + * @dataProvider providerSUBTOTALHIDDEN * * @param mixed $expectedResult + * @param mixed $type expect an integer */ - public function testHiddenSUBTOTAL($expectedResult, ...$args): void + public function testSubtotalRowHidden($expectedResult, $type): void { - $visibilityGenerator = $this->rowVisibility(); - - $rowDimension = $this->getMockBuilder(RowDimension::class) - ->setMethods(['getVisible']) - ->disableOriginalConstructor() - ->getMock(); - $rowDimension->method('getVisible') - ->willReturnCallback(function () use ($visibilityGenerator) { - $result = $visibilityGenerator->current(); - $visibilityGenerator->next(); - - return $result; - }); - $columnDimension = $this->getMockBuilder(ColumnDimension::class) - ->setMethods(['getVisible']) - ->disableOriginalConstructor() - ->getMock(); - $columnDimension->method('getVisible') - ->willReturn(true); - $cell = $this->getMockBuilder(Cell::class) - ->setMethods(['getValue', 'isFormula']) - ->disableOriginalConstructor() - ->getMock(); - $cell->method('getValue') - ->willReturn(''); - $cell->method('getValue') - ->willReturn(false); - $worksheet = $this->getMockBuilder(Worksheet::class) - ->setMethods(['cellExists', 'getCell', 'getRowDimension', 'getColumnDimension']) - ->disableOriginalConstructor() - ->getMock(); - $worksheet->method('cellExists') - ->willReturn(true); - $worksheet->method('getCell') - ->willReturn($cell); - $worksheet->method('getRowDimension') - ->willReturn($rowDimension); - $worksheet->method('getColumnDimension') - ->willReturn($columnDimension); - $cellReference = $this->getMockBuilder(Cell::class) - ->setMethods(['getWorksheet']) - ->disableOriginalConstructor() - ->getMock(); - $cellReference->method('getWorksheet') - ->willReturn($worksheet); - - array_push($args, $cellReference); - $result = MathTrig::SUBTOTAL(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->fromArray([[0], [1], [1], [2], [3], [5], [8], [13], [21], [34], [55], [89]], null, 'A1', true); + $maxCol = $sheet->getHighestColumn(); + $maxRow = $sheet->getHighestRow(); + $visibleRows = [ + '1' => false, + '2' => true, + '3' => false, + '4' => true, + '5' => false, + '6' => false, + '7' => false, + '8' => true, + '9' => false, + '10' => true, + '11' => true, + '12' => false, + ]; + foreach ($visibleRows as $row => $visible) { + $rowDimension = $sheet->getRowDimension((int) $row); + $rowDimension->setVisible($visible); + } + $sheet->getCell('D2')->setValue("=SUBTOTAL($type, A1:$maxCol$maxRow)"); + $result = $sheet->getCell('D2')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerHiddenSUBTOTAL() + public function providerSUBTOTALHIDDEN(): array { return require 'tests/data/Calculation/MathTrig/SUBTOTALHIDDEN.php'; } - protected function cellValues(array $cellValues) + public function testSubtotalNested(): void { - foreach ($cellValues as $k => $v) { - yield $k => $v; - } - } - - protected function cellIsFormula(array $cellValues) - { - foreach ($cellValues as $cellValue) { - yield is_string($cellValue) && $cellValue[0] === '='; - } - } - - /** - * @dataProvider providerNestedSUBTOTAL - * - * @param mixed $expectedResult - */ - public function testNestedSUBTOTAL($expectedResult, ...$args): void - { - $cellValueGenerator = $this->cellValues(Functions::flattenArray(array_slice($args, 1))); - $cellIsFormulaGenerator = $this->cellIsFormula(Functions::flattenArray(array_slice($args, 1))); - - $cell = $this->getMockBuilder(Cell::class) - ->setMethods(['getValue', 'isFormula']) - ->disableOriginalConstructor() - ->getMock(); - $cell->method('getValue') - ->willReturnCallback(function () use ($cellValueGenerator) { - $result = $cellValueGenerator->current(); - $cellValueGenerator->next(); - - return $result; - }); - $cell->method('isFormula') - ->willReturnCallback(function () use ($cellIsFormulaGenerator) { - $result = $cellIsFormulaGenerator->current(); - $cellIsFormulaGenerator->next(); - - return $result; - }); - $worksheet = $this->getMockBuilder(Worksheet::class) - ->setMethods(['cellExists', 'getCell']) - ->disableOriginalConstructor() - ->getMock(); - $worksheet->method('cellExists') - ->willReturn(true); - $worksheet->method('getCell') - ->willReturn($cell); - $cellReference = $this->getMockBuilder(Cell::class) - ->setMethods(['getWorksheet']) - ->disableOriginalConstructor() - ->getMock(); - $cellReference->method('getWorksheet') - ->willReturn($worksheet); - - array_push($args, $cellReference); - - $result = MathTrig::SUBTOTAL(...$args); - self::assertEqualsWithDelta($expectedResult, $result, 1E-12); - } - - public function providerNestedSUBTOTAL() - { - return require 'tests/data/Calculation/MathTrig/SUBTOTALNESTED.php'; + $sheet = $this->getSheet(); + $sheet->fromArray( + [ + [123], + [234], + ['=SUBTOTAL(1,A1:A2)'], + ['=ROMAN(SUBTOTAL(1, A1:A2))'], + ['This is text containing "=" and "SUBTOTAL("'], + ['=AGGREGATE(1, 0, A1:A2)'], + ['=SUM(2, 3)'], + ], + null, + 'A1', + true + ); + $maxCol = $sheet->getHighestColumn(); + $maxRow = $sheet->getHighestRow(); + $sheet->getCell('H1')->setValue("=SUBTOTAL(9, A1:$maxCol$maxRow)"); + self::assertEquals(362, $sheet->getCell('H1')->getCalculatedValue()); } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumIfTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumIfTest.php index f7ff928f..93c2ae32 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumIfTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumIfTest.php @@ -2,29 +2,39 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class SumIfTest extends TestCase +class SumIfTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerSUMIF * * @param mixed $expectedResult + * @param mixed $condition */ - public function testSUMIF($expectedResult, ...$args): void + public function testSUMIF2($expectedResult, array $array1, $condition, ?array $array2 = null): void { - $result = MathTrig::SUMIF(...$args); + $this->mightHaveException($expectedResult); + if ($expectedResult === 'incomplete') { + self::markTestIncomplete('Raises formula error - researching solution'); + } + $sheet = $this->getSheet(); + $sheet->fromArray($array1, null, 'A1', true); + $maxARow = count($array1); + $firstArg = "A1:A$maxARow"; + $this->setCell('B1', $condition); + $secondArg = 'B1'; + if (empty($array2)) { + $sheet->getCell('D1')->setValue("=SUMIF($firstArg, $secondArg)"); + } else { + $sheet->fromArray($array2, null, 'C1', true); + $maxCRow = count($array2); + $thirdArg = "C1:C$maxCRow"; + $sheet->getCell('D1')->setValue("=SUMIF($firstArg, $secondArg, $thirdArg)"); + } + $result = $sheet->getCell('D1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerSUMIF() + public function providerSUMIF(): array { return require 'tests/data/Calculation/MathTrig/SUMIF.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumIfsTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumIfsTest.php index b7be17c9..1ae6e231 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumIfsTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumIfsTest.php @@ -2,17 +2,10 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; +use PhpOffice\PhpSpreadsheet\Calculation\Statistical; -class SumIfsTest extends TestCase +class SumIfsTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerSUMIFS * @@ -20,11 +13,11 @@ class SumIfsTest extends TestCase */ public function testSUMIFS($expectedResult, ...$args): void { - $result = MathTrig::SUMIFS(...$args); + $result = Statistical\Conditional::SUMIFS(...$args); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerSUMIFS() + public function providerSUMIFS(): array { return require 'tests/data/Calculation/MathTrig/SUMIFS.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumProductTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumProductTest.php index b34036e5..9bc197f7 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumProductTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumProductTest.php @@ -3,16 +3,9 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; -class SumProductTest extends TestCase +class SumProductTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerSUMPRODUCT * @@ -20,11 +13,28 @@ class SumProductTest extends TestCase */ public function testSUMPRODUCT($expectedResult, ...$args): void { - $result = MathTrig::SUMPRODUCT(...$args); + $sheet = $this->getSheet(); + $row = 0; + $arrayArg = ''; + foreach ($args as $arr) { + $arr2 = Functions::flattenArray($arr); + $startRow = 0; + foreach ($arr2 as $arr3) { + ++$row; + if (!$startRow) { + $startRow = $row; + } + $sheet->getCell("A$row")->setValue($arr3); + } + $arrayArg .= "A$startRow:A$row,"; + } + $arrayArg = substr($arrayArg, 0, -1); // strip trailing comma + $sheet->getCell('B1')->setValue("=SUMPRODUCT($arrayArg)"); + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerSUMPRODUCT() + public function providerSUMPRODUCT(): array { return require 'tests/data/Calculation/MathTrig/SUMPRODUCT.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumSqTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumSqTest.php index f1165e7b..4de3f551 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumSqTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumSqTest.php @@ -2,17 +2,8 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class SumSqTest extends TestCase +class SumSqTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerSUMSQ * @@ -20,11 +11,23 @@ class SumSqTest extends TestCase */ public function testSUMSQ($expectedResult, ...$args): void { - $result = MathTrig::SUMSQ(...$args); + $this->mightHaveException($expectedResult); + $maxRow = 0; + $funcArg = ''; + $sheet = $this->getSheet(); + foreach ($args as $arg) { + ++$maxRow; + $funcArg = "A1:A$maxRow"; + if ($arg !== null) { + $sheet->getCell("A$maxRow")->setValue($arg); + } + } + $sheet->getCell('B1')->setValue("=SUMSQ($funcArg)"); + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerSUMSQ() + public function providerSUMSQ(): array { return require 'tests/data/Calculation/MathTrig/SUMSQ.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumTest.php new file mode 100644 index 00000000..3f80b8ec --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumTest.php @@ -0,0 +1,47 @@ +getSheet(); + $row = 0; + foreach ($args as $arg) { + ++$row; + $sheet->getCell("A$row")->setValue($arg); + } + $sheet->getCell('B1')->setValue("=SUM(A1:A$row)"); + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + } + + public function providerSUM(): array + { + return require 'tests/data/Calculation/MathTrig/SUM.php'; + } + + /** + * @dataProvider providerSUMLiterals + * + * @param mixed $expectedResult + */ + public function testSUMLiterals($expectedResult, string $args): void + { + $sheet = $this->getSheet(); + $sheet->getCell('B1')->setValue("=SUM($args)"); + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-12); + } + + public function providerSUMLiterals(): array + { + return require 'tests/data/Calculation/MathTrig/SUMLITERALS.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumX2MY2Test.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumX2MY2Test.php index 3bf2785b..3fbe79bf 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumX2MY2Test.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumX2MY2Test.php @@ -3,28 +3,38 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; -class SumX2MY2Test extends TestCase +class SumX2MY2Test extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerSUMX2MY2 * * @param mixed $expectedResult */ - public function testSUMX2MY2($expectedResult, ...$args): void + public function testSUMX2MY2($expectedResult, array $matrixData1, array $matrixData2): void { - $result = MathTrig::SUMX2MY2(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $maxRow = 0; + $funcArg1 = ''; + foreach (Functions::flattenArray($matrixData1) as $arg) { + ++$maxRow; + $funcArg1 = "A1:A$maxRow"; + $this->setCell("A$maxRow", $arg); + } + $maxRow = 0; + $funcArg2 = ''; + foreach (Functions::flattenArray($matrixData2) as $arg) { + ++$maxRow; + $funcArg2 = "C1:C$maxRow"; + $this->setCell("C$maxRow", $arg); + } + $sheet->getCell('B1')->setValue("=SUMX2MY2($funcArg1, $funcArg2)"); + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerSUMX2MY2() + public function providerSUMX2MY2(): array { return require 'tests/data/Calculation/MathTrig/SUMX2MY2.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumX2PY2Test.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumX2PY2Test.php index a370d79b..f3ba1826 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumX2PY2Test.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumX2PY2Test.php @@ -3,28 +3,38 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; -class SumX2PY2Test extends TestCase +class SumX2PY2Test extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerSUMX2PY2 * * @param mixed $expectedResult */ - public function testSUMX2PY2($expectedResult, ...$args): void + public function testSUMX2PY2($expectedResult, array $matrixData1, array $matrixData2): void { - $result = MathTrig::SUMX2PY2(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $maxRow = 0; + $funcArg1 = ''; + foreach (Functions::flattenArray($matrixData1) as $arg) { + ++$maxRow; + $funcArg1 = "A1:A$maxRow"; + $this->setCell("A$maxRow", $arg); + } + $maxRow = 0; + $funcArg2 = ''; + foreach (Functions::flattenArray($matrixData2) as $arg) { + ++$maxRow; + $funcArg2 = "C1:C$maxRow"; + $this->setCell("C$maxRow", $arg); + } + $sheet->getCell('B1')->setValue("=SUMX2PY2($funcArg1, $funcArg2)"); + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerSUMX2PY2() + public function providerSUMX2PY2(): array { return require 'tests/data/Calculation/MathTrig/SUMX2PY2.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumXMY2Test.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumXMY2Test.php index 1f64523b..8291d34c 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumXMY2Test.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/SumXMY2Test.php @@ -3,28 +3,38 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; -class SumXMY2Test extends TestCase +class SumXMY2Test extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerSUMXMY2 * * @param mixed $expectedResult */ - public function testSUMXMY2($expectedResult, ...$args): void + public function testSUMXMY2($expectedResult, array $matrixData1, array $matrixData2): void { - $result = MathTrig::SUMXMY2(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $maxRow = 0; + $funcArg1 = ''; + foreach (Functions::flattenArray($matrixData1) as $arg) { + ++$maxRow; + $funcArg1 = "A1:A$maxRow"; + $this->setCell("A$maxRow", $arg); + } + $maxRow = 0; + $funcArg2 = ''; + foreach (Functions::flattenArray($matrixData2) as $arg) { + ++$maxRow; + $funcArg2 = "C1:C$maxRow"; + $this->setCell("C$maxRow", $arg); + } + $sheet->getCell('B1')->setValue("=SUMXMY2($funcArg1, $funcArg2)"); + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerSUMXMY2() + public function providerSUMXMY2(): array { return require 'tests/data/Calculation/MathTrig/SUMXMY2.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/TanTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/TanTest.php new file mode 100644 index 00000000..c34a756c --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/TanTest.php @@ -0,0 +1,26 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1); + $sheet->getCell('A1')->setValue("=TAN($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-6); + } + + public function providerTan(): array + { + return require 'tests/data/Calculation/MathTrig/TAN.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/TanhTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/TanhTest.php new file mode 100644 index 00000000..d9d2741a --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/TanhTest.php @@ -0,0 +1,26 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1); + $sheet->getCell('A1')->setValue("=TANH($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEqualsWithDelta($expectedResult, $result, 1E-6); + } + + public function providerTanh(): array + { + return require 'tests/data/Calculation/MathTrig/TANH.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/TruncTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/TruncTest.php index 5fc248cc..0430d4c0 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/TruncTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/MathTrig/TruncTest.php @@ -2,29 +2,28 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\MathTrig; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PHPUnit\Framework\TestCase; - -class TruncTest extends TestCase +class TruncTest extends AllSetupTeardown { - protected function setUp(): void - { - Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); - } - /** * @dataProvider providerTRUNC * * @param mixed $expectedResult + * @param string $formula */ - public function testTRUNC($expectedResult, ...$args): void + public function testTRUNC($expectedResult, $formula): void { - $result = MathTrig::TRUNC(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $sheet->setCellValue('A2', 1.3); + $sheet->setCellValue('A3', 2.7); + $sheet->setCellValue('A4', -3.8); + $sheet->setCellValue('A5', -5.2); + $sheet->getCell('A1')->setValue("=TRUNC($formula)"); + $result = $sheet->getCell('A1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerTRUNC() + public function providerTRUNC(): array { return require 'tests/data/Calculation/MathTrig/TRUNC.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Statistical/AveDevTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Statistical/AveDevTest.php index 571c06c3..ea3df6bb 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Statistical/AveDevTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Statistical/AveDevTest.php @@ -24,7 +24,7 @@ class AveDevTest extends TestCase self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerAVEDEV() + public function providerAVEDEV(): array { return require 'tests/data/Calculation/Statistical/AVEDEV.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Statistical/AverageATest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Statistical/AverageATest.php index 1af96dfc..fec65c28 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Statistical/AverageATest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Statistical/AverageATest.php @@ -24,7 +24,7 @@ class AverageATest extends TestCase self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerAVERAGEA() + public function providerAVERAGEA(): array { return require 'tests/data/Calculation/Statistical/AVERAGEA.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Statistical/AverageIf2Test.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Statistical/AverageIf2Test.php new file mode 100644 index 00000000..1899239f --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Statistical/AverageIf2Test.php @@ -0,0 +1,40 @@ +getActiveSheet(); + $sheet->fromArray($table, null, 'A1', true); + $sheet->getCell('C1')->setValue('=AVERAGEIF(A:A,"",B:B)'); + $sheet->getCell('C2')->setValue('=AVERAGEIF(A:A,,B:B)'); + $sheet->getCell('C3')->setValue('=AVERAGEIF(A:A,"n",B:B)'); + $sheet->getCell('C4')->setValue('=AVERAGEIF(A:A,"y",B:B)'); + $sheet->getCell('C5')->setValue('=AVERAGEIF(A:A,"x",B:B)'); + + self::assertEqualsWithDelta(5.75, $sheet->getCell('C1')->getCalculatedValue(), 1E-12); + self::assertEquals('#DIV/0!', $sheet->getCell('C2')->getCalculatedValue()); + self::assertEqualsWithDelta(4.75, $sheet->getCell('C3')->getCalculatedValue(), 1E-12); + self::assertEqualsWithDelta(3, $sheet->getCell('C4')->getCalculatedValue(), 1E-12); + self::assertEquals('#DIV/0!', $sheet->getCell('C5')->getCalculatedValue()); + $spreadsheet->disconnectWorksheets(); + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Statistical/AverageIfTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Statistical/AverageIfTest.php index 69dcfb87..c9648d43 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/Statistical/AverageIfTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Statistical/AverageIfTest.php @@ -24,7 +24,7 @@ class AverageIfTest extends TestCase self::assertEqualsWithDelta($expectedResult, $result, 1E-12); } - public function providerAVERAGEIF() + public function providerAVERAGEIF(): array { return require 'tests/data/Calculation/Statistical/AVERAGEIF.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Statistical/AverageIfsTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Statistical/AverageIfsTest.php new file mode 100644 index 00000000..de593764 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Statistical/AverageIfsTest.php @@ -0,0 +1,31 @@ +locale = Settings::getLocale(); + $this->compatibilityMode = Functions::getCompatibilityMode(); + } + + protected function tearDown(): void + { + Functions::setCompatibilityMode($this->compatibilityMode); + Settings::setLocale($this->locale); + $this->sheet = null; + if ($this->spreadsheet !== null) { + $this->spreadsheet->disconnectWorksheets(); + $this->spreadsheet = null; + } + } + + protected static function setOpenOffice(): void + { + Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE); + } + + protected static function setGnumeric(): void + { + Functions::setCompatibilityMode(Functions::COMPATIBILITY_GNUMERIC); + } + + /** + * @param mixed $expectedResult + */ + protected function mightHaveException($expectedResult): void + { + if ($expectedResult === 'exception') { + $this->expectException(CalcException::class); + } + } + + /** + * @param mixed $value + */ + protected function setCell(string $cell, $value): void + { + if ($value !== null) { + if (is_string($value) && is_numeric($value)) { + $this->getSheet()->getCell($cell)->setValueExplicit($value, DataType::TYPE_STRING); + } else { + $this->getSheet()->getCell($cell)->setValue($value); + } + } + } + + protected function getSpreadsheet(): Spreadsheet + { + if ($this->spreadsheet !== null) { + return $this->spreadsheet; + } + $this->spreadsheet = new Spreadsheet(); + + return $this->spreadsheet; + } + + protected function getSheet(): Worksheet + { + if ($this->sheet !== null) { + return $this->sheet; + } + $this->sheet = $this->getSpreadsheet()->getActiveSheet(); + + return $this->sheet; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CharNonPrintableTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CharNonPrintableTest.php new file mode 100644 index 00000000..3caadcb5 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CharNonPrintableTest.php @@ -0,0 +1,47 @@ +getActiveSheet(); + $sheet->getCell('B1')->setValue('=CHAR(2)'); + $sheet->getCell('C1')->setValue('=CHAR(127)'); + $hello = "hello\nthere"; + $sheet->getCell('D2')->setValue($hello); + $sheet->getCell('D1')->setValue('=D2'); + $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $type); + $result = $reloadedSpreadsheet->getActiveSheet()->getCell('B1')->getCalculatedValue(); + self::assertEquals("\x02", $result); + $result = $reloadedSpreadsheet->getActiveSheet()->getCell('C1')->getCalculatedValue(); + self::assertEquals("\x7f", $result); + $result = $reloadedSpreadsheet->getActiveSheet()->getCell('D1')->getCalculatedValue(); + self::assertEquals($hello, $result); + $spreadsheet->disconnectWorksheets(); + $reloadedSpreadsheet->disconnectWorksheets(); + } + + public function providerType(): array + { + return [ + ['Xlsx'], + ['Xls'], + //['Ods'], // no support yet in Reader or Writer + // without csv suffix, Reader/Csv decides type via mime_get_type, + // and control character makes it guess application/octet-stream, + // so Reader/Csv decides it can't read it. + //['Csv'], + // DOMDocument.loadHTML() rejects '' even though legal html. + //['Html'], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CharTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CharTest.php index cf22df02..66d01cb0 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CharTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CharTest.php @@ -2,24 +2,29 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; - -class CharTest extends TestCase +class CharTest extends AllSetupTeardown { /** * @dataProvider providerCHAR * * @param mixed $expectedResult - * @param $character + * @param mixed $character */ - public function testCHAR($expectedResult, $character): void + public function testCHAR($expectedResult, $character = 'omitted'): void { - $result = TextData::CHARACTER($character); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($character === 'omitted') { + $sheet->getCell('B1')->setValue('=CHAR()'); + } else { + $this->setCell('A1', $character); + $sheet->getCell('B1')->setValue('=CHAR(A1)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerCHAR() + public function providerCHAR(): array { return require 'tests/data/Calculation/TextData/CHAR.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CleanTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CleanTest.php index 31dcc5e6..03939882 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CleanTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CleanTest.php @@ -2,24 +2,29 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; - -class CleanTest extends TestCase +class CleanTest extends AllSetupTeardown { /** * @dataProvider providerCLEAN * * @param mixed $expectedResult - * @param $value + * @param mixed $value */ - public function testCLEAN($expectedResult, $value): void + public function testCLEAN($expectedResult, $value = 'omitted'): void { - $result = TextData::TRIMNONPRINTABLE($value); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($value === 'omitted') { + $sheet->getCell('B1')->setValue('=CLEAN()'); + } else { + $this->setCell('A1', $value); + $sheet->getCell('B1')->setValue('=CLEAN(A1)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerCLEAN() + public function providerCLEAN(): array { return require 'tests/data/Calculation/TextData/CLEAN.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CodeTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CodeTest.php index 9c19f347..52baf1a1 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CodeTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CodeTest.php @@ -2,24 +2,29 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; - -class CodeTest extends TestCase +class CodeTest extends AllSetupTeardown { /** * @dataProvider providerCODE * * @param mixed $expectedResult - * @param $character + * @param mixed $character */ - public function testCODE($expectedResult, $character): void + public function testCODE($expectedResult, $character = 'omitted'): void { - $result = TextData::ASCIICODE($character); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($character === 'omitted') { + $sheet->getCell('B1')->setValue('=CODE()'); + } else { + $this->setCell('A1', $character); + $sheet->getCell('B1')->setValue('=CODE(A1)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerCODE() + public function providerCODE(): array { return require 'tests/data/Calculation/TextData/CODE.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ConcatenateTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ConcatenateTest.php index 068e7d8f..6c9a871d 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ConcatenateTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ConcatenateTest.php @@ -2,23 +2,31 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; - -class ConcatenateTest extends TestCase +class ConcatenateTest extends AllSetupTeardown { /** * @dataProvider providerCONCATENATE * * @param mixed $expectedResult + * @param array $args */ public function testCONCATENATE($expectedResult, ...$args): void { - $result = TextData::CONCATENATE(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $finalArg = ''; + $row = 0; + foreach ($args as $arg) { + ++$row; + $this->setCell("A$row", $arg); + $finalArg = "A1:A$row"; + } + $this->setCell('B1', "=CONCAT($finalArg)"); + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerCONCATENATE() + public function providerCONCATENATE(): array { return require 'tests/data/Calculation/TextData/CONCATENATE.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/DeprecatedTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/DeprecatedTest.php new file mode 100644 index 00000000..49ac421b --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/DeprecatedTest.php @@ -0,0 +1,44 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($amount === 'omitted') { + $sheet->getCell('B1')->setValue('=DOLLAR()'); + } elseif ($decimals === 'omitted') { + $this->setCell('A1', $amount); + $sheet->getCell('B1')->setValue('=DOLLAR(A1)'); + } else { + $this->setCell('A1', $amount); + $this->setCell('A2', $decimals); + $sheet->getCell('B1')->setValue('=DOLLAR(A1, A2)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerDOLLAR() + public function providerDOLLAR(): array { return require 'tests/data/Calculation/TextData/DOLLAR.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ExactTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ExactTest.php index 92d3935c..fc0f481e 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ExactTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ExactTest.php @@ -2,27 +2,34 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; - -class ExactTest extends TestCase +class ExactTest extends AllSetupTeardown { /** * @dataProvider providerEXACT * * @param mixed $expectedResult - * @param array $args + * @param mixed $string1 + * @param mixed $string2 */ - public function testEXACT($expectedResult, ...$args): void + public function testEXACT($expectedResult, $string1 = 'omitted', $string2 = 'omitted'): void { - $result = TextData::EXACT(...$args); - self::assertSame($expectedResult, $result); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($string1 === 'omitted') { + $sheet->getCell('B1')->setValue('=EXACT()'); + } elseif ($string2 === 'omitted') { + $this->setCell('A1', $string1); + $sheet->getCell('B1')->setValue('=EXACT(A1)'); + } else { + $this->setCell('A1', $string1); + $this->setCell('A2', $string2); + $sheet->getCell('B1')->setValue('=EXACT(A1, A2)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); } - /** - * @return array - */ - public function providerEXACT() + public function providerEXACT(): array { return require 'tests/data/Calculation/TextData/EXACT.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/FindTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/FindTest.php index d4b1b77d..14e48b7a 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/FindTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/FindTest.php @@ -2,23 +2,40 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; - -class FindTest extends TestCase +class FindTest extends AllSetupTeardown { /** * @dataProvider providerFIND * * @param mixed $expectedResult + * @param mixed $string1 + * @param mixed $string2 + * @param mixed $start */ - public function testFIND($expectedResult, ...$args): void + public function testFIND($expectedResult, $string1 = 'omitted', $string2 = 'omitted', $start = 'omitted'): void { - $result = TextData::SEARCHSENSITIVE(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($string1 === 'omitted') { + $sheet->getCell('B1')->setValue('=FIND()'); + } elseif ($string2 === 'omitted') { + $this->setCell('A1', $string1); + $sheet->getCell('B1')->setValue('=FIND(A1)'); + } elseif ($start === 'omitted') { + $this->setCell('A1', $string1); + $this->setCell('A2', $string2); + $sheet->getCell('B1')->setValue('=FIND(A1, A2)'); + } else { + $this->setCell('A1', $string1); + $this->setCell('A2', $string2); + $this->setCell('A3', $start); + $sheet->getCell('B1')->setValue('=FIND(A1, A2, A3)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerFIND() + public function providerFIND(): array { return require 'tests/data/Calculation/TextData/FIND.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/FixedTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/FixedTest.php index 0cbaf80c..a6b6e197 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/FixedTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/FixedTest.php @@ -2,23 +2,40 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; - -class FixedTest extends TestCase +class FixedTest extends AllSetupTeardown { /** * @dataProvider providerFIXED * * @param mixed $expectedResult + * @param mixed $number + * @param mixed $decimals + * @param mixed $noCommas */ - public function testFIXED($expectedResult, ...$args): void + public function testFIXED($expectedResult, $number = 'omitted', $decimals = 'omitted', $noCommas = 'omitted'): void { - $result = TextData::FIXEDFORMAT(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($number === 'omitted') { + $sheet->getCell('B1')->setValue('=FIXED()'); + } elseif ($decimals === 'omitted') { + $this->setCell('A1', $number); + $sheet->getCell('B1')->setValue('=FIXED(A1)'); + } elseif ($noCommas === 'omitted') { + $this->setCell('A1', $number); + $this->setCell('A2', $decimals); + $sheet->getCell('B1')->setValue('=FIXED(A1, A2)'); + } else { + $this->setCell('A1', $number); + $this->setCell('A2', $decimals); + $this->setCell('A3', $noCommas); + $sheet->getCell('B1')->setValue('=FIXED(A1, A2, A3)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerFIXED() + public function providerFIXED(): array { return require 'tests/data/Calculation/TextData/FIXED.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/LeftTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/LeftTest.php index e69a3fa0..37ea2f3d 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/LeftTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/LeftTest.php @@ -2,24 +2,182 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; +use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Settings; -class LeftTest extends TestCase +class LeftTest extends AllSetupTeardown { /** * @dataProvider providerLEFT * * @param mixed $expectedResult + * @param mixed $str string from which to extract + * @param mixed $cnt number of characters to extract */ - public function testLEFT($expectedResult, ...$args): void + public function testLEFT($expectedResult, $str = 'omitted', $cnt = 'omitted'): void { - $result = TextData::LEFT(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($str === 'omitted') { + $sheet->getCell('B1')->setValue('=LEFT()'); + } elseif ($cnt === 'omitted') { + $this->setCell('A1', $str); + $sheet->getCell('B1')->setValue('=LEFT(A1)'); + } else { + $this->setCell('A1', $str); + $this->setCell('A2', $cnt); + $sheet->getCell('B1')->setValue('=LEFT(A1, A2)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerLEFT() + public function providerLEFT(): array { return require 'tests/data/Calculation/TextData/LEFT.php'; } + + /** + * @dataProvider providerLocaleLEFT + * + * @param string $expectedResult + * @param mixed $value + * @param mixed $locale + * @param mixed $characters + */ + public function testLowerWithLocaleBoolean($expectedResult, $locale, $value, $characters): void + { + $newLocale = Settings::setLocale($locale); + if ($newLocale === false) { + self::markTestSkipped('Unable to set locale for locale-specific test'); + } + + $sheet = $this->getSheet(); + $this->setCell('A1', $value); + $this->setCell('A2', $characters); + $sheet->getCell('B1')->setValue('=LEFT(A1, A2)'); + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function providerLocaleLEFT(): array + { + return [ + ['VR', 'fr_FR', true, 2], + ['WA', 'nl_NL', true, 2], + ['TO', 'fi', true, 2], + ['ИСТ', 'bg', true, 3], + ['FA', 'fr_FR', false, 2], + ['ON', 'nl_NL', false, 2], + ['EPÄT', 'fi', false, 4], + ['ЛОЖ', 'bg', false, 3], + ]; + } + + /** + * @dataProvider providerCalculationTypeLEFTTrue + */ + public function testCalculationTypeTrue(string $type, string $resultB1, string $resultB2): void + { + Functions::setCompatibilityMode($type); + $sheet = $this->getSheet(); + $this->setCell('A1', true); + $this->setCell('A2', 'Hello'); + $this->setCell('B1', '=LEFT(A1, 1)'); + $this->setCell('B2', '=LEFT(A2, A1)'); + self::assertEquals($resultB1, $sheet->getCell('B1')->getCalculatedValue()); + self::assertEquals($resultB2, $sheet->getCell('B2')->getCalculatedValue()); + } + + public function providerCalculationTypeLEFTTrue(): array + { + return [ + 'Excel LEFT(true, 1) AND LEFT("hello", true)' => [ + Functions::COMPATIBILITY_EXCEL, + 'T', + 'H', + ], + 'Gnumeric LEFT(true, 1) AND LEFT("hello", true)' => [ + Functions::COMPATIBILITY_GNUMERIC, + 'T', + 'H', + ], + 'OpenOffice LEFT(true, 1) AND LEFT("hello", true)' => [ + Functions::COMPATIBILITY_OPENOFFICE, + '1', + '#VALUE!', + ], + ]; + } + + /** + * @dataProvider providerCalculationTypeLEFTFalse + */ + public function testCalculationTypeFalse(string $type, string $resultB1, string $resultB2): void + { + Functions::setCompatibilityMode($type); + $sheet = $this->getSheet(); + $this->setCell('A1', false); + $this->setCell('A2', 'Hello'); + $this->setCell('B1', '=LEFT(A1, 1)'); + $this->setCell('B2', '=LEFT(A2, A1)'); + self::assertEquals($resultB1, $sheet->getCell('B1')->getCalculatedValue()); + self::assertEquals($resultB2, $sheet->getCell('B2')->getCalculatedValue()); + } + + public function providerCalculationTypeLEFTFalse(): array + { + return [ + 'Excel LEFT(false, 1) AND LEFT("hello", false)' => [ + Functions::COMPATIBILITY_EXCEL, + 'F', + '', + ], + 'Gnumeric LEFT(false, 1) AND LEFT("hello", false)' => [ + Functions::COMPATIBILITY_GNUMERIC, + 'F', + '', + ], + 'OpenOffice LEFT(false, 1) AND LEFT("hello", false)' => [ + Functions::COMPATIBILITY_OPENOFFICE, + '0', + '#VALUE!', + ], + ]; + } + + /** + * @dataProvider providerCalculationTypeLEFTNull + */ + public function testCalculationTypeNull(string $type, string $resultB1, string $resultB2): void + { + Functions::setCompatibilityMode($type); + $sheet = $this->getSheet(); + $this->setCell('A2', 'Hello'); + $this->setCell('B1', '=LEFT(A1, 1)'); + $this->setCell('B2', '=LEFT(A2, A1)'); + self::assertEquals($resultB1, $sheet->getCell('B1')->getCalculatedValue()); + self::assertEquals($resultB2, $sheet->getCell('B2')->getCalculatedValue()); + } + + public function providerCalculationTypeLEFTNull(): array + { + return [ + 'Excel LEFT(null, 1) AND LEFT("hello", null)' => [ + Functions::COMPATIBILITY_EXCEL, + '', + '', + ], + 'Gnumeric LEFT(null, 1) AND LEFT("hello", null)' => [ + Functions::COMPATIBILITY_GNUMERIC, + '', + 'H', + ], + 'OpenOffice LEFT(null, 1) AND LEFT("hello", null)' => [ + Functions::COMPATIBILITY_OPENOFFICE, + '', + '', + ], + ]; + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/LenTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/LenTest.php index bca2b389..b2ce124e 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/LenTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/LenTest.php @@ -2,24 +2,29 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; - -class LenTest extends TestCase +class LenTest extends AllSetupTeardown { /** * @dataProvider providerLEN * * @param mixed $expectedResult - * @param $value + * @param mixed $str */ - public function testLEN($expectedResult, $value): void + public function testLEN($expectedResult, $str = 'omitted'): void { - $result = TextData::STRINGLENGTH($value); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($str === 'omitted') { + $sheet->getCell('B1')->setValue('=LEN()'); + } else { + $this->setCell('A1', $str); + $sheet->getCell('B1')->setValue('=LEN(A1)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerLEN() + public function providerLEN(): array { return require 'tests/data/Calculation/TextData/LEN.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/LowerTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/LowerTest.php index 9ba677c7..4639624a 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/LowerTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/LowerTest.php @@ -2,25 +2,66 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; +use PhpOffice\PhpSpreadsheet\Settings; -class LowerTest extends TestCase +class LowerTest extends AllSetupTeardown { /** * @dataProvider providerLOWER * * @param mixed $expectedResult - * @param $value + * @param mixed $str */ - public function testLOWER($expectedResult, $value): void + public function testLOWER($expectedResult, $str = 'omitted'): void { - $result = TextData::LOWERCASE($value); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($str === 'omitted') { + $sheet->getCell('B1')->setValue('=LOWER()'); + } else { + $this->setCell('A1', $str); + $sheet->getCell('B1')->setValue('=LOWER(A1)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerLOWER() + public function providerLOWER(): array { return require 'tests/data/Calculation/TextData/LOWER.php'; } + + /** + * @dataProvider providerLocaleLOWER + * + * @param string $expectedResult + * @param mixed $value + * @param mixed $locale + */ + public function testLowerWithLocaleBoolean($expectedResult, $locale, $value): void + { + $newLocale = Settings::setLocale($locale); + if ($newLocale === false) { + self::markTestSkipped('Unable to set locale for locale-specific test'); + } + $sheet = $this->getSheet(); + $this->setCell('A1', $value); + $sheet->getCell('B1')->setValue('=LOWER(A1)'); + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function providerLocaleLOWER(): array + { + return [ + ['vrai', 'fr_FR', true], + ['waar', 'nl_NL', true], + ['tosi', 'fi', true], + ['истина', 'bg', true], + ['faux', 'fr_FR', false], + ['onwaar', 'nl_NL', false], + ['epätosi', 'fi', false], + ['ложь', 'bg', false], + ]; + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/MidTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/MidTest.php index 4c19248a..a1eebf47 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/MidTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/MidTest.php @@ -2,24 +2,204 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; +use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Settings; -class MidTest extends TestCase +class MidTest extends AllSetupTeardown { /** * @dataProvider providerMID * * @param mixed $expectedResult + * @param mixed $str string from which to extract + * @param mixed $start position at which to start + * @param mixed $cnt number of characters to extract */ - public function testMID($expectedResult, ...$args): void + public function testMID($expectedResult, $str = 'omitted', $start = 'omitted', $cnt = 'omitted'): void { - $result = TextData::MID(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($str === 'omitted') { + $sheet->getCell('B1')->setValue('=MID()'); + } elseif ($start === 'omitted') { + $this->setCell('A1', $str); + $sheet->getCell('B1')->setValue('=MID(A1)'); + } elseif ($cnt === 'omitted') { + $this->setCell('A1', $str); + $this->setCell('A2', $start); + $sheet->getCell('B1')->setValue('=MID(A1, A2)'); + } else { + $this->setCell('A1', $str); + $this->setCell('A2', $start); + $this->setCell('A3', $cnt); + $sheet->getCell('B1')->setValue('=MID(A1, A2, A3)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerMID() + public function providerMID(): array { return require 'tests/data/Calculation/TextData/MID.php'; } + + /** + * @dataProvider providerLocaleMID + * + * @param string $expectedResult + * @param mixed $value + * @param mixed $locale + * @param mixed $offset + * @param mixed $characters + */ + public function testMiddleWithLocaleBoolean($expectedResult, $locale, $value, $offset, $characters): void + { + $newLocale = Settings::setLocale($locale); + if ($newLocale === false) { + self::markTestSkipped('Unable to set locale for locale-specific test'); + } + + $sheet = $this->getSheet(); + $this->setCell('A1', $value); + $this->setCell('A2', $offset); + $this->setCell('A3', $characters); + $sheet->getCell('B1')->setValue('=MID(A1, A2, A3)'); + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function providerLocaleMID(): array + { + return [ + ['RA', 'fr_FR', true, 2, 2], + ['AA', 'nl_NL', true, 2, 2], + ['OS', 'fi', true, 2, 2], + ['СТИН', 'bg', true, 2, 4], + ['AU', 'fr_FR', false, 2, 2], + ['NWA', 'nl_NL', false, 2, 3], + ['PÄTO', 'fi', false, 2, 4], + ['ОЖ', 'bg', false, 2, 2], + ]; + } + + /** + * @dataProvider providerCalculationTypeMIDTrue + */ + public function testCalculationTypeTrue(string $type, string $resultB1, string $resultB2, string $resultB3): void + { + Functions::setCompatibilityMode($type); + $sheet = $this->getSheet(); + $this->setCell('A1', true); + $this->setCell('A2', 'hello'); + $this->setCell('B1', '=MID(A1, 3, 1)'); + $this->setCell('B2', '=MID(A2, A1, 1)'); + $this->setCell('B3', '=MID(A2, 2, A1)'); + self::assertEquals($resultB1, $sheet->getCell('B1')->getCalculatedValue()); + self::assertEquals($resultB2, $sheet->getCell('B2')->getCalculatedValue()); + self::assertEquals($resultB3, $sheet->getCell('B3')->getCalculatedValue()); + } + + public function providerCalculationTypeMIDTrue(): array + { + return [ + 'Excel MID(true,3,1), MID("hello",true, 1), MID("hello", 2, true)' => [ + Functions::COMPATIBILITY_EXCEL, + 'U', + 'h', + 'e', + ], + 'Gnumeric MID(true,3,1), MID("hello",true, 1), MID("hello", 2, true)' => [ + Functions::COMPATIBILITY_GNUMERIC, + 'U', + 'h', + 'e', + ], + 'OpenOffice MID(true,3,1), MID("hello",true, 1), MID("hello", 2, true)' => [ + Functions::COMPATIBILITY_OPENOFFICE, + '', + '#VALUE!', + '#VALUE!', + ], + ]; + } + + /** + * @dataProvider providerCalculationTypeMIDFalse + */ + public function testCalculationTypeFalse(string $type, string $resultB1, string $resultB2): void + { + Functions::setCompatibilityMode($type); + $sheet = $this->getSheet(); + $this->setCell('A1', false); + $this->setCell('A2', 'Hello'); + $this->setCell('B1', '=MID(A1, 3, 1)'); + $this->setCell('B2', '=MID(A2, A1, 1)'); + $this->setCell('B3', '=MID(A2, 2, A1)'); + self::assertEquals($resultB1, $sheet->getCell('B1')->getCalculatedValue()); + self::assertEquals($resultB2, $sheet->getCell('B2')->getCalculatedValue()); + } + + public function providerCalculationTypeMIDFalse(): array + { + return [ + 'Excel MID(false,3,1), MID("hello", false, 1), MID("hello", 2, false)' => [ + Functions::COMPATIBILITY_EXCEL, + 'L', + '#VALUE!', + '', + ], + 'Gnumeric MID(false,3,1), MID("hello", false, 1), MID("hello", 2, false)' => [ + Functions::COMPATIBILITY_GNUMERIC, + 'L', + '#VALUE!', + '', + ], + 'OpenOffice MID(false,3,1), MID("hello", false, 1), MID("hello", 2, false)' => [ + Functions::COMPATIBILITY_OPENOFFICE, + '', + '#VALUE!', + '#VALUE!', + ], + ]; + } + + /** + * @dataProvider providerCalculationTypeMIDNull + */ + public function testCalculationTypeNull(string $type, string $resultB1, string $resultB2, string $resultB3): void + { + Functions::setCompatibilityMode($type); + $sheet = $this->getSheet(); + $this->setCell('A2', 'Hello'); + $this->setCell('B1', '=MID(A1, 3, 1)'); + $this->setCell('B2', '=MID(A2, A1, 1)'); + $this->setCell('B3', '=MID(A2, 2, A1)'); + self::assertEquals($resultB1, $sheet->getCell('B1')->getCalculatedValue()); + self::assertEquals($resultB2, $sheet->getCell('B2')->getCalculatedValue()); + self::assertEquals($resultB3, $sheet->getCell('B3')->getCalculatedValue()); + } + + public function providerCalculationTypeMIDNull(): array + { + return [ + 'Excel MID(null,3,1), MID("hello", null, 1), MID("hello", 2, null)' => [ + Functions::COMPATIBILITY_EXCEL, + '', + '#VALUE!', + '', + ], + 'Gnumeric MID(null,3,1), MID("hello", null, 1), MID("hello", 2, null)' => [ + Functions::COMPATIBILITY_GNUMERIC, + '', + '#VALUE!', + '', + ], + 'OpenOffice MID(null,3,1), MID("hello", null, 1), MID("hello", 2, null)' => [ + Functions::COMPATIBILITY_OPENOFFICE, + '', + '#VALUE!', + '', + ], + ]; + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/NumberValueTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/NumberValueTest.php index c186bb0b..86d8ca8b 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/NumberValueTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/NumberValueTest.php @@ -2,23 +2,40 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; - -class NumberValueTest extends TestCase +class NumberValueTest extends AllSetupTeardown { /** * @dataProvider providerNUMBERVALUE * * @param mixed $expectedResult + * @param mixed $number + * @param mixed $decimal + * @param mixed $group */ - public function testNUMBERVALUE($expectedResult, array $args): void + public function testNUMBERVALUE($expectedResult, $number = 'omitted', $decimal = 'omitted', $group = 'omitted'): void { - $result = TextData::NUMBERVALUE(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($number === 'omitted') { + $sheet->getCell('B1')->setValue('=NUMBERVALUE()'); + } elseif ($decimal === 'omitted') { + $this->setCell('A1', $number); + $sheet->getCell('B1')->setValue('=NUMBERVALUE(A1)'); + } elseif ($group === 'omitted') { + $this->setCell('A1', $number); + $this->setCell('A2', $decimal); + $sheet->getCell('B1')->setValue('=NUMBERVALUE(A1, A2)'); + } else { + $this->setCell('A1', $number); + $this->setCell('A2', $decimal); + $this->setCell('A3', $group); + $sheet->getCell('B1')->setValue('=NUMBERVALUE(A1, A2, A3)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerNUMBERVALUE() + public function providerNUMBERVALUE(): array { return require 'tests/data/Calculation/TextData/NUMBERVALUE.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/OpenOfficeTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/OpenOfficeTest.php new file mode 100644 index 00000000..7421e41a --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/OpenOfficeTest.php @@ -0,0 +1,26 @@ +setOpenOffice(); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $this->setCell('A1', $formula); + $result = $sheet->getCell('A1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function providerOpenOffice(): array + { + return require 'tests/data/Calculation/TextData/OpenOffice.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ProperTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ProperTest.php index aae0e696..51968d83 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ProperTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ProperTest.php @@ -2,25 +2,66 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; +use PhpOffice\PhpSpreadsheet\Settings; -class ProperTest extends TestCase +class ProperTest extends AllSetupTeardown { /** * @dataProvider providerPROPER * * @param mixed $expectedResult - * @param $value + * @param mixed $str */ - public function testPROPER($expectedResult, $value): void + public function testPROPER($expectedResult, $str = 'omitted'): void { - $result = TextData::PROPERCASE($value); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($str === 'omitted') { + $sheet->getCell('B1')->setValue('=PROPER()'); + } else { + $this->setCell('A1', $str); + $sheet->getCell('B1')->setValue('=PROPER(A1)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerPROPER() + public function providerPROPER(): array { return require 'tests/data/Calculation/TextData/PROPER.php'; } + + /** + * @dataProvider providerLocaleLOWER + * + * @param string $expectedResult + * @param mixed $value + * @param mixed $locale + */ + public function testLowerWithLocaleBoolean($expectedResult, $locale, $value): void + { + $newLocale = Settings::setLocale($locale); + if ($newLocale === false) { + self::markTestSkipped('Unable to set locale for locale-specific test'); + } + $sheet = $this->getSheet(); + $this->setCell('A1', $value); + $sheet->getCell('B1')->setValue('=PROPER(A1)'); + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function providerLocaleLOWER(): array + { + return [ + ['Vrai', 'fr_FR', true], + ['Waar', 'nl_NL', true], + ['Tosi', 'fi', true], + ['Истина', 'bg', true], + ['Faux', 'fr_FR', false], + ['Onwaar', 'nl_NL', false], + ['Epätosi', 'fi', false], + ['Ложь', 'bg', false], + ]; + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ReplaceTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ReplaceTest.php index ff9236e6..0e120864 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ReplaceTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ReplaceTest.php @@ -2,23 +2,47 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; - -class ReplaceTest extends TestCase +class ReplaceTest extends AllSetupTeardown { /** * @dataProvider providerREPLACE * * @param mixed $expectedResult + * @param mixed $oldText + * @param mixed $start + * @param mixed $count + * @param mixed $newText */ - public function testREPLACE($expectedResult, ...$args): void + public function testREPLACE($expectedResult, $oldText = 'omitted', $start = 'omitted', $count = 'omitted', $newText = 'omitted'): void { - $result = TextData::REPLACE(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($oldText === 'omitted') { + $sheet->getCell('B1')->setValue('=REPLACE()'); + } elseif ($start === 'omitted') { + $this->setCell('A1', $oldText); + $sheet->getCell('B1')->setValue('=REPLACE(A1)'); + } elseif ($count === 'omitted') { + $this->setCell('A1', $oldText); + $this->setCell('A2', $start); + $sheet->getCell('B1')->setValue('=REPLACE(A1, A2)'); + } elseif ($newText === 'omitted') { + $this->setCell('A1', $oldText); + $this->setCell('A2', $start); + $this->setCell('A3', $count); + $sheet->getCell('B1')->setValue('=REPLACE(A1, A2, A3)'); + } else { + $this->setCell('A1', $oldText); + $this->setCell('A2', $start); + $this->setCell('A3', $count); + $this->setCell('A4', $newText); + $sheet->getCell('B1')->setValue('=REPLACE(A1, A2, A3, A4)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerREPLACE() + public function providerREPLACE(): array { return require 'tests/data/Calculation/TextData/REPLACE.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ReptTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ReptTest.php new file mode 100644 index 00000000..ea86d1b6 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ReptTest.php @@ -0,0 +1,36 @@ +mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($val === 'omitted') { + $sheet->getCell('B1')->setValue('=REPT()'); + } elseif ($rpt === 'omitted') { + $this->setCell('A1', $val); + $sheet->getCell('B1')->setValue('=REPT(A1)'); + } else { + $this->setCell('A1', $val); + $this->setCell('A2', $rpt); + $sheet->getCell('B1')->setValue('=REPT(A1, A2)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function providerREPT(): array + { + return require 'tests/data/Calculation/TextData/REPT.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/RightTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/RightTest.php index 50fc86dc..b9051d0d 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/RightTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/RightTest.php @@ -2,24 +2,182 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; +use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Settings; -class RightTest extends TestCase +class RightTest extends AllSetupTeardown { /** * @dataProvider providerRIGHT * * @param mixed $expectedResult + * @param mixed $str string from which to extract + * @param mixed $cnt number of characters to extract */ - public function testRIGHT($expectedResult, ...$args): void + public function testRIGHT($expectedResult, $str = 'omitted', $cnt = 'omitted'): void { - $result = TextData::RIGHT(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($str === 'omitted') { + $sheet->getCell('B1')->setValue('=RIGHT()'); + } elseif ($cnt === 'omitted') { + $this->setCell('A1', $str); + $sheet->getCell('B1')->setValue('=RIGHT(A1)'); + } else { + $this->setCell('A1', $str); + $this->setCell('A2', $cnt); + $sheet->getCell('B1')->setValue('=RIGHT(A1, A2)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerRIGHT() + public function providerRIGHT(): array { return require 'tests/data/Calculation/TextData/RIGHT.php'; } + + /** + * @dataProvider providerLocaleRIGHT + * + * @param string $expectedResult + * @param mixed $value + * @param mixed $locale + * @param mixed $characters + */ + public function testLowerWithLocaleBoolean($expectedResult, $locale, $value, $characters): void + { + $newLocale = Settings::setLocale($locale); + if ($newLocale === false) { + self::markTestSkipped('Unable to set locale for locale-specific test'); + } + + $sheet = $this->getSheet(); + $this->setCell('A1', $value); + $this->setCell('A2', $characters); + $sheet->getCell('B1')->setValue('=RIGHT(A1, A2)'); + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function providerLocaleRIGHT(): array + { + return [ + ['RAI', 'fr_FR', true, 3], + ['AAR', 'nl_NL', true, 3], + ['OSI', 'fi', true, 3], + ['ИНА', 'bg', true, 3], + ['UX', 'fr_FR', false, 2], + ['WAAR', 'nl_NL', false, 4], + ['ÄTOSI', 'fi', false, 5], + ['ЖЬ', 'bg', false, 2], + ]; + } + + /** + * @dataProvider providerCalculationTypeRIGHTTrue + */ + public function testCalculationTypeTrue(string $type, string $resultB1, string $resultB2): void + { + Functions::setCompatibilityMode($type); + $sheet = $this->getSheet(); + $this->setCell('A1', true); + $this->setCell('A2', 'Hello'); + $this->setCell('B1', '=RIGHT(A1, 1)'); + $this->setCell('B2', '=RIGHT(A2, A1)'); + self::assertEquals($resultB1, $sheet->getCell('B1')->getCalculatedValue()); + self::assertEquals($resultB2, $sheet->getCell('B2')->getCalculatedValue()); + } + + public function providerCalculationTypeRIGHTTrue(): array + { + return [ + 'Excel RIGHT(true, 1) AND RIGHT("hello", true)' => [ + Functions::COMPATIBILITY_EXCEL, + 'E', + 'o', + ], + 'Gnumeric RIGHT(true, 1) AND RIGHT("hello", true)' => [ + Functions::COMPATIBILITY_GNUMERIC, + 'E', + 'o', + ], + 'OpenOffice RIGHT(true, 1) AND RIGHT("hello", true)' => [ + Functions::COMPATIBILITY_OPENOFFICE, + '1', + '#VALUE!', + ], + ]; + } + + /** + * @dataProvider providerCalculationTypeRIGHTFalse + */ + public function testCalculationTypeFalse(string $type, string $resultB1, string $resultB2): void + { + Functions::setCompatibilityMode($type); + $sheet = $this->getSheet(); + $this->setCell('A1', false); + $this->setCell('A2', 'Hello'); + $this->setCell('B1', '=RIGHT(A1, 1)'); + $this->setCell('B2', '=RIGHT(A2, A1)'); + self::assertEquals($resultB1, $sheet->getCell('B1')->getCalculatedValue()); + self::assertEquals($resultB2, $sheet->getCell('B2')->getCalculatedValue()); + } + + public function providerCalculationTypeRIGHTFalse(): array + { + return [ + 'Excel RIGHT(false, 1) AND RIGHT("hello", false)' => [ + Functions::COMPATIBILITY_EXCEL, + 'E', + '', + ], + 'Gnumeric RIGHT(false, 1) AND RIGHT("hello", false)' => [ + Functions::COMPATIBILITY_GNUMERIC, + 'E', + '', + ], + 'OpenOffice RIGHT(false, 1) AND RIGHT("hello", false)' => [ + Functions::COMPATIBILITY_OPENOFFICE, + '0', + '#VALUE!', + ], + ]; + } + + /** + * @dataProvider providerCalculationTypeRIGHTNull + */ + public function testCalculationTypeNull(string $type, string $resultB1, string $resultB2): void + { + Functions::setCompatibilityMode($type); + $sheet = $this->getSheet(); + $this->setCell('A2', 'Hello'); + $this->setCell('B1', '=RIGHT(A1, 1)'); + $this->setCell('B2', '=RIGHT(A2, A1)'); + self::assertEquals($resultB1, $sheet->getCell('B1')->getCalculatedValue()); + self::assertEquals($resultB2, $sheet->getCell('B2')->getCalculatedValue()); + } + + public function providerCalculationTypeRIGHTNull(): array + { + return [ + 'Excel RIGHT(null, 1) AND RIGHT("hello", null)' => [ + Functions::COMPATIBILITY_EXCEL, + '', + '', + ], + 'Gnumeric RIGHT(null, 1) AND RIGHT("hello", null)' => [ + Functions::COMPATIBILITY_GNUMERIC, + '', + 'o', + ], + 'OpenOffice RIGHT(null, 1) AND RIGHT("hello", null)' => [ + Functions::COMPATIBILITY_OPENOFFICE, + '', + '', + ], + ]; + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/SearchTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/SearchTest.php index 7bb92e83..5f1c526d 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/SearchTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/SearchTest.php @@ -2,23 +2,40 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; - -class SearchTest extends TestCase +class SearchTest extends AllSetupTeardown { /** * @dataProvider providerSEARCH * * @param mixed $expectedResult + * @param mixed $findText + * @param mixed $withinText + * @param mixed $start */ - public function testSEARCH($expectedResult, ...$args): void + public function testSEARCH($expectedResult, $findText = 'omitted', $withinText = 'omitted', $start = 'omitted'): void { - $result = TextData::SEARCHINSENSITIVE(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($findText === 'omitted') { + $sheet->getCell('B1')->setValue('=SEARCH()'); + } elseif ($withinText === 'omitted') { + $this->setCell('A1', $findText); + $sheet->getCell('B1')->setValue('=SEARCH(A1)'); + } elseif ($start === 'omitted') { + $this->setCell('A1', $findText); + $this->setCell('A2', $withinText); + $sheet->getCell('B1')->setValue('=SEARCH(A1, A2)'); + } else { + $this->setCell('A1', $findText); + $this->setCell('A2', $withinText); + $this->setCell('A3', $start); + $sheet->getCell('B1')->setValue('=SEARCH(A1, A2, A3)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerSEARCH() + public function providerSEARCH(): array { return require 'tests/data/Calculation/TextData/SEARCH.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/SubstituteTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/SubstituteTest.php index 2a9d1012..bbb05591 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/SubstituteTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/SubstituteTest.php @@ -2,23 +2,47 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; - -class SubstituteTest extends TestCase +class SubstituteTest extends AllSetupTeardown { /** * @dataProvider providerSUBSTITUTE * * @param mixed $expectedResult + * @param mixed $text + * @param mixed $oldText + * @param mixed $newText + * @param mixed $instance */ - public function testSUBSTITUTE($expectedResult, ...$args): void + public function testSUBSTITUTE($expectedResult, $text = 'omitted', $oldText = 'omitted', $newText = 'omitted', $instance = 'omitted'): void { - $result = TextData::SUBSTITUTE(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($text === 'omitted') { + $sheet->getCell('B1')->setValue('=SUBSTITUTE()'); + } elseif ($oldText === 'omitted') { + $this->setCell('A1', $text); + $sheet->getCell('B1')->setValue('=SUBSTITUTE(A1)'); + } elseif ($newText === 'omitted') { + $this->setCell('A1', $text); + $this->setCell('A2', $oldText); + $sheet->getCell('B1')->setValue('=SUBSTITUTE(A1, A2)'); + } elseif ($instance === 'omitted') { + $this->setCell('A1', $text); + $this->setCell('A2', $oldText); + $this->setCell('A3', $newText); + $sheet->getCell('B1')->setValue('=SUBSTITUTE(A1, A2, A3)'); + } else { + $this->setCell('A1', $text); + $this->setCell('A2', $oldText); + $this->setCell('A3', $newText); + $this->setCell('A4', $instance); + $sheet->getCell('B1')->setValue('=SUBSTITUTE(A1, A2, A3, A4)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerSUBSTITUTE() + public function providerSUBSTITUTE(): array { return require 'tests/data/Calculation/TextData/SUBSTITUTE.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TTest.php index c7606c05..9ca47f91 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TTest.php @@ -11,7 +11,7 @@ class TTest extends TestCase * @dataProvider providerT * * @param mixed $expectedResult - * @param $value + * @param mixed $value */ public function testT($expectedResult, $value): void { @@ -19,7 +19,7 @@ class TTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerT() + public function providerT(): array { return require 'tests/data/Calculation/TextData/T.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TextJoinTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TextJoinTest.php index e8fb404d..60b21661 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TextJoinTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TextJoinTest.php @@ -2,10 +2,7 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; - -class TextJoinTest extends TestCase +class TextJoinTest extends AllSetupTeardown { /** * @dataProvider providerTEXTJOIN @@ -14,11 +11,24 @@ class TextJoinTest extends TestCase */ public function testTEXTJOIN($expectedResult, array $args): void { - $result = TextData::TEXTJOIN(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + $b1Formula = '=TEXTJOIN('; + $comma = ''; + $row = 0; + foreach ($args as $arg) { + ++$row; + $this->setCell("A$row", $arg); + $b1Formula .= $comma . "A$row"; + $comma = ','; + } + $b1Formula .= ')'; + $this->setCell('B1', $b1Formula); + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerTEXTJOIN() + public function providerTEXTJOIN(): array { return require 'tests/data/Calculation/TextData/TEXTJOIN.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TextTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TextTest.php index 8d7b238b..3ede2ffe 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TextTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TextTest.php @@ -2,23 +2,34 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; - -class TextTest extends TestCase +class TextTest extends AllSetupTeardown { /** * @dataProvider providerTEXT * * @param mixed $expectedResult + * @param mixed $value + * @param mixed $format */ - public function testTEXT($expectedResult, ...$args): void + public function testTEXT($expectedResult, $value = 'omitted', $format = 'omitted'): void { - $result = TextData::TEXTFORMAT(...$args); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($value === 'omitted') { + $sheet->getCell('B1')->setValue('=TEXT()'); + } elseif ($format === 'omitted') { + $this->setCell('A1', $value); + $sheet->getCell('B1')->setValue('=TEXT(A1)'); + } else { + $this->setCell('A1', $value); + $this->setCell('A2', $format); + $sheet->getCell('B1')->setValue('=TEXT(A1, A2)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerTEXT() + public function providerTEXT(): array { return require 'tests/data/Calculation/TextData/TEXT.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TrimTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TrimTest.php index 91890ded..133e850f 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TrimTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TrimTest.php @@ -2,24 +2,29 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; - -class TrimTest extends TestCase +class TrimTest extends AllSetupTeardown { /** * @dataProvider providerTRIM * * @param mixed $expectedResult - * @param $character + * @param mixed $character */ - public function testTRIM($expectedResult, $character): void + public function testTRIM($expectedResult, $character = 'omitted'): void { - $result = TextData::TRIMSPACES($character); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($character === 'omitted') { + $sheet->getCell('B1')->setValue('=TRIM()'); + } else { + $this->setCell('A1', $character); + $sheet->getCell('B1')->setValue('=TRIM(A1)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerTRIM() + public function providerTRIM(): array { return require 'tests/data/Calculation/TextData/TRIM.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/UpperTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/UpperTest.php index 13fb0b86..0147b5c1 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/UpperTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/UpperTest.php @@ -2,25 +2,66 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; -use PHPUnit\Framework\TestCase; +use PhpOffice\PhpSpreadsheet\Settings; -class UpperTest extends TestCase +class UpperTest extends AllSetupTeardown { /** * @dataProvider providerUPPER * * @param mixed $expectedResult - * @param $value + * @param mixed $str */ - public function testUPPER($expectedResult, $value): void + public function testUPPER($expectedResult, $str = 'omitted'): void { - $result = TextData::UPPERCASE($value); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($str === 'omitted') { + $sheet->getCell('B1')->setValue('=UPPER()'); + } else { + $this->setCell('A1', $str); + $sheet->getCell('B1')->setValue('=UPPER(A1)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEquals($expectedResult, $result); } - public function providerUPPER() + public function providerUPPER(): array { return require 'tests/data/Calculation/TextData/UPPER.php'; } + + /** + * @dataProvider providerLocaleLOWER + * + * @param string $expectedResult + * @param mixed $value + * @param mixed $locale + */ + public function testLowerWithLocaleBoolean($expectedResult, $locale, $value): void + { + $newLocale = Settings::setLocale($locale); + if ($newLocale === false) { + self::markTestSkipped('Unable to set locale for locale-specific test'); + } + $sheet = $this->getSheet(); + $this->setCell('A1', $value); + $sheet->getCell('B1')->setValue('=UPPER(A1)'); + $result = $sheet->getCell('B1')->getCalculatedValue(); + self::assertEquals($expectedResult, $result); + } + + public function providerLocaleLOWER(): array + { + return [ + ['VRAI', 'fr_FR', true], + ['WAAR', 'nl_NL', true], + ['TOSI', 'fi', true], + ['ИСТИНА', 'bg', true], + ['FAUX', 'fr_FR', false], + ['ONWAAR', 'nl_NL', false], + ['EPÄTOSI', 'fi', false], + ['ЛОЖЬ', 'bg', false], + ]; + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ValueTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ValueTest.php index 355193de..fbef254b 100644 --- a/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ValueTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ValueTest.php @@ -2,20 +2,28 @@ namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData; -use PhpOffice\PhpSpreadsheet\Calculation\TextData; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; -use PHPUnit\Framework\TestCase; -class ValueTest extends TestCase +class ValueTest extends AllSetupTeardown { + /** + * @var string + */ private $currencyCode; + /** + * @var string + */ private $decimalSeparator; + /** + * @var string + */ private $thousandsSeparator; protected function setUp(): void { + parent::setUp(); $this->currencyCode = StringHelper::getCurrencyCode(); $this->decimalSeparator = StringHelper::getDecimalSeparator(); $this->thousandsSeparator = StringHelper::getThousandsSeparator(); @@ -23,6 +31,7 @@ class ValueTest extends TestCase protected function tearDown(): void { + parent::tearDown(); StringHelper::setCurrencyCode($this->currencyCode); StringHelper::setDecimalSeparator($this->decimalSeparator); StringHelper::setThousandsSeparator($this->thousandsSeparator); @@ -32,19 +41,27 @@ class ValueTest extends TestCase * @dataProvider providerVALUE * * @param mixed $expectedResult - * @param $value + * @param mixed $value */ - public function testVALUE($expectedResult, $value): void + public function testVALUE($expectedResult, $value = 'omitted'): void { StringHelper::setDecimalSeparator('.'); StringHelper::setThousandsSeparator(' '); StringHelper::setCurrencyCode('$'); - $result = TextData::VALUE($value); + $this->mightHaveException($expectedResult); + $sheet = $this->getSheet(); + if ($value === 'omitted') { + $sheet->getCell('B1')->setValue('=VALUE()'); + } else { + $this->setCell('A1', $value); + $sheet->getCell('B1')->setValue('=VALUE(A1)'); + } + $result = $sheet->getCell('B1')->getCalculatedValue(); self::assertEqualsWithDelta($expectedResult, $result, 1E-8); } - public function providerVALUE() + public function providerVALUE(): array { return require 'tests/data/Calculation/TextData/VALUE.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/Functions/Web/UrlEncodeTest.php b/tests/PhpSpreadsheetTests/Calculation/Functions/Web/UrlEncodeTest.php new file mode 100644 index 00000000..3ce6098d --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/Functions/Web/UrlEncodeTest.php @@ -0,0 +1,26 @@ +getMockBuilder(Cell::class) - ->disableOriginalConstructor() - ->getMock(); - $remoteCell->method('isFormula') - ->willReturn(substr($value, 0, 1) == '='); - - $remoteSheet = $this->getMockBuilder(Worksheet::class) - ->disableOriginalConstructor() - ->getMock(); - $remoteSheet->method('getCell') - ->willReturn($remoteCell); - - $workbook = $this->getMockBuilder(Spreadsheet::class) - ->disableOriginalConstructor() - ->getMock(); - $workbook->method('getSheetByName') - ->willReturn($remoteSheet); - - $sheet = $this->getMockBuilder(Worksheet::class) - ->disableOriginalConstructor() - ->getMock(); - $sheet->method('getCell') - ->willReturn($remoteCell); - $sheet->method('getParent') - ->willReturn($workbook); - - $ourCell = $this->getMockBuilder(Cell::class) - ->disableOriginalConstructor() - ->getMock(); - $ourCell->method('getWorksheet') - ->willReturn($sheet); - } - - $result = Functions::isFormula($reference, $ourCell); - self::assertEqualsWithDelta($expectedResult, $result, 1E-8); - } - - public function providerIsFormula() - { - return require 'tests/data/Calculation/Functions/ISFORMULA.php'; - } - /** * @dataProvider providerIfCondition * @@ -384,7 +334,7 @@ class FunctionsTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerIfCondition() + public function providerIfCondition(): array { return require 'tests/data/Calculation/Functions/IF_CONDITION.php'; } diff --git a/tests/PhpSpreadsheetTests/Calculation/IsFormulaTest.php b/tests/PhpSpreadsheetTests/Calculation/IsFormulaTest.php new file mode 100644 index 00000000..40e0d949 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/IsFormulaTest.php @@ -0,0 +1,90 @@ +getActiveSheet(); + $sheet1->setTitle('SheetOne'); // no space in sheet title + $sheet2 = $spreadsheet->createSheet(); + $sheet2->setTitle('Sheet Two'); // space in sheet title + $values = [ + [null, false], + [-1, false], + [0, false], + [1, false], + ['', false], + [false, false], + [true, false], + ['=-1', true], + ['="ABC"', true], + ['=SUM(1,2,3)', true], + ]; + $row = 0; + foreach ($values as $valArray) { + ++$row; + if ($valArray[0] !== null) { + $sheet1->getCell("A$row")->setValue($valArray[0]); + } + $sheet1->getCell("B$row")->setValue("=ISFORMULA(A$row)"); + self::assertSame($valArray[1], $sheet1->getCell("B$row")->getCalculatedValue(), "sheet1 error in B$row"); + } + $row = 0; + foreach ($values as $valArray) { + ++$row; + if ($valArray[0] !== null) { + $sheet2->getCell("A$row")->setValue($valArray[0]); + } + $sheet2->getCell("B$row")->setValue("=ISFORMULA(A$row)"); + self::assertSame($valArray[1], $sheet2->getCell("B$row")->getCalculatedValue(), "sheet2 error in B$row"); + } + $sheet1->getCell('C1')->setValue(0); + $sheet1->getCell('C2')->setValue('=0'); + $sheet2->getCell('C3')->setValue(0); + $sheet2->getCell('C4')->setValue('=0'); + $sheet1->getCell('D1')->setValue('=ISFORMULA(SheetOne!C1)'); + $sheet1->getCell('D2')->setValue('=ISFORMULA(SheetOne!C2)'); + $sheet1->getCell('E1')->setValue('=ISFORMULA(\'SheetOne\'!C1)'); + $sheet1->getCell('E2')->setValue('=ISFORMULA(\'SheetOne\'!C2)'); + $sheet1->getCell('F1')->setValue('=ISFORMULA(\'Sheet Two\'!C3)'); + $sheet1->getCell('F2')->setValue('=ISFORMULA(\'Sheet Two\'!C4)'); + self::assertFalse($sheet1->getCell('D1')->getCalculatedValue()); + self::assertTrue($sheet1->getCell('D2')->getCalculatedValue()); + self::assertFalse($sheet1->getCell('E1')->getCalculatedValue()); + self::assertTrue($sheet1->getCell('E2')->getCalculatedValue()); + self::assertFalse($sheet1->getCell('F1')->getCalculatedValue()); + self::assertTrue($sheet1->getCell('F2')->getCalculatedValue()); + + $spreadsheet->addNamedRange(new NamedRange('range1f', $sheet1, '$C$1')); + $spreadsheet->addNamedRange(new NamedRange('range1t', $sheet1, '$C$2')); + $spreadsheet->addNamedRange(new NamedRange('range2f', $sheet2, '$C$3')); + $spreadsheet->addNamedRange(new NamedRange('range2t', $sheet2, '$C$4')); + $spreadsheet->addNamedRange(new NamedRange('range2ft', $sheet2, '$C$3:$C$4')); + $sheet1->getCell('G1')->setValue('=ISFORMULA(ABCDEFG)'); + $sheet1->getCell('G3')->setValue('=ISFORMULA(range1f)'); + $sheet1->getCell('G4')->setValue('=ISFORMULA(range1t)'); + $sheet1->getCell('G5')->setValue('=ISFORMULA(range2f)'); + $sheet1->getCell('G6')->setValue('=ISFORMULA(range2t)'); + $sheet1->getCell('G7')->setValue('=ISFORMULA(range2ft)'); + self::assertSame('#NAME?', $sheet1->getCell('G1')->getCalculatedValue()); + self::assertFalse($sheet1->getCell('G3')->getCalculatedValue()); + self::assertTrue($sheet1->getCell('G4')->getCalculatedValue()); + self::assertFalse($sheet1->getCell('G5')->getCalculatedValue()); + self::assertTrue($sheet1->getCell('G6')->getCalculatedValue()); + self::assertFalse($sheet1->getCell('G7')->getCalculatedValue()); + + $sheet1->getCell('H1')->setValue('=ISFORMULA(C1:C2)'); + $sheet1->getCell('H3')->setValue('=ISFORMULA(C2:C3)'); + self::assertFalse($sheet1->getCell('H1')->getCalculatedValue()); + self::assertTrue($sheet1->getCell('H3')->getCalculatedValue()); + + $spreadsheet->disconnectWorksheets(); + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/LookupRefTest.php b/tests/PhpSpreadsheetTests/Calculation/LookupRefTest.php index 04dc0a32..9f4c90b3 100644 --- a/tests/PhpSpreadsheetTests/Calculation/LookupRefTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/LookupRefTest.php @@ -41,6 +41,8 @@ class LookupRefTest extends TestCase $remoteSheet = $this->getMockBuilder(Worksheet::class) ->disableOriginalConstructor() ->getMock(); + $remoteSheet->method('cellExists') + ->willReturn(true); $remoteSheet->method('getCell') ->willReturn($remoteCell); @@ -53,6 +55,8 @@ class LookupRefTest extends TestCase $sheet = $this->getMockBuilder(Worksheet::class) ->disableOriginalConstructor() ->getMock(); + $sheet->method('cellExists') + ->willReturn(true); $sheet->method('getCell') ->willReturn($remoteCell); $sheet->method('getParent') @@ -69,8 +73,14 @@ class LookupRefTest extends TestCase self::assertEqualsWithDelta($expectedResult, $result, 1E-8); } - public function providerFormulaText() + public function providerFormulaText(): array { return require 'tests/data/Calculation/LookupRef/FORMULATEXT.php'; } + + public function testFormulaTextWithoutCell(): void + { + $result = LookupRef::FORMULATEXT('A1'); + self::assertEquals(Functions::REF(), $result); + } } diff --git a/tests/PhpSpreadsheetTests/Calculation/MergedCellTest.php b/tests/PhpSpreadsheetTests/Calculation/MergedCellTest.php new file mode 100644 index 00000000..6a710436 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/MergedCellTest.php @@ -0,0 +1,53 @@ +spreadSheet = new Spreadsheet(); + + $dataSheet = $this->spreadSheet->getActiveSheet(); + $dataSheet->setCellValue('A1', 1.1); + $dataSheet->setCellValue('A2', 2.2); + $dataSheet->mergeCells('A2:A4'); + $dataSheet->setCellValue('A5', 3.3); + } + + /** + * @param mixed $expectedResult + * + * @dataProvider providerWorksheetFormulae + */ + public function testMergedCellBehaviour(string $formula, $expectedResult): void + { + $worksheet = $this->spreadSheet->getActiveSheet(); + + $worksheet->setCellValue('A7', $formula); + + $result = $worksheet->getCell('A7')->getCalculatedValue(); + self::assertSame($expectedResult, $result); + } + + public function providerWorksheetFormulae(): array + { + return [ + ['=SUM(A1:A5)', 6.6], + ['=COUNT(A1:A5)', 3], + ['=COUNTA(A1:A5)', 3], + ['=SUM(A3:A4)', 0], + ['=A2+A3+A4', 2.2], + ['=A2/A3', Functions::DIV0()], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/RowColumnReferenceTest.php b/tests/PhpSpreadsheetTests/Calculation/RowColumnReferenceTest.php new file mode 100644 index 00000000..8c9d23f7 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/RowColumnReferenceTest.php @@ -0,0 +1,84 @@ +spreadSheet = new Spreadsheet(); + + $dataSheet = new Worksheet($this->spreadSheet, 'data sheet'); + $this->spreadSheet->addSheet($dataSheet, 0); + $dataSheet->setCellValue('B1', 1.1); + $dataSheet->setCellValue('B2', 2.2); + $dataSheet->setCellValue('B3', 4.4); + $dataSheet->setCellValue('C3', 8.8); + $dataSheet->setCellValue('D3', 16.16); + + $calcSheet = new Worksheet($this->spreadSheet, 'summary sheet'); + $this->spreadSheet->addSheet($calcSheet, 1); + $calcSheet->setCellValue('B1', 2.2); + $calcSheet->setCellValue('B2', 4.4); + $calcSheet->setCellValue('B3', 8.8); + $calcSheet->setCellValue('C3', 16.16); + $calcSheet->setCellValue('D3', 32.32); + + $this->spreadSheet->setActiveSheetIndexByName('summary sheet'); + } + + /** + * @dataProvider providerCurrentWorksheetFormulae + */ + public function testCurrentWorksheet(string $formula, float $expectedResult): void + { + $worksheet = $this->spreadSheet->getActiveSheet(); + + $worksheet->setCellValue('A1', $formula); + + $result = $worksheet->getCell('A1')->getCalculatedValue(); + self::assertSame($expectedResult, $result); + } + + public function providerCurrentWorksheetFormulae(): array + { + return [ + 'relative range in active worksheet' => ['=SUM(B1:B3)', 15.4], + 'range with absolute columns in active worksheet' => ['=SUM($B1:$B3)', 15.4], + 'range with absolute rows in active worksheet' => ['=SUM(B$1:B$3)', 15.4], + 'range with absolute columns and rows in active worksheet' => ['=SUM($B$1:$B$3)', 15.4], + 'another relative range in active worksheet' => ['=SUM(B3:D3)', 57.28], + 'relative column range in active worksheet' => ['=SUM(B:B)', 15.4], + 'absolute column range in active worksheet' => ['=SUM($B:$B)', 15.4], + 'relative row range in active worksheet' => ['=SUM(3:3)', 57.28], + 'absolute row range in active worksheet' => ['=SUM($3:$3)', 57.28], + 'relative range in specified active worksheet' => ['=SUM(\'summary sheet\'!B1:B3)', 15.4], + 'range with absolute columns in specified active worksheet' => ['=SUM(\'summary sheet\'!$B1:$B3)', 15.4], + 'range with absolute rows in specified active worksheet' => ['=SUM(\'summary sheet\'!B$1:B$3)', 15.4], + 'range with absolute columns and rows in specified active worksheet' => ['=SUM(\'summary sheet\'!$B$1:$B$3)', 15.4], + 'another relative range in specified active worksheet' => ['=SUM(\'summary sheet\'!B3:D3)', 57.28], + 'relative column range in specified active worksheet' => ['=SUM(\'summary sheet\'!B:B)', 15.4], + 'absolute column range in specified active worksheet' => ['=SUM(\'summary sheet\'!$B:$B)', 15.4], + 'relative row range in specified active worksheet' => ['=SUM(\'summary sheet\'!3:3)', 57.28], + 'absolute row range in specified active worksheet' => ['=SUM(\'summary sheet\'!$3:$3)', 57.28], + 'relative range in specified other worksheet' => ['=SUM(\'data sheet\'!B1:B3)', 7.7], + 'range with absolute columns in specified other worksheet' => ['=SUM(\'data sheet\'!$B1:$B3)', 7.7], + 'range with absolute rows in specified other worksheet' => ['=SUM(\'data sheet\'!B$1:B$3)', 7.7], + 'range with absolute columns and rows in specified other worksheet' => ['=SUM(\'data sheet\'!$B$1:$B$3)', 7.7], + 'another relative range in specified other worksheet' => ['=SUM(\'data sheet\'!B3:D3)', 29.36], + 'relative column range in specified other worksheet' => ['=SUM(\'data sheet\'!B:B)', 7.7], + 'absolute column range in specified other worksheet' => ['=SUM(\'data sheet\'!$B:$B)', 7.7], + 'relative row range in specified other worksheet' => ['=SUM(\'data sheet\'!3:3)', 29.36], + 'absolute row range in specified other worksheet' => ['=SUM(\'data sheet\'!$3:$3)', 29.36], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/TranslationTest.php b/tests/PhpSpreadsheetTests/Calculation/TranslationTest.php new file mode 100644 index 00000000..e2384460 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Calculation/TranslationTest.php @@ -0,0 +1,57 @@ +compatibilityMode = Functions::getCompatibilityMode(); + $this->returnDate = Functions::getReturnDateType(); + Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL); + Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); + } + + protected function tearDown(): void + { + Functions::setCompatibilityMode($this->compatibilityMode); + Functions::setReturnDateType($this->returnDate); + } + + /** + * @dataProvider providerTranslations + */ + public function testTranslation(string $expectedResult, string $locale, string $formula): void + { + $validLocale = Settings::setLocale($locale); + if (!$validLocale) { + self::markTestSkipped("Unable to set locale to {$locale}"); + } + + $translatedFormula = Calculation::getInstance()->_translateFormulaToLocale($formula); + self::assertSame($expectedResult, $translatedFormula); + + $restoredFormula = Calculation::getInstance()->_translateFormulaToEnglish($translatedFormula); + self::assertSame($formula, $restoredFormula); + } + + public function providerTranslations(): array + { + return require 'tests/data/Calculation/Translations.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Calculation/XlfnFunctionsTest.php b/tests/PhpSpreadsheetTests/Calculation/XlfnFunctionsTest.php index ea20fbf3..f8f02f0e 100644 --- a/tests/PhpSpreadsheetTests/Calculation/XlfnFunctionsTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/XlfnFunctionsTest.php @@ -75,7 +75,7 @@ class XlfnFunctionsTest extends \PHPUnit\Framework\TestCase $sheet->setSelectedCell('B1'); $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($workbook, 'Xlsx'); - $oufil = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); + $oufil = File::temporaryFilename(); $writer->save($oufil); $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx'); diff --git a/tests/PhpSpreadsheetTests/Cell/AddressHelperTest.php b/tests/PhpSpreadsheetTests/Cell/AddressHelperTest.php index 9b21767b..58c696ef 100644 --- a/tests/PhpSpreadsheetTests/Cell/AddressHelperTest.php +++ b/tests/PhpSpreadsheetTests/Cell/AddressHelperTest.php @@ -18,7 +18,7 @@ class AddressHelperTest extends TestCase self::assertSame($expectedValue, $actualValue); } - public function providerR1C1ConversionToA1Absolute() + public function providerR1C1ConversionToA1Absolute(): array { return require 'tests/data/Cell/R1C1ConversionToA1Absolute.php'; } @@ -26,9 +26,13 @@ class AddressHelperTest extends TestCase /** * @dataProvider providerR1C1ConversionToA1Relative */ - public function testR1C1ConversionToA1Relative(string $expectedValue, string $address, ?int $row = null, ?int $column = null): void - { - $args = [$address]; + public function testR1C1ConversionToA1Relative( + string $expectedValue, + string $address, + ?int $row = null, + ?int $column = null + ): void { + $args = []; if ($row !== null) { $args[] = $row; } @@ -36,12 +40,12 @@ class AddressHelperTest extends TestCase $args[] = $column; } - $actualValue = AddressHelper::convertToA1(...$args); + $actualValue = AddressHelper::convertToA1($address, ...$args); self::assertSame($expectedValue, $actualValue); } - public function providerR1C1ConversionToA1Relative() + public function providerR1C1ConversionToA1Relative(): array { return require 'tests/data/Cell/R1C1ConversionToA1Relative.php'; } @@ -56,7 +60,7 @@ class AddressHelperTest extends TestCase AddressHelper::convertToA1($address); } - public function providerR1C1ConversionToA1Exception() + public function providerR1C1ConversionToA1Exception(): array { return require 'tests/data/Cell/R1C1ConversionToA1Exception.php'; } @@ -71,7 +75,7 @@ class AddressHelperTest extends TestCase self::assertSame($expectedValue, $actualValue); } - public function providerA1ConversionToR1C1Absolute() + public function providerA1ConversionToR1C1Absolute(): array { return require 'tests/data/Cell/A1ConversionToR1C1Absolute.php'; } @@ -86,7 +90,7 @@ class AddressHelperTest extends TestCase self::assertSame($expectedValue, $actualValue); } - public function providerA1ConversionToR1C1Relative() + public function providerA1ConversionToR1C1Relative(): array { return require 'tests/data/Cell/A1ConversionToR1C1Relative.php'; } @@ -101,8 +105,53 @@ class AddressHelperTest extends TestCase AddressHelper::convertToR1C1($address); } - public function providerA1ConversionToR1C1Exception() + public function providerA1ConversionToR1C1Exception(): array { return require 'tests/data/Cell/A1ConversionToR1C1Exception.php'; } + + /** + * @dataProvider providerConvertFormulaToA1FromSpreadsheetXml + */ + public function testConvertFormulaToA1SpreadsheetXml(string $expectedValue, string $formula): void + { + $actualValue = AddressHelper::convertFormulaToA1($formula); + + self::assertSame($expectedValue, $actualValue); + } + + public function providerConvertFormulaToA1FromSpreadsheetXml(): array + { + return require 'tests/data/Cell/ConvertFormulaToA1FromSpreadsheetXml.php'; + } + + /** + * @dataProvider providerConvertFormulaToA1FromR1C1Absolute + */ + public function testConvertFormulaToA1R1C1Absolute(string $expectedValue, string $formula): void + { + $actualValue = AddressHelper::convertFormulaToA1($formula); + + self::assertSame($expectedValue, $actualValue); + } + + public function providerConvertFormulaToA1FromR1C1Absolute(): array + { + return require 'tests/data/Cell/ConvertFormulaToA1FromR1C1Absolute.php'; + } + + /** + * @dataProvider providerConvertFormulaToA1FromR1C1Relative + */ + public function testConvertFormulaToA1FromR1C1Relative(string $expectedValue, string $formula, int $row, int $column): void + { + $actualValue = AddressHelper::convertFormulaToA1($formula, $row, $column); + + self::assertSame($expectedValue, $actualValue); + } + + public function providerConvertFormulaToA1FromR1C1Relative(): array + { + return require 'tests/data/Cell/ConvertFormulaToA1FromR1C1Relative.php'; + } } diff --git a/tests/PhpSpreadsheetTests/Cell/AdvancedValueBinderTest.php b/tests/PhpSpreadsheetTests/Cell/AdvancedValueBinderTest.php index 630a2944..3fa8b69b 100644 --- a/tests/PhpSpreadsheetTests/Cell/AdvancedValueBinderTest.php +++ b/tests/PhpSpreadsheetTests/Cell/AdvancedValueBinderTest.php @@ -9,14 +9,24 @@ use PhpOffice\PhpSpreadsheet\Collection\Cells; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class AdvancedValueBinderTest extends TestCase { + /** + * @var string + */ private $currencyCode; + /** + * @var string + */ private $decimalSeparator; + /** + * @var string + */ private $thousandsSeparator; protected function setUp(): void @@ -33,25 +43,25 @@ class AdvancedValueBinderTest extends TestCase StringHelper::setThousandsSeparator($this->thousandsSeparator); } - public function provider() + public function testNullValue(): void { - $currencyUSD = NumberFormat::FORMAT_CURRENCY_USD_SIMPLE; - $currencyEURO = str_replace('$', '€', NumberFormat::FORMAT_CURRENCY_USD_SIMPLE); + /** @var Cell&MockObject $cellStub */ + $cellStub = $this->getMockBuilder(Cell::class) + ->disableOriginalConstructor() + ->getMock(); - return [ - ['10%', 0.1, NumberFormat::FORMAT_PERCENTAGE_00, ',', '.', '$'], - ['$10.11', 10.11, $currencyUSD, ',', '.', '$'], - ['$1,010.12', 1010.12, $currencyUSD, ',', '.', '$'], - ['$20,20', 20.2, $currencyUSD, '.', ',', '$'], - ['$2.020,20', 2020.2, $currencyUSD, '.', ',', '$'], - ['€2.020,20', 2020.2, $currencyEURO, '.', ',', '€'], - ['€ 2.020,20', 2020.2, $currencyEURO, '.', ',', '€'], - ['€2,020.22', 2020.22, $currencyEURO, ',', '.', '€'], - ]; + // Configure the stub. + $cellStub->expects(self::once()) + ->method('setValueExplicit') + ->with(null, DataType::TYPE_NULL) + ->willReturn(true); + + $binder = new AdvancedValueBinder(); + $binder->bindValue($cellStub, null); } /** - * @dataProvider provider + * @dataProvider currencyProvider * * @param mixed $value * @param mixed $valueBinded @@ -63,7 +73,8 @@ class AdvancedValueBinderTest extends TestCase public function testCurrency($value, $valueBinded, $format, $thousandsSeparator, $decimalSeparator, $currencyCode): void { $sheet = $this->getMockBuilder(Worksheet::class) - ->setMethods(['getStyle', 'getNumberFormat', 'setFormatCode', 'getCellCollection']) + ->onlyMethods(['getStyle', 'getCellCollection']) + ->addMethods(['getNumberFormat', 'setFormatCode']) ->getMock(); $cellCollection = $this->getMockBuilder(Cells::class) ->disableOriginalConstructor() @@ -75,9 +86,11 @@ class AdvancedValueBinderTest extends TestCase $sheet->expects(self::once()) ->method('getStyle') ->willReturnSelf(); + // @phpstan-ignore-next-line $sheet->expects(self::once()) ->method('getNumberFormat') ->willReturnSelf(); + // @phpstan-ignore-next-line $sheet->expects(self::once()) ->method('setFormatCode') ->with($format) @@ -96,4 +109,236 @@ class AdvancedValueBinderTest extends TestCase $binder->bindValue($cell, $value); self::assertEquals($valueBinded, $cell->getValue()); } + + public function currencyProvider(): array + { + $currencyUSD = NumberFormat::FORMAT_CURRENCY_USD_SIMPLE; + $currencyEURO = str_replace('$', '€', NumberFormat::FORMAT_CURRENCY_USD_SIMPLE); + + return [ + ['$10.11', 10.11, $currencyUSD, ',', '.', '$'], + ['$1,010.12', 1010.12, $currencyUSD, ',', '.', '$'], + ['$20,20', 20.2, $currencyUSD, '.', ',', '$'], + ['$2.020,20', 2020.2, $currencyUSD, '.', ',', '$'], + ['€2.020,20', 2020.2, $currencyEURO, '.', ',', '€'], + ['€ 2.020,20', 2020.2, $currencyEURO, '.', ',', '€'], + ['€2,020.22', 2020.22, $currencyEURO, ',', '.', '€'], + ['$10.11', 10.11, $currencyUSD, ',', '.', '€'], + ]; + } + + /** + * @dataProvider fractionProvider + * + * @param mixed $value + * @param mixed $valueBinded + * @param mixed $format + */ + public function testFractions($value, $valueBinded, $format): void + { + $sheet = $this->getMockBuilder(Worksheet::class) + ->onlyMethods(['getStyle', 'getCellCollection']) + ->addMethods(['getNumberFormat', 'setFormatCode']) + ->getMock(); + + $cellCollection = $this->getMockBuilder(Cells::class) + ->disableOriginalConstructor() + ->getMock(); + $cellCollection->expects(self::any()) + ->method('getParent') + ->willReturn($sheet); + + $sheet->expects(self::once()) + ->method('getStyle') + ->willReturnSelf(); + // @phpstan-ignore-next-line + $sheet->expects(self::once()) + ->method('getNumberFormat') + ->willReturnSelf(); + // @phpstan-ignore-next-line + $sheet->expects(self::once()) + ->method('setFormatCode') + ->with($format) + ->willReturnSelf(); + $sheet->expects(self::any()) + ->method('getCellCollection') + ->willReturn($cellCollection); + + $cell = new Cell(null, DataType::TYPE_STRING, $sheet); + + $binder = new AdvancedValueBinder(); + $binder->bindValue($cell, $value); + self::assertEquals($valueBinded, $cell->getValue()); + } + + public function fractionProvider(): array + { + return [ + ['1/5', 0.2, '?/?'], + ['-1/5', -0.2, '?/?'], + ['12/5', 2.4, '??/?'], + ['2/100', 0.02, '?/???'], + ['15/12', 1.25, '??/??'], + ['20/100', 0.2, '??/???'], + ['1 3/5', 1.6, '# ?/?'], + ['-1 3/5', -1.6, '# ?/?'], + ['1 4/20', 1.2, '# ?/??'], + ['1 16/20', 1.8, '# ??/??'], + ['12 20/100', 12.2, '# ??/???'], + ]; + } + + /** + * @dataProvider percentageProvider + * + * @param mixed $value + * @param mixed $valueBinded + * @param mixed $format + */ + public function testPercentages($value, $valueBinded, $format): void + { + $sheet = $this->getMockBuilder(Worksheet::class) + ->onlyMethods(['getStyle', 'getCellCollection']) + ->addMethods(['getNumberFormat', 'setFormatCode']) + ->getMock(); + $cellCollection = $this->getMockBuilder(Cells::class) + ->disableOriginalConstructor() + ->getMock(); + $cellCollection->expects(self::any()) + ->method('getParent') + ->willReturn($sheet); + + $sheet->expects(self::once()) + ->method('getStyle') + ->willReturnSelf(); + // @phpstan-ignore-next-line + $sheet->expects(self::once()) + ->method('getNumberFormat') + ->willReturnSelf(); + // @phpstan-ignore-next-line + $sheet->expects(self::once()) + ->method('setFormatCode') + ->with($format) + ->willReturnSelf(); + $sheet->expects(self::any()) + ->method('getCellCollection') + ->willReturn($cellCollection); + + $cell = new Cell(null, DataType::TYPE_STRING, $sheet); + + $binder = new AdvancedValueBinder(); + $binder->bindValue($cell, $value); + self::assertEquals($valueBinded, $cell->getValue()); + } + + public function percentageProvider(): array + { + return [ + ['10%', 0.1, NumberFormat::FORMAT_PERCENTAGE_00], + ['-12%', -0.12, NumberFormat::FORMAT_PERCENTAGE_00], + ['120%', 1.2, NumberFormat::FORMAT_PERCENTAGE_00], + ['12.5%', 0.125, NumberFormat::FORMAT_PERCENTAGE_00], + ]; + } + + /** + * @dataProvider timeProvider + * + * @param mixed $value + * @param mixed $valueBinded + * @param mixed $format + */ + public function testTimes($value, $valueBinded, $format): void + { + $sheet = $this->getMockBuilder(Worksheet::class) + ->onlyMethods(['getStyle', 'getCellCollection']) + ->addMethods(['getNumberFormat', 'setFormatCode']) + ->getMock(); + + $cellCollection = $this->getMockBuilder(Cells::class) + ->disableOriginalConstructor() + ->getMock(); + $cellCollection->expects(self::any()) + ->method('getParent') + ->willReturn($sheet); + + $sheet->expects(self::once()) + ->method('getStyle') + ->willReturnSelf(); + // @phpstan-ignore-next-line + $sheet->expects(self::once()) + ->method('getNumberFormat') + ->willReturnSelf(); + // @phpstan-ignore-next-line + $sheet->expects(self::once()) + ->method('setFormatCode') + ->with($format) + ->willReturnSelf(); + $sheet->expects(self::any()) + ->method('getCellCollection') + ->willReturn($cellCollection); + + $cell = new Cell(null, DataType::TYPE_STRING, $sheet); + + $binder = new AdvancedValueBinder(); + $binder->bindValue($cell, $value); + self::assertEquals($valueBinded, $cell->getValue()); + } + + public function timeProvider(): array + { + return [ + ['1:20', 0.05555555556, NumberFormat::FORMAT_DATE_TIME3], + ['09:17', 0.386805555556, NumberFormat::FORMAT_DATE_TIME3], + ['15:00', 0.625, NumberFormat::FORMAT_DATE_TIME3], + ['17:12:35', 0.71707175926, NumberFormat::FORMAT_DATE_TIME4], + ['23:58:20', 0.99884259259, NumberFormat::FORMAT_DATE_TIME4], + ]; + } + + /** + * @dataProvider stringProvider + */ + public function testStringWrapping(string $value, bool $wrapped): void + { + $sheet = $this->getMockBuilder(Worksheet::class) + ->onlyMethods(['getStyle', 'getCellCollection']) + ->addMethods(['getAlignment', 'setWrapText']) + ->getMock(); + $cellCollection = $this->getMockBuilder(Cells::class) + ->disableOriginalConstructor() + ->getMock(); + $cellCollection->expects(self::any()) + ->method('getParent') + ->willReturn($sheet); + + $sheet->expects($wrapped ? self::once() : self::never()) + ->method('getStyle') + ->willReturnSelf(); + // @phpstan-ignore-next-line + $sheet->expects($wrapped ? self::once() : self::never()) + ->method('getAlignment') + ->willReturnSelf(); + // @phpstan-ignore-next-line + $sheet->expects($wrapped ? self::once() : self::never()) + ->method('setWrapText') + ->with($wrapped) + ->willReturnSelf(); + $sheet->expects(self::any()) + ->method('getCellCollection') + ->willReturn($cellCollection); + + $cell = new Cell(null, DataType::TYPE_STRING, $sheet); + + $binder = new AdvancedValueBinder(); + $binder->bindValue($cell, $value); + } + + public function stringProvider(): array + { + return [ + ['Hello World', false], + ["Hello\nWorld", true], + ]; + } } diff --git a/tests/PhpSpreadsheetTests/Cell/CellTest.php b/tests/PhpSpreadsheetTests/Cell/CellTest.php index 0d9ce337..980f0170 100644 --- a/tests/PhpSpreadsheetTests/Cell/CellTest.php +++ b/tests/PhpSpreadsheetTests/Cell/CellTest.php @@ -23,7 +23,7 @@ class CellTest extends TestCase self::assertSame($expected, $cell->getValue()); } - public function providerSetValueExplicit() + public function providerSetValueExplicit(): array { return require 'tests/data/Cell/SetValueExplicit.php'; } @@ -42,7 +42,7 @@ class CellTest extends TestCase $cell->setValueExplicit($value, $dataType); } - public function providerSetValueExplicitException() + public function providerSetValueExplicitException(): array { return require 'tests/data/Cell/SetValueExplicitException.php'; } diff --git a/tests/PhpSpreadsheetTests/Cell/CoordinateTest.php b/tests/PhpSpreadsheetTests/Cell/CoordinateTest.php index 8e0e98a9..9a0a2c21 100644 --- a/tests/PhpSpreadsheetTests/Cell/CoordinateTest.php +++ b/tests/PhpSpreadsheetTests/Cell/CoordinateTest.php @@ -24,7 +24,7 @@ class CoordinateTest extends TestCase self::assertEquals($stringBack, $string, 'should be able to get the original input with opposite method'); } - public function providerColumnString() + public function providerColumnString(): array { return require 'tests/data/ColumnString.php'; } @@ -74,7 +74,7 @@ class CoordinateTest extends TestCase self::assertEquals($columnIndexBack, $columnIndex, 'should be able to get the original input with opposite method'); } - public function providerColumnIndex() + public function providerColumnIndex(): array { return require 'tests/data/ColumnIndex.php'; } @@ -91,11 +91,25 @@ class CoordinateTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerCoordinates() + public function providerCoordinates(): array { return require 'tests/data/CellCoordinates.php'; } + /** + * @dataProvider providerIndexesFromString + */ + public function testIndexesFromString(array $expectedResult, string $rangeSet): void + { + $result = Coordinate::indexesFromString($rangeSet); + self::assertSame($expectedResult, $result); + } + + public function providerIndexesFromString(): array + { + return require 'tests/data/Cell/IndexesFromString.php'; + } + public function testCoordinateFromStringWithRangeAddress(): void { $cellAddress = 'A1:AI2012'; @@ -153,7 +167,7 @@ class CoordinateTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerAbsoluteCoordinates() + public function providerAbsoluteCoordinates(): array { return require 'tests/data/CellAbsoluteCoordinate.php'; } @@ -185,7 +199,7 @@ class CoordinateTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerAbsoluteReferences() + public function providerAbsoluteReferences(): array { return require 'tests/data/CellAbsoluteReference.php'; } @@ -223,7 +237,7 @@ class CoordinateTest extends TestCase } } - public function providerSplitRange() + public function providerSplitRange(): array { return require 'tests/data/CellSplitRange.php'; } @@ -232,14 +246,15 @@ class CoordinateTest extends TestCase * @dataProvider providerBuildRange * * @param mixed $expectedResult + * @param mixed $rangeSets */ - public function testBuildRange($expectedResult, ...$args): void + public function testBuildRange($expectedResult, $rangeSets): void { - $result = Coordinate::buildRange(...$args); + $result = Coordinate::buildRange($rangeSets); self::assertEquals($expectedResult, $result); } - public function providerBuildRange() + public function providerBuildRange(): array { return require 'tests/data/CellBuildRange.php'; } @@ -248,7 +263,17 @@ class CoordinateTest extends TestCase { $this->expectException(TypeError::class); - $cellRange = ''; + $cellRange = null; + // @phpstan-ignore-next-line + Coordinate::buildRange($cellRange); + } + + public function testBuildRangeInvalid2(): void + { + $this->expectException(Exception::class); + $this->expectExceptionMessage('Range does not contain any information'); + + $cellRange = []; Coordinate::buildRange($cellRange); } @@ -264,7 +289,7 @@ class CoordinateTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerRangeBoundaries() + public function providerRangeBoundaries(): array { return require 'tests/data/CellRangeBoundaries.php'; } @@ -281,7 +306,7 @@ class CoordinateTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerRangeDimension() + public function providerRangeDimension(): array { return require 'tests/data/CellRangeDimension.php'; } @@ -298,7 +323,7 @@ class CoordinateTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerGetRangeBoundaries() + public function providerGetRangeBoundaries(): array { return require 'tests/data/CellGetRangeBoundaries.php'; } @@ -315,7 +340,7 @@ class CoordinateTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerExtractAllCellReferencesInRange() + public function providerExtractAllCellReferencesInRange(): array { return require 'tests/data/CellExtractAllCellReferencesInRange.php'; } @@ -333,7 +358,7 @@ class CoordinateTest extends TestCase Coordinate::extractAllCellReferencesInRange($range); } - public function providerInvalidRange() + public function providerInvalidRange(): array { return [['Z1:A1'], ['A4:A1'], ['B1:A1'], ['AA1:Z1']]; } @@ -342,14 +367,15 @@ class CoordinateTest extends TestCase * @dataProvider providerMergeRangesInCollection * * @param mixed $expectedResult + * @param mixed $rangeSets */ - public function testMergeRangesInCollection($expectedResult, ...$args): void + public function testMergeRangesInCollection($expectedResult, $rangeSets): void { - $result = Coordinate::mergeRangesInCollection(...$args); + $result = Coordinate::mergeRangesInCollection($rangeSets); self::assertEquals($expectedResult, $result); } - public function providerMergeRangesInCollection() + public function providerMergeRangesInCollection(): array { return require 'tests/data/CellMergeRangesInCollection.php'; } @@ -366,7 +392,7 @@ class CoordinateTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerCoordinateIsRange() + public function providerCoordinateIsRange(): array { return require 'tests/data/CoordinateIsRange.php'; } diff --git a/tests/PhpSpreadsheetTests/Cell/DataTypeTest.php b/tests/PhpSpreadsheetTests/Cell/DataTypeTest.php index 95454c16..176dd6ac 100644 --- a/tests/PhpSpreadsheetTests/Cell/DataTypeTest.php +++ b/tests/PhpSpreadsheetTests/Cell/DataTypeTest.php @@ -25,6 +25,7 @@ class DataTypeTest extends TestCase $stringLimit = 32767; $randString = $this->randr($stringLimit + 10); $result2 = DataType::checkString($randString); + self::assertIsString($result2); self::assertSame($stringLimit, strlen($result2)); $dirtyString = "bla bla\r\n bla\r test\n"; diff --git a/tests/PhpSpreadsheetTests/Cell/DataValidator2Test.php b/tests/PhpSpreadsheetTests/Cell/DataValidator2Test.php new file mode 100644 index 00000000..9153a5b8 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Cell/DataValidator2Test.php @@ -0,0 +1,75 @@ +load('tests/data/Reader/XLSX/issue.1432b.xlsx'); + $sheet = $spreadsheet->getActiveSheet(); + self::assertSame('H1', $sheet->getTopLeftCell()); + self::assertSame('K3', $sheet->getSelectedCells()); + + $testCell = $sheet->getCell('K3'); + $validation = $testCell->getDataValidation(); + self::assertSame(DataValidation::TYPE_LIST, $validation->getType()); + + $testCell = $sheet->getCell('R2'); + $validation = $testCell->getDataValidation(); + self::assertSame(DataValidation::TYPE_LIST, $validation->getType()); + + $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xlsx'); + $sheet = $reloadedSpreadsheet->getActiveSheet(); + + $cell = 'K3'; + $testCell = $sheet->getCell($cell); + $validation = $testCell->getDataValidation(); + self::assertSame(DataValidation::TYPE_LIST, $validation->getType()); + $testCell->setValue('Y'); + self::assertTrue($testCell->hasValidValue(), 'K3 other sheet has valid value'); + $testCell = $sheet->getCell($cell); + $testCell->setValue('X'); + self::assertFalse($testCell->hasValidValue(), 'K3 other sheet has invalid value'); + + $cell = 'J2'; + $testCell = $sheet->getCell($cell); + $validation = $testCell->getDataValidation(); + self::assertSame(DataValidation::TYPE_LIST, $validation->getType()); + $testCell = $sheet->getCell($cell); + $testCell->setValue('GBP'); + self::assertTrue($testCell->hasValidValue(), 'J2 other sheet has valid value'); + $testCell = $sheet->getCell($cell); + $testCell->setValue('XYZ'); + self::assertFalse($testCell->hasValidValue(), 'J2 other sheet has invalid value'); + + $cell = 'R2'; + $testCell = $sheet->getCell($cell); + $validation = $testCell->getDataValidation(); + self::assertSame(DataValidation::TYPE_LIST, $validation->getType()); + $testCell->setValue('ListItem2'); + self::assertTrue($testCell->hasValidValue(), 'R2 same sheet has valid value'); + $testCell = $sheet->getCell($cell); + $testCell->setValue('ListItem99'); + self::assertFalse($testCell->hasValidValue(), 'R2 same sheet has invalid value'); + + $styles = $sheet->getConditionalStyles('I1:I1048576'); + self::assertCount(1, $styles); + $style = $styles[0]; + self::assertSame(Conditional::CONDITION_CELLIS, $style->getConditionType()); + self::assertSame(Conditional::OPERATOR_BETWEEN, $style->getOperatorType()); + $conditions = $style->getConditions(); + self::assertSame('10', $conditions[0]); + self::assertSame('20', $conditions[1]); + self::assertSame('FF70AD47', $style->getStyle()->getFill()->getEndColor()->getARGB()); + + $spreadsheet->disconnectWorksheets(); + $reloadedSpreadsheet->disconnectWorksheets(); + } +} diff --git a/tests/PhpSpreadsheetTests/Cell/DefaultValueBinderTest.php b/tests/PhpSpreadsheetTests/Cell/DefaultValueBinderTest.php index e13cd942..cc9098bf 100644 --- a/tests/PhpSpreadsheetTests/Cell/DefaultValueBinderTest.php +++ b/tests/PhpSpreadsheetTests/Cell/DefaultValueBinderTest.php @@ -8,14 +8,15 @@ use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder; use PhpOffice\PhpSpreadsheet\RichText\RichText; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class DefaultValueBinderTest extends TestCase { - private function createCellStub() + private function createCellStub(): Cell { // Create a stub for the Cell class. - /** @var Cell $cellStub */ + /** @var Cell&MockObject $cellStub */ $cellStub = $this->getMockBuilder(Cell::class) ->disableOriginalConstructor() ->getMock(); @@ -41,7 +42,7 @@ class DefaultValueBinderTest extends TestCase self::assertTrue($result); } - public function binderProvider() + public function binderProvider(): array { return [ [null], @@ -65,14 +66,15 @@ class DefaultValueBinderTest extends TestCase * @dataProvider providerDataTypeForValue * * @param mixed $expectedResult + * @param mixed $value */ - public function testDataTypeForValue($expectedResult, ...$args): void + public function testDataTypeForValue($expectedResult, $value): void { - $result = DefaultValueBinder::dataTypeForValue(...$args); + $result = DefaultValueBinder::dataTypeForValue($value); self::assertEquals($expectedResult, $result); } - public function providerDataTypeForValue() + public function providerDataTypeForValue(): array { return require 'tests/data/Cell/DefaultValueBinder.php'; } diff --git a/tests/PhpSpreadsheetTests/Cell/HyperlinkTest.php b/tests/PhpSpreadsheetTests/Cell/HyperlinkTest.php index 9c09aa75..e92fbaf3 100644 --- a/tests/PhpSpreadsheetTests/Cell/HyperlinkTest.php +++ b/tests/PhpSpreadsheetTests/Cell/HyperlinkTest.php @@ -34,7 +34,7 @@ class HyperlinkTest extends TestCase { $tooltipValue = 'PhpSpreadsheet Web Site'; - $testInstance = new Hyperlink(null, $tooltipValue); + $testInstance = new Hyperlink('', $tooltipValue); $result = $testInstance->getTooltip(); self::assertEquals($tooltipValue, $result); @@ -45,7 +45,7 @@ class HyperlinkTest extends TestCase $initialTooltipValue = 'PhpSpreadsheet Web Site'; $newTooltipValue = 'PhpSpreadsheet Repository on Github'; - $testInstance = new Hyperlink(null, $initialTooltipValue); + $testInstance = new Hyperlink('', $initialTooltipValue); $result = $testInstance->setTooltip($newTooltipValue); self::assertInstanceOf(Hyperlink::class, $result); diff --git a/tests/PhpSpreadsheetTests/Cell/StringValueBinderTest.php b/tests/PhpSpreadsheetTests/Cell/StringValueBinderTest.php new file mode 100644 index 00000000..411af353 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Cell/StringValueBinderTest.php @@ -0,0 +1,261 @@ +getMockBuilder(Style::class) + ->disableOriginalConstructor() + ->getMock(); + + /** @var Cell&MockObject $cellStub */ + $cellStub = $this->getMockBuilder(Cell::class) + ->disableOriginalConstructor() + ->getMock(); + + // Configure the stub. + $cellStub->expects(self::once()) + ->method('setValueExplicit') + ->with($expectedValue, $expectedDataType) + ->willReturn(true); + $cellStub->expects($quotePrefix ? self::once() : self::never()) + ->method('getStyle') + ->willReturn($styleStub); + + return $cellStub; + } + + /** + * @dataProvider providerDataValuesDefault + * + * @param mixed $value + * @param mixed $expectedValue + */ + public function testStringValueBinderDefaultBehaviour( + $value, + $expectedValue, + string $expectedDataType, + bool $quotePrefix = false + ): void { + $cellStub = $this->createCellStub($expectedValue, $expectedDataType, $quotePrefix); + + $binder = new StringValueBinder(); + $binder->bindValue($cellStub, $value); + } + + public function providerDataValuesDefault(): array + { + return [ + [null, '', DataType::TYPE_STRING], + [true, '1', DataType::TYPE_STRING], + [false, '', DataType::TYPE_STRING], + ['', '', DataType::TYPE_STRING], + ['123', '123', DataType::TYPE_STRING], + ['123.456', '123.456', DataType::TYPE_STRING], + ['0.123', '0.123', DataType::TYPE_STRING], + ['.123', '.123', DataType::TYPE_STRING], + ['-0.123', '-0.123', DataType::TYPE_STRING], + ['-.123', '-.123', DataType::TYPE_STRING], + ['1.23e-4', '1.23e-4', DataType::TYPE_STRING], + ['ABC', 'ABC', DataType::TYPE_STRING], + ['=SUM(A1:C3)', '=SUM(A1:C3)', DataType::TYPE_STRING, true], + [123, '123', DataType::TYPE_STRING], + [123.456, '123.456', DataType::TYPE_STRING], + [0.123, '0.123', DataType::TYPE_STRING], + [.123, '0.123', DataType::TYPE_STRING], + [-0.123, '-0.123', DataType::TYPE_STRING], + [-.123, '-0.123', DataType::TYPE_STRING], + [1.23e-4, '0.000123', DataType::TYPE_STRING], + [1.23e-24, '1.23E-24', DataType::TYPE_STRING], + [new DateTime('2021-06-01 00:00:00', new DateTimeZone('UTC')), '2021-06-01 00:00:00', DataType::TYPE_STRING], + ]; + } + + /** + * @dataProvider providerDataValuesSuppressNullConversion + * + * @param mixed $value + * @param mixed $expectedValue + */ + public function testStringValueBinderSuppressNullConversion( + $value, + $expectedValue, + string $expectedDataType, + bool $quotePrefix = false + ): void { + $cellStub = $this->createCellStub($expectedValue, $expectedDataType, $quotePrefix); + + $binder = new StringValueBinder(); + $binder->setNullConversion(false); + $binder->bindValue($cellStub, $value); + } + + public function providerDataValuesSuppressNullConversion(): array + { + return [ + [null, null, DataType::TYPE_NULL], + ]; + } + + /** + * @dataProvider providerDataValuesSuppressBooleanConversion + * + * @param mixed $value + * @param mixed $expectedValue + */ + public function testStringValueBinderSuppressBooleanConversion( + $value, + $expectedValue, + string $expectedDataType, + bool $quotePrefix = false + ): void { + $cellStub = $this->createCellStub($expectedValue, $expectedDataType, $quotePrefix); + + $binder = new StringValueBinder(); + $binder->setBooleanConversion(false); + $binder->bindValue($cellStub, $value); + } + + public function providerDataValuesSuppressBooleanConversion(): array + { + return [ + [true, true, DataType::TYPE_BOOL], + [false, false, DataType::TYPE_BOOL], + ]; + } + + /** + * @dataProvider providerDataValuesSuppressNumericConversion + * + * @param mixed $value + * @param mixed $expectedValue + */ + public function testStringValueBinderSuppressNumericConversion( + $value, + $expectedValue, + string $expectedDataType, + bool $quotePrefix = false + ): void { + $cellStub = $this->createCellStub($expectedValue, $expectedDataType, $quotePrefix); + + $binder = new StringValueBinder(); + $binder->setNumericConversion(false); + $binder->bindValue($cellStub, $value); + } + + public function providerDataValuesSuppressNumericConversion(): array + { + return [ + [123, 123, DataType::TYPE_NUMERIC], + [123.456, 123.456, DataType::TYPE_NUMERIC], + [0.123, 0.123, DataType::TYPE_NUMERIC], + [.123, 0.123, DataType::TYPE_NUMERIC], + [-0.123, -0.123, DataType::TYPE_NUMERIC], + [-.123, -0.123, DataType::TYPE_NUMERIC], + [1.23e-4, 0.000123, DataType::TYPE_NUMERIC], + [1.23e-24, 1.23E-24, DataType::TYPE_NUMERIC], + ]; + } + + /** + * @dataProvider providerDataValuesSuppressFormulaConversion + * + * @param mixed $value + * @param mixed $expectedValue + */ + public function testStringValueBinderSuppressFormulaConversion( + $value, + $expectedValue, + string $expectedDataType, + bool $quotePrefix = false + ): void { + $cellStub = $this->createCellStub($expectedValue, $expectedDataType, $quotePrefix); + + $binder = new StringValueBinder(); + $binder->setFormulaConversion(false); + $binder->bindValue($cellStub, $value); + } + + public function providerDataValuesSuppressFormulaConversion(): array + { + return [ + ['=SUM(A1:C3)', '=SUM(A1:C3)', DataType::TYPE_FORMULA, false], + ]; + } + + /** + * @dataProvider providerDataValuesSuppressAllConversion + * + * @param mixed $value + * @param mixed $expectedValue + */ + public function testStringValueBinderSuppressAllConversion( + $value, + $expectedValue, + string $expectedDataType, + bool $quotePrefix = false + ): void { + $cellStub = $this->createCellStub($expectedValue, $expectedDataType, $quotePrefix); + + $binder = new StringValueBinder(); + $binder->setConversionForAllValueTypes(false); + $binder->bindValue($cellStub, $value); + } + + public function providerDataValuesSuppressAllConversion(): array + { + return [ + [null, null, DataType::TYPE_NULL], + [true, true, DataType::TYPE_BOOL], + [false, false, DataType::TYPE_BOOL], + ['', '', DataType::TYPE_STRING], + ['123', '123', DataType::TYPE_STRING], + ['123.456', '123.456', DataType::TYPE_STRING], + ['0.123', '0.123', DataType::TYPE_STRING], + ['.123', '.123', DataType::TYPE_STRING], + ['-0.123', '-0.123', DataType::TYPE_STRING], + ['-.123', '-.123', DataType::TYPE_STRING], + ['1.23e-4', '1.23e-4', DataType::TYPE_STRING], + ['ABC', 'ABC', DataType::TYPE_STRING], + ['=SUM(A1:C3)', '=SUM(A1:C3)', DataType::TYPE_FORMULA, false], + [123, 123, DataType::TYPE_NUMERIC], + [123.456, 123.456, DataType::TYPE_NUMERIC], + [0.123, 0.123, DataType::TYPE_NUMERIC], + [.123, 0.123, DataType::TYPE_NUMERIC], + [-0.123, -0.123, DataType::TYPE_NUMERIC], + [-.123, -0.123, DataType::TYPE_NUMERIC], + [1.23e-4, 0.000123, DataType::TYPE_NUMERIC], + [1.23e-24, 1.23E-24, DataType::TYPE_NUMERIC], + ]; + } + + public function testStringValueBinderForRichTextObject(): void + { + $objRichText = new RichText(); + $objRichText->createText('Hello World'); + + $cellStub = $this->createCellStub($objRichText, DataType::TYPE_INLINE); + + $binder = new StringValueBinder(); + $binder->setConversionForAllValueTypes(false); + $binder->bindValue($cellStub, $objRichText); + } +} diff --git a/tests/PhpSpreadsheetTests/Cell/ValueBinderWithOverriddenDataTypeForValue.php b/tests/PhpSpreadsheetTests/Cell/ValueBinderWithOverriddenDataTypeForValue.php index d1b025a9..e2ddc602 100644 --- a/tests/PhpSpreadsheetTests/Cell/ValueBinderWithOverriddenDataTypeForValue.php +++ b/tests/PhpSpreadsheetTests/Cell/ValueBinderWithOverriddenDataTypeForValue.php @@ -6,12 +6,15 @@ use PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder; class ValueBinderWithOverriddenDataTypeForValue extends DefaultValueBinder { + /** + * @var bool + */ public static $called = false; - public static function dataTypeForValue($pValue) + public static function dataTypeForValue($value) { self::$called = true; - return parent::dataTypeForValue($pValue); + return parent::dataTypeForValue($value); } } diff --git a/tests/PhpSpreadsheetTests/Chart/LegendTest.php b/tests/PhpSpreadsheetTests/Chart/LegendTest.php index 30715365..b12658a4 100644 --- a/tests/PhpSpreadsheetTests/Chart/LegendTest.php +++ b/tests/PhpSpreadsheetTests/Chart/LegendTest.php @@ -98,22 +98,11 @@ class LegendTest extends TestCase $testInstance = new Legend(); foreach ($overlayValues as $overlayValue) { - $result = $testInstance->setOverlay($overlayValue); - self::assertTrue($result); + $testInstance->setOverlay($overlayValue); + self::assertSame($overlayValue, $testInstance->getOverlay()); } } - public function testSetInvalidOverlayReturnsFalse(): void - { - $testInstance = new Legend(); - - $result = $testInstance->setOverlay('INVALID'); - self::assertFalse($result); - - $result = $testInstance->getOverlay(); - self::assertFalse($result); - } - public function testGetOverlay(): void { $OverlayValue = true; diff --git a/tests/PhpSpreadsheetTests/Chart/TitleTest.php b/tests/PhpSpreadsheetTests/Chart/TitleTest.php new file mode 100644 index 00000000..9247b0c2 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Chart/TitleTest.php @@ -0,0 +1,58 @@ +getCaption()); + self::assertSame('hello', $title->getCaptionText()); + } + + public function testStringArray(): void + { + $title = new Title(); + $title->setCaption(['Hello', ', ', 'world.']); + self::assertSame('Hello, world.', $title->getCaptionText()); + } + + public function testRichText(): void + { + $title = new Title(); + $richText = new RichText(); + $part = $richText->createTextRun('Hello'); + $font = $part->getFont(); + if ($font === null) { + self::fail('Unable to retrieve font'); + } else { + $font->setBold(true); + $title->setCaption($richText); + self::assertSame('Hello', $title->getCaptionText()); + } + } + + public function testMixedArray(): void + { + $title = new Title(); + $richText1 = new RichText(); + $part1 = $richText1->createTextRun('Hello'); + $font1 = $part1->getFont(); + $richText2 = new RichText(); + $part2 = $richText2->createTextRun('world'); + $font2 = $part2->getFont(); + if ($font1 === null || $font2 === null) { + self::fail('Unable to retrieve font'); + } else { + $font1->setBold(true); + $font2->setItalic(true); + $title->setCaption([$richText1, ', ', $richText2, '.']); + self::assertSame('Hello, world.', $title->getCaptionText()); + } + } +} diff --git a/tests/PhpSpreadsheetTests/Collection/CellsTest.php b/tests/PhpSpreadsheetTests/Collection/CellsTest.php index 539d0232..5e656cf5 100644 --- a/tests/PhpSpreadsheetTests/Collection/CellsTest.php +++ b/tests/PhpSpreadsheetTests/Collection/CellsTest.php @@ -91,7 +91,7 @@ class CellsTest extends TestCase $collection = $this->getMockBuilder(Cells::class) ->setConstructorArgs([new Worksheet(), new Memory()]) - ->setMethods(['has']) + ->onlyMethods(['has']) ->getMock(); $collection->method('has') diff --git a/tests/PhpSpreadsheetTests/Custom/ComplexAssert.php b/tests/PhpSpreadsheetTests/Custom/ComplexAssert.php index 4d1025d2..828329ac 100644 --- a/tests/PhpSpreadsheetTests/Custom/ComplexAssert.php +++ b/tests/PhpSpreadsheetTests/Custom/ComplexAssert.php @@ -6,9 +6,16 @@ use Complex\Complex; class ComplexAssert { + /** + * @var string + */ private $errorMessage = ''; - private function testExpectedExceptions($expected, $actual) + /** + * @param mixed $expected + * @param mixed $actual + */ + private function testExpectedExceptions($expected, $actual): bool { // Expecting an error, so we do a straight string comparison if ($expected === $actual) { @@ -21,7 +28,7 @@ class ComplexAssert return false; } - private function adjustDelta($expected, $actual, $delta) + private function adjustDelta(float $expected, float $actual, float $delta): float { $adjustedDelta = $delta; @@ -33,7 +40,11 @@ class ComplexAssert return $adjustedDelta > 1.0 ? 1.0 : $adjustedDelta; } - public function assertComplexEquals($expected, $actual, $delta = 0) + /** + * @param mixed $expected + * @param mixed $actual + */ + public function assertComplexEquals($expected, $actual, float $delta = 0): bool { if ($expected === INF || (is_string($expected) && $expected[0] === '#')) { return $this->testExpectedExceptions($expected, $actual); @@ -42,16 +53,6 @@ class ComplexAssert $expectedComplex = new Complex($expected); $actualComplex = new Complex($actual); - if (!is_numeric($actualComplex->getReal()) || !is_numeric($expectedComplex->getReal())) { - if ($actualComplex->getReal() !== $expectedComplex->getReal()) { - $this->errorMessage = 'Mismatched String: ' . $actualComplex->getReal() . ' !== ' . $expectedComplex->getReal(); - - return false; - } - - return true; - } - $adjustedDelta = $this->adjustDelta($expectedComplex->getReal(), $actualComplex->getReal(), $delta); if (abs($actualComplex->getReal() - $expectedComplex->getReal()) > $adjustedDelta) { $this->errorMessage = 'Mismatched Real part: ' . $actualComplex->getReal() . ' != ' . $expectedComplex->getReal(); @@ -75,7 +76,7 @@ class ComplexAssert return true; } - public function getErrorMessage() + public function getErrorMessage(): string { return $this->errorMessage; } diff --git a/tests/PhpSpreadsheetTests/DefinedNameFormulaTest.php b/tests/PhpSpreadsheetTests/DefinedNameFormulaTest.php index 14843091..4b17230e 100644 --- a/tests/PhpSpreadsheetTests/DefinedNameFormulaTest.php +++ b/tests/PhpSpreadsheetTests/DefinedNameFormulaTest.php @@ -31,7 +31,7 @@ class DefinedNameFormulaTest extends TestCase } $allDefinedNames = $spreadSheet->getDefinedNames(); - self::assertSame(count($definedNamesForTest), count($allDefinedNames)); + self::assertCount(count($definedNamesForTest), $allDefinedNames); } public function testGetNamedRanges(): void @@ -49,7 +49,7 @@ class DefinedNameFormulaTest extends TestCase } $allNamedRanges = $spreadSheet->getNamedRanges(); - self::assertSame(count(array_filter($rangeOrFormula)), count($allNamedRanges)); + self::assertCount(count(array_filter($rangeOrFormula)), $allNamedRanges); } public function testGetScopedNamedRange(): void @@ -65,6 +65,7 @@ class DefinedNameFormulaTest extends TestCase $spreadSheet->addDefinedName(DefinedName::createInstance($rangeName, $workSheet, $localRangeValue, true)); $localScopedRange = $spreadSheet->getNamedRange($rangeName, $workSheet); + self::assertNotNull($localScopedRange); self::assertSame($localRangeValue, $localScopedRange->getValue()); } @@ -83,6 +84,7 @@ class DefinedNameFormulaTest extends TestCase $spreadSheet->addDefinedName(DefinedName::createInstance($rangeName, $workSheet1, $localRangeValue, true)); $localScopedRange = $spreadSheet->getNamedRange($rangeName, $workSheet2); + self::assertNotNull($localScopedRange); self::assertSame($globalRangeValue, $localScopedRange->getValue()); } @@ -101,7 +103,7 @@ class DefinedNameFormulaTest extends TestCase } $allNamedFormulae = $spreadSheet->getNamedFormulae(); - self::assertSame(count(array_filter($rangeOrFormula)), count($allNamedFormulae)); + self::assertCount(count(array_filter($rangeOrFormula)), $allNamedFormulae); } public function testGetScopedNamedFormula(): void @@ -117,6 +119,7 @@ class DefinedNameFormulaTest extends TestCase $spreadSheet->addDefinedName(DefinedName::createInstance($formulaName, $workSheet, $localFormulaValue, true)); $localScopedFormula = $spreadSheet->getNamedFormula($formulaName, $workSheet); + self::assertNotNull($localScopedFormula); self::assertSame($localFormulaValue, $localScopedFormula->getValue()); } @@ -135,6 +138,7 @@ class DefinedNameFormulaTest extends TestCase $spreadSheet->addDefinedName(DefinedName::createInstance($formulaName, $workSheet1, $localFormulaValue, true)); $localScopedFormula = $spreadSheet->getNamedFormula($formulaName, $workSheet2); + self::assertNotNull($localScopedFormula); self::assertSame($globalFormulaValue, $localScopedFormula->getValue()); } diff --git a/tests/PhpSpreadsheetTests/DefinedNameTest.php b/tests/PhpSpreadsheetTests/DefinedNameTest.php index 8a411775..43eddc8a 100644 --- a/tests/PhpSpreadsheetTests/DefinedNameTest.php +++ b/tests/PhpSpreadsheetTests/DefinedNameTest.php @@ -47,10 +47,9 @@ class DefinedNameTest extends TestCase ); self::assertCount(1, $this->spreadsheet->getDefinedNames()); - self::assertSame( - '=B1', - $this->spreadsheet->getDefinedName('foo', $this->spreadsheet->getActiveSheet())->getValue() - ); + $definedName = $this->spreadsheet->getDefinedName('foo', $this->spreadsheet->getActiveSheet()); + self::assertNotNull($definedName); + self::assertSame('=B1', $definedName->getValue()); } public function testAddScopedDefinedNameWithSameName(): void @@ -63,14 +62,13 @@ class DefinedNameTest extends TestCase ); self::assertCount(2, $this->spreadsheet->getDefinedNames()); - self::assertSame( - '=A1', - $this->spreadsheet->getDefinedName('foo', $this->spreadsheet->getActiveSheet())->getValue() - ); - self::assertSame( - '=B1', - $this->spreadsheet->getDefinedName('foo', $this->spreadsheet->getSheetByName('Sheet #2'))->getValue() - ); + $definedName1 = $this->spreadsheet->getDefinedName('foo', $this->spreadsheet->getActiveSheet()); + self::assertNotNull($definedName1); + self::assertSame('=A1', $definedName1->getValue()); + + $definedName2 = $this->spreadsheet->getDefinedName('foo', $this->spreadsheet->getSheetByName('Sheet #2')); + self::assertNotNull($definedName2); + self::assertSame('=B1', $definedName2->getValue()); } public function testRemoveDefinedName(): void @@ -99,10 +97,9 @@ class DefinedNameTest extends TestCase $this->spreadsheet->removeDefinedName('Foo', $this->spreadsheet->getActiveSheet()); self::assertCount(1, $this->spreadsheet->getDefinedNames()); - self::assertSame( - '=B1', - $this->spreadsheet->getDefinedName('foo', $this->spreadsheet->getSheetByName('Sheet #2'))->getValue() - ); + $definedName = $this->spreadsheet->getDefinedName('foo', $this->spreadsheet->getSheetByName('Sheet #2')); + self::assertNotNull($definedName); + self::assertSame('=B1', $definedName->getValue()); } public function testRemoveScopedDefinedNameWhenDuplicateNames(): void @@ -117,10 +114,9 @@ class DefinedNameTest extends TestCase $this->spreadsheet->removeDefinedName('Foo', $this->spreadsheet->getSheetByName('Sheet #2')); self::assertCount(1, $this->spreadsheet->getDefinedNames()); - self::assertSame( - '=A1', - $this->spreadsheet->getDefinedName('foo')->getValue() - ); + $definedName = $this->spreadsheet->getDefinedName('foo'); + self::assertNotNull($definedName); + self::assertSame('=A1', $definedName->getValue()); } public function testDefinedNameNoWorksheetNoScope(): void @@ -135,6 +131,7 @@ class DefinedNameTest extends TestCase DefinedName::createInstance('xyz', $this->spreadsheet->getActiveSheet(), 'A1') ); + /** @var NamedRange $namedRange */ $namedRange = $this->spreadsheet->getDefinedName('XYZ'); self::assertInstanceOf(NamedRange::class, $namedRange); self::assertEquals('A1', $namedRange->getRange()); @@ -147,6 +144,9 @@ class DefinedNameTest extends TestCase { $sheet1 = $this->spreadsheet->getSheetByName('Sheet #1'); $sheet2 = $this->spreadsheet->getSheetByName('Sheet #2'); + self::assertNotNull($sheet1); + self::assertNotNull($sheet2); + $sheet1->getCell('A1')->setValue(1); $sheet2->getCell('A1')->setValue(2); $namedRange = new NamedRange('xyz', $sheet2, '$A$1'); @@ -162,6 +162,9 @@ class DefinedNameTest extends TestCase { $sheet1 = $this->spreadsheet->getSheetByName('Sheet #1'); $sheet2 = $this->spreadsheet->getSheetByName('Sheet #2'); + self::assertNotNull($sheet1); + self::assertNotNull($sheet2); + $sheet1->getCell('A1')->setValue(1); $sheet2->getCell('A1')->setValue(2); $namedRange = new NamedRange('abc', $sheet2, '$A$1'); @@ -177,6 +180,9 @@ class DefinedNameTest extends TestCase { $sheet1 = $this->spreadsheet->getSheetByName('Sheet #1'); $sheet2 = $this->spreadsheet->getSheetByName('Sheet #2'); + self::assertNotNull($sheet1); + self::assertNotNull($sheet2); + $sheet1->getCell('A1')->setValue(1); $sheet2->getCell('A1')->setValue(2); $namedRange = new NamedRange('abc', $sheet2, '$A$1'); @@ -192,12 +198,17 @@ class DefinedNameTest extends TestCase { $sheet1 = $this->spreadsheet->getSheetByName('Sheet #1'); $sheet2 = $this->spreadsheet->getSheetByName('Sheet #2'); + self::assertNotNull($sheet1); + self::assertNotNull($sheet2); + $sheet1->getCell('A1')->setValue(1); $sheet2->getCell('A1')->setValue(2); $namedRange = new NamedRange('abc', $sheet2, '$A$1'); $namedRangeClone = clone $namedRange; $ss1 = $namedRange->getWorksheet(); $ss2 = $namedRangeClone->getWorksheet(); + self::assertNotNull($ss1); + self::assertNotNull($ss2); self::assertNotSame($ss1, $ss2); self::assertEquals($ss1->getTitle(), $ss2->getTitle()); } diff --git a/tests/PhpSpreadsheetTests/Document/EpochTest.php b/tests/PhpSpreadsheetTests/Document/EpochTest.php new file mode 100644 index 00000000..5ea5c5a8 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Document/EpochTest.php @@ -0,0 +1,97 @@ +getActiveSheet(); + $sheet->getCell('A1')->setValue(1); + $spreadsheet->getProperties()->setCreated($timestamp); + $timestamp2 = preg_replace('/1-/', '2-', $timestamp); + self::AssertNotEquals($timestamp, $timestamp2); + $spreadsheet->getProperties()->setModified($timestamp2); + $timestamp3 = preg_replace('/1-/', '3-', $timestamp); + self::AssertNotEquals($timestamp, $timestamp3); + self::AssertNotEquals($timestamp2, $timestamp3); + $spreadsheet->getProperties()->setCustomProperty('cprop', $timestamp3, 'd'); + $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format); + $created = $reloadedSpreadsheet->getProperties()->getCreated(); + $dt1 = DateTime::createFromFormat('U', "$created"); + $modified = $reloadedSpreadsheet->getProperties()->getModified(); + $dt2 = DateTime::createFromFormat('U', "$modified"); + if ($dt1 === false || $dt2 === false) { + self::fail('Invalid timestamp for created or modified'); + } else { + self::assertSame($timestamp, $dt1->format('Y-m-d H:i:s') . 'Z'); + self::assertSame($timestamp2, $dt2->format('Y-m-d H:i:s') . 'Z'); + } + if ($format === 'Xlsx' || $format === 'Ods') { + // No custom property support in Xls + $cprop = $reloadedSpreadsheet->getProperties()->getCustomPropertyValue('cprop'); + if (!is_numeric($cprop)) { + self::fail('Cannot find custom property'); + } else { + $dt3 = DateTime::createFromFormat('U', "$cprop"); + if ($dt3 === false) { + self::fail('Invalid timestamp for custom property'); + } else { + self::assertSame($timestamp3, $dt3->format('Y-m-d H:i:s') . 'Z'); + } + } + } + } + + public function providerFormats2(): array + { + return [ + ['Ods'], + ['Xls'], + ['Xlsx'], + ]; + } + + /** + * @dataProvider providerFormats2 + */ + public function testConsistentTimeStamp(string $format): void + { + $pgmstart = (float) (new DateTime())->format('U'); + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->getCell('A1')->setValue(1); + $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format); + $pgmend = (float) (new DateTime())->format('U'); + self::assertLessThanOrEqual($pgmend, $pgmstart); + $created = $reloadedSpreadsheet->getProperties()->getCreated(); + $modified = $reloadedSpreadsheet->getProperties()->getModified(); + self::assertLessThanOrEqual($pgmend, $created); + self::assertLessThanOrEqual($pgmend, $modified); + self::assertLessThanOrEqual($created, $pgmstart); + self::assertLessThanOrEqual($modified, $pgmstart); + } +} diff --git a/tests/PhpSpreadsheetTests/Document/PropertiesTest.php b/tests/PhpSpreadsheetTests/Document/PropertiesTest.php new file mode 100644 index 00000000..c539da09 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Document/PropertiesTest.php @@ -0,0 +1,192 @@ +properties = new Properties(); + } + + public function testNewInstance(): void + { + $createdTime = $modifiedTime = time(); + self::assertSame('Unknown Creator', $this->properties->getCreator()); + self::assertSame('Unknown Creator', $this->properties->getLastModifiedBy()); + self::assertSame('Untitled Spreadsheet', $this->properties->getTitle()); + self::assertSame('', $this->properties->getCompany()); + self::assertSame($createdTime, $this->properties->getCreated()); + self::assertSame($modifiedTime, $this->properties->getModified()); + } + + public function testSetCreator(): void + { + $creator = 'Mark Baker'; + + $this->properties->setCreator($creator); + self::assertSame($creator, $this->properties->getCreator()); + } + + /** + * @dataProvider providerCreationTime + * + * @param mixed $expectedCreationTime + * @param mixed $created + */ + public function testSetCreated($expectedCreationTime, $created): void + { + $expectedCreationTime = $expectedCreationTime ?? time(); + + $this->properties->setCreated($created); + self::assertSame($expectedCreationTime, $this->properties->getCreated()); + } + + public function providerCreationTime(): array + { + return [ + [null, null], + [1615980600, 1615980600], + [1615980600, '1615980600'], + [1615980600, '2021-03-17 11:30:00Z'], + ]; + } + + public function testSetModifier(): void + { + $creator = 'Mark Baker'; + + $this->properties->setLastModifiedBy($creator); + self::assertSame($creator, $this->properties->getLastModifiedBy()); + } + + /** + * @dataProvider providerModifiedTime + * + * @param mixed $expectedModifiedTime + * @param mixed $modified + */ + public function testSetModified($expectedModifiedTime, $modified): void + { + $expectedModifiedTime = $expectedModifiedTime ?? time(); + + $this->properties->setModified($modified); + self::assertSame($expectedModifiedTime, $this->properties->getModified()); + } + + public function providerModifiedTime(): array + { + return [ + [null, null], + [1615980600, 1615980600], + [1615980600, '1615980600'], + [1615980600, '2021-03-17 11:30:00Z'], + ]; + } + + public function testSetTitle(): void + { + $title = 'My spreadsheet title test'; + + $this->properties->setTitle($title); + self::assertSame($title, $this->properties->getTitle()); + } + + public function testSetDescription(): void + { + $description = 'A test for spreadsheet description'; + + $this->properties->setDescription($description); + self::assertSame($description, $this->properties->getDescription()); + } + + public function testSetSubject(): void + { + $subject = 'Test spreadsheet'; + + $this->properties->setSubject($subject); + self::assertSame($subject, $this->properties->getSubject()); + } + + public function testSetKeywords(): void + { + $keywords = 'Test PHPSpreadsheet Spreadsheet Excel LibreOffice Gnumeric OpenSpreadsheetML OASIS'; + + $this->properties->setKeywords($keywords); + self::assertSame($keywords, $this->properties->getKeywords()); + } + + public function testSetCategory(): void + { + $category = 'Testing'; + + $this->properties->setCategory($category); + self::assertSame($category, $this->properties->getCategory()); + } + + public function testSetCompany(): void + { + $company = 'PHPOffice Suite'; + + $this->properties->setCompany($company); + self::assertSame($company, $this->properties->getCompany()); + } + + public function testSetManager(): void + { + $manager = 'Mark Baker'; + + $this->properties->setManager($manager); + self::assertSame($manager, $this->properties->getManager()); + } + + /** + * @dataProvider providerCustomProperties + * + * @param mixed $expectedType + * @param mixed $expectedValue + * @param mixed $propertyName + */ + public function testSetCustomProperties($expectedType, $expectedValue, $propertyName, ...$args): void + { + $this->properties->setCustomProperty($propertyName, ...$args); + self::assertTrue($this->properties->isCustomPropertySet($propertyName)); + self::assertSame($expectedType, $this->properties->getCustomPropertyType($propertyName)); + $result = $this->properties->getCustomPropertyValue($propertyName); + if ($expectedType === Properties::PROPERTY_TYPE_DATE) { + $result = Date::formattedDateTimeFromTimestamp("$result", 'Y-m-d', new DateTimeZone('UTC')); + } + self::assertSame($expectedValue, $result); + } + + public function providerCustomProperties(): array + { + return [ + [Properties::PROPERTY_TYPE_STRING, null, 'Editor', null], + [Properties::PROPERTY_TYPE_STRING, 'Mark Baker', 'Editor', 'Mark Baker'], + [Properties::PROPERTY_TYPE_FLOAT, 1.17, 'Version', 1.17], + [Properties::PROPERTY_TYPE_INTEGER, 2, 'Revision', 2], + [Properties::PROPERTY_TYPE_BOOLEAN, true, 'Tested', true], + [Properties::PROPERTY_TYPE_DATE, '2021-03-17', 'Test Date', '2021-03-17', Properties::PROPERTY_TYPE_DATE], + ]; + } + + public function testGetUnknownCustomProperties(): void + { + $propertyName = 'I DONT EXIST'; + + self::assertFalse($this->properties->isCustomPropertySet($propertyName)); + self::assertNull($this->properties->getCustomPropertyValue($propertyName)); + self::assertNull($this->properties->getCustomPropertyType($propertyName)); + } +} diff --git a/tests/PhpSpreadsheetTests/Document/SecurityTest.php b/tests/PhpSpreadsheetTests/Document/SecurityTest.php new file mode 100644 index 00000000..c2c66577 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Document/SecurityTest.php @@ -0,0 +1,75 @@ +getActiveSheet()->getCell('A1')->setValue('Hello'); + $security = $spreadsheet->getSecurity(); + $security->setLockRevision(true); + $revisionsPassword = 'revpasswd'; + $security->setRevisionsPassword($revisionsPassword); + $hashedRevisionsPassword = $security->getRevisionsPassword(); + self::assertNotEquals($revisionsPassword, $hashedRevisionsPassword); + $security->setLockWindows(true); + $security->setLockStructure(true); + $workbookPassword = 'wbpasswd'; + $security->setWorkbookPassword($workbookPassword); + $hashedWorkbookPassword = $security->getWorkbookPassword(); + self::assertNotEquals($workbookPassword, $hashedWorkbookPassword); + + $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xlsx'); + $reloadedSecurity = $reloadedSpreadsheet->getSecurity(); + self::assertTrue($reloadedSecurity->getLockRevision()); + self::assertTrue($reloadedSecurity->getLockWindows()); + self::assertTrue($reloadedSecurity->getLockStructure()); + self::assertSame($hashedWorkbookPassword, $reloadedSecurity->getWorkbookPassword()); + self::assertSame($hashedRevisionsPassword, $reloadedSecurity->getRevisionsPassword()); + + $reloadedSecurity->setRevisionsPassword($hashedWorkbookPassword, true); + self::assertSame($hashedWorkbookPassword, $reloadedSecurity->getRevisionsPassword()); + $reloadedSecurity->setWorkbookPassword($hashedRevisionsPassword, true); + self::assertSame($hashedRevisionsPassword, $reloadedSecurity->getWorkbookPassword()); + } + + public function providerLocks(): array + { + return [ + [false, false, false], + [false, false, true], + [false, true, false], + [false, true, true], + [true, false, false], + [true, false, true], + [true, true, false], + [true, true, true], + ]; + } + + /** + * @dataProvider providerLocks + */ + public function testLocks(bool $revision, bool $windows, bool $structure): void + { + $spreadsheet = new Spreadsheet(); + $spreadsheet->getActiveSheet()->getCell('A1')->setValue('Hello'); + $security = $spreadsheet->getSecurity(); + $security->setLockRevision($revision); + $security->setLockWindows($windows); + $security->setLockStructure($structure); + $enabled = $security->isSecurityEnabled(); + self::assertSame($enabled, $revision || $windows || $structure); + + $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xlsx'); + $reloadedSecurity = $reloadedSpreadsheet->getSecurity(); + self::assertSame($revision, $reloadedSecurity->getLockRevision()); + self::assertSame($windows, $reloadedSecurity->getLockWindows()); + self::assertSame($structure, $reloadedSecurity->getLockStructure()); + } +} diff --git a/tests/PhpSpreadsheetTests/DocumentGeneratorTest.php b/tests/PhpSpreadsheetTests/DocumentGeneratorTest.php index 45000f8e..bb553577 100644 --- a/tests/PhpSpreadsheetTests/DocumentGeneratorTest.php +++ b/tests/PhpSpreadsheetTests/DocumentGeneratorTest.php @@ -5,7 +5,7 @@ namespace PhpOffice\PhpSpreadsheetTests; use PhpOffice\PhpSpreadsheet\Calculation\Category as Cat; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Logical; -use PhpOffice\PhpSpreadsheet\DocumentGenerator; +use PhpOffice\PhpSpreadsheetInfra\DocumentGenerator; use PHPUnit\Framework\TestCase; use UnexpectedValueException; @@ -41,16 +41,16 @@ class DocumentGeneratorTest extends TestCase ## A -Excel Function | Category | PhpSpreadsheet Function ---------------------|--------------------------------|------------------------------------------- -ABS | CATEGORY_MATH_AND_TRIG | abs -AND | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical::logicalAnd +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +ABS | CATEGORY_MATH_AND_TRIG | abs +AND | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical::logicalAnd ## I -Excel Function | Category | PhpSpreadsheet Function ---------------------|--------------------------------|------------------------------------------- -IFS | CATEGORY_LOGICAL | **Not yet Implemented** +Excel Function | Category | PhpSpreadsheet Function +-------------------------|--------------------------------|-------------------------------------- +IFS | CATEGORY_LOGICAL | **Not yet Implemented** EXPECTED @@ -72,66 +72,66 @@ EXPECTED ## CATEGORY_CUBE -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- ## CATEGORY_DATABASE -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- ## CATEGORY_DATE_AND_TIME -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- ## CATEGORY_ENGINEERING -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- ## CATEGORY_FINANCIAL -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- ## CATEGORY_INFORMATION -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- ## CATEGORY_LOGICAL -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- -AND | \PhpOffice\PhpSpreadsheet\Calculation\Logical::logicalAnd -IFS | **Not yet Implemented** +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- +AND | \PhpOffice\PhpSpreadsheet\Calculation\Logical::logicalAnd +IFS | **Not yet Implemented** ## CATEGORY_LOOKUP_AND_REFERENCE -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- ## CATEGORY_MATH_AND_TRIG -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- -ABS | abs +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- +ABS | abs ## CATEGORY_STATISTICAL -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- ## CATEGORY_TEXT_AND_DATA -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- ## CATEGORY_WEB -Excel Function | PhpSpreadsheet Function ---------------------|------------------------------------------- +Excel Function | PhpSpreadsheet Function +-------------------------|-------------------------------------- EXPECTED diff --git a/tests/PhpSpreadsheetTests/Features/AutoFilter/Xlsx/BasicLoadTest.php b/tests/PhpSpreadsheetTests/Features/AutoFilter/Xlsx/BasicLoadTest.php new file mode 100644 index 00000000..c36e6741 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Features/AutoFilter/Xlsx/BasicLoadTest.php @@ -0,0 +1,74 @@ +load($filename); + + $worksheet = $spreadsheet->getActiveSheet(); + self::assertSame('A1:D57', $worksheet->getAutoFilter()->getRange()); + self::assertSame(2, $worksheet->getAutoFilter()->getColumn('C')->ruleCount()); + self::assertSame( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + $worksheet->getAutoFilter()->getColumn('C')->getRules()[0]->getOperator() + ); + self::assertSame('UK', $worksheet->getAutoFilter()->getColumn('C')->getRules()[0]->getValue()); + self::assertSame( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + $worksheet->getAutoFilter()->getColumn('C')->getRules()[1]->getOperator() + ); + self::assertSame('United States', $worksheet->getAutoFilter()->getColumn('C')->getRules()[1]->getValue()); + self::assertSame(2, $worksheet->getAutoFilter()->getColumn('D')->ruleCount()); + self::assertSame( + Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN, + $worksheet->getAutoFilter()->getColumn('D')->getRules()[0]->getOperator() + ); + self::assertSame('650', $worksheet->getAutoFilter()->getColumn('D')->getRules()[0]->getValue()); + self::assertSame( + Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN, + $worksheet->getAutoFilter()->getColumn('D')->getRules()[1]->getOperator() + ); + self::assertSame('800', $worksheet->getAutoFilter()->getColumn('D')->getRules()[1]->getValue()); + } + + public function testLoadOffice365AutoFilter(): void + { + $filename = 'tests/data/Features/AutoFilter/Xlsx/AutoFilter_Basic_Office365.xlsx'; + $reader = new Xlsx(); + $spreadsheet = $reader->load($filename); + + $worksheet = $spreadsheet->getActiveSheet(); + self::assertSame('A1:D57', $worksheet->getAutoFilter()->getRange()); + self::assertSame(2, $worksheet->getAutoFilter()->getColumn('C')->ruleCount()); + self::assertSame( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + $worksheet->getAutoFilter()->getColumn('C')->getRules()[0]->getOperator() + ); + self::assertSame('UK', $worksheet->getAutoFilter()->getColumn('C')->getRules()[0]->getValue()); + self::assertSame( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + $worksheet->getAutoFilter()->getColumn('C')->getRules()[1]->getOperator() + ); + self::assertSame('United States', $worksheet->getAutoFilter()->getColumn('C')->getRules()[1]->getValue()); + self::assertSame(2, $worksheet->getAutoFilter()->getColumn('D')->ruleCount()); + self::assertSame( + Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN, + $worksheet->getAutoFilter()->getColumn('D')->getRules()[0]->getOperator() + ); + self::assertSame('650', $worksheet->getAutoFilter()->getColumn('D')->getRules()[0]->getValue()); + self::assertSame( + Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN, + $worksheet->getAutoFilter()->getColumn('D')->getRules()[1]->getOperator() + ); + self::assertSame('800', $worksheet->getAutoFilter()->getColumn('D')->getRules()[1]->getValue()); + } +} diff --git a/tests/PhpSpreadsheetTests/Functional/AbstractFunctional.php b/tests/PhpSpreadsheetTests/Functional/AbstractFunctional.php index f242c698..da821532 100644 --- a/tests/PhpSpreadsheetTests/Functional/AbstractFunctional.php +++ b/tests/PhpSpreadsheetTests/Functional/AbstractFunctional.php @@ -21,7 +21,7 @@ abstract class AbstractFunctional extends TestCase */ protected function writeAndReload(Spreadsheet $spreadsheet, $format, ?callable $readerCustomizer = null) { - $filename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); + $filename = File::temporaryFilename(); $writer = IOFactory::createWriter($spreadsheet, $format); $writer->save($filename); diff --git a/tests/PhpSpreadsheetTests/Functional/ActiveSheetTest.php b/tests/PhpSpreadsheetTests/Functional/ActiveSheetTest.php index 56682b34..024185c6 100644 --- a/tests/PhpSpreadsheetTests/Functional/ActiveSheetTest.php +++ b/tests/PhpSpreadsheetTests/Functional/ActiveSheetTest.php @@ -3,10 +3,11 @@ namespace PhpOffice\PhpSpreadsheetTests\Functional; use PhpOffice\PhpSpreadsheet\Spreadsheet; +use PhpOffice\PhpSpreadsheet\Style\Protection; class ActiveSheetTest extends AbstractFunctional { - public function providerFormats() + public function providerFormats(): array { return [ ['Xls'], @@ -46,6 +47,12 @@ class ActiveSheetTest extends AbstractFunctional $spreadsheet->createSheet(2); + $spreadsheet->setActiveSheetIndex(2) + ->setCellValue('F1', 2) + ->getCell('F1') + ->getStyle() + ->getProtection() + ->setHidden(Protection::PROTECTION_PROTECTED); $spreadsheet->setActiveSheetIndex(2) ->setTitle('Test3') ->setCellValue('A1', 4) diff --git a/tests/PhpSpreadsheetTests/Functional/ColumnWidthTest.php b/tests/PhpSpreadsheetTests/Functional/ColumnWidthTest.php index 5cd0aec7..41122885 100644 --- a/tests/PhpSpreadsheetTests/Functional/ColumnWidthTest.php +++ b/tests/PhpSpreadsheetTests/Functional/ColumnWidthTest.php @@ -3,10 +3,11 @@ namespace PhpOffice\PhpSpreadsheetTests\Functional; use PhpOffice\PhpSpreadsheet\Spreadsheet; +use PhpOffice\PhpSpreadsheet\Worksheet\ColumnDimension; class ColumnWidthTest extends AbstractFunctional { - public function providerFormats() + public function providerFormats(): array { return [ ['Xlsx'], @@ -15,8 +16,6 @@ class ColumnWidthTest extends AbstractFunctional /** * @dataProvider providerFormats - * - * @param $format */ public function testReadColumnWidth($format): void { @@ -38,6 +37,7 @@ class ColumnWidthTest extends AbstractFunctional self::assertArrayHasKey('A', $columnDimensions); $column = array_shift($columnDimensions); + self::assertInstanceOf(ColumnDimension::class, $column); self::assertEquals(20, $column->getWidth()); } } diff --git a/tests/PhpSpreadsheetTests/Functional/CommentsTest.php b/tests/PhpSpreadsheetTests/Functional/CommentsTest.php index 5ba4e7c8..03be3e00 100644 --- a/tests/PhpSpreadsheetTests/Functional/CommentsTest.php +++ b/tests/PhpSpreadsheetTests/Functional/CommentsTest.php @@ -7,7 +7,7 @@ use PhpOffice\PhpSpreadsheet\Style\Alignment; class CommentsTest extends AbstractFunctional { - public function providerFormats() + public function providerFormats(): array { return [ ['Html'], @@ -21,8 +21,6 @@ class CommentsTest extends AbstractFunctional * count of comments in correct coords. * * @dataProvider providerFormats - * - * @param $format */ public function testComments($format): void { @@ -42,8 +40,9 @@ class CommentsTest extends AbstractFunctional $commentCoordinate = key($commentsLoaded); self::assertSame('E10', $commentCoordinate); + self::assertSame('Comment', $sheet->getCell('E10')->getValue()); $comment = $commentsLoaded[$commentCoordinate]; - self::assertEquals('Comment to test', (string) $comment); + self::assertSame('Comment to test', (string) $comment); $commentClone = clone $comment; self::assertEquals($comment, $commentClone); self::assertNotSame($comment, $commentClone); @@ -53,5 +52,7 @@ class CommentsTest extends AbstractFunctional $comment->setAlignment(Alignment::HORIZONTAL_RIGHT); self::assertEquals(Alignment::HORIZONTAL_RIGHT, $comment->getAlignment()); } + $spreadsheet->disconnectWorksheets(); + $reloadedSpreadsheet->disconnectWorksheets(); } } diff --git a/tests/PhpSpreadsheetTests/Functional/ConditionalStopIfTrueTest.php b/tests/PhpSpreadsheetTests/Functional/ConditionalStopIfTrueTest.php index 3183450f..5ee0b1f5 100644 --- a/tests/PhpSpreadsheetTests/Functional/ConditionalStopIfTrueTest.php +++ b/tests/PhpSpreadsheetTests/Functional/ConditionalStopIfTrueTest.php @@ -9,7 +9,7 @@ class ConditionalStopIfTrueTest extends AbstractFunctional const COLOR_GREEN = 'FF99FF66'; const COLOR_RED = 'FFFF5050'; - public function providerFormats() + public function providerFormats(): array { return [ ['Xlsx'], diff --git a/tests/PhpSpreadsheetTests/Functional/EnclosureTest.php b/tests/PhpSpreadsheetTests/Functional/EnclosureTest.php index 1f1cb7eb..2ddecfd2 100644 --- a/tests/PhpSpreadsheetTests/Functional/EnclosureTest.php +++ b/tests/PhpSpreadsheetTests/Functional/EnclosureTest.php @@ -6,7 +6,7 @@ use PhpOffice\PhpSpreadsheet\Spreadsheet; class EnclosureTest extends AbstractFunctional { - public function providerFormats() + public function providerFormats(): array { return [ ['Html'], diff --git a/tests/PhpSpreadsheetTests/Functional/FreezePaneTest.php b/tests/PhpSpreadsheetTests/Functional/FreezePaneTest.php index 4e725d03..67083949 100644 --- a/tests/PhpSpreadsheetTests/Functional/FreezePaneTest.php +++ b/tests/PhpSpreadsheetTests/Functional/FreezePaneTest.php @@ -6,7 +6,7 @@ use PhpOffice\PhpSpreadsheet\Spreadsheet; class FreezePaneTest extends AbstractFunctional { - public function providerFormats() + public function providerFormats(): array { return [ ['Xls'], diff --git a/tests/PhpSpreadsheetTests/Functional/MergedCellsTest.php b/tests/PhpSpreadsheetTests/Functional/MergedCellsTest.php index 39865817..d2e9234f 100644 --- a/tests/PhpSpreadsheetTests/Functional/MergedCellsTest.php +++ b/tests/PhpSpreadsheetTests/Functional/MergedCellsTest.php @@ -6,7 +6,7 @@ use PhpOffice\PhpSpreadsheet\Spreadsheet; class MergedCellsTest extends AbstractFunctional { - public function providerFormats() + public function providerFormats(): array { return [ ['Html'], diff --git a/tests/PhpSpreadsheetTests/Functional/PrintAreaTest.php b/tests/PhpSpreadsheetTests/Functional/PrintAreaTest.php index 584f6dd5..93753762 100644 --- a/tests/PhpSpreadsheetTests/Functional/PrintAreaTest.php +++ b/tests/PhpSpreadsheetTests/Functional/PrintAreaTest.php @@ -7,7 +7,7 @@ use PhpOffice\PhpSpreadsheet\Spreadsheet; class PrintAreaTest extends AbstractFunctional { - public function providerFormats() + public function providerFormats(): array { return [ ['Xls'], diff --git a/tests/PhpSpreadsheetTests/Functional/ReadBlankCellsTest.php b/tests/PhpSpreadsheetTests/Functional/ReadBlankCellsTest.php index 9dac3437..585871dc 100644 --- a/tests/PhpSpreadsheetTests/Functional/ReadBlankCellsTest.php +++ b/tests/PhpSpreadsheetTests/Functional/ReadBlankCellsTest.php @@ -6,7 +6,7 @@ use PhpOffice\PhpSpreadsheet\Spreadsheet; class ReadBlankCellsTest extends AbstractFunctional { - public function providerSheetFormat() + public function providerSheetFormat(): array { return [ ['Xlsx'], diff --git a/tests/PhpSpreadsheetTests/Functional/ReadFilterTest.php b/tests/PhpSpreadsheetTests/Functional/ReadFilterTest.php index 9ab86baa..930288a7 100644 --- a/tests/PhpSpreadsheetTests/Functional/ReadFilterTest.php +++ b/tests/PhpSpreadsheetTests/Functional/ReadFilterTest.php @@ -7,7 +7,7 @@ use PhpOffice\PhpSpreadsheet\Spreadsheet; class ReadFilterTest extends AbstractFunctional { - public function providerCellsValues() + public function providerCellsValues(): array { $cellValues = [ // one argument as a multidimensional array diff --git a/tests/PhpSpreadsheetTests/Functional/SelectedCellsTest.php b/tests/PhpSpreadsheetTests/Functional/SelectedCellsTest.php index 625f2428..a1866b09 100644 --- a/tests/PhpSpreadsheetTests/Functional/SelectedCellsTest.php +++ b/tests/PhpSpreadsheetTests/Functional/SelectedCellsTest.php @@ -6,7 +6,7 @@ use PhpOffice\PhpSpreadsheet\Spreadsheet; class SelectedCellsTest extends AbstractFunctional { - public function providerFormats() + public function providerFormats(): array { return [ ['Xls'], diff --git a/tests/PhpSpreadsheetTests/Functional/TypeAttributePreservationTest.php b/tests/PhpSpreadsheetTests/Functional/TypeAttributePreservationTest.php index e6d6377b..bebf0589 100644 --- a/tests/PhpSpreadsheetTests/Functional/TypeAttributePreservationTest.php +++ b/tests/PhpSpreadsheetTests/Functional/TypeAttributePreservationTest.php @@ -6,7 +6,7 @@ use PhpOffice\PhpSpreadsheet\Spreadsheet; class TypeAttributePreservationTest extends AbstractFunctional { - public function providerFormulae() + public function providerFormulae(): array { $formats = ['Xlsx']; $data = require 'tests/data/Functional/TypeAttributePreservation/Formula.php'; diff --git a/tests/PhpSpreadsheetTests/Functional/WorkbookViewAttributesTest.php b/tests/PhpSpreadsheetTests/Functional/WorkbookViewAttributesTest.php index f97ad9cf..8d44c4d2 100644 --- a/tests/PhpSpreadsheetTests/Functional/WorkbookViewAttributesTest.php +++ b/tests/PhpSpreadsheetTests/Functional/WorkbookViewAttributesTest.php @@ -6,7 +6,7 @@ use PhpOffice\PhpSpreadsheet\Spreadsheet; class WorkbookViewAttributesTest extends AbstractFunctional { - public function providerFormats() + public function providerFormats(): array { return [ ['Xlsx'], diff --git a/tests/PhpSpreadsheetTests/HashTableTest.php b/tests/PhpSpreadsheetTests/HashTableTest.php new file mode 100644 index 00000000..09c2fc92 --- /dev/null +++ b/tests/PhpSpreadsheetTests/HashTableTest.php @@ -0,0 +1,92 @@ +setAuthor('Author1'); + $comment2 = new Comment(); + $comment2->setAuthor('Author2'); + + return [$comment1, $comment2]; + } + + /** + * @param mixed $comment + */ + public static function getAuthor($comment): string + { + return ($comment instanceof Comment) ? $comment->getAuthor() : ''; + } + + public function testAddRemoveClear(): void + { + $array1 = self::createArray(); + $hash1 = new HashTable($array1); + self::assertSame(2, $hash1->count()); + $comment3 = new Comment(); + $comment3->setAuthor('Author3'); + $hash1->add($comment3); + $comment4 = new Comment(); + $comment4->setAuthor('Author4'); + $hash1->add($comment4); + $comment5 = new Comment(); + $comment5->setAuthor('Author5'); + // don't add comment5 + self::assertSame(4, $hash1->count()); + self::assertNull($hash1->getByIndex(10)); + $comment = $hash1->getByIndex(2); + self::assertSame('Author3', self::getAuthor($comment)); + $hash1->remove($comment3); + self::assertSame(3, $hash1->count()); + $comment = $hash1->getByIndex(2); + self::assertSame('Author4', self::getAuthor($comment)); + $hash1->remove($comment5); + self::assertSame(3, $hash1->count(), 'Remove non-hash member'); + $comment = $hash1->getByIndex(2); + self::assertSame('Author4', self::getAuthor($comment)); + self::assertNull($hash1->getByHashCode('xyz')); + $hash1->clear(); + self::AssertSame(0, $hash1->count()); + } + + public function testToArray(): void + { + $array1 = self::createArray(); + $count1 = count($array1); + $hash1 = new HashTable($array1); + $array2 = $hash1->toArray(); + self::assertCount($count1, $array2); + $idx = 0; + foreach ($array2 as $key => $value) { + self::assertEquals($array1[$idx], $value, "Item $idx"); + self::assertSame($idx, $hash1->getIndexForHashCode($key)); + ++$idx; + } + } + + public function testClone(): void + { + $array1 = self::createArray(); + $hash1 = new HashTable($array1); + $hash2 = new HashTable(); + self::assertSame(0, $hash2->count()); + $hash2->addFromSource(); + self::assertSame(0, $hash2->count()); + $hash2->addFromSource($array1); + self::assertSame(2, $hash2->count()); + self::assertEquals($hash1, $hash2, 'Add in constructor same as addFromSource'); + $hash3 = clone $hash1; + self::assertEquals($hash1, $hash3, 'Clone equal to original'); + self::assertSame($hash1->getByIndex(0), $hash2->getByIndex(0)); + self::assertEquals($hash1->getByIndex(0), $hash3->getByIndex(0)); + self::assertNotSame($hash1->getByIndex(0), $hash3->getByIndex(0)); + } +} diff --git a/tests/PhpSpreadsheetTests/Helper/DimensionTest.php b/tests/PhpSpreadsheetTests/Helper/DimensionTest.php new file mode 100644 index 00000000..87bce380 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Helper/DimensionTest.php @@ -0,0 +1,72 @@ +width(); + self::assertSame($expectedResult, $result); + } + + /** + * @dataProvider providerConvertUoM + */ + public function testConvertDimension(float $expectedResult, string $dimension, string $unitOfMeasure): void + { + $result = (new Dimension($dimension))->toUnit($unitOfMeasure); + self::assertSame($expectedResult, $result); + } + + public function testConvertDimensionInvalidUoM(): void + { + $this->expectException(Exception::class); + $this->expectExceptionMessage('pikachu is not a vaid unit of measure'); + (new Dimension('999'))->toUnit('pikachu'); + } + + public function providerCellWidth(): array + { + return [ + [12.0, '12'], + [2.2852, '12pt'], + [4.5703, '24 pt'], + [5.1416, '36px'], + [5.7129, '2.5pc'], + [13.7109, '2.54cm'], + [13.7109, '25.4mm'], + [13.7109, '1in'], + [4.27, '50%'], + [3.7471, '3.2em'], + [2.3419, '2ch'], + [4.6838, '4ex'], + [14.0515, '12rem'], + ]; + } + + public function providerConvertUoM(): array + { + return [ + [60, '8.54', Dimension::UOM_PIXELS], + [100, '100px', Dimension::UOM_PIXELS], + [150, '200px', Dimension::UOM_POINTS], + [45, '8.54', Dimension::UOM_POINTS], + [12.5, '200px', Dimension::UOM_PICA], + [3.75, '8.54', Dimension::UOM_PICA], + [3.125, '300px', Dimension::UOM_INCHES], + [0.625, '8.54', Dimension::UOM_INCHES], + [7.9375, '300px', Dimension::UOM_CENTIMETERS], + [1.5875, '8.54', Dimension::UOM_CENTIMETERS], + [79.375, '300px', Dimension::UOM_MILLIMETERS], + [15.875, '8.54', Dimension::UOM_MILLIMETERS], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Helper/HtmlTest.php b/tests/PhpSpreadsheetTests/Helper/HtmlTest.php index d47c2f64..b2fadf42 100644 --- a/tests/PhpSpreadsheetTests/Helper/HtmlTest.php +++ b/tests/PhpSpreadsheetTests/Helper/HtmlTest.php @@ -21,7 +21,7 @@ class HtmlTest extends TestCase self::assertSame($expected, $actual->getPlainText()); } - public function providerUtf8EncodingSupport() + public function providerUtf8EncodingSupport(): array { return [ ['foo', 'foo'], diff --git a/tests/PhpSpreadsheetTests/Helper/SampleCoverageTest.php b/tests/PhpSpreadsheetTests/Helper/SampleCoverageTest.php new file mode 100644 index 00000000..f3f616fe --- /dev/null +++ b/tests/PhpSpreadsheetTests/Helper/SampleCoverageTest.php @@ -0,0 +1,39 @@ +getSamples(); + self::assertArrayHasKey('Basic', $samples); + $basic = $samples['Basic']; + self::assertArrayHasKey('02 Types', $basic); + self::assertSame('Basic/02_Types.php', $basic['02 Types']); + self::assertSame('phpunit', $helper->getPageTitle()); + self::assertSame('

phpunit

', $helper->getPageHeading()); + } + + public function testDirectoryFail(): void + { + $this->expectException(RuntimeException::class); + + $helper = $this->getMockBuilder(Sample::class) + ->onlyMethods(['isDirOrMkdir']) + ->getMock(); + $helper->expects(self::once()) + ->method('isDirOrMkdir') + ->with(self::isType('string')) + ->willReturn(false); + self::assertSame('', $helper->getFilename('a.xlsx')); + } +} diff --git a/tests/PhpSpreadsheetTests/Helper/SampleTest.php b/tests/PhpSpreadsheetTests/Helper/SampleTest.php index 8fd6bb47..a86d8405 100644 --- a/tests/PhpSpreadsheetTests/Helper/SampleTest.php +++ b/tests/PhpSpreadsheetTests/Helper/SampleTest.php @@ -25,11 +25,12 @@ class SampleTest extends TestCase self::assertTrue(true); } - public function providerSample() + public function providerSample(): array { $skipped = [ 'Chart/32_Chart_read_write_PDF.php', // Unfortunately JpGraph is not up to date for latest PHP and raise many warnings 'Chart/32_Chart_read_write_HTML.php', // idem + 'Chart/35_Chart_render.php', // idem ]; // TCPDF and DomPDF libraries don't support PHP8 yet if (\PHP_VERSION_ID >= 80000) { @@ -57,9 +58,12 @@ class SampleTest extends TestCase $result = []; foreach ($helper->getSamples() as $samples) { foreach ($samples as $sample) { +// if (array_pop(explode('/', $sample)) !== 'DGET.php') { +// continue; +// } if (!in_array($sample, $skipped)) { $file = 'samples/' . $sample; - $result[] = [$file]; + $result[$sample] = [$file]; } } } diff --git a/tests/PhpSpreadsheetTests/IOFactoryTest.php b/tests/PhpSpreadsheetTests/IOFactoryTest.php index 886fcb36..b8c6ff83 100644 --- a/tests/PhpSpreadsheetTests/IOFactoryTest.php +++ b/tests/PhpSpreadsheetTests/IOFactoryTest.php @@ -2,9 +2,9 @@ namespace PhpOffice\PhpSpreadsheetTests; -use InvalidArgumentException; use PhpOffice\PhpSpreadsheet\IOFactory; use PhpOffice\PhpSpreadsheet\Reader; +use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer; use PHPUnit\Framework\TestCase; @@ -24,7 +24,7 @@ class IOFactoryTest extends TestCase self::assertInstanceOf($expected, $actual); } - public function providerCreateWriter() + public function providerCreateWriter(): array { return [ ['Xls', Writer\Xls::class], @@ -58,7 +58,7 @@ class IOFactoryTest extends TestCase self::assertInstanceOf($expected, $actual); } - public function providerCreateReader() + public function providerCreateReader(): array { return [ ['Xls', Reader\Xls::class], @@ -118,7 +118,7 @@ class IOFactoryTest extends TestCase self::assertInstanceOf(Spreadsheet::class, $actual); } - public function providerIdentify() + public function providerIdentify(): array { return [ ['samples/templates/26template.xlsx', 'Xlsx', Reader\Xlsx::class], @@ -136,14 +136,14 @@ class IOFactoryTest extends TestCase public function testIdentifyNonExistingFileThrowException(): void { - $this->expectException(InvalidArgumentException::class); + $this->expectException(ReaderException::class); IOFactory::identify('/non/existing/file'); } public function testIdentifyExistingDirectoryThrowExceptions(): void { - $this->expectException(InvalidArgumentException::class); + $this->expectException(ReaderException::class); IOFactory::identify('.'); } diff --git a/tests/PhpSpreadsheetTests/LocaleGeneratorTest.php b/tests/PhpSpreadsheetTests/LocaleGeneratorTest.php new file mode 100644 index 00000000..e7429a25 --- /dev/null +++ b/tests/PhpSpreadsheetTests/LocaleGeneratorTest.php @@ -0,0 +1,41 @@ +getProperty('phpSpreadsheetFunctions'); + $phpSpreadsheetFunctionsProperty->setAccessible(true); + $phpSpreadsheetFunctions = $phpSpreadsheetFunctionsProperty->getValue(); + + $localeGenerator = new LocaleGenerator( + (string) realpath(__DIR__ . '/../../src/PhpSpreadsheet/Calculation/locale/'), + 'Translations.xlsx', + $phpSpreadsheetFunctions + ); + $localeGenerator->generateLocales(); + + $testLocales = [ + 'fr', + 'nl', + 'pt', + 'pt_br', + 'ru', + ]; + + foreach ($testLocales as $locale) { + $locale = str_replace('_', '/', $locale); + $path = realpath(__DIR__ . "/../../src/PhpSpreadsheet/Calculation/locale/{$locale}"); + self::assertFileExists("{$path}/config"); + self::assertFileExists("{$path}/functions"); + } + } +} diff --git a/tests/PhpSpreadsheetTests/NamedRange2Test.php b/tests/PhpSpreadsheetTests/NamedRange2Test.php new file mode 100644 index 00000000..2082f479 --- /dev/null +++ b/tests/PhpSpreadsheetTests/NamedRange2Test.php @@ -0,0 +1,120 @@ +spreadsheet = new Spreadsheet(); + + $worksheet1 = $spreadsheet->getActiveSheet(); + $worksheet1->setTitle('SheetOne'); + $spreadsheet->addNamedRange( + new NamedRange('FirstRel', $worksheet1, '=A1') + ); + $spreadsheet->addNamedRange( + new NamedRange('FirstAbs', $worksheet1, '=$B$1') + ); + $spreadsheet->addNamedRange( + new NamedRange('FirstRelMult', $worksheet1, '=C1:D2') + ); + $spreadsheet->addNamedRange( + new NamedRange('FirstAbsMult', $worksheet1, '$E$3:$F$4') + ); + + $worksheet2 = $spreadsheet->createSheet(); + $worksheet2->setTitle('SheetTwo'); + $spreadsheet->addNamedRange( + new NamedRange('SecondRel', $worksheet2, '=A1') + ); + $spreadsheet->addNamedRange( + new NamedRange('SecondAbs', $worksheet2, '=$B$1') + ); + $spreadsheet->addNamedRange( + new NamedRange('SecondRelMult', $worksheet2, '=C1:D2') + ); + $spreadsheet->addNamedRange( + new NamedRange('SecondAbsMult', $worksheet2, '$E$3:$F$4') + ); + + $spreadsheet->addDefinedName(DefinedName::createInstance('FirstFormula', $worksheet1, '=TODAY()-1')); + $spreadsheet->addDefinedName(DefinedName::createInstance('SecondFormula', $worksheet2, '=TODAY()-2')); + + $this->spreadsheet->setActiveSheetIndex(0); + } + + protected function tearDown(): void + { + if ($this->spreadsheet !== null) { + $this->spreadsheet->disconnectWorksheets(); + $this->spreadsheet = null; + } + } + + private function getSpreadsheet(): Spreadsheet + { + if ($this->spreadsheet !== null) { + return $this->spreadsheet; + } + $this->spreadsheet = new Spreadsheet(); + + return $this->spreadsheet; + } + + public function testNamedRangeSetStyle(): void + { + $spreadsheet = $this->getSpreadsheet(); + $sheet = $spreadsheet->getSheet(0); + $sheet->getStyle('FirstRel')->getNumberFormat()->setFormatCode('yyyy-mm-dd'); + self::assertSame('yyyy-mm-dd', $sheet->getStyle('A1')->getNumberFormat()->getFormatCode()); + $sheet->getStyle('FirstAbs')->getFont()->setName('Georgia'); + self::assertSame('Georgia', $sheet->getStyle('B1')->getFont()->getName()); + $sheet->getStyle('FirstRelMult')->getFont()->setItalic(true); + self::assertTrue($sheet->getStyle('D2')->getFont()->getItalic()); + $sheet->getStyle('FirstAbsMult')->getFill()->setFillType('gray125'); + self::assertSame('gray125', $sheet->getStyle('F4')->getFill()->getFillType()); + self::assertSame('none', $sheet->getStyle('A1')->getFill()->getFillType()); + $sheet = $spreadsheet->getSheet(1); + $sheet->getStyle('SecondAbsMult')->getFill()->setFillType('lightDown'); + self::assertSame('lightDown', $sheet->getStyle('E3')->getFill()->getFillType()); + } + + /** + * @dataProvider providerRangeOrFormula + */ + public function testNamedRangeSetStyleBad(string $name): void + { + $this->expectException(Except::class); + $spreadsheet = $this->getSpreadsheet(); + $sheet = $spreadsheet->getSheet(0); + $sheet->getStyle($name)->getNumberFormat()->setFormatCode('yyyy-mm-dd'); + self::assertSame('yyyy-mm-dd', $sheet->getStyle('A1')->getNumberFormat()->getFormatCode()); + } + + public function providerRangeOrFormula(): array + { + return [ + 'wrong sheet rel' => ['SecondRel'], + 'wrong sheet abs' => ['SecondAbs'], + 'wrong sheet relmult' => ['SecondRelMult'], + 'wrong sheet absmult' => ['SecondAbsMult'], + 'wrong sheet formula' => ['SecondFormula'], + 'right sheet formula' => ['FirstFormula'], + 'non-existent name' => ['NonExistentName'], + 'this sheet name' => ['SheetOne!G7'], + 'other sheet name' => ['SheetTwo!G7'], + 'non-existent sheet name' => ['SheetAbc!G7'], + 'unnamed formula' => ['=2+3'], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Csv/CsvCallbackTest.php b/tests/PhpSpreadsheetTests/Reader/Csv/CsvCallbackTest.php new file mode 100644 index 00000000..c27d3b71 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Csv/CsvCallbackTest.php @@ -0,0 +1,93 @@ +setInputEncoding(Csv::GUESS_ENCODING); + $spreadsheet = $reader->load($filename); + $sheet = $spreadsheet->getActiveSheet(); + self::assertEquals('Å', $sheet->getCell('A1')->getValue()); + } + + public function callbackSetFallbackEncoding(Csv $reader): void + { + $reader->setFallbackEncoding('ISO-8859-2'); + $reader->setInputEncoding(Csv::GUESS_ENCODING); + $reader->setEscapeCharacter((version_compare(PHP_VERSION, '7.4') < 0) ? "\x0" : ''); + } + + public function testFallbackEncodingDefltIso2(): void + { + Csv::setConstructorCallback([$this, 'callbackSetFallbackEncoding']); + $filename = 'tests/data/Reader/CSV/premiere.win1252.csv'; + $reader = new Csv(); + $spreadsheet = $reader->load($filename); + $sheet = $spreadsheet->getActiveSheet(); + self::assertEquals('premičre', $sheet->getCell('A1')->getValue()); + self::assertEquals('sixičme', $sheet->getCell('C2')->getValue()); + } + + public function testIOFactory(): void + { + Csv::setConstructorCallback([$this, 'callbackSetFallbackEncoding']); + $filename = 'tests/data/Reader/CSV/premiere.win1252.csv'; + $spreadsheet = IOFactory::load($filename); + $sheet = $spreadsheet->getActiveSheet(); + self::assertEquals('premičre', $sheet->getCell('A1')->getValue()); + self::assertEquals('sixičme', $sheet->getCell('C2')->getValue()); + } + + public function testNonFallbackEncoding(): void + { + Csv::setConstructorCallback([$this, 'callbackSetFallbackEncoding']); + $filename = 'tests/data/Reader/CSV/premiere.utf16be.csv'; + $reader = new Csv(); + $spreadsheet = $reader->load($filename); + $sheet = $spreadsheet->getActiveSheet(); + self::assertEquals('première', $sheet->getCell('A1')->getValue()); + self::assertEquals('sixième', $sheet->getCell('C2')->getValue()); + } + + public function testDefaultEscape(): void + { + self::assertNull(Csv::getConstructorCallback()); + $filename = 'tests/data/Reader/CSV/escape.csv'; + $spreadsheet = IOFactory::load($filename); + $sheet = $spreadsheet->getActiveSheet(); + // this is not how Excel views the file + self::assertEquals('a\"hello', $sheet->getCell('A1')->getValue()); + } + + public function testBetterEscape(): void + { + Csv::setConstructorCallback([$this, 'callbackSetFallbackEncoding']); + $filename = 'tests/data/Reader/CSV/escape.csv'; + $spreadsheet = IOFactory::load($filename); + $sheet = $spreadsheet->getActiveSheet(); + // this is how Excel views the file + self::assertEquals('a\"hello;hello;hello;\"', $sheet->getCell('A1')->getValue()); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/CsvContiguousFilter.php b/tests/PhpSpreadsheetTests/Reader/Csv/CsvContiguousFilter.php similarity index 80% rename from tests/PhpSpreadsheetTests/Reader/CsvContiguousFilter.php rename to tests/PhpSpreadsheetTests/Reader/Csv/CsvContiguousFilter.php index b6b24751..eac37afc 100644 --- a/tests/PhpSpreadsheetTests/Reader/CsvContiguousFilter.php +++ b/tests/PhpSpreadsheetTests/Reader/Csv/CsvContiguousFilter.php @@ -1,16 +1,25 @@ endRow = $startRow + $chunkSize; } - public function setFilterType($type): void + public function setFilterType(int $type): void { $this->filterType = $type; } - public function filter1($row) + public function filter1(int $row): bool { // Include rows 1-10, followed by 100-110, etc. return $row % 100 <= 10; } - public function filter0($row) + public function filter0(int $row): bool { // Only read the heading row, and the rows that are configured in $this->_startRow and $this->_endRow if (($row == 1) || ($row >= $this->startRow && $row < $this->endRow)) { diff --git a/tests/PhpSpreadsheetTests/Reader/CsvContiguousTest.php b/tests/PhpSpreadsheetTests/Reader/Csv/CsvContiguousTest.php similarity index 76% rename from tests/PhpSpreadsheetTests/Reader/CsvContiguousTest.php rename to tests/PhpSpreadsheetTests/Reader/Csv/CsvContiguousTest.php index 3a417791..ff095dba 100644 --- a/tests/PhpSpreadsheetTests/Reader/CsvContiguousTest.php +++ b/tests/PhpSpreadsheetTests/Reader/Csv/CsvContiguousTest.php @@ -1,6 +1,6 @@ getContiguous()); - $reader->setReadFilter($chunkFilter) - ->setContiguous(true); + $reader->setReadFilter($chunkFilter); + $reader->setContiguous(true); // Instantiate a new PhpSpreadsheet object manually $spreadsheet = new Spreadsheet(); @@ -46,12 +49,19 @@ class CsvContiguousTest extends TestCase $spreadsheet->getActiveSheet()->setTitle('Country Data #' . (++$sheet)); } - $sheet = $spreadsheet->getSheetByName('Country Data #1'); - self::assertEquals('Kabul', $sheet->getCell('A2')->getValue()); - $sheet = $spreadsheet->getSheetByName('Country Data #2'); - self::assertEquals('Lesotho', $sheet->getCell('B4')->getValue()); - $sheet = $spreadsheet->getSheetByName('Country Data #3'); - self::assertEquals(-20.1, $sheet->getCell('C6')->getValue()); + self::assertSame('Kabul', self::getCellValue($spreadsheet, 'Country Data #1', 'A2')); + self::assertSame('Lesotho', self::getCellValue($spreadsheet, 'Country Data #2', 'B4')); + self::assertSame('-20.1', self::getCellValue($spreadsheet, 'Country Data #3', 'C6')); + } + + private static function getCellValue(Spreadsheet $spreadsheet, string $sheetName, string $cellAddress): string + { + $sheet = $spreadsheet->getSheetByName($sheetName); + if ($sheet === null) { + return ''; + } + + return (string) $sheet->getCell($cellAddress)->getValue(); } public function testContiguous2(): void @@ -65,8 +75,8 @@ class CsvContiguousTest extends TestCase // Tell the Reader that we want to use the Read Filter that we've Instantiated // and that we want to store it in contiguous rows/columns - $reader->setReadFilter($chunkFilter) - ->setContiguous(true); + $reader->setReadFilter($chunkFilter); + $reader->setContiguous(true); // Instantiate a new PhpSpreadsheet object manually $spreadsheet = new Spreadsheet(); diff --git a/tests/PhpSpreadsheetTests/Reader/Csv/CsvEncodingTest.php b/tests/PhpSpreadsheetTests/Reader/Csv/CsvEncodingTest.php new file mode 100644 index 00000000..448d3d1e --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Csv/CsvEncodingTest.php @@ -0,0 +1,122 @@ +setInputEncoding($encoding); + $spreadsheet = $reader->load($filename); + $sheet = $spreadsheet->getActiveSheet(); + self::assertEquals('Å', $sheet->getCell('A1')->getValue()); + } + + /** + * @dataProvider providerEncodings + * + * @param string $filename + * @param string $encoding + */ + public function testWorkSheetInfo($filename, $encoding): void + { + $reader = new Csv(); + $reader->setInputEncoding($encoding); + $info = $reader->listWorksheetInfo($filename); + self::assertEquals('Worksheet', $info[0]['worksheetName']); + self::assertEquals('B', $info[0]['lastColumnLetter']); + self::assertEquals(1, $info[0]['lastColumnIndex']); + self::assertEquals(2, $info[0]['totalRows']); + self::assertEquals(2, $info[0]['totalColumns']); + } + + public function providerEncodings(): array + { + return [ + ['tests/data/Reader/CSV/encoding.iso88591.csv', 'ISO-8859-1'], + ['tests/data/Reader/CSV/encoding.utf8.csv', 'UTF-8'], + ['tests/data/Reader/CSV/encoding.utf8bom.csv', 'UTF-8'], + ['tests/data/Reader/CSV/encoding.utf16be.csv', 'UTF-16BE'], + ['tests/data/Reader/CSV/encoding.utf16le.csv', 'UTF-16LE'], + ['tests/data/Reader/CSV/encoding.utf32be.csv', 'UTF-32BE'], + ['tests/data/Reader/CSV/encoding.utf32le.csv', 'UTF-32LE'], + ]; + } + + /** + * @dataProvider providerGuessEncoding + */ + public function testGuessEncoding(string $filename): void + { + $reader = new Csv(); + $reader->setInputEncoding(Csv::guessEncoding($filename)); + $spreadsheet = $reader->load($filename); + $sheet = $spreadsheet->getActiveSheet(); + self::assertEquals('première', $sheet->getCell('A1')->getValue()); + self::assertEquals('sixième', $sheet->getCell('C2')->getValue()); + } + + /** + * @dataProvider providerGuessEncoding + */ + public function testFallbackEncoding(string $filename): void + { + $reader = new Csv(); + $reader->setInputEncoding(Csv::GUESS_ENCODING); + $spreadsheet = $reader->load($filename); + $sheet = $spreadsheet->getActiveSheet(); + self::assertEquals('première', $sheet->getCell('A1')->getValue()); + self::assertEquals('sixième', $sheet->getCell('C2')->getValue()); + } + + public function providerGuessEncoding(): array + { + return [ + ['tests/data/Reader/CSV/premiere.utf8.csv'], + ['tests/data/Reader/CSV/premiere.utf8bom.csv'], + ['tests/data/Reader/CSV/premiere.utf16be.csv'], + ['tests/data/Reader/CSV/premiere.utf16bebom.csv'], + ['tests/data/Reader/CSV/premiere.utf16le.csv'], + ['tests/data/Reader/CSV/premiere.utf16lebom.csv'], + ['tests/data/Reader/CSV/premiere.utf32be.csv'], + ['tests/data/Reader/CSV/premiere.utf32bebom.csv'], + ['tests/data/Reader/CSV/premiere.utf32le.csv'], + ['tests/data/Reader/CSV/premiere.utf32lebom.csv'], + ['tests/data/Reader/CSV/premiere.win1252.csv'], + ]; + } + + public function testGuessEncodingDefltIso2(): void + { + $filename = 'tests/data/Reader/CSV/premiere.win1252.csv'; + $reader = new Csv(); + $reader->setInputEncoding(Csv::guessEncoding($filename, 'ISO-8859-2')); + $spreadsheet = $reader->load($filename); + $sheet = $spreadsheet->getActiveSheet(); + self::assertEquals('premičre', $sheet->getCell('A1')->getValue()); + self::assertEquals('sixičme', $sheet->getCell('C2')->getValue()); + } + + public function testFallbackEncodingDefltIso2(): void + { + $filename = 'tests/data/Reader/CSV/premiere.win1252.csv'; + $reader = new Csv(); + self::assertSame('CP1252', $reader->getFallbackEncoding()); + $reader->setInputEncoding(Csv::GUESS_ENCODING); + $reader->setFallbackEncoding('ISO-8859-2'); + $spreadsheet = $reader->load($filename); + $sheet = $spreadsheet->getActiveSheet(); + self::assertEquals('premičre', $sheet->getCell('A1')->getValue()); + self::assertEquals('sixičme', $sheet->getCell('C2')->getValue()); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Csv/CsvLineEndingTest.php b/tests/PhpSpreadsheetTests/Reader/Csv/CsvLineEndingTest.php new file mode 100644 index 00000000..38f2aaa1 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Csv/CsvLineEndingTest.php @@ -0,0 +1,47 @@ +tempFile !== '') { + unlink($this->tempFile); + $this->tempFile = ''; + } + } + + /** + * @dataProvider providerEndings + */ + public function testEndings(string $ending): void + { + $this->tempFile = $filename = File::temporaryFilename(); + $data = ['123', '456', '789']; + file_put_contents($filename, implode($ending, $data)); + $reader = new Csv(); + $spreadsheet = $reader->load($filename); + $sheet = $spreadsheet->getActiveSheet(); + self::assertEquals($data[0], $sheet->getCell('A1')->getValue()); + self::assertEquals($data[1], $sheet->getCell('A2')->getValue()); + self::assertEquals($data[2], $sheet->getCell('A3')->getValue()); + $spreadsheet->disconnectWorksheets(); + } + + public function providerEndings(): array + { + return [ + 'Unix endings' => ["\n"], + 'Mac endings' => ["\r"], + 'Windows endings' => ["\r\n"], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/CsvTest.php b/tests/PhpSpreadsheetTests/Reader/Csv/CsvTest.php similarity index 69% rename from tests/PhpSpreadsheetTests/Reader/CsvTest.php rename to tests/PhpSpreadsheetTests/Reader/Csv/CsvTest.php index e543ff48..24887f1b 100644 --- a/tests/PhpSpreadsheetTests/Reader/CsvTest.php +++ b/tests/PhpSpreadsheetTests/Reader/Csv/CsvTest.php @@ -1,6 +1,6 @@ getDelimiter()); + $delim1 = $reader->getDelimiter(); + self::assertNull($delim1); $spreadsheet = $reader->load($filename); @@ -29,7 +30,7 @@ class CsvTest extends TestCase self::assertSame($expectedValue, $actual, 'should be able to retrieve correct value'); } - public function providerDelimiterDetection() + public function providerDelimiterDetection(): array { return [ [ @@ -101,7 +102,7 @@ class CsvTest extends TestCase self::assertSame($expected, $reader->canRead($filename)); } - public function providerCanLoad() + public function providerCanLoad(): array { return [ [false, 'tests/data/Reader/Ods/data.ods'], @@ -132,21 +133,6 @@ class CsvTest extends TestCase self::assertSame($expected, $worksheet->toArray()); } - /** - * @dataProvider providerEncodings - * - * @param string $filename - * @param string $encoding - */ - public function testEncodings($filename, $encoding): void - { - $reader = new Csv(); - $reader->setInputEncoding($encoding); - $spreadsheet = $reader->load($filename); - $sheet = $spreadsheet->getActiveSheet(); - self::assertEquals('Å', $sheet->getCell('A1')->getValue()); - } - public function testInvalidWorkSheetInfo(): void { $this->expectException(ReaderException::class); @@ -154,37 +140,6 @@ class CsvTest extends TestCase $reader->listWorksheetInfo(''); } - /** - * @dataProvider providerEncodings - * - * @param string $filename - * @param string $encoding - */ - public function testWorkSheetInfo($filename, $encoding): void - { - $reader = new Csv(); - $reader->setInputEncoding($encoding); - $info = $reader->listWorksheetInfo($filename); - self::assertEquals('Worksheet', $info[0]['worksheetName']); - self::assertEquals('B', $info[0]['lastColumnLetter']); - self::assertEquals(1, $info[0]['lastColumnIndex']); - self::assertEquals(2, $info[0]['totalRows']); - self::assertEquals(2, $info[0]['totalColumns']); - } - - public function providerEncodings() - { - return [ - ['tests/data/Reader/CSV/encoding.iso88591.csv', 'ISO-8859-1'], - ['tests/data/Reader/CSV/encoding.utf8.csv', 'UTF-8'], - ['tests/data/Reader/CSV/encoding.utf8bom.csv', 'UTF-8'], - ['tests/data/Reader/CSV/encoding.utf16be.csv', 'UTF-16BE'], - ['tests/data/Reader/CSV/encoding.utf16le.csv', 'UTF-16LE'], - ['tests/data/Reader/CSV/encoding.utf32be.csv', 'UTF-32BE'], - ['tests/data/Reader/CSV/encoding.utf32le.csv', 'UTF-32LE'], - ]; - } - public function testUtf16LineBreak(): void { $reader = new Csv(); @@ -288,7 +243,7 @@ EOF; self::assertEquals($delimiter, $reader->getDelimiter()); } - public function providerEscapes() + public function providerEscapes(): array { return [ ['\\', ';'], @@ -298,43 +253,23 @@ EOF; } /** - * @dataProvider providerGuessEncoding + * This test could be simpler, but Scrutinizer has a minor (and silly) problem. + * + * @dataProvider providerNull */ - public function testGuessEncoding(string $filename): void + public function testSetDelimiterNull(?string $setNull): void { $reader = new Csv(); - $reader->setInputEncoding(Csv::guessEncoding($filename)); - $spreadsheet = $reader->load($filename); - $sheet = $spreadsheet->getActiveSheet(); - self::assertEquals('première', $sheet->getCell('A1')->getValue()); - self::assertEquals('sixième', $sheet->getCell('C2')->getValue()); + $reader->setDelimiter(','); + self::assertSame(',', $reader->getDelimiter()); + $reader->setDelimiter($setNull); + self::assertSame($setNull, $reader->getDelimiter()); } - public function providerGuessEncoding() + public function providerNull(): array { return [ - ['tests/data/Reader/CSV/premiere.utf8.csv'], - ['tests/data/Reader/CSV/premiere.utf8bom.csv'], - ['tests/data/Reader/CSV/premiere.utf16be.csv'], - ['tests/data/Reader/CSV/premiere.utf16bebom.csv'], - ['tests/data/Reader/CSV/premiere.utf16le.csv'], - ['tests/data/Reader/CSV/premiere.utf16lebom.csv'], - ['tests/data/Reader/CSV/premiere.utf32be.csv'], - ['tests/data/Reader/CSV/premiere.utf32bebom.csv'], - ['tests/data/Reader/CSV/premiere.utf32le.csv'], - ['tests/data/Reader/CSV/premiere.utf32lebom.csv'], - ['tests/data/Reader/CSV/premiere.win1252.csv'], + [null], ]; } - - public function testGuessEncodingDefltIso2(): void - { - $filename = 'tests/data/Reader/CSV/premiere.win1252.csv'; - $reader = new Csv(); - $reader->setInputEncoding(Csv::guessEncoding($filename, 'ISO-8859-2')); - $spreadsheet = $reader->load($filename); - $sheet = $spreadsheet->getActiveSheet(); - self::assertEquals('premičre', $sheet->getCell('A1')->getValue()); - self::assertEquals('sixičme', $sheet->getCell('C2')->getValue()); - } } diff --git a/tests/PhpSpreadsheetTests/Reader/Gnumeric/AutoFilterTest.php b/tests/PhpSpreadsheetTests/Reader/Gnumeric/AutoFilterTest.php new file mode 100644 index 00000000..18dde473 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Gnumeric/AutoFilterTest.php @@ -0,0 +1,31 @@ +spreadsheet = $reader->load($filename); + } + + public function testAutoFilterRange(): void + { + $worksheet = $this->spreadsheet->getActiveSheet(); + + $autoFilterRange = $worksheet->getAutoFilter()->getRange(); + + self::assertSame('A1:D57', $autoFilterRange); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Gnumeric/GnumericLoadTest.php b/tests/PhpSpreadsheetTests/Reader/Gnumeric/GnumericLoadTest.php index e24178e5..58dbe501 100644 --- a/tests/PhpSpreadsheetTests/Reader/Gnumeric/GnumericLoadTest.php +++ b/tests/PhpSpreadsheetTests/Reader/Gnumeric/GnumericLoadTest.php @@ -2,7 +2,9 @@ namespace PhpOffice\PhpSpreadsheetTests\Reader\Gnumeric; +use DateTimeZone; use PhpOffice\PhpSpreadsheet\Reader\Gnumeric; +use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Borders; use PhpOffice\PhpSpreadsheet\Style\Color; @@ -26,6 +28,12 @@ class GnumericLoadTest extends TestCase self::assertEquals('BCD', $sheet->getCell('A4')->getValue()); $props = $spreadsheet->getProperties(); self::assertEquals('Mark Baker', $props->getCreator()); + $creationDate = $props->getCreated(); + $result = Date::formattedDateTimeFromTimestamp("$creationDate", 'Y-m-d\\TH:i:s\\Z', new DateTimeZone('UTC')); + self::assertEquals('2010-09-02T20:48:39Z', $result); + $creationDate = $props->getModified(); + $result = Date::formattedDateTimeFromTimestamp("$creationDate", 'Y-m-d\\TH:i:s\\Z', new DateTimeZone('UTC')); + self::assertEquals('2020-06-05T05:15:21Z', $result); $sheet = $spreadsheet->getSheet(0); self::assertEquals('Sample Data', $sheet->getTitle()); @@ -115,7 +123,8 @@ class GnumericLoadTest extends TestCase self::assertEquals(Font::UNDERLINE_DOUBLE, $sheet->getCell('A24')->getStyle()->getFont()->getUnderline()); self::assertTrue($sheet->getCell('B23')->getStyle()->getFont()->getSubScript()); self::assertTrue($sheet->getCell('B24')->getStyle()->getFont()->getSuperScript()); - self::assertFalse($sheet->getRowDimension(30)->getVisible()); + $rowDimension = $sheet->getRowDimension(30); + self::assertFalse($rowDimension->getVisible()); } public function testLoadFilter(): void diff --git a/tests/PhpSpreadsheetTests/Reader/Html/HtmlHelper.php b/tests/PhpSpreadsheetTests/Reader/Html/HtmlHelper.php index c09902ff..a6be40c9 100644 --- a/tests/PhpSpreadsheetTests/Reader/Html/HtmlHelper.php +++ b/tests/PhpSpreadsheetTests/Reader/Html/HtmlHelper.php @@ -3,13 +3,14 @@ namespace PhpOffice\PhpSpreadsheetTests\Reader\Html; use PhpOffice\PhpSpreadsheet\Reader\Html; +use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Spreadsheet; class HtmlHelper { public static function createHtml(string $html): string { - $filename = tempnam(sys_get_temp_dir(), 'html'); + $filename = File::temporaryFilename(); file_put_contents($filename, $html); return $filename; diff --git a/tests/PhpSpreadsheetTests/Reader/Html/HtmlLoadStringTest.php b/tests/PhpSpreadsheetTests/Reader/Html/HtmlLoadStringTest.php index e1041507..bc4c30ff 100644 --- a/tests/PhpSpreadsheetTests/Reader/Html/HtmlLoadStringTest.php +++ b/tests/PhpSpreadsheetTests/Reader/Html/HtmlLoadStringTest.php @@ -89,4 +89,33 @@ class HtmlLoadStringTest extends TestCase $spreadsheet = $reader->loadFromString($html, $spreadsheet); self::assertEquals(2, $spreadsheet->getSheetCount()); } + + public function testCanLoadDuplicateTitle(): void + { + $html = <<<'EOF' + + +Sheet + + +
1
+ + +EOF; + $reader = new \PhpOffice\PhpSpreadsheet\Reader\Html(); + $spreadsheet = $reader->loadFromString($html); + $reader->setSheetIndex(1); + $reader->loadFromString($html, $spreadsheet); + $reader->setSheetIndex(2); + $reader->loadFromString($html, $spreadsheet); + $sheet = $spreadsheet->getSheet(0); + self::assertEquals(1, $sheet->getCell('A1')->getValue()); + self::assertEquals('Sheet', $sheet->getTitle()); + $sheet = $spreadsheet->getSheet(1); + self::assertEquals(1, $sheet->getCell('A1')->getValue()); + self::assertEquals('Sheet 1', $sheet->getTitle()); + $sheet = $spreadsheet->getSheet(2); + self::assertEquals(1, $sheet->getCell('A1')->getValue()); + self::assertEquals('Sheet 2', $sheet->getTitle()); + } } diff --git a/tests/PhpSpreadsheetTests/Reader/Html/HtmlTest.php b/tests/PhpSpreadsheetTests/Reader/Html/HtmlTest.php index 14bdb39a..38a9bc9e 100644 --- a/tests/PhpSpreadsheetTests/Reader/Html/HtmlTest.php +++ b/tests/PhpSpreadsheetTests/Reader/Html/HtmlTest.php @@ -20,22 +20,22 @@ class HtmlTest extends TestCase public function testBadHtml(): void { - $this->expectException(ReaderException::class); $filename = 'tests/data/Reader/HTML/badhtml.html'; $reader = new Html(); self::assertTrue($reader->canRead($filename)); + + $this->expectException(ReaderException::class); $reader->load($filename); - self::assertTrue(false); } public function testNonHtml(): void { - $this->expectException(ReaderException::class); $filename = __FILE__; $reader = new Html(); self::assertFalse($reader->canRead($filename)); + + $this->expectException(ReaderException::class); $reader->load($filename); - self::assertTrue(false); } public function testInvalidFilename(): void @@ -45,7 +45,7 @@ class HtmlTest extends TestCase self::assertFalse($reader->canRead('')); } - public function providerCanReadVerySmallFile() + public function providerCanReadVerySmallFile(): array { $padding = str_repeat('a', 2048); @@ -136,6 +136,7 @@ class HtmlTest extends TestCase 50px 100px + 50px '; $filename = HtmlHelper::createHtml($html); @@ -143,10 +144,16 @@ class HtmlTest extends TestCase $firstSheet = $spreadsheet->getSheet(0); $dimension = $firstSheet->getColumnDimension('A'); + self::assertNotNull($dimension); self::assertEquals(50, $dimension->getWidth()); $dimension = $firstSheet->getColumnDimension('B'); - self::assertEquals(100, $dimension->getWidth()); + self::assertNotNull($dimension); + self::assertEquals(100, $dimension->getWidth('px')); + + $dimension = $firstSheet->getColumnDimension('C'); + self::assertNotNull($dimension); + self::assertEquals(50, $dimension->getWidth('px')); } public function testCanApplyInlineHeight(): void @@ -158,16 +165,25 @@ class HtmlTest extends TestCase 2 + + 1 + '; $filename = HtmlHelper::createHtml($html); $spreadsheet = HtmlHelper::loadHtmlIntoSpreadsheet($filename, true); $firstSheet = $spreadsheet->getSheet(0); $dimension = $firstSheet->getRowDimension(1); + self::assertNotNull($dimension); self::assertEquals(50, $dimension->getRowHeight()); $dimension = $firstSheet->getRowDimension(2); - self::assertEquals(100, $dimension->getRowHeight()); + self::assertNotNull($dimension); + self::assertEquals(100, $dimension->getRowHeight('px')); + + $dimension = $firstSheet->getRowDimension(3); + self::assertNotNull($dimension); + self::assertEquals(50, $dimension->getRowHeight('px')); } public function testCanApplyAlignment(): void diff --git a/tests/PhpSpreadsheetTests/Reader/Html/Issue2029Test.php b/tests/PhpSpreadsheetTests/Reader/Html/Issue2029Test.php new file mode 100644 index 00000000..08cdbc25 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Html/Issue2029Test.php @@ -0,0 +1,115 @@ + + + + + Declaracion en Linea + + + + + + +
+ + + + +
+ + + + + + + + + + + + + + + + + + + + +
CUIT:
Período
Secuencia:
Contribuyente:
+
+
+ + + + + + + + + + + + + + + + + + + + + +
+ CUIL + + Apellido y Nombre + + Obra Social + + Corresponde Reducción? +
+ 12345678901 + + EMILIANO ZAPATA SALAZAR + + 101208 + + Yes +
+ 23456789012 + + FRANCISCO PANCHO VILLA + + 101208 + + No +
+ + + +EOF; + $reader = new Html(); + $spreadsheet = $reader->loadFromString($content); + $sheet = $spreadsheet->getActiveSheet(); + self::assertSame('CUIT:', $sheet->getCell('A1')->getValue()); + self::assertSame('30-53914190-9', $sheet->getCell('B1')->getValue()); + self::assertSame('Contribuyente:', $sheet->getCell('A4')->getValue()); + self::assertSame('Apellido y Nombre', $sheet->getCell('B9')->getValue()); + self::assertEquals('101208', $sheet->getCell('C10')->getValue()); + self::assertEquals('Yes', $sheet->getCell('D10')->getValue()); + self::assertEquals('23456789012', $sheet->getCell('A11')->getValue()); + self::assertEquals('No', $sheet->getCell('D11')->getValue()); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Ods/AutoFilterTest.php b/tests/PhpSpreadsheetTests/Reader/Ods/AutoFilterTest.php new file mode 100644 index 00000000..47c7ee6a --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Ods/AutoFilterTest.php @@ -0,0 +1,31 @@ +spreadsheet = $reader->load($filename); + } + + public function testAutoFilterRange(): void + { + $worksheet = $this->spreadsheet->getActiveSheet(); + + $autoFilterRange = $worksheet->getAutoFilter()->getRange(); + + self::assertSame('A1:C9', $autoFilterRange); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Ods/DefinedNamesTest.php b/tests/PhpSpreadsheetTests/Reader/Ods/DefinedNamesTest.php new file mode 100644 index 00000000..760421ce --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Ods/DefinedNamesTest.php @@ -0,0 +1,35 @@ +spreadsheet = $reader->load($filename); + } + + public function testDefinedNames(): void + { + $worksheet = $this->spreadsheet->getActiveSheet(); + + $firstDefinedNameValue = $worksheet->getCell('First')->getValue(); + $secondDefinedNameValue = $worksheet->getCell('Second')->getValue(); + $calculatedFormulaValue = $worksheet->getCell('B2')->getCalculatedValue(); + + self::assertSame(3, $firstDefinedNameValue); + self::assertSame(4, $secondDefinedNameValue); + self::assertSame(12, $calculatedFormulaValue); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Ods/EmptyFileTest.php b/tests/PhpSpreadsheetTests/Reader/Ods/EmptyFileTest.php new file mode 100644 index 00000000..5876eaab --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Ods/EmptyFileTest.php @@ -0,0 +1,52 @@ +tempfile !== '') { + unlink($this->tempfile); + $this->tempfile = ''; + } + } + + public function testEmptyFileLoad(): void + { + $this->expectException(ReaderException::class); + $this->expectExceptionMessage('Could not find zip member'); + $this->tempfile = $temp = File::temporaryFileName(); + file_put_contents($temp, ''); + $reader = new Ods(); + $reader->load($temp); + } + + public function testEmptyFileNames(): void + { + $this->expectException(ReaderException::class); + $this->expectExceptionMessage('Could not find zip member'); + $this->tempfile = $temp = File::temporaryFileName(); + file_put_contents($temp, ''); + $reader = new Ods(); + $reader->listWorksheetNames($temp); + } + + public function testEmptyInfo(): void + { + $this->expectException(ReaderException::class); + $this->expectExceptionMessage('Could not find zip member'); + $this->tempfile = $temp = File::temporaryFileName(); + file_put_contents($temp, ''); + $reader = new Ods(); + $reader->listWorksheetInfo($temp); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Ods/InvalidFileTest.php b/tests/PhpSpreadsheetTests/Reader/Ods/InvalidFileTest.php new file mode 100644 index 00000000..d56af4de --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Ods/InvalidFileTest.php @@ -0,0 +1,64 @@ +expectException(ReaderException::class); + $this->expectExceptionMessage('Could not find zip member'); + $temp = __FILE__; + $reader = new Ods(); + $reader->load($temp); + } + + public function testInvalidFileNames(): void + { + $this->expectException(ReaderException::class); + $this->expectExceptionMessage('Could not find zip member'); + $temp = __FILE__; + $reader = new Ods(); + $reader->listWorksheetNames($temp); + } + + public function testInvalidInfo(): void + { + $this->expectException(ReaderException::class); + $this->expectExceptionMessage('Could not find zip member'); + $temp = __FILE__; + $reader = new Ods(); + $reader->listWorksheetInfo($temp); + } + + public function testXlsxFileLoad(): void + { + $this->expectException(ReaderException::class); + $this->expectExceptionMessage('Could not find zip member'); + $temp = 'samples/templates/26template.xlsx'; + $reader = new Ods(); + $reader->load($temp); + } + + public function testXlsxFileNames(): void + { + $this->expectException(ReaderException::class); + $this->expectExceptionMessage('Could not find zip member'); + $temp = 'samples/templates/26template.xlsx'; + $reader = new Ods(); + $reader->listWorksheetNames($temp); + } + + public function testXlsxInfo(): void + { + $this->expectException(ReaderException::class); + $this->expectExceptionMessage('Could not find zip member'); + $temp = 'samples/templates/26template.xlsx'; + $reader = new Ods(); + $reader->listWorksheetInfo($temp); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Ods/OdsPropertiesTest.php b/tests/PhpSpreadsheetTests/Reader/Ods/OdsPropertiesTest.php new file mode 100644 index 00000000..577b4221 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Ods/OdsPropertiesTest.php @@ -0,0 +1,112 @@ +timeZone = date_default_timezone_get(); + date_default_timezone_set('UTC'); + } + + protected function tearDown(): void + { + date_default_timezone_set($this->timeZone); + } + + public function testLoadOdsWorkbookProperties(): void + { + $customPropertySet = [ + 'Owner' => ['type' => Properties::PROPERTY_TYPE_STRING, 'value' => 'PHPOffice'], + 'Tested' => ['type' => Properties::PROPERTY_TYPE_BOOLEAN, 'value' => true], + 'Counter' => ['type' => Properties::PROPERTY_TYPE_FLOAT, 'value' => 10.0], + 'TestDate' => ['type' => Properties::PROPERTY_TYPE_DATE, 'value' => '2019-06-30'], + 'HereAndNow' => ['type' => Properties::PROPERTY_TYPE_DATE, 'value' => '2019-06-30'], + ]; + + $filename = 'tests/data/Reader/Ods/propertyTest.ods'; + $reader = new Ods(); + $spreadsheet = $reader->load($filename); + + $properties = $spreadsheet->getProperties(); + // Core Properties +// self::assertSame('Mark Baker', $properties->getCreator()); + self::assertSame('Property Test File', $properties->getTitle()); + self::assertSame('Testing for Properties', $properties->getSubject()); + self::assertSame('TEST ODS PHPSpreadsheet', $properties->getKeywords()); + + // Extended Properties +// self::assertSame('PHPOffice', $properties->getCompany()); +// self::assertSame('The Big Boss', $properties->getManager()); + + // Custom Properties + $customProperties = $properties->getCustomProperties(); + self::assertIsArray($customProperties); + $customProperties = array_flip($customProperties); + self::assertArrayHasKey('TestDate', $customProperties); + + foreach ($customPropertySet as $propertyName => $testData) { + self::assertTrue($properties->isCustomPropertySet($propertyName)); + self::assertSame($testData['type'], $properties->getCustomPropertyType($propertyName)); + $result = $properties->getCustomPropertyValue($propertyName); + if ($properties->getCustomPropertyType($propertyName) == Properties::PROPERTY_TYPE_DATE) { + $result = Date::formattedDateTimeFromTimestamp("$result", 'Y-m-d'); + } + self::assertSame($testData['value'], $result); + } + } + + public function testReloadOdsWorkbookProperties(): void + { + $customPropertySet = [ + 'Owner' => ['type' => Properties::PROPERTY_TYPE_STRING, 'value' => 'PHPOffice'], + 'Tested' => ['type' => Properties::PROPERTY_TYPE_BOOLEAN, 'value' => true], + 'Counter' => ['type' => Properties::PROPERTY_TYPE_FLOAT, 'value' => 10.0], + 'TestDate' => ['type' => Properties::PROPERTY_TYPE_DATE, 'value' => '2019-06-30'], + 'HereAndNow' => ['type' => Properties::PROPERTY_TYPE_DATE, 'value' => '2019-06-30'], + ]; + + $filename = 'tests/data/Reader/Ods/propertyTest.ods'; + $reader = new Ods(); + $spreadsheetOld = $reader->load($filename); + $spreadsheet = $this->writeAndReload($spreadsheetOld, 'Ods'); + + $properties = $spreadsheet->getProperties(); + // Core Properties +// self::assertSame('Mark Baker', $properties->getCreator()); + self::assertSame('Property Test File', $properties->getTitle()); + self::assertSame('Testing for Properties', $properties->getSubject()); + self::assertSame('TEST ODS PHPSpreadsheet', $properties->getKeywords()); + + // Extended Properties +// self::assertSame('PHPOffice', $properties->getCompany()); +// self::assertSame('The Big Boss', $properties->getManager()); + + // Custom Properties + $customProperties = $properties->getCustomProperties(); + self::assertIsArray($customProperties); + $customProperties = array_flip($customProperties); + self::assertArrayHasKey('TestDate', $customProperties); + + foreach ($customPropertySet as $propertyName => $testData) { + self::assertTrue($properties->isCustomPropertySet($propertyName)); + self::assertSame($testData['type'], $properties->getCustomPropertyType($propertyName)); + $result = $properties->getCustomPropertyValue($propertyName); + if ($properties->getCustomPropertyType($propertyName) == Properties::PROPERTY_TYPE_DATE) { + $result = Date::formattedDateTimeFromTimestamp("$result", 'Y-m-d'); + } + self::assertSame($testData['value'], $result); + } + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Ods/OdsTest.php b/tests/PhpSpreadsheetTests/Reader/Ods/OdsTest.php index 8be1aa7c..a7f1466c 100644 --- a/tests/PhpSpreadsheetTests/Reader/Ods/OdsTest.php +++ b/tests/PhpSpreadsheetTests/Reader/Ods/OdsTest.php @@ -15,6 +15,22 @@ use PHPUnit\Framework\TestCase; */ class OdsTest extends TestCase { + /** + * @var string + */ + private $timeZone; + + protected function setUp(): void + { + $this->timeZone = date_default_timezone_get(); + date_default_timezone_set('UTC'); + } + + protected function tearDown(): void + { + date_default_timezone_set($this->timeZone); + } + /** * @var Spreadsheet */ @@ -30,7 +46,7 @@ class OdsTest extends TestCase */ private function loadOdsTestFile() { - if (!$this->spreadsheetOdsTest) { + if (!isset($this->spreadsheetOdsTest)) { $filename = 'samples/templates/OOCalcTest.ods'; // Load into this instance @@ -46,7 +62,7 @@ class OdsTest extends TestCase */ protected function loadDataFile() { - if (!$this->spreadsheetData) { + if (!isset($this->spreadsheetData)) { $filename = 'tests/data/Reader/Ods/data.ods'; // Load into this instance @@ -88,6 +104,20 @@ class OdsTest extends TestCase self::assertEquals('Sheet1', $spreadsheet->getSheet(0)->getTitle()); } + public function testLoadOneWorksheetNotActive(): void + { + $filename = 'tests/data/Reader/Ods/data.ods'; + + // Load into this instance + $reader = new Ods(); + $reader->setLoadSheetsOnly(['Second Sheet']); + $spreadsheet = $reader->load($filename); + + self::assertEquals(1, $spreadsheet->getSheetCount()); + + self::assertEquals('Second Sheet', $spreadsheet->getSheet(0)->getTitle()); + } + public function testLoadBadFile(): void { $this->expectException(ReaderException::class); @@ -153,13 +183,13 @@ class OdsTest extends TestCase self::assertEquals(0, $firstSheet->getCell('G10')->getValue()); self::assertEquals(DataType::TYPE_NUMERIC, $firstSheet->getCell('A10')->getDataType()); // Date - self::assertEquals(22269.0, $firstSheet->getCell('A10')->getValue()); + self::assertEquals('19-Dec-60', $firstSheet->getCell('A10')->getFormattedValue()); self::assertEquals(DataType::TYPE_NUMERIC, $firstSheet->getCell('A13')->getDataType()); // Time - self::assertEquals(25569.0625, $firstSheet->getCell('A13')->getValue()); + self::assertEquals('2:30:00', $firstSheet->getCell('A13')->getFormattedValue()); self::assertEquals(DataType::TYPE_NUMERIC, $firstSheet->getCell('A15')->getDataType()); // Date + Time - self::assertEquals(22269.0625, $firstSheet->getCell('A15')->getValue()); + self::assertEquals('19-Dec-60 1:30:00', $firstSheet->getCell('A15')->getFormattedValue()); self::assertEquals(DataType::TYPE_NUMERIC, $firstSheet->getCell('A11')->getDataType()); // Fraction @@ -260,46 +290,4 @@ class OdsTest extends TestCase self::assertTrue($style->getFont()->getBold()); self::assertTrue($style->getFont()->getItalic()); } - - public function testLoadOdsWorkbookProperties(): void - { - $customPropertySet = [ - 'Owner' => ['type' => Properties::PROPERTY_TYPE_STRING, 'value' => 'PHPOffice'], - 'Tested' => ['type' => Properties::PROPERTY_TYPE_BOOLEAN, 'value' => true], - 'Counter' => ['type' => Properties::PROPERTY_TYPE_FLOAT, 'value' => 10.0], - 'TestDate' => ['type' => Properties::PROPERTY_TYPE_DATE, 'value' => '2019-06-30'], - 'HereAndNow' => ['type' => Properties::PROPERTY_TYPE_DATE, 'value' => '2019-06-30'], - ]; - - $filename = 'tests/data/Reader/Ods/propertyTest.ods'; - $reader = new Ods(); - $spreadsheet = $reader->load($filename); - - $properties = $spreadsheet->getProperties(); - // Core Properties -// self::assertSame('Mark Baker', $properties->getCreator()); - self::assertSame('Property Test File', $properties->getTitle()); - self::assertSame('Testing for Properties', $properties->getSubject()); - self::assertSame('TEST ODS PHPSpreadsheet', $properties->getKeywords()); - - // Extended Properties -// self::assertSame('PHPOffice', $properties->getCompany()); -// self::assertSame('The Big Boss', $properties->getManager()); - - // Custom Properties - $customProperties = $properties->getCustomProperties(); - self::assertIsArray($customProperties); - $customProperties = array_flip($customProperties); - self::assertArrayHasKey('TestDate', $customProperties); - - foreach ($customPropertySet as $propertyName => $testData) { - self::assertTrue($properties->isCustomPropertySet($propertyName)); - self::assertSame($testData['type'], $properties->getCustomPropertyType($propertyName)); - if ($properties->getCustomPropertyType($propertyName) == Properties::PROPERTY_TYPE_DATE) { - self::assertSame($testData['value'], date('Y-m-d', $properties->getCustomPropertyValue($propertyName))); - } else { - self::assertSame($testData['value'], $properties->getCustomPropertyValue($propertyName)); - } - } - } } diff --git a/tests/PhpSpreadsheetTests/Reader/Ods/PageSetupBug1772Test.php b/tests/PhpSpreadsheetTests/Reader/Ods/PageSetupBug1772Test.php new file mode 100644 index 00000000..883664fc --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Ods/PageSetupBug1772Test.php @@ -0,0 +1,98 @@ +spreadsheet = $reader->load($filename); + } + + public function testPageSetup(): void + { + $assertions = $this->pageSetupAssertions(); + + foreach ($this->spreadsheet->getAllSheets() as $worksheet) { + if (!array_key_exists($worksheet->getTitle(), $assertions)) { + continue; + } + + $sheetAssertions = $assertions[$worksheet->getTitle()]; + foreach ($sheetAssertions as $test => $expectedResult) { + $testMethodName = 'get' . ucfirst($test); + $actualResult = $worksheet->getPageSetup()->$testMethodName(); + self::assertSame( + $expectedResult, + $actualResult, + "Failed assertion for Worksheet '{$worksheet->getTitle()}' {$test}" + ); + } + } + } + + public function testPageMargins(): void + { + $assertions = $this->pageMarginAssertions(); + + foreach ($this->spreadsheet->getAllSheets() as $worksheet) { + if (!array_key_exists($worksheet->getTitle(), $assertions)) { + continue; + } + + $sheetAssertions = $assertions[$worksheet->getTitle()]; + foreach ($sheetAssertions as $test => $expectedResult) { + $testMethodName = 'get' . ucfirst($test); + $actualResult = $worksheet->getPageMargins()->$testMethodName(); + self::assertEqualsWithDelta( + $expectedResult, + $actualResult, + self::MARGIN_PRECISION, + "Failed assertion for Worksheet '{$worksheet->getTitle()}' {$test} margin" + ); + } + } + } + + private function pageSetupAssertions(): array + { + return [ + 'Employee update template' => [ + 'orientation' => PageSetup::ORIENTATION_DEFAULT, + 'scale' => 100, + 'horizontalCentered' => false, + 'verticalCentered' => false, + 'pageOrder' => PageSetup::PAGEORDER_DOWN_THEN_OVER, + ], + ]; + } + + private function pageMarginAssertions(): array + { + return [ + 'Employee update template' => [ + // Here the values are in cm + 'top' => 0.0, + 'header' => 0.2953, + 'left' => 0.0, + 'right' => 0.0, + 'bottom' => 0.0, + 'footer' => 0.2953, + ], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Security/XmlScannerTest.php b/tests/PhpSpreadsheetTests/Reader/Security/XmlScannerTest.php index f98ff7e1..39bc864c 100644 --- a/tests/PhpSpreadsheetTests/Reader/Security/XmlScannerTest.php +++ b/tests/PhpSpreadsheetTests/Reader/Security/XmlScannerTest.php @@ -23,7 +23,6 @@ class XmlScannerTest extends TestCase * * @param mixed $filename * @param mixed $expectedResult - * @param $libxmlDisableEntityLoader */ public function testValidXML($filename, $expectedResult, $libxmlDisableEntityLoader): void { @@ -37,12 +36,12 @@ class XmlScannerTest extends TestCase self::assertEquals($expectedResult, $result); // php 8.+ deprecated libxml_disable_entity_loader() - It's on by default - if (\PHP_VERSION_ID < 80000) { + if (isset($oldDisableEntityLoaderState)) { libxml_disable_entity_loader($oldDisableEntityLoaderState); } } - public function providerValidXML() + public function providerValidXML(): array { $tests = []; foreach (glob('tests/data/Reader/Xml/XEETestValid*.xml') as $file) { @@ -59,7 +58,6 @@ class XmlScannerTest extends TestCase * @dataProvider providerInvalidXML * * @param mixed $filename - * @param $libxmlDisableEntityLoader */ public function testInvalidXML($filename, $libxmlDisableEntityLoader): void { @@ -80,7 +78,7 @@ class XmlScannerTest extends TestCase } } - public function providerInvalidXML() + public function providerInvalidXML(): array { $tests = []; foreach (glob('tests/data/Reader/Xml/XEETestInvalidUTF*.xml') as $file) { @@ -127,7 +125,7 @@ class XmlScannerTest extends TestCase self::assertEquals(strrev($expectedResult), $xml); } - public function providerValidXMLForCallback() + public function providerValidXMLForCallback(): array { $tests = []; foreach (glob('tests/data/Reader/Xml/SecurityScannerWithCallback*.xml') as $file) { diff --git a/tests/PhpSpreadsheetTests/Reader/Slk/SlkCommentsTest.php b/tests/PhpSpreadsheetTests/Reader/Slk/SlkCommentsTest.php new file mode 100644 index 00000000..6f8a7ef5 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Slk/SlkCommentsTest.php @@ -0,0 +1,23 @@ +load($testbook); + $sheet = $spreadsheet->getActiveSheet(); + $comments = $sheet->getComments(); + self::assertCount(2, $comments); + self::assertArrayHasKey('A1', $comments); + self::assertArrayHasKey('B2', $comments); + self::assertSame("Zeratul:\nEn Taro Adun!", $sheet->getComment('A1')->getText()->getPlainText()); + self::assertSame("Arthas:\nFrostmourne Hungers.", $sheet->getComment('B2')->getText()->getPlainText()); + $spreadsheet->disconnectWorksheets(); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/SlkTest.php b/tests/PhpSpreadsheetTests/Reader/Slk/SlkTest.php similarity index 95% rename from tests/PhpSpreadsheetTests/Reader/SlkTest.php rename to tests/PhpSpreadsheetTests/Reader/Slk/SlkTest.php index e461557e..3a7dff6c 100644 --- a/tests/PhpSpreadsheetTests/Reader/SlkTest.php +++ b/tests/PhpSpreadsheetTests/Reader/Slk/SlkTest.php @@ -1,6 +1,6 @@ filename) { + if ($this->filename !== '') { unlink($this->filename); $this->filename = ''; } @@ -128,6 +134,7 @@ class SlkTest extends \PHPUnit\Framework\TestCase self::assertEquals(Border::BORDER_THIN, $sheet->getCell('C18')->getStyle()->getBorders()->getBottom()->getBorderStyle()); self::assertEquals(Border::BORDER_THIN, $sheet->getCell('C18')->getStyle()->getBorders()->getLeft()->getBorderStyle()); // Have not yet figured out how C6/C7 are centred + $spreadsheet->disconnectWorksheets(); } public function testSheetIndex(): void @@ -141,6 +148,7 @@ class SlkTest extends \PHPUnit\Framework\TestCase self::assertEquals('SylkTest', $sheet->getTitle()); self::assertEquals('FFFF0000', $sheet->getCell('A1')->getStyle()->getFont()->getColor()->getARGB()); + $spreadsheet->disconnectWorksheets(); } public function testLongName(): void @@ -154,5 +162,6 @@ class SlkTest extends \PHPUnit\Framework\TestCase $sheet = $spreadsheet->getActiveSheet(); self::assertEquals('123456789a123456789b123456789c1', $sheet->getTitle()); self::assertEquals('FFFF0000', $sheet->getCell('A1')->getStyle()->getFont()->getColor()->getARGB()); + $spreadsheet->disconnectWorksheets(); } } diff --git a/tests/PhpSpreadsheetTests/Reader/Utility/File.php b/tests/PhpSpreadsheetTests/Reader/Utility/File.php new file mode 100644 index 00000000..f2283326 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Utility/File.php @@ -0,0 +1,199 @@ + '3g2', + 'video/3gp' => '3gp', + 'video/3gpp' => '3gp', + 'application/x-compressed' => '7zip', + 'audio/x-acc' => 'aac', + 'audio/ac3' => 'ac3', + 'application/postscript' => 'ai', + 'audio/x-aiff' => 'aif', + 'audio/aiff' => 'aif', + 'audio/x-au' => 'au', + 'video/x-msvideo' => 'avi', + 'video/msvideo' => 'avi', + 'video/avi' => 'avi', + 'application/x-troff-msvideo' => 'avi', + 'application/macbinary' => 'bin', + 'application/mac-binary' => 'bin', + 'application/x-binary' => 'bin', + 'application/x-macbinary' => 'bin', + 'image/bmp' => 'bmp', + 'image/x-bmp' => 'bmp', + 'image/x-bitmap' => 'bmp', + 'image/x-xbitmap' => 'bmp', + 'image/x-win-bitmap' => 'bmp', + 'image/x-windows-bmp' => 'bmp', + 'image/ms-bmp' => 'bmp', + 'image/x-ms-bmp' => 'bmp', + 'application/bmp' => 'bmp', + 'application/x-bmp' => 'bmp', + 'application/x-win-bitmap' => 'bmp', + 'application/cdr' => 'cdr', + 'application/coreldraw' => 'cdr', + 'application/x-cdr' => 'cdr', + 'application/x-coreldraw' => 'cdr', + 'image/cdr' => 'cdr', + 'image/x-cdr' => 'cdr', + 'zz-application/zz-winassoc-cdr' => 'cdr', + 'application/mac-compactpro' => 'cpt', + 'application/pkix-crl' => 'crl', + 'application/pkcs-crl' => 'crl', + 'application/x-x509-ca-cert' => 'crt', + 'application/pkix-cert' => 'crt', + 'text/css' => 'css', + 'text/x-comma-separated-values' => 'csv', + 'text/comma-separated-values' => 'csv', + 'application/vnd.msexcel' => 'csv', + 'application/x-director' => 'dcr', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx', + 'application/x-dvi' => 'dvi', + 'message/rfc822' => 'eml', + 'application/x-msdownload' => 'exe', + 'video/x-f4v' => 'f4v', + 'audio/x-flac' => 'flac', + 'video/x-flv' => 'flv', + 'image/gif' => 'gif', + 'application/gpg-keys' => 'gpg', + 'application/x-gtar' => 'gtar', + 'application/x-gzip' => 'gzip', + 'application/mac-binhex40' => 'hqx', + 'application/mac-binhex' => 'hqx', + 'application/x-binhex40' => 'hqx', + 'application/x-mac-binhex40' => 'hqx', + 'text/html' => 'html', + 'image/x-icon' => 'ico', + 'image/x-ico' => 'ico', + 'image/vnd.microsoft.icon' => 'ico', + 'text/calendar' => 'ics', + 'application/java-archive' => 'jar', + 'application/x-java-application' => 'jar', + 'application/x-jar' => 'jar', + 'image/jp2' => 'jp2', + 'video/mj2' => 'jp2', + 'image/jpx' => 'jp2', + 'image/jpm' => 'jp2', + 'image/jpeg' => 'jpeg', + 'image/pjpeg' => 'jpeg', + 'application/x-javascript' => 'js', + 'application/json' => 'json', + 'text/json' => 'json', + 'application/vnd.google-earth.kml+xml' => 'kml', + 'application/vnd.google-earth.kmz' => 'kmz', + 'text/x-log' => 'log', + 'audio/x-m4a' => 'm4a', + 'audio/mp4' => 'm4a', + 'application/vnd.mpegurl' => 'm4u', + 'audio/midi' => 'mid', + 'application/vnd.mif' => 'mif', + 'video/quicktime' => 'mov', + 'video/x-sgi-movie' => 'movie', + 'audio/mpeg' => 'mp3', + 'audio/mpg' => 'mp3', + 'audio/mpeg3' => 'mp3', + 'audio/mp3' => 'mp3', + 'video/mp4' => 'mp4', + 'video/mpeg' => 'mpeg', + 'application/oda' => 'oda', + 'audio/ogg' => 'ogg', + 'video/ogg' => 'ogg', + 'application/ogg' => 'ogg', + 'font/otf' => 'otf', + 'application/x-pkcs10' => 'p10', + 'application/pkcs10' => 'p10', + 'application/x-pkcs12' => 'p12', + 'application/x-pkcs7-signature' => 'p7a', + 'application/pkcs7-mime' => 'p7c', + 'application/x-pkcs7-mime' => 'p7c', + 'application/x-pkcs7-certreqresp' => 'p7r', + 'application/pkcs7-signature' => 'p7s', + 'application/pdf' => 'pdf', + 'application/octet-stream' => 'pdf', + 'application/x-x509-user-cert' => 'pem', + 'application/x-pem-file' => 'pem', + 'application/pgp' => 'pgp', + 'application/x-httpd-php' => 'php', + 'application/php' => 'php', + 'application/x-php' => 'php', + 'text/php' => 'php', + 'text/x-php' => 'php', + 'application/x-httpd-php-source' => 'php', + 'image/png' => 'png', + 'image/x-png' => 'png', + 'application/powerpoint' => 'ppt', + 'application/vnd.ms-powerpoint' => 'ppt', + 'application/vnd.ms-office' => 'ppt', + 'application/msword' => 'doc', + 'application/vnd.openxmlformats-officedocument.presentationml.presentation' => 'pptx', + 'application/x-photoshop' => 'psd', + 'image/vnd.adobe.photoshop' => 'psd', + 'audio/x-realaudio' => 'ra', + 'audio/x-pn-realaudio' => 'ram', + 'application/x-rar' => 'rar', + 'application/rar' => 'rar', + 'application/x-rar-compressed' => 'rar', + 'audio/x-pn-realaudio-plugin' => 'rpm', + 'application/x-pkcs7' => 'rsa', + 'text/rtf' => 'rtf', + 'text/richtext' => 'rtx', + 'video/vnd.rn-realvideo' => 'rv', + 'application/x-stuffit' => 'sit', + 'application/smil' => 'smil', + 'text/srt' => 'srt', + 'image/svg+xml' => 'svg', + 'application/x-shockwave-flash' => 'swf', + 'application/x-tar' => 'tar', + 'application/x-gzip-compressed' => 'tgz', + 'image/tiff' => 'tiff', + 'font/ttf' => 'ttf', + 'text/plain' => 'txt', + 'text/x-vcard' => 'vcf', + 'application/videolan' => 'vlc', + 'text/vtt' => 'vtt', + 'audio/x-wav' => 'wav', + 'audio/wave' => 'wav', + 'audio/wav' => 'wav', + 'application/wbxml' => 'wbxml', + 'video/webm' => 'webm', + 'image/webp' => 'webp', + 'audio/x-ms-wma' => 'wma', + 'application/wmlc' => 'wmlc', + 'video/x-ms-wmv' => 'wmv', + 'video/x-ms-asf' => 'wmv', + 'font/woff' => 'woff', + 'font/woff2' => 'woff2', + 'application/xhtml+xml' => 'xhtml', + 'application/excel' => 'xl', + 'application/msexcel' => 'xls', + 'application/x-msexcel' => 'xls', + 'application/x-ms-excel' => 'xls', + 'application/x-excel' => 'xls', + 'application/x-dos_ms_excel' => 'xls', + 'application/xls' => 'xls', + 'application/x-xls' => 'xls', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx', + 'application/vnd.ms-excel' => 'xlsx', + 'application/xml' => 'xml', + 'text/xml' => 'xml', + 'text/xsl' => 'xsl', + 'application/xspf+xml' => 'xspf', + 'application/x-compress' => 'z', + 'application/x-zip' => 'zip', + 'application/zip' => 'zip', + 'application/x-zip-compressed' => 'zip', + 'application/s-compressed' => 'zip', + 'multipart/x-zip' => 'zip', + 'text/x-scriptzsh' => 'zsh', + ]; + + return $mime_map[$mime] ?? ''; + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xls/ColourTest.php b/tests/PhpSpreadsheetTests/Reader/Xls/ColourTest.php new file mode 100644 index 00000000..d17e7e16 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xls/ColourTest.php @@ -0,0 +1,42 @@ +spreadsheet = $reader->load($filename); + } + + public function testColours(): void + { + $colours = []; + + $worksheet = $this->spreadsheet->getActiveSheet(); + for ($row = 1; $row <= 7; ++$row) { + for ($column = 'A'; $column !== 'J'; ++$column) { + $cellAddress = "{$column}{$row}"; + $colours[$cellAddress] = $worksheet->getStyle($cellAddress)->getFill()->getStartColor()->getRGB(); + } + } + + $newSpreadsheet = $this->writeAndReload($this->spreadsheet, 'Xls'); + $newWorksheet = $newSpreadsheet->getActiveSheet(); + foreach ($colours as $cellAddress => $expectedColourValue) { + $actualColourValue = $newWorksheet->getStyle($cellAddress)->getFill()->getStartColor()->getRGB(); + self::assertSame($expectedColourValue, $actualColourValue); + } + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xls/NonExistentFileTest.php b/tests/PhpSpreadsheetTests/Reader/Xls/NonExistentFileTest.php new file mode 100644 index 00000000..76db7b62 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xls/NonExistentFileTest.php @@ -0,0 +1,19 @@ +canRead($temp)); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xls/NumberFormatGeneralTest.php b/tests/PhpSpreadsheetTests/Reader/Xls/NumberFormatGeneralTest.php new file mode 100644 index 00000000..a67fbb34 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xls/NumberFormatGeneralTest.php @@ -0,0 +1,34 @@ +load($filename); + $sheet = $spreadsheet->getSheetByName('Blad1'); + if ($sheet === null) { + self::fail('Expected to find sheet Blad1'); + } else { + $array = $sheet->toArray(); + self::assertSame('€ 2.95', $array[1][3]); + self::assertSame(2.95, $sheet->getCell('D2')->getValue()); + self::assertSame(2.95, $sheet->getCell('D2')->getCalculatedValue()); + self::assertSame('€ 2.95', $sheet->getCell('D2')->getFormattedValue()); + self::assertSame(21, $array[1][4]); + self::assertSame(21, $sheet->getCell('E2')->getValue()); + self::assertSame(21, $sheet->getCell('E2')->getCalculatedValue()); + self::assertSame('21', $sheet->getCell('E2')->getFormattedValue()); + } + $spreadsheet->disconnectWorksheets(); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/XlsTest.php b/tests/PhpSpreadsheetTests/Reader/Xls/XlsTest.php similarity index 57% rename from tests/PhpSpreadsheetTests/Reader/XlsTest.php rename to tests/PhpSpreadsheetTests/Reader/Xls/XlsTest.php index 130374b3..2cd14a87 100644 --- a/tests/PhpSpreadsheetTests/Reader/XlsTest.php +++ b/tests/PhpSpreadsheetTests/Reader/Xls/XlsTest.php @@ -1,8 +1,10 @@ load($filename); self::assertEquals('Title', $spreadsheet->getSheet(0)->getCell('A1')->getValue()); + $spreadsheet->disconnectWorksheets(); } /** @@ -42,6 +45,8 @@ class XlsTest extends AbstractFunctional self::assertEquals($row, $newrow); self::assertEquals($sheet->getCell('A1')->getFormattedValue(), $newsheet->getCell('A1')->getFormattedValue()); self::assertEquals($sheet->getCell("$col$row")->getFormattedValue(), $newsheet->getCell("$col$row")->getFormattedValue()); + $spreadsheet->disconnectWorksheets(); + $newspreadsheet->disconnectWorksheets(); } /** @@ -71,11 +76,58 @@ class XlsTest extends AbstractFunctional $rowIterator = $sheet->getRowIterator(); foreach ($rowIterator as $row) { - foreach ($row->getCellIterator() as $cell) { + foreach ($row->getCellIterator() as $cellx) { + /** @var Cell */ + $cell = $cellx; $valOld = $cell->getFormattedValue(); $valNew = $newsheet->getCell($cell->getCoordinate())->getFormattedValue(); self::assertEquals($valOld, $valNew); } } + $spreadsheet->disconnectWorksheets(); + $newspreadsheet->disconnectWorksheets(); + } + + /** + * Test load Xls file with MACCENTRALEUROPE encoding, which is implemented + * as MAC-CENTRALEUROPE on some systems. Issue #549. + */ + public function testLoadMacCentralEurope(): void + { + $codePages = CodePage::getEncodings(); + self::assertIsArray($codePages[10029]); + $filename = 'tests/data/Reader/XLS/maccentraleurope.xls'; + $reader = new Xls(); + // When no fix applied, spreadsheet fails to load on some systems + $spreadsheet = $reader->load($filename); + $sheet = $spreadsheet->getActiveSheet(); + self::assertSame('Ładowność', $sheet->getCell('I1')->getValue()); + $spreadsheet->disconnectWorksheets(); + } + + /** + * First test changes array entry in CodePage. + * This test confirms new that new entry is okay. + */ + public function testLoadMacCentralEurope2(): void + { + $codePages = CodePage::getEncodings(); + self::assertIsString($codePages[10029]); + $filename = 'tests/data/Reader/XLS/maccentraleurope.xls'; + $reader = new Xls(); + // When no fix applied, spreadsheet fails to load on some systems + $spreadsheet = $reader->load($filename); + $sheet = $spreadsheet->getActiveSheet(); + self::assertSame('Ładowność', $sheet->getCell('I1')->getValue()); + $spreadsheet->disconnectWorksheets(); + } + + public function testLoadXlsBug1114(): void + { + $filename = 'tests/data/Reader/XLS/bug1114.xls'; + $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($filename); + $sheet = $spreadsheet->getActiveSheet(); + self::assertSame(1148140800.0, $sheet->getCell('B2')->getValue()); + $spreadsheet->disconnectWorksheets(); } } diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/AbsolutePathTest.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/AbsolutePathTest.php new file mode 100644 index 00000000..6a886abb --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/AbsolutePathTest.php @@ -0,0 +1,19 @@ +listWorksheetInfo($xlsxFile); + + self::assertIsArray($result); + self::assertEquals(3, $result[0]['totalRows']); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/AutoFilterTest.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/AutoFilterTest.php index 63da2d05..7287b711 100644 --- a/tests/PhpSpreadsheetTests/Reader/Xlsx/AutoFilterTest.php +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/AutoFilterTest.php @@ -36,7 +36,7 @@ class AutoFilterTest extends TestCase return $instance; } - public function loadDataProvider() + public function loadDataProvider(): array { return [ ['$B3$E8', 0, 'B3E8'], diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/ChartsTitleTest.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/ChartsTitleTest.php new file mode 100644 index 00000000..5cde677d --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/ChartsTitleTest.php @@ -0,0 +1,59 @@ +getCaptionText(); + } + + public function testChartTitles(): void + { + $filename = 'tests/data/Reader/XLSX/excelChartsTest.xlsx'; + $reader = IOFactory::createReader('Xlsx')->setIncludeCharts(true); + $spreadsheet = $reader->load($filename); + $worksheet = $spreadsheet->getActiveSheet(); + + $charts = $worksheet->getChartCollection(); + self::assertEquals(5, $worksheet->getChartCount()); + self::assertCount(5, $charts); + + // No title or axis labels + $chart1 = $charts[0]; + $title = self::getTitleText($chart1->getTitle()); + self::assertEmpty($title); + self::assertEmpty(self::getTitleText($chart1->getXAxisLabel())); + self::assertEmpty(self::getTitleText($chart1->getYAxisLabel())); + + // Title, no axis labels + $chart2 = $charts[1]; + + self::assertEquals('Chart with Title and no Axis Labels', self::getTitleText($chart2->getTitle())); + self::assertEmpty(self::getTitleText($chart2->getXAxisLabel())); + self::assertEmpty(self::getTitleText($chart2->getYAxisLabel())); + + // No title, only horizontal axis label + $chart3 = $charts[2]; + self::assertEmpty(self::getTitleText($chart3->getTitle())); + self::assertEquals('Horizontal Axis Title Only', self::getTitleText($chart3->getXAxisLabel())); + self::assertEmpty(self::getTitleText($chart3->getYAxisLabel())); + + // No title, only vertical axis label + $chart4 = $charts[3]; + self::assertEmpty(self::getTitleText($chart4->getTitle())); + self::assertEquals('Vertical Axis Title Only', self::getTitleText($chart4->getYAxisLabel())); + self::assertEmpty(self::getTitleText($chart4->getXAxisLabel())); + + // Title and both axis labels + $chart5 = $charts[4]; + self::assertEquals('Complete Annotations', self::getTitleText($chart5->getTitle())); + self::assertEquals('Horizontal Axis Title', self::getTitleText($chart5->getXAxisLabel())); + self::assertEquals('Vertical Axis Title', self::getTitleText($chart5->getYAxisLabel())); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/CommentTest.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/CommentTest.php new file mode 100644 index 00000000..a80323a5 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/CommentTest.php @@ -0,0 +1,26 @@ +load($filename); + + $sheet = $spreadsheet->getActiveSheet(); + $comment = $sheet->getComment('A1'); + $commentString = (string) $comment; + self::assertStringContainsString('編號長度限制:', $commentString); + self::assertSame('jill.chen', $comment->getAuthor()); + $comment = $sheet->getComment('E1'); + $commentString = (string) $comment; + self::assertStringContainsString('若為宅配物流僅能選「純配送」', $commentString); + self::assertSame('Anderson Chen 陳宗棠', $comment->getAuthor()); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/CondNumFmtTest.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/CondNumFmtTest.php similarity index 96% rename from tests/PhpSpreadsheetTests/Reader/CondNumFmtTest.php rename to tests/PhpSpreadsheetTests/Reader/Xlsx/CondNumFmtTest.php index c7474c6a..350baa76 100644 --- a/tests/PhpSpreadsheetTests/Reader/CondNumFmtTest.php +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/CondNumFmtTest.php @@ -1,6 +1,6 @@ load($filename); + $worksheet = $spreadsheet->getActiveSheet(); + + $this->pattern1Assertion($worksheet); + $this->pattern2Assertion($worksheet); + $this->pattern3Assertion($worksheet); + $this->pattern4Assertion($worksheet); + } + + public function testReloadXlsxConditionalFormattingDataBar(): void + { + // Make sure conditionals from existing file are maintained across save + $filename = 'tests/data/Reader/XLSX/conditionalFormattingDataBarTest.xlsx'; + $outfile = File::temporaryFilename(); + $reader = IOFactory::createReader('Xlsx'); + $spreadshee1 = $reader->load($filename); + $writer = IOFactory::createWriter($spreadshee1, 'Xlsx'); + $writer->save($outfile); + $spreadsheet = $reader->load($outfile); + unlink($outfile); + $worksheet = $spreadsheet->getActiveSheet(); + + $this->pattern1Assertion($worksheet); + $this->pattern2Assertion($worksheet); + $this->pattern3Assertion($worksheet); + $this->pattern4Assertion($worksheet); + } + + public function testNewXlsxConditionalFormattingDataBar(): void + { + // Make sure blanks/non-blanks added by PhpSpreadsheet are handled correctly + $outfile = File::temporaryFilename(); + $spreadshee1 = new \PhpOffice\PhpSpreadsheet\Spreadsheet(); + $sheet = $spreadshee1->getActiveSheet(); + $sheet->setCellValue('A1', 1); + $sheet->setCellValue('A2', 2); + $sheet->setCellValue('A3', 3); + $sheet->setCellValue('A4', 4); + $sheet->setCellValue('A5', 5); + $cond1 = new Conditional(); + $cond1->setConditionType(Conditional::CONDITION_DATABAR); + $cond1->setDataBar(new ConditionalDataBar()); + $cond1->getDataBar() + ->setMinimumConditionalFormatValueObject(new ConditionalFormatValueObject('min')) + ->setMaximumConditionalFormatValueObject(new ConditionalFormatValueObject('max')) + ->setColor(Color::COLOR_GREEN); + $cond = [$cond1]; + $sheet->getStyle('A1:A5')->setConditionalStyles($cond); + $writer = IOFactory::createWriter($spreadshee1, 'Xlsx'); + $writer->save($outfile); + $reader = IOFactory::createReader('Xlsx'); + $spreadsheet = $reader->load($outfile); + unlink($outfile); + $worksheet = $spreadsheet->getActiveSheet(); + + $conditionalStyle = $worksheet->getConditionalStyles('A1:A5'); + self::assertNotEmpty($conditionalStyle); + /** @var Conditional $conditionalRule */ + $conditionalRule = $conditionalStyle[0]; + $conditions = $conditionalRule->getConditions(); + self::assertNotEmpty($conditions); + self::assertEquals(Conditional::CONDITION_DATABAR, $conditionalRule->getConditionType()); + self::assertNotEmpty($conditionalRule->getDataBar()); + + $dataBar = $conditionalRule->getDataBar(); + self::assertNotEmpty($dataBar->getMinimumConditionalFormatValueObject()); + self::assertNotEmpty($dataBar->getMaximumConditionalFormatValueObject()); + self::assertEquals('min', $dataBar->getMinimumConditionalFormatValueObject()->getType()); + self::assertEquals('max', $dataBar->getMaximumConditionalFormatValueObject()->getType()); + self::assertEquals(Color::COLOR_GREEN, $dataBar->getColor()); + } + + private function pattern1Assertion(Worksheet $worksheet): void + { + self::assertEquals( + "Type: Automatic, Automatic\nDirection: Automatic\nFills: Gradient\nAxis Position: Automatic", + $worksheet->getCell('A2')->getValue() + ); + + $conditionalStyle = $worksheet->getConditionalStyles('A3:A23'); + self::assertNotEmpty($conditionalStyle); + /** @var Conditional $conditionalRule */ + $conditionalRule = $conditionalStyle[0]; + $dataBar = $conditionalRule->getDataBar(); + + self::assertNotEmpty($dataBar); + self::assertEquals(Conditional::CONDITION_DATABAR, $conditionalRule->getConditionType()); + self::assertNotEmpty($dataBar->getMinimumConditionalFormatValueObject()); + self::assertNotEmpty($dataBar->getMaximumConditionalFormatValueObject()); + self::assertEquals('min', $dataBar->getMinimumConditionalFormatValueObject()->getType()); + self::assertEquals('max', $dataBar->getMaximumConditionalFormatValueObject()->getType()); + + self::assertEquals('FF638EC6', $dataBar->getColor()); + self::assertNotEmpty($dataBar->getConditionalFormattingRuleExt()); + //ext + $rule1ext = $dataBar->getConditionalFormattingRuleExt(); + self::assertEquals('{72C64AE0-5CD9-164F-83D1-AB720F263E79}', $rule1ext->getId()); + self::assertEquals('dataBar', $rule1ext->getCfRule()); + self::assertEquals('A3:A23', $rule1ext->getSqref()); + $extDataBar = $rule1ext->getDataBarExt(); + self::assertNotEmpty($extDataBar); + $pattern1 = [ + 'minLength' => 0, + 'maxLength' => 100, + 'border' => true, + 'gradient' => null, + 'direction' => null, + 'axisPosition' => null, + 'negativeBarBorderColorSameAsPositive' => false, + 'borderColor' => 'FF638EC6', + 'negativeFillColor' => 'FFFF0000', + 'negativeBorderColor' => 'FFFF0000', + ]; + foreach ($pattern1 as $key => $value) { + $funcName = 'get' . ucwords($key); + self::assertEquals($value, $extDataBar->$funcName(), __METHOD__ . '::' . $funcName . ' function patten'); + } + + self::assertNotEmpty($extDataBar->getMinimumConditionalFormatValueObject()); + self::assertNotEmpty($extDataBar->getMaximumConditionalFormatValueObject()); + self::assertEquals('autoMin', $extDataBar->getMinimumConditionalFormatValueObject()->getType()); + self::assertEquals('autoMax', $extDataBar->getMaximumConditionalFormatValueObject()->getType()); + + self::assertArrayHasKey('rgb', $extDataBar->getAxisColor()); + self::assertEquals('FF000000', $extDataBar->getAxisColor()['rgb']); + } + + private function pattern2Assertion(Worksheet $worksheet): void + { + self::assertEquals( + "Type: Number, Number\nValue: -5, 5\nDirection: Automatic\nFills: Solid\nAxis Position: Automatic", + $worksheet->getCell('B2')->getValue() + ); + + $conditionalStyle = $worksheet->getConditionalStyles('B3:B23'); + self::assertNotEmpty($conditionalStyle); + /** @var Conditional $conditionalRule */ + $conditionalRule = $conditionalStyle[0]; + $dataBar = $conditionalRule->getDataBar(); + + self::assertNotEmpty($dataBar); + self::assertEquals(Conditional::CONDITION_DATABAR, $conditionalRule->getConditionType()); + self::assertNotEmpty($dataBar->getMinimumConditionalFormatValueObject()); + self::assertNotEmpty($dataBar->getMaximumConditionalFormatValueObject()); + self::assertEquals('num', $dataBar->getMinimumConditionalFormatValueObject()->getType()); + self::assertEquals('num', $dataBar->getMaximumConditionalFormatValueObject()->getType()); + self::assertEquals('-5', $dataBar->getMinimumConditionalFormatValueObject()->getValue()); + self::assertEquals('5', $dataBar->getMaximumConditionalFormatValueObject()->getValue()); + self::assertEquals('FF63C384', $dataBar->getColor()); + self::assertNotEmpty($dataBar->getConditionalFormattingRuleExt()); + //ext + $rule1ext = $dataBar->getConditionalFormattingRuleExt(); + self::assertEquals('{98904F60-57F0-DF47-B480-691B20D325E3}', $rule1ext->getId()); + self::assertEquals('dataBar', $rule1ext->getCfRule()); + self::assertEquals('B3:B23', $rule1ext->getSqref()); + $extDataBar = $rule1ext->getDataBarExt(); + self::assertNotEmpty($extDataBar); + $pattern1 = [ + 'minLength' => 0, + 'maxLength' => 100, + 'border' => null, + 'gradient' => false, + 'direction' => null, + 'axisPosition' => null, + 'negativeBarBorderColorSameAsPositive' => null, + 'borderColor' => null, + 'negativeFillColor' => 'FFFF0000', + 'negativeBorderColor' => null, + ]; + foreach ($pattern1 as $key => $value) { + $funcName = 'get' . ucwords($key); + self::assertEquals($value, $extDataBar->$funcName(), $funcName . ' function patten'); + } + + self::assertNotEmpty($extDataBar->getMinimumConditionalFormatValueObject()); + self::assertNotEmpty($extDataBar->getMaximumConditionalFormatValueObject()); + self::assertEquals('num', $extDataBar->getMinimumConditionalFormatValueObject()->getType()); + self::assertEquals('num', $extDataBar->getMaximumConditionalFormatValueObject()->getType()); + self::assertEquals('-5', $extDataBar->getMinimumConditionalFormatValueObject()->getCellFormula()); + self::assertEquals('5', $extDataBar->getMaximumConditionalFormatValueObject()->getCellFormula()); + + self::assertArrayHasKey('rgb', $extDataBar->getAxisColor()); + self::assertEquals('FF000000', $extDataBar->getAxisColor()['rgb']); + } + + private function pattern3Assertion(Worksheet $worksheet): void + { + self::assertEquals( + "Type: Automatic, Automatic\nDirection: rightToLeft\nFills: Solid\nAxis Position: None", + $worksheet->getCell('C2')->getValue() + ); + + $conditionalStyle = $worksheet->getConditionalStyles('C3:C23'); + self::assertNotEmpty($conditionalStyle); + /** @var Conditional $conditionalRule */ + $conditionalRule = $conditionalStyle[0]; + $dataBar = $conditionalRule->getDataBar(); + + self::assertNotEmpty($dataBar); + self::assertEquals(Conditional::CONDITION_DATABAR, $conditionalRule->getConditionType()); + self::assertNotEmpty($dataBar->getMinimumConditionalFormatValueObject()); + self::assertNotEmpty($dataBar->getMaximumConditionalFormatValueObject()); + self::assertEquals('min', $dataBar->getMinimumConditionalFormatValueObject()->getType()); + self::assertEquals('max', $dataBar->getMaximumConditionalFormatValueObject()->getType()); + self::assertEmpty($dataBar->getMinimumConditionalFormatValueObject()->getValue()); + self::assertEmpty($dataBar->getMaximumConditionalFormatValueObject()->getValue()); + self::assertEquals('FFFF555A', $dataBar->getColor()); + self::assertNotEmpty($dataBar->getConditionalFormattingRuleExt()); + + //ext + $rule1ext = $dataBar->getConditionalFormattingRuleExt(); + self::assertEquals('{453C04BA-7ABD-8548-8A17-D9CFD2BDABE9}', $rule1ext->getId()); + self::assertEquals('dataBar', $rule1ext->getCfRule()); + self::assertEquals('C3:C23', $rule1ext->getSqref()); + $extDataBar = $rule1ext->getDataBarExt(); + self::assertNotEmpty($extDataBar); + $pattern1 = [ + 'minLength' => 0, + 'maxLength' => 100, + 'border' => null, + 'gradient' => false, + 'direction' => 'rightToLeft', + 'axisPosition' => 'none', + 'negativeBarBorderColorSameAsPositive' => null, + 'borderColor' => null, + 'negativeFillColor' => 'FFFF0000', + 'negativeBorderColor' => null, + ]; + foreach ($pattern1 as $key => $value) { + $funcName = 'get' . ucwords($key); + self::assertEquals($value, $extDataBar->$funcName(), $funcName . ' function patten'); + } + + self::assertNotEmpty($extDataBar->getMinimumConditionalFormatValueObject()); + self::assertNotEmpty($extDataBar->getMaximumConditionalFormatValueObject()); + self::assertEquals('autoMin', $extDataBar->getMinimumConditionalFormatValueObject()->getType()); + self::assertEquals('autoMax', $extDataBar->getMaximumConditionalFormatValueObject()->getType()); + self::assertEmpty($extDataBar->getMinimumConditionalFormatValueObject()->getCellFormula()); + self::assertEmpty($extDataBar->getMaximumConditionalFormatValueObject()->getCellFormula()); + + self::assertArrayHasKey('rgb', $extDataBar->getAxisColor()); + self::assertEmpty($extDataBar->getAxisColor()['rgb']); + } + + private function pattern4Assertion(Worksheet $worksheet): void + { + self::assertEquals( + "type: formula, formula\nValue: =2+3, =10+10\nDirection: leftToRight\nShowDataBarOnly\nFills: Solid\nBorder: Solid\nAxis Position: Midpoint", + $worksheet->getCell('D2')->getValue() + ); + + $conditionalStyle = $worksheet->getConditionalStyles('D3:D23'); + self::assertNotEmpty($conditionalStyle); + /** @var Conditional $conditionalRule */ + $conditionalRule = $conditionalStyle[0]; + $dataBar = $conditionalRule->getDataBar(); + + self::assertNotEmpty($dataBar); + self::assertEquals(Conditional::CONDITION_DATABAR, $conditionalRule->getConditionType()); + + self::assertTrue($dataBar->getShowValue()); + self::assertNotEmpty($dataBar->getMinimumConditionalFormatValueObject()); + self::assertNotEmpty($dataBar->getMaximumConditionalFormatValueObject()); + self::assertEquals('formula', $dataBar->getMinimumConditionalFormatValueObject()->getType()); + self::assertEquals('formula', $dataBar->getMaximumConditionalFormatValueObject()->getType()); + self::assertEquals('3+2', $dataBar->getMinimumConditionalFormatValueObject()->getValue()); + self::assertEquals('10+10', $dataBar->getMaximumConditionalFormatValueObject()->getValue()); + self::assertEquals('FFFF555A', $dataBar->getColor()); + self::assertNotEmpty($dataBar->getConditionalFormattingRuleExt()); + + //ext + $rule1ext = $dataBar->getConditionalFormattingRuleExt(); + self::assertEquals('{6C1E066A-E240-3D4A-98F8-8CC218B0DFD2}', $rule1ext->getId()); + self::assertEquals('dataBar', $rule1ext->getCfRule()); + self::assertEquals('D3:D23', $rule1ext->getSqref()); + $extDataBar = $rule1ext->getDataBarExt(); + self::assertNotEmpty($extDataBar); + $pattern1 = [ + 'minLength' => 0, + 'maxLength' => 100, + 'border' => true, + 'gradient' => false, + 'direction' => 'leftToRight', + 'axisPosition' => 'middle', + 'negativeBarBorderColorSameAsPositive' => null, + 'borderColor' => 'FF000000', + 'negativeFillColor' => 'FFFF0000', + 'negativeBorderColor' => null, + ]; + foreach ($pattern1 as $key => $value) { + $funcName = 'get' . ucwords($key); + self::assertEquals($value, $extDataBar->$funcName(), $funcName . ' function patten'); + } + + self::assertNotEmpty($extDataBar->getMaximumConditionalFormatValueObject()); + self::assertNotEmpty($extDataBar->getMinimumConditionalFormatValueObject()); + self::assertEquals('formula', $extDataBar->getMinimumConditionalFormatValueObject()->getType()); + self::assertEquals('formula', $extDataBar->getMaximumConditionalFormatValueObject()->getType()); + self::assertEquals('3+2', $extDataBar->getMinimumConditionalFormatValueObject()->getCellFormula()); + self::assertEquals('10+10', $extDataBar->getMaximumConditionalFormatValueObject()->getCellFormula()); + + self::assertArrayHasKey('rgb', $extDataBar->getAxisColor()); + self::assertEquals('FF000000', $extDataBar->getAxisColor()['rgb']); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/ConditionalTest.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/ConditionalTest.php new file mode 100644 index 00000000..8108d988 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/ConditionalTest.php @@ -0,0 +1,30 @@ +load($filename); + $worksheet = $spreadsheet->getActiveSheet(); + $styles = $worksheet->getConditionalStyles('A1:A5'); + + self::assertCount(1, $styles); + + /** @var Conditional $notContainsTextStyle */ + $notContainsTextStyle = $styles[0]; + self::assertEquals('A', $notContainsTextStyle->getText()); + self::assertEquals(Conditional::CONDITION_NOTCONTAINSTEXT, $notContainsTextStyle->getConditionType()); + self::assertEquals(Conditional::OPERATOR_NOTCONTAINS, $notContainsTextStyle->getOperatorType()); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/DataValidationBooleanValue.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/DataValidationBooleanValue.php new file mode 100644 index 00000000..34ac2112 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/DataValidationBooleanValue.php @@ -0,0 +1,57 @@ +load($xlsxFile); + + $a1 = $spreadsheet->getActiveSheet()->getDataValidation('A1'); + $a2 = $spreadsheet->getActiveSheet()->getDataValidation('A2'); + + // + // + + self::assertFalse($a1->getAllowBlank(), 'A1 validation does not allow blanks, flag should be false'); + self::assertTrue($a1->getShowDropDown(), 'A1 is set to show the drop down in Excel, which is false in the file'); + self::assertTrue($a1->getShowErrorMessage(), 'A1 Shows error message, flag should be true'); + self::assertTrue($a1->getShowInputMessage(), 'A1 Shows input message, flag should be true'); + + self::assertTrue($a2->getAllowBlank(), 'A2 validation allows blanks, flag should be true'); + self::assertFalse($a2->getShowDropDown(), 'A2 is set to not show the drop down in Excel, which is true in the file'); + self::assertFalse($a2->getShowErrorMessage(), 'A2 does not show error message, flag should be false'); + self::assertFalse($a2->getShowInputMessage(), 'A2 does not show input message, flag should be false'); + } + + //This file was created with Google Sheets export to XLSX + public static function testPr2225OneZero(): void + { + $xlsxFile = 'tests/data/Reader/XLSX/pr2225-datavalidation-onezero.xlsx'; + $reader = new Xlsx(); + $spreadsheet = $reader->load($xlsxFile); + + $a1 = $spreadsheet->getActiveSheet()->getDataValidation('A1'); + $a2 = $spreadsheet->getActiveSheet()->getDataValidation('A2'); + + // + // + + self::assertTrue($a1->getAllowBlank(), 'A1 validation allows blanks, flag should be true'); + self::assertTrue($a1->getShowDropDown(), 'A1 is set to show the drop down in Excel, which is false in the file'); + self::assertTrue($a1->getShowErrorMessage(), 'A1 Shows error message, flag should be true'); + self::assertTrue($a1->getShowInputMessage(), 'A1 Shows input message, flag should be true'); + + self::assertTrue($a2->getAllowBlank(), 'A2 validation allows blanks, flag should be true'); + self::assertFalse($a2->getShowDropDown(), 'A2 is set to not show the drop down in Excel, which is true in the file'); + self::assertFalse($a2->getShowErrorMessage(), 'A2 does not show error message, flag should be false'); + self::assertFalse($a2->getShowInputMessage(), 'A2 does not show input message, flag should be false'); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/DefaultFillTest.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/DefaultFillTest.php new file mode 100644 index 00000000..dc61b953 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/DefaultFillTest.php @@ -0,0 +1,43 @@ +', $data); + } + $reader = IOFactory::createReader('Xlsx'); + $spreadsheet = $reader->load($filename); + $sheet = $spreadsheet->getActiveSheet(); + self::assertSame('none', $sheet->getCell('A1')->getStyle()->getFill()->getFillType()); + self::assertSame('none', $sheet->getCell('D4')->getStyle()->getFill()->getFillType()); + self::assertSame('none', $sheet->getCell('J16')->getStyle()->getFill()->getFillType()); + self::assertSame('solid', $sheet->getCell('C2')->getStyle()->getFill()->getFillType()); + } + + public function testDefaultConditionalFill(): void + { + // default fill pattern for a conditional style where the filltype is not defined + $filename = 'tests/data/Reader/XLSX/pr2050cf-fill.xlsx'; + $reader = IOFactory::createReader('Xlsx'); + $spreadsheet = $reader->load($filename); + + $style = $spreadsheet->getActiveSheet()->getConditionalStyles('A1')[0]->getStyle(); + self::assertSame('solid', $style->getFill()->getFillType()); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/DefaultFontTest.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/DefaultFontTest.php new file mode 100644 index 00000000..a4e94804 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/DefaultFontTest.php @@ -0,0 +1,22 @@ +load($filename); + + $style = $spreadsheet->getActiveSheet()->getConditionalStyles('A1')[0]->getStyle(); + self::assertSame('9C0006', $style->getFont()->getColor()->getRGB()); + self::assertNull($style->getFont()->getName()); + self::assertNull($style->getFont()->getSize()); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/EmptyFileTest.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/EmptyFileTest.php new file mode 100644 index 00000000..a2e78da4 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/EmptyFileTest.php @@ -0,0 +1,52 @@ +tempfile !== '') { + unlink($this->tempfile); + $this->tempfile = ''; + } + } + + public function testEmptyFileLoad(): void + { + $this->expectException(ReaderException::class); + $this->expectExceptionMessage('Could not find zip member'); + $this->tempfile = $temp = File::temporaryFileName(); + file_put_contents($temp, ''); + $reader = new Xlsx(); + $reader->load($temp); + } + + public function testEmptyFileNames(): void + { + $this->expectException(ReaderException::class); + $this->expectExceptionMessage('Could not find zip member'); + $this->tempfile = $temp = File::temporaryFileName(); + file_put_contents($temp, ''); + $reader = new Xlsx(); + $reader->listWorksheetNames($temp); + } + + public function testEmptyInfo(): void + { + $this->expectException(ReaderException::class); + $this->expectExceptionMessage('Could not find zip member'); + $this->tempfile = $temp = File::temporaryFileName(); + file_put_contents($temp, ''); + $reader = new Xlsx(); + $reader->listWorksheetInfo($temp); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/InvalidFileTest.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/InvalidFileTest.php new file mode 100644 index 00000000..05acd874 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/InvalidFileTest.php @@ -0,0 +1,64 @@ +expectException(ReaderException::class); + $this->expectExceptionMessage('Could not find zip member'); + $temp = __FILE__; + $reader = new Xlsx(); + $reader->load($temp); + } + + public function testInvalidFileNames(): void + { + $this->expectException(ReaderException::class); + $this->expectExceptionMessage('Could not find zip member'); + $temp = __FILE__; + $reader = new Xlsx(); + $reader->listWorksheetNames($temp); + } + + public function testInvalidInfo(): void + { + $this->expectException(ReaderException::class); + $this->expectExceptionMessage('Could not find zip member'); + $temp = __FILE__; + $reader = new Xlsx(); + $reader->listWorksheetInfo($temp); + } + + public function testOdsFileLoad(): void + { + $this->expectException(ReaderException::class); + $this->expectExceptionMessage('Could not find zip member'); + $temp = 'samples/templates/OOCalcTest.ods'; + $reader = new Xlsx(); + $reader->load($temp); + } + + public function testOdsFileNames(): void + { + $this->expectException(ReaderException::class); + $this->expectExceptionMessage('Could not find zip member'); + $temp = 'samples/templates/OOCalcTest.ods'; + $reader = new Xlsx(); + $reader->listWorksheetNames($temp); + } + + public function testOdsInfo(): void + { + $this->expectException(ReaderException::class); + $this->expectExceptionMessage('Could not find zip member'); + $temp = 'samples/templates/OOCalcTest.ods'; + $reader = new Xlsx(); + $reader->listWorksheetInfo($temp); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/Issue2301Test.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/Issue2301Test.php new file mode 100644 index 00000000..4484b9e0 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/Issue2301Test.php @@ -0,0 +1,28 @@ +getActiveSheet(); + $value = $sheet->getCell('B45')->getValue(); + self::assertInstanceOf(RichText::class, $value); + $richtext = $value->getRichTextElements(); + $font = $richtext[1]->getFont(); + self::assertNotNull($font); + self::assertSame('Arial CE', $font->getName()); + self::assertSame(9.0, $font->getSize()); + self::assertSame('protected', $sheet->getCell('BT10')->getStyle()->getProtection()->getHidden()); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/Issue2331Test.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/Issue2331Test.php new file mode 100644 index 00000000..afa2ff52 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/Issue2331Test.php @@ -0,0 +1,26 @@ +load($filename); + $properties = $spreadsheet->getProperties(); + $created = (string) $properties->getCreated(); + $modified = (string) $properties->getModified(); + + self::assertEquals('2021-08-02', Date::formattedDateTimeFromTimestamp($created, 'Y-m-d', new DateTimeZone('UTC'))); + self::assertEquals('2021-09-03', Date::formattedDateTimeFromTimestamp($modified, 'Y-m-d', new DateTimeZone('UTC'))); + $spreadsheet->disconnectWorksheets(); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/Namespace.Issue2109bTest.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/Namespace.Issue2109bTest.php new file mode 100644 index 00000000..98da11ba --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/Namespace.Issue2109bTest.php @@ -0,0 +1,89 @@ +listWorkSheetInfo(self::$testbook); + $info0 = $workSheetInfo[0]; + self::assertEquals('Sheet1', $info0['worksheetName']); + self::assertEquals('AF', $info0['lastColumnLetter']); + self::assertEquals(31, $info0['lastColumnIndex']); + self::assertEquals(4, $info0['totalRows']); + self::assertEquals(32, $info0['totalColumns']); + } + + public function testSheetNames(): void + { + $reader = new Xlsx(); + $worksheetNames = $reader->listWorksheetNames(self::$testbook); + self::assertEquals(['Sheet1'], $worksheetNames); + } + + public function testActive(): void + { + $reader = new Xlsx(); + $spreadsheet = $reader->load(self::$testbook); + $sheet = $spreadsheet->getActiveSheet(); + self::assertSame('Sheet1', $sheet->getTitle()); + self::assertNull($sheet->getFreezePane()); + self::assertNull($sheet->getTopLeftCell()); + self::assertSame('A1', $sheet->getSelectedCells()); + $spreadsheet->disconnectWorksheets(); + } + + private static function getCellValue(Worksheet $sheet, string $cell): string + { + $result = $sheet->getCell($cell)->getValue(); + + return (string) $result; + } + + public function testLoadXlsx(): void + { + $reader = new Xlsx(); + $spreadsheet = $reader->load(self::$testbook); + $sheet = $spreadsheet->getSheet(0); + self::assertEquals('Sheet1', $sheet->getTitle()); + $expectedArray = [ + 'A1' => 'Channel Name = Cartoon Network RSE', + 'B2' => 'Event ID', + 'C3' => '2021-05-17 03:00', + 'F4' => 'The Internet', + 'AF3' => '902476', + 'AF4' => '902477', + 'J2' => 'Episode Synopsis', + 'J3' => 'Gumball and Darwin\'s reputation is challenged and they really couldn\'t care less...', + 'J4' => 'Gumball accidentally uploads a video of himself and wants it gone.', + ]; + foreach ($expectedArray as $key => $value) { + self::assertSame($value, self::getCellValue($sheet, $key), "error in cell $key"); + } + $spreadsheet->disconnectWorksheets(); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/Namespace.Openpyxl35Test.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/Namespace.Openpyxl35Test.php new file mode 100644 index 00000000..16988a07 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/Namespace.Openpyxl35Test.php @@ -0,0 +1,111 @@ +listWorkSheetInfo(self::$testbook); + $info0 = $workSheetInfo[0]; + self::assertEquals('Shofar 5781', $info0['worksheetName']); + self::assertEquals('D', $info0['lastColumnLetter']); + self::assertEquals(3, $info0['lastColumnIndex']); + self::assertEquals(30, $info0['totalRows']); + self::assertEquals(4, $info0['totalColumns']); + } + + public function testSheetNames(): void + { + $reader = new Xlsx(); + $worksheetNames = $reader->listWorksheetNames(self::$testbook); + self::assertEquals(['Shofar 5781', 'Shofar 5782', 'Shofar 5783'], $worksheetNames); + } + + public function testActive(): void + { + $reader = new Xlsx(); + $spreadsheet = $reader->load(self::$testbook); + $sheet = $spreadsheet->getActiveSheet(); + self::assertSame('Shofar 5781', $sheet->getTitle()); + self::assertSame('A2', $sheet->getFreezePane()); + self::assertSame('A2', $sheet->getTopLeftCell()); + self::assertSame('D2', $sheet->getSelectedCells()); + $spreadsheet->disconnectWorksheets(); + } + + private static function getCellValue(Worksheet $sheet, string $cell): string + { + $result = $sheet->getCell($cell)->getValue(); + + return (string) $result; + } + + public function testLoadXlsx(): void + { + $reader = new Xlsx(); + $spreadsheet = $reader->load(self::$testbook); + $sheet = $spreadsheet->getSheet(0); + self::assertEquals('Shofar 5781', $sheet->getTitle()); + $expectedArray = [ + 'Shofar 5781' => [ + 'A1' => 'Weekday', + 'B6' => 'August 13', + 'A14' => 'Saturday', + 'C14' => 'Elul 13', + 'D30' => 'N/A', + 'B30' => 'September 6', + ], + 'Shofar 5782' => [ + 'C1' => 'Jewish Date', + 'B6' => 'September 1', + 'A14' => 'Friday', + 'C14' => 'Elul 13', + 'D28' => '', + 'B30' => 'September 25', + ], + 'Shofar 5783' => [ + 'B1' => 'Civil Date', + 'B6' => 'August 22', + 'A14' => 'Wednesday', + 'C14' => 'Elul 13', + 'D30' => 'N/A', + 'B30' => 'September 15', + ], + ]; + foreach ($expectedArray as $sheetName => $array1) { + $sheet = $spreadsheet->getSheetByName($sheetName); + if ($sheet === null) { + self::fail("Unable to find sheet $sheetName"); + } else { + foreach ($array1 as $key => $value) { + self::assertSame($value, self::getCellValue($sheet, $key), "error in sheet $sheetName cell $key"); + } + } + } + $spreadsheet->disconnectWorksheets(); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/NamespaceNonStdTest.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/NamespaceNonStdTest.php new file mode 100644 index 00000000..5002b5d7 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/NamespaceNonStdTest.php @@ -0,0 +1,179 @@ +listWorkSheetInfo(self::$testbook); + $info0 = $workSheetInfo[0]; + self::assertEquals('SylkTest', $info0['worksheetName']); + self::assertEquals('J', $info0['lastColumnLetter']); + self::assertEquals(9, $info0['lastColumnIndex']); + self::assertEquals(18, $info0['totalRows']); + self::assertEquals(10, $info0['totalColumns']); + } + + public function testSheetNames(): void + { + $reader = new Xlsx(); + $worksheetNames = $reader->listWorksheetNames(self::$testbook); + self::assertEquals(['SylkTest', 'Second'], $worksheetNames); + } + + public function testActive(): void + { + $reader = new Xlsx(); + $spreadsheet = $reader->load(self::$testbook); + $sheet = $spreadsheet->getActiveSheet(); + self::assertSame('Second', $sheet->getTitle()); + self::assertSame('A2', $sheet->getFreezePane()); + self::assertSame('A2', $sheet->getTopLeftCell()); + self::assertSame('B3', $sheet->getSelectedCells()); + $sheet = $spreadsheet->getSheetByName('SylkTest'); + if ($sheet === null) { + self::fail('Unable to load expected sheet'); + } else { + self::assertNull($sheet->getFreezePane()); + self::assertNull($sheet->getTopLeftCell()); + } + } + + public function testLoadXlsx(): void + { + $reader = new Xlsx(); + $spreadsheet = $reader->load(self::$testbook); + $sheet = $spreadsheet->getSheet(0); + self::assertEquals('SylkTest', $sheet->getTitle()); + if (strpos(__FILE__, 'NonStd') !== false) { + self::markTestIncomplete('Not yet ready'); + } + + self::assertEquals('FFFF0000', $sheet->getCell('A1')->getStyle()->getFont()->getColor()->getARGB()); + self::assertEquals(Fill::FILL_PATTERN_GRAY125, $sheet->getCell('A2')->getStyle()->getFill()->getFillType()); + self::assertEquals(Font::UNDERLINE_SINGLE, $sheet->getCell('A4')->getStyle()->getFont()->getUnderline()); + self::assertEquals('Test with (;) in string', $sheet->getCell('A4')->getValue()); + + self::assertEquals(22269, $sheet->getCell('A10')->getValue()); + self::assertEquals('dd/mm/yyyy', $sheet->getCell('A10')->getStyle()->getNumberFormat()->getFormatCode()); + self::assertEquals('19/12/1960', $sheet->getCell('A10')->getFormattedValue()); + self::assertEquals(1.5, $sheet->getCell('A11')->getValue()); + self::assertEquals('# ?/?', $sheet->getCell('A11')->getStyle()->getNumberFormat()->getFormatCode()); + self::assertEquals('1 1/2', $sheet->getCell('A11')->getFormattedValue()); + + self::assertEquals('=B1+C1', $sheet->getCell('H1')->getValue()); + self::assertEquals('=E2&F2', $sheet->getCell('J2')->getValue()); + self::assertEquals('=SUM(C1:C4)', $sheet->getCell('I5')->getValue()); + self::assertEquals('=MEDIAN(B6:B8)', $sheet->getCell('B9')->getValue()); + + self::assertEquals(11, $sheet->getCell('E1')->getStyle()->getFont()->getSize()); + self::assertTrue($sheet->getCell('E1')->getStyle()->getFont()->getBold()); + self::assertTrue($sheet->getCell('E1')->getStyle()->getFont()->getItalic()); + self::assertEquals(Font::UNDERLINE_SINGLE, $sheet->getCell('E1')->getStyle()->getFont()->getUnderline()); + self::assertFalse($sheet->getCell('E2')->getStyle()->getFont()->getBold()); + self::assertFalse($sheet->getCell('E2')->getStyle()->getFont()->getItalic()); + self::assertEquals(Font::UNDERLINE_NONE, $sheet->getCell('E2')->getStyle()->getFont()->getUnderline()); + self::assertTrue($sheet->getCell('E3')->getStyle()->getFont()->getBold()); + self::assertFalse($sheet->getCell('E3')->getStyle()->getFont()->getItalic()); + self::assertEquals(Font::UNDERLINE_NONE, $sheet->getCell('E3')->getStyle()->getFont()->getUnderline()); + self::assertFalse($sheet->getCell('E4')->getStyle()->getFont()->getBold()); + self::assertTrue($sheet->getCell('E4')->getStyle()->getFont()->getItalic()); + self::assertEquals(Font::UNDERLINE_NONE, $sheet->getCell('E4')->getStyle()->getFont()->getUnderline()); + + self::assertTrue($sheet->getCell('F1')->getStyle()->getFont()->getBold()); + self::assertFalse($sheet->getCell('F1')->getStyle()->getFont()->getItalic()); + self::assertEquals(Font::UNDERLINE_SINGLE, $sheet->getCell('F1')->getStyle()->getFont()->getUnderline()); + self::assertFalse($sheet->getCell('F2')->getStyle()->getFont()->getBold()); + self::assertFalse($sheet->getCell('F2')->getStyle()->getFont()->getItalic()); + self::assertEquals(Font::UNDERLINE_NONE, $sheet->getCell('F2')->getStyle()->getFont()->getUnderline()); + self::assertTrue($sheet->getCell('F3')->getStyle()->getFont()->getBold()); + self::assertTrue($sheet->getCell('F3')->getStyle()->getFont()->getItalic()); + self::assertEquals(Font::UNDERLINE_NONE, $sheet->getCell('F3')->getStyle()->getFont()->getUnderline()); + self::assertFalse($sheet->getCell('F4')->getStyle()->getFont()->getBold()); + self::assertFalse($sheet->getCell('F4')->getStyle()->getFont()->getItalic()); + self::assertEquals(Font::UNDERLINE_NONE, $sheet->getCell('F4')->getStyle()->getFont()->getUnderline()); + + self::assertEquals(Border::BORDER_THIN, $sheet->getCell('C10')->getStyle()->getBorders()->getTop()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C10')->getStyle()->getBorders()->getRight()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C10')->getStyle()->getBorders()->getBottom()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C10')->getStyle()->getBorders()->getLeft()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C12')->getStyle()->getBorders()->getTop()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C12')->getStyle()->getBorders()->getRight()->getBorderStyle()); + self::assertEquals(Border::BORDER_THIN, $sheet->getCell('C12')->getStyle()->getBorders()->getBottom()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C12')->getStyle()->getBorders()->getLeft()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C14')->getStyle()->getBorders()->getTop()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C14')->getStyle()->getBorders()->getRight()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C14')->getStyle()->getBorders()->getBottom()->getBorderStyle()); + self::assertEquals(Border::BORDER_THIN, $sheet->getCell('C14')->getStyle()->getBorders()->getLeft()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C16')->getStyle()->getBorders()->getTop()->getBorderStyle()); + self::assertEquals(Border::BORDER_THIN, $sheet->getCell('C16')->getStyle()->getBorders()->getRight()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C16')->getStyle()->getBorders()->getBottom()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C16')->getStyle()->getBorders()->getLeft()->getBorderStyle()); + self::assertEquals(Border::BORDER_THIN, $sheet->getCell('C18')->getStyle()->getBorders()->getTop()->getBorderStyle()); + self::assertEquals(Border::BORDER_THIN, $sheet->getCell('C18')->getStyle()->getBorders()->getRight()->getBorderStyle()); + self::assertEquals(Border::BORDER_THIN, $sheet->getCell('C18')->getStyle()->getBorders()->getBottom()->getBorderStyle()); + self::assertEquals(Border::BORDER_THIN, $sheet->getCell('C18')->getStyle()->getBorders()->getLeft()->getBorderStyle()); + } + + public function testLoadXlsxSheet2Contents(): void + { + $reader = new Xlsx(); + $spreadsheet = $reader->load(self::$testbook); + $sheet = $spreadsheet->getSheet(1); + self::assertEquals('Second', $sheet->getTitle()); + self::assertSame('Hyperlink', $sheet->getCell('B2')->getValue()); + $hyper = $sheet->getCell('B2')->getHyperlink(); + self::assertSame('http://www.example.com/', $hyper->getUrl()); + self::assertSame('Comment', $sheet->getCell('B3')->getValue()); + $comment = $sheet->getComment('B3'); + // Created as "threaded comment" with Excel 365, not quite as expected. + self::assertStringContainsString('This is a comment', (string) $comment); + } + + public function testLoadXlsxSheet2Styles(): void + { + $reader = new Xlsx(); + $spreadsheet = $reader->load(self::$testbook); + $sheet = $spreadsheet->getSheet(1); + self::assertEquals('Second', $sheet->getTitle()); + if (strpos(__FILE__, 'NonStd') !== false) { + self::markTestIncomplete('Not yet ready'); + } + self::assertEquals('center', $sheet->getCell('A2')->getStyle()->getAlignment()->getHorizontal()); + self::assertSame('inherit', $sheet->getCell('A2')->getStyle()->getProtection()->getLocked()); + self::assertEquals('top', $sheet->getCell('A3')->getStyle()->getAlignment()->getVertical()); + self::assertSame('unprotected', $sheet->getCell('A3')->getStyle()->getProtection()->getLocked()); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/NamespacePurlTest.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/NamespacePurlTest.php new file mode 100644 index 00000000..ddd6ac5d --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/NamespacePurlTest.php @@ -0,0 +1,62 @@ +canRead($filename); + self::assertTrue($actual); + + $sheets = $reader->listWorksheetNames($filename); + self::assertEquals(['ml_out'], $sheets); + + $actual = $reader->listWorksheetInfo($filename); + $expected = [ + [ + 'worksheetName' => 'ml_out', + 'lastColumnLetter' => 'R', + 'lastColumnIndex' => 17, + 'totalRows' => '76', + 'totalColumns' => 18, + ], + ]; + + self::assertEquals($expected, $actual); + } + + public function testPurlLoad(): void + { + $filename = self::$testbook; + $reader = new Xlsx(); + $spreadsheet = $reader->load($filename); + $sheet = $spreadsheet->getActiveSheet(); + self::assertSame('ml_out', $sheet->getTitle()); + self::assertSame('Item', $sheet->getCell('A1')->getValue()); + self::assertEquals(97.91, $sheet->getCell('G3')->getValue()); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/NamespaceStdTest.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/NamespaceStdTest.php new file mode 100644 index 00000000..73e5d5c3 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/NamespaceStdTest.php @@ -0,0 +1,179 @@ +listWorkSheetInfo(self::$testbook); + $info0 = $workSheetInfo[0]; + self::assertEquals('SylkTest', $info0['worksheetName']); + self::assertEquals('J', $info0['lastColumnLetter']); + self::assertEquals(9, $info0['lastColumnIndex']); + self::assertEquals(18, $info0['totalRows']); + self::assertEquals(10, $info0['totalColumns']); + } + + public function testSheetNames(): void + { + $reader = new Xlsx(); + $worksheetNames = $reader->listWorksheetNames(self::$testbook); + self::assertEquals(['SylkTest', 'Second'], $worksheetNames); + } + + public function testActive(): void + { + $reader = new Xlsx(); + $spreadsheet = $reader->load(self::$testbook); + $sheet = $spreadsheet->getActiveSheet(); + self::assertSame('Second', $sheet->getTitle()); + self::assertSame('A2', $sheet->getFreezePane()); + self::assertSame('A2', $sheet->getTopLeftCell()); + self::assertSame('B3', $sheet->getSelectedCells()); + $sheet = $spreadsheet->getSheetByName('SylkTest'); + if ($sheet === null) { + self::fail('Unable to load expected sheet'); + } else { + self::assertNull($sheet->getFreezePane()); + self::assertNull($sheet->getTopLeftCell()); + } + } + + public function testLoadXlsx(): void + { + $reader = new Xlsx(); + $spreadsheet = $reader->load(self::$testbook); + $sheet = $spreadsheet->getSheet(0); + self::assertEquals('SylkTest', $sheet->getTitle()); + if (strpos(__FILE__, 'NonStd') !== false) { + self::markTestIncomplete('Not yet ready'); + } + + self::assertEquals('FFFF0000', $sheet->getCell('A1')->getStyle()->getFont()->getColor()->getARGB()); + self::assertEquals(Fill::FILL_PATTERN_GRAY125, $sheet->getCell('A2')->getStyle()->getFill()->getFillType()); + self::assertEquals(Font::UNDERLINE_SINGLE, $sheet->getCell('A4')->getStyle()->getFont()->getUnderline()); + self::assertEquals('Test with (;) in string', $sheet->getCell('A4')->getValue()); + + self::assertEquals(22269, $sheet->getCell('A10')->getValue()); + self::assertEquals('dd/mm/yyyy', $sheet->getCell('A10')->getStyle()->getNumberFormat()->getFormatCode()); + self::assertEquals('19/12/1960', $sheet->getCell('A10')->getFormattedValue()); + self::assertEquals(1.5, $sheet->getCell('A11')->getValue()); + self::assertEquals('# ?/?', $sheet->getCell('A11')->getStyle()->getNumberFormat()->getFormatCode()); + self::assertEquals('1 1/2', $sheet->getCell('A11')->getFormattedValue()); + + self::assertEquals('=B1+C1', $sheet->getCell('H1')->getValue()); + self::assertEquals('=E2&F2', $sheet->getCell('J2')->getValue()); + self::assertEquals('=SUM(C1:C4)', $sheet->getCell('I5')->getValue()); + self::assertEquals('=MEDIAN(B6:B8)', $sheet->getCell('B9')->getValue()); + + self::assertEquals(11, $sheet->getCell('E1')->getStyle()->getFont()->getSize()); + self::assertTrue($sheet->getCell('E1')->getStyle()->getFont()->getBold()); + self::assertTrue($sheet->getCell('E1')->getStyle()->getFont()->getItalic()); + self::assertEquals(Font::UNDERLINE_SINGLE, $sheet->getCell('E1')->getStyle()->getFont()->getUnderline()); + self::assertFalse($sheet->getCell('E2')->getStyle()->getFont()->getBold()); + self::assertFalse($sheet->getCell('E2')->getStyle()->getFont()->getItalic()); + self::assertEquals(Font::UNDERLINE_NONE, $sheet->getCell('E2')->getStyle()->getFont()->getUnderline()); + self::assertTrue($sheet->getCell('E3')->getStyle()->getFont()->getBold()); + self::assertFalse($sheet->getCell('E3')->getStyle()->getFont()->getItalic()); + self::assertEquals(Font::UNDERLINE_NONE, $sheet->getCell('E3')->getStyle()->getFont()->getUnderline()); + self::assertFalse($sheet->getCell('E4')->getStyle()->getFont()->getBold()); + self::assertTrue($sheet->getCell('E4')->getStyle()->getFont()->getItalic()); + self::assertEquals(Font::UNDERLINE_NONE, $sheet->getCell('E4')->getStyle()->getFont()->getUnderline()); + + self::assertTrue($sheet->getCell('F1')->getStyle()->getFont()->getBold()); + self::assertFalse($sheet->getCell('F1')->getStyle()->getFont()->getItalic()); + self::assertEquals(Font::UNDERLINE_SINGLE, $sheet->getCell('F1')->getStyle()->getFont()->getUnderline()); + self::assertFalse($sheet->getCell('F2')->getStyle()->getFont()->getBold()); + self::assertFalse($sheet->getCell('F2')->getStyle()->getFont()->getItalic()); + self::assertEquals(Font::UNDERLINE_NONE, $sheet->getCell('F2')->getStyle()->getFont()->getUnderline()); + self::assertTrue($sheet->getCell('F3')->getStyle()->getFont()->getBold()); + self::assertTrue($sheet->getCell('F3')->getStyle()->getFont()->getItalic()); + self::assertEquals(Font::UNDERLINE_NONE, $sheet->getCell('F3')->getStyle()->getFont()->getUnderline()); + self::assertFalse($sheet->getCell('F4')->getStyle()->getFont()->getBold()); + self::assertFalse($sheet->getCell('F4')->getStyle()->getFont()->getItalic()); + self::assertEquals(Font::UNDERLINE_NONE, $sheet->getCell('F4')->getStyle()->getFont()->getUnderline()); + + self::assertEquals(Border::BORDER_THIN, $sheet->getCell('C10')->getStyle()->getBorders()->getTop()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C10')->getStyle()->getBorders()->getRight()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C10')->getStyle()->getBorders()->getBottom()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C10')->getStyle()->getBorders()->getLeft()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C12')->getStyle()->getBorders()->getTop()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C12')->getStyle()->getBorders()->getRight()->getBorderStyle()); + self::assertEquals(Border::BORDER_THIN, $sheet->getCell('C12')->getStyle()->getBorders()->getBottom()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C12')->getStyle()->getBorders()->getLeft()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C14')->getStyle()->getBorders()->getTop()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C14')->getStyle()->getBorders()->getRight()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C14')->getStyle()->getBorders()->getBottom()->getBorderStyle()); + self::assertEquals(Border::BORDER_THIN, $sheet->getCell('C14')->getStyle()->getBorders()->getLeft()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C16')->getStyle()->getBorders()->getTop()->getBorderStyle()); + self::assertEquals(Border::BORDER_THIN, $sheet->getCell('C16')->getStyle()->getBorders()->getRight()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C16')->getStyle()->getBorders()->getBottom()->getBorderStyle()); + self::assertEquals(Border::BORDER_NONE, $sheet->getCell('C16')->getStyle()->getBorders()->getLeft()->getBorderStyle()); + self::assertEquals(Border::BORDER_THIN, $sheet->getCell('C18')->getStyle()->getBorders()->getTop()->getBorderStyle()); + self::assertEquals(Border::BORDER_THIN, $sheet->getCell('C18')->getStyle()->getBorders()->getRight()->getBorderStyle()); + self::assertEquals(Border::BORDER_THIN, $sheet->getCell('C18')->getStyle()->getBorders()->getBottom()->getBorderStyle()); + self::assertEquals(Border::BORDER_THIN, $sheet->getCell('C18')->getStyle()->getBorders()->getLeft()->getBorderStyle()); + } + + public function testLoadXlsxSheet2Contents(): void + { + $reader = new Xlsx(); + $spreadsheet = $reader->load(self::$testbook); + $sheet = $spreadsheet->getSheet(1); + self::assertEquals('Second', $sheet->getTitle()); + self::assertSame('Hyperlink', $sheet->getCell('B2')->getValue()); + $hyper = $sheet->getCell('B2')->getHyperlink(); + self::assertSame('http://www.example.com/', $hyper->getUrl()); + self::assertSame('Comment', $sheet->getCell('B3')->getValue()); + $comment = $sheet->getComment('B3'); + // Created as "threaded comment" with Excel 365, not quite as expected. + self::assertStringContainsString('This is a comment', (string) $comment); + } + + public function testLoadXlsxSheet2Styles(): void + { + $reader = new Xlsx(); + $spreadsheet = $reader->load(self::$testbook); + $sheet = $spreadsheet->getSheet(1); + self::assertEquals('Second', $sheet->getTitle()); + if (strpos(__FILE__, 'NonStd') !== false) { + self::markTestIncomplete('Not yet ready'); + } + self::assertEquals('center', $sheet->getCell('A2')->getStyle()->getAlignment()->getHorizontal()); + self::assertSame('inherit', $sheet->getCell('A2')->getStyle()->getProtection()->getLocked()); + self::assertEquals('top', $sheet->getCell('A3')->getStyle()->getAlignment()->getVertical()); + self::assertSame('unprotected', $sheet->getCell('A3')->getStyle()->getProtection()->getLocked()); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/OddColumnReadFilter.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/OddColumnReadFilter.php similarity index 85% rename from tests/PhpSpreadsheetTests/Reader/OddColumnReadFilter.php rename to tests/PhpSpreadsheetTests/Reader/Xlsx/OddColumnReadFilter.php index 2ee6015b..859e5b56 100644 --- a/tests/PhpSpreadsheetTests/Reader/OddColumnReadFilter.php +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/OddColumnReadFilter.php @@ -1,6 +1,6 @@ ['type' => Properties::PROPERTY_TYPE_STRING, 'value' => 'PHPOffice Suite'], + 'Tested' => ['type' => Properties::PROPERTY_TYPE_BOOLEAN, 'value' => true], + 'Counter' => ['type' => Properties::PROPERTY_TYPE_INTEGER, 'value' => 15], + 'Rate' => ['type' => Properties::PROPERTY_TYPE_FLOAT, 'value' => 1.15], + 'Refactor Date' => ['type' => Properties::PROPERTY_TYPE_DATE, 'value' => '2019-06-10'], + ]; + + $filename = 'tests/data/Reader/XLSX/propertyTest.xlsx'; + $reader = new Xlsx(); + $spreadsheet = $reader->load($filename); + + $properties = $spreadsheet->getProperties(); + // Core Properties + self::assertSame('Mark Baker', $properties->getCreator()); + self::assertSame('Unit Testing', $properties->getTitle()); + self::assertSame('Property Test', $properties->getSubject()); + + // Extended Properties + self::assertSame('PHPOffice', $properties->getCompany()); + self::assertSame('The Big Boss', $properties->getManager()); + + // Custom Properties + $customProperties = $properties->getCustomProperties(); + self::assertIsArray($customProperties); + $customProperties = array_flip($customProperties); + self::assertArrayHasKey('Publisher', $customProperties); + + foreach ($customPropertySet as $propertyName => $testData) { + self::assertTrue($properties->isCustomPropertySet($propertyName)); + self::assertSame($testData['type'], $properties->getCustomPropertyType($propertyName)); + $result = $properties->getCustomPropertyValue($propertyName); + if ($properties->getCustomPropertyType($propertyName) == Properties::PROPERTY_TYPE_DATE) { + $result = Date::formattedDateTimeFromTimestamp("$result", 'Y-m-d', new DateTimeZone('UTC')); + } + self::assertSame($testData['value'], $result); + } + } + + public function testReloadXlsxWorkbookProperties(): void + { + $customPropertySet = [ + 'Publisher' => ['type' => Properties::PROPERTY_TYPE_STRING, 'value' => 'PHPOffice Suite'], + 'Tested' => ['type' => Properties::PROPERTY_TYPE_BOOLEAN, 'value' => true], + 'Counter' => ['type' => Properties::PROPERTY_TYPE_INTEGER, 'value' => 15], + 'Rate' => ['type' => Properties::PROPERTY_TYPE_FLOAT, 'value' => 1.15], + 'Refactor Date' => ['type' => Properties::PROPERTY_TYPE_DATE, 'value' => '2019-06-10'], + ]; + + $filename = 'tests/data/Reader/XLSX/propertyTest.xlsx'; + $reader = new Xlsx(); + $spreadsheetOld = $reader->load($filename); + $spreadsheet = $this->writeAndReload($spreadsheetOld, 'Xlsx'); + + $properties = $spreadsheet->getProperties(); + // Core Properties + self::assertSame('Mark Baker', $properties->getCreator()); + self::assertSame('Unit Testing', $properties->getTitle()); + self::assertSame('Property Test', $properties->getSubject()); + + // Extended Properties + self::assertSame('PHPOffice', $properties->getCompany()); + self::assertSame('The Big Boss', $properties->getManager()); + + // Custom Properties + $customProperties = $properties->getCustomProperties(); + self::assertIsArray($customProperties); + $customProperties = array_flip($customProperties); + self::assertArrayHasKey('Publisher', $customProperties); + + foreach ($customPropertySet as $propertyName => $testData) { + self::assertTrue($properties->isCustomPropertySet($propertyName)); + self::assertSame($testData['type'], $properties->getCustomPropertyType($propertyName)); + $result = $properties->getCustomPropertyValue($propertyName); + if ($properties->getCustomPropertyType($propertyName) == Properties::PROPERTY_TYPE_DATE) { + $result = Date::formattedDateTimeFromTimestamp("$result", 'Y-m-d', new DateTimeZone('UTC')); + } + self::assertSame($testData['value'], $result); + } + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/SharedFormulaTest.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/SharedFormulaTest.php new file mode 100644 index 00000000..94f8e349 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/SharedFormulaTest.php @@ -0,0 +1,41 @@ +', $data); + self::assertStringContainsString('', $data); + } + } + + public function testLoadSheetsXlsxChart(): void + { + $filename = self::$testbook; + $reader = IOFactory::createReader('Xlsx'); + $spreadsheet = $reader->load($filename, IReader::LOAD_WITH_CHARTS); + $sheet = $spreadsheet->getActiveSheet(); + self::assertSame('=(RANDBETWEEN(-50,250)+100)*10', $sheet->getCell('D6')->getValue()); + self::assertSame('=(RANDBETWEEN(-50,250)+100)*10', $sheet->getCell('E6')->getValue()); + $spreadsheet->disconnectWorksheets(); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/SheetsXlsxChartTest.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/SheetsXlsxChartTest.php new file mode 100644 index 00000000..d701c3c7 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/SheetsXlsxChartTest.php @@ -0,0 +1,52 @@ +load($filename, IReader::LOAD_WITH_CHARTS); + $worksheet = $spreadsheet->getActiveSheet(); + + $charts = $worksheet->getChartCollection(); + self::assertEquals(2, $worksheet->getChartCount()); + self::assertCount(2, $charts); + + $chart1 = $charts[0]; + $pa1 = $chart1->getPlotArea(); + self::assertEquals(2, $pa1->getPlotSeriesCount()); + + $pg1 = $pa1->getPlotGroup()[0]; + + self::assertEquals(DataSeries::TYPE_LINECHART, $pg1->getPlotType()); + self::assertCount(2, $pg1->getPlotLabels()); + self::assertCount(2, $pg1->getPlotValues()); + self::assertCount(2, $pg1->getPlotCategories()); + + $chart2 = $charts[1]; + $pa1 = $chart2->getPlotArea(); + self::assertEquals(2, $pa1->getPlotSeriesCount()); + + $pg1 = $pa1->getPlotGroupByIndex(0); + //Before a refresh, data values are empty + foreach ($pg1->getPlotValues() as $dv) { + self::assertEmpty($dv->getPointCount()); + } + $pg1->refresh($worksheet); + foreach ($pg1->getPlotValues() as $dv) { + self::assertEquals(9, $dv->getPointCount()); + } + self::assertEquals(DataSeries::TYPE_SCATTERCHART, $pg1->getPlotType()); + self::assertCount(2, $pg1->getPlotLabels()); + self::assertCount(2, $pg1->getPlotValues()); + self::assertCount(2, $pg1->getPlotCategories()); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/URLImageTest.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/URLImageTest.php new file mode 100644 index 00000000..b8e81501 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/URLImageTest.php @@ -0,0 +1,62 @@ +load($filename); + $worksheet = $spreadsheet->getActiveSheet(); + + foreach ($worksheet->getDrawingCollection() as $drawing) { + if ($drawing instanceof MemoryDrawing) { + // Skip memory drawings + } elseif ($drawing instanceof Drawing) { + // Check if the source is a URL or a file path + if ($drawing->getPath() && $drawing->getIsURL()) { + $imageContents = file_get_contents($drawing->getPath()); + $filePath = tempnam(sys_get_temp_dir(), 'Drawing'); + if ($filePath) { + file_put_contents($filePath, $imageContents); + if (file_exists($filePath)) { + $mimeType = mime_content_type($filePath); + // You could use the below to find the extension from mime type. + if ($mimeType) { + $extension = File::mime2ext($mimeType); + self::assertEquals('jpeg', $extension); + unlink($filePath); + } else { + self::fail('Could establish mime type.'); + } + } else { + self::fail('Could not write file to disk.'); + } + } else { + self::fail('Could not create fiel path.'); + } + } else { + self::fail('Could not assert that the file contains an image that is URL sourced.'); + } + } else { + self::fail('No image path found.'); + } + } + + if (empty($worksheet->getDrawingCollection())) { + self::fail('No image found in file.'); + } + } + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx/WorksheetInfoNamesTest.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/WorksheetInfoNamesTest.php new file mode 100644 index 00000000..ed01db25 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/WorksheetInfoNamesTest.php @@ -0,0 +1,80 @@ +listWorksheetInfo($filename); + + $expected = [ + [ + 'worksheetName' => 'Sheet1', + 'lastColumnLetter' => 'F', + 'lastColumnIndex' => 5, + 'totalRows' => '6', + 'totalColumns' => 6, + ], + ]; + + self::assertEquals($expected, $actual); + } + + public function testListWorksheetInfoNamespace(): void + { + $filename = 'tests/data/Reader/XLSX/namespaces.xlsx'; + $file = 'zip://'; + $file .= $filename; + $file .= '#xl/workbook.xml'; + $data = file_get_contents($file); + // confirm that file contains expected namespaced xml tag + if ($data === false) { + self::fail('Unable to read file'); + } else { + self::assertStringContainsString('listWorksheetInfo($filename); + + $expected = [ + [ + 'worksheetName' => 'transactions', + 'lastColumnLetter' => 'K', + 'lastColumnIndex' => 10, + 'totalRows' => 2, + 'totalColumns' => 11, + ], + ]; + + self::assertEquals($expected, $actual); + } + + public function testListWorksheetNames(): void + { + $filename = 'tests/data/Reader/XLSX/rowColumnAttributeTest.xlsx'; + $reader = new Xlsx(); + $actual = $reader->listWorksheetNames($filename); + + $expected = ['Sheet1']; + + self::assertEquals($expected, $actual); + } + + public function testListWorksheetNamesNamespace(): void + { + $filename = 'tests/data/Reader/XLSX/namespaces.xlsx'; + $reader = new Xlsx(); + $actual = $reader->listWorksheetNames($filename); + + $expected = ['transactions']; + + self::assertEquals($expected, $actual); + } +} diff --git a/tests/PhpSpreadsheetTests/Reader/Xlsx2Test.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/Xlsx2Test.php similarity index 96% rename from tests/PhpSpreadsheetTests/Reader/Xlsx2Test.php rename to tests/PhpSpreadsheetTests/Reader/Xlsx/Xlsx2Test.php index 1220c378..8212f089 100644 --- a/tests/PhpSpreadsheetTests/Reader/Xlsx2Test.php +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/Xlsx2Test.php @@ -1,6 +1,6 @@ load($filename); $writer = IOFactory::createWriter($spreadshee1, 'Xlsx'); @@ -87,7 +87,7 @@ class Xlsx2Test extends TestCase public function testNewXlsxConditionalFormatting2(): void { // Make sure blanks/non-blanks added by PhpSpreadsheet are handled correctly - $outfile = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); + $outfile = File::temporaryFilename(); $spreadshee1 = new \PhpOffice\PhpSpreadsheet\Spreadsheet(); $sheet = $spreadshee1->getActiveSheet(); $sheet->setCellValue('A2', 'a2'); diff --git a/tests/PhpSpreadsheetTests/Reader/XlsxTest.php b/tests/PhpSpreadsheetTests/Reader/Xlsx/XlsxTest.php similarity index 73% rename from tests/PhpSpreadsheetTests/Reader/XlsxTest.php rename to tests/PhpSpreadsheetTests/Reader/Xlsx/XlsxTest.php index b326c142..e1271b9a 100644 --- a/tests/PhpSpreadsheetTests/Reader/XlsxTest.php +++ b/tests/PhpSpreadsheetTests/Reader/Xlsx/XlsxTest.php @@ -1,9 +1,10 @@ ['type' => Properties::PROPERTY_TYPE_STRING, 'value' => 'PHPOffice Suite'], - 'Tested' => ['type' => Properties::PROPERTY_TYPE_BOOLEAN, 'value' => true], - 'Counter' => ['type' => Properties::PROPERTY_TYPE_INTEGER, 'value' => 15], - 'Rate' => ['type' => Properties::PROPERTY_TYPE_FLOAT, 'value' => 1.15], - 'Refactor Date' => ['type' => Properties::PROPERTY_TYPE_DATE, 'value' => '2019-06-10'], - ]; - - $filename = 'tests/data/Reader/XLSX/propertyTest.xlsx'; - $reader = new Xlsx(); - $spreadsheet = $reader->load($filename); - - $properties = $spreadsheet->getProperties(); - // Core Properties - self::assertSame('Mark Baker', $properties->getCreator()); - self::assertSame('Unit Testing', $properties->getTitle()); - self::assertSame('Property Test', $properties->getSubject()); - - // Extended Properties - self::assertSame('PHPOffice', $properties->getCompany()); - self::assertSame('The Big Boss', $properties->getManager()); - - // Custom Properties - $customProperties = $properties->getCustomProperties(); - self::assertIsArray($customProperties); - $customProperties = array_flip($customProperties); - self::assertArrayHasKey('Publisher', $customProperties); - - foreach ($customPropertySet as $propertyName => $testData) { - self::assertTrue($properties->isCustomPropertySet($propertyName)); - self::assertSame($testData['type'], $properties->getCustomPropertyType($propertyName)); - if ($properties->getCustomPropertyType($propertyName) == Properties::PROPERTY_TYPE_DATE) { - self::assertSame($testData['value'], date('Y-m-d', $properties->getCustomPropertyValue($propertyName))); - } else { - self::assertSame($testData['value'], $properties->getCustomPropertyValue($propertyName)); - } - } - } - public function testLoadXlsxRowColumnAttributes(): void { $filename = 'tests/data/Reader/XLSX/rowColumnAttributeTest.xlsx'; @@ -103,6 +63,49 @@ class XlsxTest extends TestCase } } + /** + * Test load Xlsx file without styles.xml. + */ + public function testLoadXlsxWithoutStyles(): void + { + $filename = 'tests/data/Reader/XLSX/issue.2246a.xlsx'; + $reader = new Xlsx(); + $spreadsheet = $reader->load($filename); + + $tempFilename = File::temporaryFilename(); + $writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); + $writer->save($tempFilename); + + $reader = new Xlsx(); + $reloadedSpreadsheet = $reader->load($tempFilename); + unlink($tempFilename); + + $reloadedWorksheet = $reloadedSpreadsheet->getActiveSheet(); + + self::assertEquals('TipoDato', $reloadedWorksheet->getCell('A1')->getValue()); + } + + /** + * Test load Xlsx file with empty styles.xml. + */ + public function testLoadXlsxWithEmptyStyles(): void + { + $filename = 'tests/data/Reader/XLSX/issue.2246b.xlsx'; + $reader = new Xlsx(); + $spreadsheet = $reader->load($filename); + + $tempFilename = File::temporaryFilename(); + $writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); + $writer->save($tempFilename); + + $reader = new Xlsx(); + $reloadedSpreadsheet = $reader->load($tempFilename); + unlink($tempFilename); + + $reloadedWorksheet = $reloadedSpreadsheet->getActiveSheet(); + self::assertEquals('TipoDato', $reloadedWorksheet->getCell('A1')->getValue()); + } + public function testLoadXlsxAutofilter(): void { $filename = 'tests/data/Reader/XLSX/autofilterTest.xlsx'; @@ -169,6 +172,31 @@ class XlsxTest extends TestCase self::assertTrue($worksheet->getCell('B3')->hasDataValidation()); } + /* + * Test for load drop down lists of another sheet. + * Pull #2150, issue #2149 + */ + public function testLoadXlsxDataValidationOfAnotherSheet(): void + { + $filename = 'tests/data/Reader/XLSX/dataValidation2Test.xlsx'; + $reader = new Xlsx(); + $spreadsheet = $reader->load($filename); + + $worksheet = $spreadsheet->getActiveSheet(); + + // same sheet + $validationCell = $worksheet->getCell('B5'); + self::assertTrue($validationCell->hasDataValidation()); + self::assertSame(DataValidation::TYPE_LIST, $validationCell->getDataValidation()->getType()); + self::assertSame('$A$5:$A$7', $validationCell->getDataValidation()->getFormula1()); + + // another sheet + $validationCell = $worksheet->getCell('B14'); + self::assertTrue($validationCell->hasDataValidation()); + self::assertSame(DataValidation::TYPE_LIST, $validationCell->getDataValidation()->getType()); + self::assertSame('Feuil2!$A$3:$A$5', $validationCell->getDataValidation()->getFormula1()); + } + /** * Test load Xlsx file without cell reference. * @@ -218,7 +246,7 @@ class XlsxTest extends TestCase $filename = 'tests/data/Reader/XLSX/empty_drawing.xlsx'; $reader = new Xlsx(); $excel = $reader->load($filename); - $resultFilename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); + $resultFilename = File::temporaryFilename(); $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($excel); $writer->save($resultFilename); $excel = $reader->load($resultFilename); @@ -231,16 +259,15 @@ class XlsxTest extends TestCase * Test if all whitespace is removed from a style definition string. * This is needed to parse it into properties with the correct keys. * - * @param $string * @dataProvider providerStripsWhiteSpaceFromStyleString */ - public function testStripsWhiteSpaceFromStyleString($string): void + public function testStripsWhiteSpaceFromStyleString(string $string): void { $string = Xlsx::stripWhiteSpaceFromStyleString($string); self::assertEquals(preg_match('/\s/', $string), 0); } - public function providerStripsWhiteSpaceFromStyleString() + public function providerStripsWhiteSpaceFromStyleString(): array { return [ ['position:absolute;margin-left:424.5pt;margin-top:169.5pt;width:67.5pt; diff --git a/tests/PhpSpreadsheetTests/Reader/Xml/XmlLoadTest.php b/tests/PhpSpreadsheetTests/Reader/Xml/XmlLoadTest.php index 969571f2..29d81299 100644 --- a/tests/PhpSpreadsheetTests/Reader/Xml/XmlLoadTest.php +++ b/tests/PhpSpreadsheetTests/Reader/Xml/XmlLoadTest.php @@ -2,7 +2,9 @@ namespace PhpOffice\PhpSpreadsheetTests\Reader\Xml; +use DateTimeZone; use PhpOffice\PhpSpreadsheet\Reader\Xml; +use PhpOffice\PhpSpreadsheet\Shared\Date; use PHPUnit\Framework\TestCase; class XmlLoadTest extends TestCase @@ -21,8 +23,17 @@ class XmlLoadTest extends TestCase self::assertEquals('BCD', $sheet->getCell('A4')->getValue()); $props = $spreadsheet->getProperties(); self::assertEquals('Mark Baker', $props->getCreator()); + $creationDate = $props->getCreated(); + $result = Date::formattedDateTimeFromTimestamp("$creationDate", 'Y-m-d\\TH:i:s\\Z', new DateTimeZone('UTC')); + self::assertEquals('2010-09-02T20:48:39Z', $result); + $creationDate = $props->getModified(); + $result = Date::formattedDateTimeFromTimestamp("$creationDate", 'Y-m-d\\TH:i:s\\Z', new DateTimeZone('UTC')); + self::assertEquals('2010-09-03T21:48:39Z', $result); self::assertEquals('AbCd1234', $props->getCustomPropertyValue('my_API_Token')); self::assertEquals('2', $props->getCustomPropertyValue('myאInt')); + $creationDate = $props->getCustomPropertyValue('my_API_Token_Expiry'); + $result = Date::formattedDateTimeFromTimestamp("$creationDate", 'Y-m-d\\TH:i:s\\Z', new DateTimeZone('UTC')); + self::assertEquals('2019-01-31T07:00:00Z', $result); $sheet = $spreadsheet->getSheet(0); self::assertEquals('Sample Data', $sheet->getTitle()); @@ -36,6 +47,10 @@ class XmlLoadTest extends TestCase self::assertEquals('# ?0/??0', $sheet->getCell('A11')->getStyle()->getNumberFormat()->getFormatCode()); // Same pattern, same value, different display in Gnumeric vs Excel //self::assertEquals('1 1/2', $sheet->getCell('A11')->getFormattedValue()); + self::assertEquals('hh":"mm":"ss', $sheet->getCell('A13')->getStyle()->getNumberFormat()->getFormatCode()); + self::assertEquals('02:30:00', $sheet->getCell('A13')->getFormattedValue()); + self::assertEquals('d/m/yy hh":"mm', $sheet->getCell('A15')->getStyle()->getNumberFormat()->getFormatCode()); + self::assertEquals('19/12/60 01:30', $sheet->getCell('A15')->getFormattedValue()); self::assertEquals('=B1+C1', $sheet->getCell('H1')->getValue()); self::assertEquals('=E2&F2', $sheet->getCell('J2')->getValue()); diff --git a/tests/PhpSpreadsheetTests/Reader/Xml/XmlOddTest.php b/tests/PhpSpreadsheetTests/Reader/Xml/XmlOddTest.php index e0b43113..8b9e05ff 100644 --- a/tests/PhpSpreadsheetTests/Reader/Xml/XmlOddTest.php +++ b/tests/PhpSpreadsheetTests/Reader/Xml/XmlOddTest.php @@ -8,6 +8,9 @@ use PHPUnit\Framework\TestCase; class XmlOddTest extends TestCase { + /** + * @var string + */ private $filename = ''; protected function teardown(): void @@ -53,7 +56,7 @@ class XmlOddTest extends TestCase EOT; - $this->filename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); + $this->filename = File::temporaryFilename(); file_put_contents($this->filename, $xmldata); $reader = new Xml(); $spreadsheet = $reader->load($this->filename); diff --git a/tests/PhpSpreadsheetTests/Reader/Xml/XmlTest.php b/tests/PhpSpreadsheetTests/Reader/Xml/XmlTest.php index 2b66c7b4..a0b05a56 100644 --- a/tests/PhpSpreadsheetTests/Reader/Xml/XmlTest.php +++ b/tests/PhpSpreadsheetTests/Reader/Xml/XmlTest.php @@ -10,8 +10,6 @@ class XmlTest extends TestCase { /** * @dataProvider providerInvalidSimpleXML - * - * @param $filename */ public function testInvalidSimpleXML($filename): void { @@ -21,7 +19,7 @@ class XmlTest extends TestCase $xmlReader->trySimpleXMLLoadString($filename); } - public function providerInvalidSimpleXML() + public function providerInvalidSimpleXML(): array { $tests = []; foreach (glob('tests/data/Reader/Xml/XEETestInvalidSimpleXML*.xml') as $file) { @@ -47,4 +45,28 @@ class XmlTest extends TestCase self::assertEquals('PhpSpreadsheet', $hyperlink->getValue()); self::assertEquals('https://phpspreadsheet.readthedocs.io', $hyperlink->getHyperlink()->getUrl()); } + + public function testLoadCorruptedFile(): void + { + $this->expectException(\PhpOffice\PhpSpreadsheet\Reader\Exception::class); + + $xmlReader = new Xml(); + $xmlReader->load('tests/data/Reader/Xml/CorruptedXmlFile.xml'); + } + + public function testListWorksheetNamesCorruptedFile(): void + { + $this->expectException(\PhpOffice\PhpSpreadsheet\Reader\Exception::class); + + $xmlReader = new Xml(); + $xmlReader->listWorksheetNames('tests/data/Reader/Xml/CorruptedXmlFile.xml'); + } + + public function testListWorksheetInfoCorruptedFile(): void + { + $this->expectException(\PhpOffice\PhpSpreadsheet\Reader\Exception::class); + + $xmlReader = new Xml(); + $xmlReader->listWorksheetInfo('tests/data/Reader/Xml/CorruptedXmlFile.xml'); + } } diff --git a/tests/PhpSpreadsheetTests/SettingsTest.php b/tests/PhpSpreadsheetTests/SettingsTest.php index 92f3bb1f..80dc07ab 100644 --- a/tests/PhpSpreadsheetTests/SettingsTest.php +++ b/tests/PhpSpreadsheetTests/SettingsTest.php @@ -8,9 +8,9 @@ use PHPUnit\Framework\TestCase; class SettingsTest extends TestCase { /** - * @var string + * @var bool */ - protected $prevValue; + private $prevValue; protected function setUp(): void { @@ -41,6 +41,7 @@ class SettingsTest extends TestCase public function testSetXMLSettings(): void { + $original = Settings::getLibXmlLoaderOptions(); Settings::setLibXmlLoaderOptions(LIBXML_DTDLOAD | LIBXML_DTDATTR | LIBXML_DTDVALID); $result = Settings::getLibXmlLoaderOptions(); self::assertTrue((bool) ((LIBXML_DTDLOAD | LIBXML_DTDATTR | LIBXML_DTDVALID) & $result)); @@ -48,5 +49,6 @@ class SettingsTest extends TestCase if (\PHP_VERSION_ID < 80000) { self::assertFalse(libxml_disable_entity_loader()); } + Settings::setLibXmlLoaderOptions($original); } } diff --git a/tests/PhpSpreadsheetTests/Shared/CodePageTest.php b/tests/PhpSpreadsheetTests/Shared/CodePageTest.php index 2bdbda72..af036f4e 100644 --- a/tests/PhpSpreadsheetTests/Shared/CodePageTest.php +++ b/tests/PhpSpreadsheetTests/Shared/CodePageTest.php @@ -12,14 +12,22 @@ class CodePageTest extends TestCase * @dataProvider providerCodePage * * @param mixed $expectedResult + * @param mixed $codePageIndex */ - public function testCodePageNumberToName($expectedResult, ...$args): void + public function testCodePageNumberToName($expectedResult, $codePageIndex): void { - $result = CodePage::numberToName(...$args); - self::assertEquals($expectedResult, $result); + if ($expectedResult === 'exception') { + $this->expectException(Exception::class); + } + $result = CodePage::numberToName($codePageIndex); + if (is_array($expectedResult)) { + self::assertContains($result, $expectedResult); + } else { + self::assertEquals($expectedResult, $result); + } } - public function providerCodePage() + public function providerCodePage(): array { return require 'tests/data/Shared/CodePage.php'; } diff --git a/tests/PhpSpreadsheetTests/Shared/DateTest.php b/tests/PhpSpreadsheetTests/Shared/DateTest.php index 7254635e..e4bf6838 100644 --- a/tests/PhpSpreadsheetTests/Shared/DateTest.php +++ b/tests/PhpSpreadsheetTests/Shared/DateTest.php @@ -2,22 +2,33 @@ namespace PhpOffice\PhpSpreadsheetTests\Shared; +use DateTimeZone; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PHPUnit\Framework\TestCase; class DateTest extends TestCase { + /** + * @var int + */ + private $excelCalendar; + + /** + * @var null|DateTimeZone + */ private $dttimezone; protected function setUp(): void { - $this->dttimezone = Date::getDefaultTimeZone(); + $this->dttimezone = Date::getDefaultTimeZoneOrNull(); + $this->excelCalendar = Date::getExcelCalendar(); } protected function tearDown(): void { Date::setDefaultTimeZone($this->dttimezone); + Date::setExcelCalendar($this->excelCalendar); } public function testSetExcelCalendar(): void @@ -35,7 +46,7 @@ class DateTest extends TestCase public function testSetExcelCalendarWithInvalidValue(): void { - $unsupportedCalendar = '2012'; + $unsupportedCalendar = 2012; $result = Date::setExcelCalendar($unsupportedCalendar); self::assertFalse($result); } @@ -44,16 +55,20 @@ class DateTest extends TestCase * @dataProvider providerDateTimeExcelToTimestamp1900 * * @param mixed $expectedResult + * @param mixed $excelDateTimeValue */ - public function testDateTimeExcelToTimestamp1900($expectedResult, ...$args): void + public function testDateTimeExcelToTimestamp1900($expectedResult, $excelDateTimeValue): void { + if (is_numeric($expectedResult) && ($expectedResult > PHP_INT_MAX || $expectedResult < PHP_INT_MIN)) { + self::markTestSkipped('Test invalid on 32-bit system.'); + } Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - $result = Date::excelToTimestamp(...$args); + $result = Date::excelToTimestamp($excelDateTimeValue); self::assertEquals($expectedResult, $result); } - public function providerDateTimeExcelToTimestamp1900() + public function providerDateTimeExcelToTimestamp1900(): array { return require 'tests/data/Shared/Date/ExcelToTimestamp1900.php'; } @@ -62,16 +77,17 @@ class DateTest extends TestCase * @dataProvider providerDateTimeTimestampToExcel1900 * * @param mixed $expectedResult + * @param mixed $unixTimestamp */ - public function testDateTimeTimestampToExcel1900($expectedResult, ...$args): void + public function testDateTimeTimestampToExcel1900($expectedResult, $unixTimestamp): void { Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - $result = Date::timestampToExcel(...$args); + $result = Date::timestampToExcel($unixTimestamp); self::assertEqualsWithDelta($expectedResult, $result, 1E-5); } - public function providerDateTimeTimestampToExcel1900() + public function providerDateTimeTimestampToExcel1900(): array { return require 'tests/data/Shared/Date/TimestampToExcel1900.php'; } @@ -80,16 +96,17 @@ class DateTest extends TestCase * @dataProvider providerDateTimeDateTimeToExcel * * @param mixed $expectedResult + * @param mixed $dateTimeObject */ - public function testDateTimeDateTimeToExcel($expectedResult, ...$args): void + public function testDateTimeDateTimeToExcel($expectedResult, $dateTimeObject): void { Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - $result = Date::dateTimeToExcel(...$args); + $result = Date::dateTimeToExcel($dateTimeObject); self::assertEqualsWithDelta($expectedResult, $result, 1E-5); } - public function providerDateTimeDateTimeToExcel() + public function providerDateTimeDateTimeToExcel(): array { return require 'tests/data/Shared/Date/DateTimeToExcel.php'; } @@ -107,7 +124,7 @@ class DateTest extends TestCase self::assertEqualsWithDelta($expectedResult, $result, 1E-5); } - public function providerDateTimeFormattedPHPToExcel1900() + public function providerDateTimeFormattedPHPToExcel1900(): array { return require 'tests/data/Shared/Date/FormattedPHPToExcel1900.php'; } @@ -116,16 +133,20 @@ class DateTest extends TestCase * @dataProvider providerDateTimeExcelToTimestamp1904 * * @param mixed $expectedResult + * @param mixed $excelDateTimeValue */ - public function testDateTimeExcelToTimestamp1904($expectedResult, ...$args): void + public function testDateTimeExcelToTimestamp1904($expectedResult, $excelDateTimeValue): void { + if (is_numeric($expectedResult) && ($expectedResult > PHP_INT_MAX || $expectedResult < PHP_INT_MIN)) { + self::markTestSkipped('Test invalid on 32-bit system.'); + } Date::setExcelCalendar(Date::CALENDAR_MAC_1904); - $result = Date::excelToTimestamp(...$args); + $result = Date::excelToTimestamp($excelDateTimeValue); self::assertEquals($expectedResult, $result); } - public function providerDateTimeExcelToTimestamp1904() + public function providerDateTimeExcelToTimestamp1904(): array { return require 'tests/data/Shared/Date/ExcelToTimestamp1904.php'; } @@ -134,16 +155,17 @@ class DateTest extends TestCase * @dataProvider providerDateTimeTimestampToExcel1904 * * @param mixed $expectedResult + * @param mixed $unixTimestamp */ - public function testDateTimeTimestampToExcel1904($expectedResult, ...$args): void + public function testDateTimeTimestampToExcel1904($expectedResult, $unixTimestamp): void { Date::setExcelCalendar(Date::CALENDAR_MAC_1904); - $result = Date::timestampToExcel(...$args); + $result = Date::timestampToExcel($unixTimestamp); self::assertEqualsWithDelta($expectedResult, $result, 1E-5); } - public function providerDateTimeTimestampToExcel1904() + public function providerDateTimeTimestampToExcel1904(): array { return require 'tests/data/Shared/Date/TimestampToExcel1904.php'; } @@ -159,7 +181,7 @@ class DateTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerIsDateTimeFormatCode() + public function providerIsDateTimeFormatCode(): array { return require 'tests/data/Shared/Date/FormatCodes.php'; } @@ -168,16 +190,21 @@ class DateTest extends TestCase * @dataProvider providerDateTimeExcelToTimestamp1900Timezone * * @param mixed $expectedResult + * @param mixed $excelDateTimeValue + * @param mixed $timezone */ - public function testDateTimeExcelToTimestamp1900Timezone($expectedResult, ...$args): void + public function testDateTimeExcelToTimestamp1900Timezone($expectedResult, $excelDateTimeValue, $timezone): void { + if (is_numeric($expectedResult) && ($expectedResult > PHP_INT_MAX || $expectedResult < PHP_INT_MIN)) { + self::markTestSkipped('Test invalid on 32-bit system.'); + } Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - $result = Date::excelToTimestamp(...$args); + $result = Date::excelToTimestamp($excelDateTimeValue, $timezone); self::assertEquals($expectedResult, $result); } - public function providerDateTimeExcelToTimestamp1900Timezone() + public function providerDateTimeExcelToTimestamp1900Timezone(): array { return require 'tests/data/Shared/Date/ExcelToTimestamp1900Timezone.php'; } @@ -189,29 +216,37 @@ class DateTest extends TestCase self::assertTrue((bool) Date::stringToExcel('2019-02-28')); self::assertTrue((bool) Date::stringToExcel('2019-02-28 11:18')); self::assertFalse(Date::stringToExcel('2019-02-28 11:71')); + $date = Date::PHPToExcel('2020-01-01'); self::assertEquals(43831.0, $date); + $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->setCellValue('B1', 'x'); $val = $sheet->getCell('B1')->getValue(); self::assertFalse(Date::timestampToExcel($val)); + $cell = $sheet->getCell('A1'); self::assertNotNull($cell); + $cell->setValue($date); $sheet->getStyle('A1') ->getNumberFormat() ->setFormatCode(NumberFormat::FORMAT_DATE_DATETIME); self::assertTrue(null !== $cell && Date::isDateTime($cell)); + $cella2 = $sheet->getCell('A2'); self::assertNotNull($cella2); + $cella2->setValue('=A1+2'); $sheet->getStyle('A2') ->getNumberFormat() ->setFormatCode(NumberFormat::FORMAT_DATE_DATETIME); self::assertTrue(null !== $cella2 && Date::isDateTime($cella2)); + $cella3 = $sheet->getCell('A3'); self::assertNotNull($cella3); + $cella3->setValue('=A1+4'); $sheet->getStyle('A3') ->getNumberFormat() diff --git a/tests/PhpSpreadsheetTests/Shared/DrawingTest.php b/tests/PhpSpreadsheetTests/Shared/DrawingTest.php new file mode 100644 index 00000000..dc0ff631 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Shared/DrawingTest.php @@ -0,0 +1,80 @@ +setName($fontName); + $font->setSize($fontSize); + + $result = Drawing::pixelsToCellDimension($pixelSize, $font); + self::assertSame($expectedResult, $result); + } + + /** + * @dataProvider providerCellDimensionToPixels + */ + public function testCellDimensionToPixels( + int $expectedResult, + int $cellSize, + string $fontName, + int $fontSize + ): void { + $font = new Font(); + $font->setName($fontName); + $font->setSize($fontSize); + + $result = Drawing::cellDimensionToPixels($cellSize, $font); + self::assertSame($expectedResult, $result); + } + + public function providerPixelsToCellDimension(): array + { + return [ + [19.9951171875, 100, 'Arial', 7], + [14.2822265625, 100, 'Arial', 9], + [14.2822265625, 100, 'Arial', 11], + [13.092041015625, 100, 'Arial', 12], // approximation by extrapolating from Calibri 11 + [19.9951171875, 100, 'Calibri', 7], + [16.664341517857142, 100, 'Calibri', 9], + [14.2822265625, 100, 'Calibri', 11], + [13.092041015625, 100, 'Calibri', 12], // approximation by extrapolating from Calibri 11 + [19.9951171875, 100, 'Verdana', 7], + [12.5, 100, 'Verdana', 9], + [13.092041015625, 100, 'Verdana', 12], // approximation by extrapolating from Calibri 11 + [17.4560546875, 100, 'Wingdings', 9], // approximation by extrapolating from Calibri 11 + ]; + } + + public function providerCellDimensionToPixels(): array + { + return [ + [500, 100, 'Arial', 7], + [700, 100, 'Arial', 9], + [700, 100, 'Arial', 11], + [764, 100, 'Arial', 12], // approximation by extrapolating from Calibri 11 + [500, 100, 'Calibri', 7], + [600, 100, 'Calibri', 9], + [700, 100, 'Calibri', 11], + [764, 100, 'Calibri', 12], // approximation by extrapolating from Calibri 11 + [500, 100, 'Verdana', 7], + [800, 100, 'Verdana', 9], + [764, 100, 'Verdana', 12], // approximation by extrapolating from Calibri 11 + [573, 100, 'Wingdings', 9], // approximation by extrapolating from Calibri 11 + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Shared/FileTest.php b/tests/PhpSpreadsheetTests/Shared/FileTest.php index 6b9500f6..ddc54b5e 100644 --- a/tests/PhpSpreadsheetTests/Shared/FileTest.php +++ b/tests/PhpSpreadsheetTests/Shared/FileTest.php @@ -2,11 +2,32 @@ namespace PhpOffice\PhpSpreadsheetTests\Shared; +use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException; use PhpOffice\PhpSpreadsheet\Shared\File; use PHPUnit\Framework\TestCase; class FileTest extends TestCase { + /** @var bool */ + private $uploadFlag = false; + + /** @var string */ + private $tempfile = ''; + + protected function setUp(): void + { + $this->uploadFlag = File::getUseUploadTempDirectory(); + } + + protected function tearDown(): void + { + File::setUseUploadTempDirectory($this->uploadFlag); + if ($this->tempfile !== '') { + unlink($this->tempfile); + $this->tempfile = ''; + } + } + public function testGetUseUploadTempDirectory(): void { $expectedResult = false; @@ -21,12 +42,71 @@ class FileTest extends TestCase true, false, ]; + $temp = ini_get('upload_tmp_dir') ?: ''; + $badArray = ['', sys_get_temp_dir()]; foreach ($useUploadTempDirectoryValues as $useUploadTempDirectoryValue) { File::setUseUploadTempDirectory($useUploadTempDirectoryValue); $result = File::getUseUploadTempDirectory(); self::assertEquals($useUploadTempDirectoryValue, $result); + $result = File::sysGetTempDir(); + if (!$useUploadTempDirectoryValue || in_array($temp, $badArray, true)) { + self::assertSame(realpath(sys_get_temp_dir()), $result); + } else { + self::assertSame(realpath($temp), $result); + } } } + + public function testUploadTmpDir(): void + { + $temp = ini_get('upload_tmp_dir') ?: ''; + $badArray = ['', sys_get_temp_dir()]; + if (in_array($temp, $badArray, true)) { + self::markTestSkipped('upload_tmp_dir setting unusable for this test'); + } else { + File::setUseUploadTempDirectory(true); + $result = File::sysGetTempDir(); + self::assertSame(realpath($temp), $result); + } + } + + public function testNotExists(): void + { + $temp = File::temporaryFileName(); + file_put_contents($temp, ''); + File::assertFile($temp); + self::assertTrue(File::testFileNoThrow($temp)); + unlink($temp); + self::assertFalse(File::testFileNoThrow($temp)); + $this->expectException(ReaderException::class); + $this->expectExceptionMessage('does not exist'); + File::assertFile($temp); + } + + public function testNotReadable(): void + { + if (PHP_OS_FAMILY === 'Windows') { + self::markTestSkipped('chmod does not work reliably on Windows'); + } + $this->tempfile = $temp = File::temporaryFileName(); + file_put_contents($temp, ''); + chmod($temp, 0070); + self::assertFalse(File::testFileNoThrow($temp)); + $this->expectException(ReaderException::class); + $this->expectExceptionMessage('for reading'); + File::assertFile($temp); + } + + public function testZip(): void + { + $temp = 'samples/templates/26template.xlsx'; + File::assertFile($temp, 'xl/workbook.xml'); + self::assertTrue(File::testFileNoThrow($temp, 'xl/workbook.xml')); + self::assertFalse(File::testFileNoThrow($temp, 'xl/xworkbook.xml')); + $this->expectException(ReaderException::class); + $this->expectExceptionMessage('Could not find zip member'); + File::assertFile($temp, 'xl/xworkbook.xml'); + } } diff --git a/tests/PhpSpreadsheetTests/Shared/FontTest.php b/tests/PhpSpreadsheetTests/Shared/FontTest.php index 5eb70852..9bc1d18a 100644 --- a/tests/PhpSpreadsheetTests/Shared/FontTest.php +++ b/tests/PhpSpreadsheetTests/Shared/FontTest.php @@ -3,6 +3,7 @@ namespace PhpOffice\PhpSpreadsheetTests\Shared; use PhpOffice\PhpSpreadsheet\Shared\Font; +use PhpOffice\PhpSpreadsheet\Style\Font as StyleFont; use PHPUnit\Framework\TestCase; class FontTest extends TestCase @@ -40,14 +41,15 @@ class FontTest extends TestCase * @dataProvider providerFontSizeToPixels * * @param mixed $expectedResult + * @param mixed $size */ - public function testFontSizeToPixels($expectedResult, ...$args): void + public function testFontSizeToPixels($expectedResult, $size): void { - $result = Font::fontSizeToPixels(...$args); + $result = Font::fontSizeToPixels($size); self::assertEquals($expectedResult, $result); } - public function providerFontSizeToPixels() + public function providerFontSizeToPixels(): array { return require 'tests/data/Shared/FontSizeToPixels.php'; } @@ -56,14 +58,15 @@ class FontTest extends TestCase * @dataProvider providerInchSizeToPixels * * @param mixed $expectedResult + * @param mixed $size */ - public function testInchSizeToPixels($expectedResult, ...$args): void + public function testInchSizeToPixels($expectedResult, $size): void { - $result = Font::inchSizeToPixels(...$args); + $result = Font::inchSizeToPixels($size); self::assertEquals($expectedResult, $result); } - public function providerInchSizeToPixels() + public function providerInchSizeToPixels(): array { return require 'tests/data/Shared/InchSizeToPixels.php'; } @@ -72,15 +75,28 @@ class FontTest extends TestCase * @dataProvider providerCentimeterSizeToPixels * * @param mixed $expectedResult + * @param mixed $size */ - public function testCentimeterSizeToPixels($expectedResult, ...$args): void + public function testCentimeterSizeToPixels($expectedResult, $size): void { - $result = Font::centimeterSizeToPixels(...$args); + $result = Font::centimeterSizeToPixels($size); self::assertEquals($expectedResult, $result); } - public function providerCentimeterSizeToPixels() + public function providerCentimeterSizeToPixels(): array { return require 'tests/data/Shared/CentimeterSizeToPixels.php'; } + + public function testVerdanaRotation(): void + { + $font = new StyleFont(); + $font->setName('Verdana')->setSize(10); + $width = Font::getTextWidthPixelsApprox('n', $font, 0); + self::assertEquals(8, $width); + $width = Font::getTextWidthPixelsApprox('n', $font, 45); + self::assertEquals(7, $width); + $width = Font::getTextWidthPixelsApprox('n', $font, -165); + self::assertEquals(4, $width); + } } diff --git a/tests/PhpSpreadsheetTests/Shared/PasswordHasherTest.php b/tests/PhpSpreadsheetTests/Shared/PasswordHasherTest.php index 0d286725..4b7923d8 100644 --- a/tests/PhpSpreadsheetTests/Shared/PasswordHasherTest.php +++ b/tests/PhpSpreadsheetTests/Shared/PasswordHasherTest.php @@ -2,6 +2,7 @@ namespace PhpOffice\PhpSpreadsheetTests\Shared; +use PhpOffice\PhpSpreadsheet\Exception as SpException; use PhpOffice\PhpSpreadsheet\Shared\PasswordHasher; use PHPUnit\Framework\TestCase; @@ -14,11 +15,14 @@ class PasswordHasherTest extends TestCase */ public function testHashPassword($expectedResult, ...$args): void { + if ($expectedResult === 'exception') { + $this->expectException(SpException::class); + } $result = PasswordHasher::hashPassword(...$args); self::assertEquals($expectedResult, $result); } - public function providerHashPassword() + public function providerHashPassword(): array { return require 'tests/data/Shared/PasswordHashes.php'; } diff --git a/tests/PhpSpreadsheetTests/Shared/PasswordReloadTest.php b/tests/PhpSpreadsheetTests/Shared/PasswordReloadTest.php new file mode 100644 index 00000000..b6c28b17 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Shared/PasswordReloadTest.php @@ -0,0 +1,51 @@ +getActiveSheet(); + $sheet->getCell('A1')->setValue(1); + $protection = $sheet->getProtection(); + $protection->setAlgorithm($algorithm); + $protection->setPassword($password); + $protection->setSheet(true); + + $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format); + $resheet = $reloadedSpreadsheet->getActiveSheet(); + $reprot = $resheet->getProtection(); + $repassword = $reprot->getPassword(); + $hash = ''; + if ($supported) { + $readAlgorithm = $reprot->getAlgorithm(); + self::assertSame($algorithm, $readAlgorithm); + $salt = $reprot->getSalt(); + $spin = $reprot->getSpinCount(); + $hash = PasswordHasher::hashPassword($password, $readAlgorithm, $salt, $spin); + } + self::assertSame($repassword, $hash); + $spreadsheet->disconnectWorksheets(); + $reloadedSpreadsheet->disconnectWorksheets(); + } + + public function providerPasswords(): array + { + return [ + 'Xls basic algorithm' => ['Xls', ''], + 'Xls cannot use SHA512' => ['Xls', 'SHA-512', false], + 'Xlsx basic algorithm' => ['Xlsx', ''], + 'Xlsx can use SHA512' => ['Xlsx', 'SHA-512'], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Shared/StringHelperTest.php b/tests/PhpSpreadsheetTests/Shared/StringHelperTest.php index 41ed0b21..92f197a2 100644 --- a/tests/PhpSpreadsheetTests/Shared/StringHelperTest.php +++ b/tests/PhpSpreadsheetTests/Shared/StringHelperTest.php @@ -7,10 +7,19 @@ use PHPUnit\Framework\TestCase; class StringHelperTest extends TestCase { + /** + * @var string + */ private $currencyCode; + /** + * @var string + */ private $decimalSeparator; + /** + * @var string + */ private $thousandsSeparator; protected function setUp(): void diff --git a/tests/PhpSpreadsheetTests/Shared/TimeZoneTest.php b/tests/PhpSpreadsheetTests/Shared/TimeZoneTest.php index ff38badf..0efdc05f 100644 --- a/tests/PhpSpreadsheetTests/Shared/TimeZoneTest.php +++ b/tests/PhpSpreadsheetTests/Shared/TimeZoneTest.php @@ -3,20 +3,27 @@ namespace PhpOffice\PhpSpreadsheetTests\Shared; use DateTime; +use DateTimeZone; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\TimeZone; use PHPUnit\Framework\TestCase; class TimeZoneTest extends TestCase { + /** + * @var string + */ private $tztimezone; + /** + * @var null|DateTimeZone + */ private $dttimezone; protected function setUp(): void { $this->tztimezone = TimeZone::getTimeZone(); - $this->dttimezone = Date::getDefaultTimeZone(); + $this->dttimezone = Date::getDefaultTimeZoneOrNull(); } protected function tearDown(): void @@ -65,24 +72,32 @@ class TimeZoneTest extends TestCase { $this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class); $dtobj = DateTime::createFromFormat('Y-m-d H:i:s', '2008-09-22 00:00:00'); - $tstmp = $dtobj->getTimestamp(); - $unsupportedTimeZone = 'XEtc/GMT+10'; - TimeZone::getTimeZoneAdjustment($unsupportedTimeZone, $tstmp); + if ($dtobj === false) { + self::fail('DateTime createFromFormat failed'); + } else { + $tstmp = $dtobj->getTimestamp(); + $unsupportedTimeZone = 'XEtc/GMT+10'; + TimeZone::getTimeZoneAdjustment($unsupportedTimeZone, $tstmp); + } } public function testTimeZoneAdjustments(): void { $dtobj = DateTime::createFromFormat('Y-m-d H:i:s', '2008-01-01 00:00:00'); - $tstmp = $dtobj->getTimestamp(); - $supportedTimeZone = 'UTC'; - $adj = TimeZone::getTimeZoneAdjustment($supportedTimeZone, $tstmp); - self::assertEquals(0, $adj); - $supportedTimeZone = 'America/Toronto'; - $adj = TimeZone::getTimeZoneAdjustment($supportedTimeZone, $tstmp); - self::assertEquals(-18000, $adj); - $supportedTimeZone = 'America/Chicago'; - TimeZone::setTimeZone($supportedTimeZone); - $adj = TimeZone::getTimeZoneAdjustment(null, $tstmp); - self::assertEquals(-21600, $adj); + if ($dtobj === false) { + self::fail('DateTime createFromFormat failed'); + } else { + $tstmp = $dtobj->getTimestamp(); + $supportedTimeZone = 'UTC'; + $adj = TimeZone::getTimeZoneAdjustment($supportedTimeZone, $tstmp); + self::assertEquals(0, $adj); + $supportedTimeZone = 'America/Toronto'; + $adj = TimeZone::getTimeZoneAdjustment($supportedTimeZone, $tstmp); + self::assertEquals(-18000, $adj); + $supportedTimeZone = 'America/Chicago'; + TimeZone::setTimeZone($supportedTimeZone); + $adj = TimeZone::getTimeZoneAdjustment(null, $tstmp); + self::assertEquals(-21600, $adj); + } } } diff --git a/tests/PhpSpreadsheetTests/Shared/Trend/ExponentialBestFitTest.php b/tests/PhpSpreadsheetTests/Shared/Trend/ExponentialBestFitTest.php new file mode 100644 index 00000000..a12a438c --- /dev/null +++ b/tests/PhpSpreadsheetTests/Shared/Trend/ExponentialBestFitTest.php @@ -0,0 +1,49 @@ +getSlope(1); + self::assertEquals($expectedSlope[0], $slope); + $slope = $bestFit->getSlope(); + self::assertEquals($expectedSlope[1], $slope); + $intersect = $bestFit->getIntersect(1); + self::assertEquals($expectedIntersect[0], $intersect); + $intersect = $bestFit->getIntersect(); + self::assertEquals($expectedIntersect[1], $intersect); + + $equation = $bestFit->getEquation(2); + self::assertEquals($expectedEquation, $equation); + + self::assertSame($expectedGoodnessOfFit[0], $bestFit->getGoodnessOfFit(6)); + self::assertSame($expectedGoodnessOfFit[1], $bestFit->getGoodnessOfFit()); + } + + public function providerExponentialBestFit(): array + { + return require 'tests/data/Shared/Trend/ExponentialBestFit.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/Shared/Trend/LinearBestFitTest.php b/tests/PhpSpreadsheetTests/Shared/Trend/LinearBestFitTest.php new file mode 100644 index 00000000..9ada87a5 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Shared/Trend/LinearBestFitTest.php @@ -0,0 +1,49 @@ +getSlope(1); + self::assertEquals($expectedSlope[0], $slope); + $slope = $bestFit->getSlope(); + self::assertEquals($expectedSlope[1], $slope); + $intersect = $bestFit->getIntersect(1); + self::assertEquals($expectedIntersect[0], $intersect); + $intersect = $bestFit->getIntersect(); + self::assertEquals($expectedIntersect[1], $intersect); + + $equation = $bestFit->getEquation(2); + self::assertEquals($expectedEquation, $equation); + + self::assertSame($expectedGoodnessOfFit[0], $bestFit->getGoodnessOfFit(6)); + self::assertSame($expectedGoodnessOfFit[1], $bestFit->getGoodnessOfFit()); + } + + public function providerLinearBestFit(): array + { + return require 'tests/data/Shared/Trend/LinearBestFit.php'; + } +} diff --git a/tests/PhpSpreadsheetTests/SpreadsheetTest.php b/tests/PhpSpreadsheetTests/SpreadsheetTest.php index 129bea7c..7f159d67 100644 --- a/tests/PhpSpreadsheetTests/SpreadsheetTest.php +++ b/tests/PhpSpreadsheetTests/SpreadsheetTest.php @@ -26,10 +26,7 @@ class SpreadsheetTest extends TestCase $this->object->addSheet($sheet); } - /** - * @return array - */ - public function dataProviderForSheetNames() + public function dataProviderForSheetNames(): array { $array = [ [0, 'someSheet1'], @@ -44,9 +41,6 @@ class SpreadsheetTest extends TestCase } /** - * @param $index - * @param $sheetName - * * @dataProvider dataProviderForSheetNames */ public function testGetSheetByName($index, $sheetName): void diff --git a/tests/PhpSpreadsheetTests/Style/ColorTest.php b/tests/PhpSpreadsheetTests/Style/ColorTest.php index ec86eb5e..9d0da3a2 100644 --- a/tests/PhpSpreadsheetTests/Style/ColorTest.php +++ b/tests/PhpSpreadsheetTests/Style/ColorTest.php @@ -78,14 +78,15 @@ class ColorTest extends TestCase * @dataProvider providerColorGetRed * * @param mixed $expectedResult + * @param mixed $color */ - public function testGetRed($expectedResult, ...$args): void + public function testGetRed($expectedResult, $color, ...$args): void { - $result = Color::getRed(...$args); + $result = Color::getRed($color, ...$args); self::assertEquals($expectedResult, $result); } - public function providerColorGetRed() + public function providerColorGetRed(): array { return require 'tests/data/Style/Color/ColorGetRed.php'; } @@ -94,14 +95,15 @@ class ColorTest extends TestCase * @dataProvider providerColorGetGreen * * @param mixed $expectedResult + * @param mixed $color */ - public function testGetGreen($expectedResult, ...$args): void + public function testGetGreen($expectedResult, $color, ...$args): void { - $result = Color::getGreen(...$args); + $result = Color::getGreen($color, ...$args); self::assertEquals($expectedResult, $result); } - public function providerColorGetGreen() + public function providerColorGetGreen(): array { return require 'tests/data/Style/Color/ColorGetGreen.php'; } @@ -110,14 +112,15 @@ class ColorTest extends TestCase * @dataProvider providerColorGetBlue * * @param mixed $expectedResult + * @param mixed $color */ - public function testGetBlue($expectedResult, ...$args): void + public function testGetBlue($expectedResult, $color, ...$args): void { - $result = Color::getBlue(...$args); + $result = Color::getBlue($color, ...$args); self::assertEquals($expectedResult, $result); } - public function providerColorGetBlue() + public function providerColorGetBlue(): array { return require 'tests/data/Style/Color/ColorGetBlue.php'; } @@ -133,7 +136,7 @@ class ColorTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerColorChangeBrightness() + public function providerColorChangeBrightness(): array { return require 'tests/data/Style/Color/ColorChangeBrightness.php'; } diff --git a/tests/PhpSpreadsheetTests/Style/FontTest.php b/tests/PhpSpreadsheetTests/Style/FontTest.php index c014a4b6..a6843c10 100644 --- a/tests/PhpSpreadsheetTests/Style/FontTest.php +++ b/tests/PhpSpreadsheetTests/Style/FontTest.php @@ -39,4 +39,36 @@ class FontTest extends TestCase self::assertTrue($font->getSuperscript()); self::assertFalse($font->getSubscript(), 'False remains unchanged'); } + + public function testSize(): void + { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $cell = $sheet->getCell('A1'); + $cell->setValue('Cell A1'); + $font = $cell->getStyle()->getFont(); + + self::assertEquals(11, $font->getSize(), 'The default is 11'); + + $font->setSize(12); + self::assertEquals(12, $font->getSize(), 'Accepted new font size'); + + $invalidFontSizeValues = [ + '', + false, + true, + 'non_numeric_string', + '-1.0', + -1.0, + 0, + [], + (object) [], + null, + ]; + foreach ($invalidFontSizeValues as $invalidFontSizeValue) { + $font->setSize(12); + $font->setSize($invalidFontSizeValue); + self::assertEquals(10, $font->getSize(), 'Set to 10 after trying to set an invalid value.'); + } + } } diff --git a/tests/PhpSpreadsheetTests/Style/NumberFormatTest.php b/tests/PhpSpreadsheetTests/Style/NumberFormatTest.php index 6bf7db04..e386b292 100644 --- a/tests/PhpSpreadsheetTests/Style/NumberFormatTest.php +++ b/tests/PhpSpreadsheetTests/Style/NumberFormatTest.php @@ -8,10 +8,19 @@ use PHPUnit\Framework\TestCase; class NumberFormatTest extends TestCase { + /** + * @var string + */ private $currencyCode; + /** + * @var string + */ private $decimalSeparator; + /** + * @var string + */ private $thousandsSeparator; protected function setUp(): void @@ -41,7 +50,7 @@ class NumberFormatTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerNumberFormat() + public function providerNumberFormat(): array { return require 'tests/data/Style/NumberFormat.php'; } @@ -57,7 +66,7 @@ class NumberFormatTest extends TestCase self::assertEquals($expectedResult, $result); } - public function providerNumberFormatDates() + public function providerNumberFormatDates(): array { return require 'tests/data/Style/NumberFormatDates.php'; } diff --git a/tests/PhpSpreadsheetTests/Style/StyleTest.php b/tests/PhpSpreadsheetTests/Style/StyleTest.php index 6f157709..3d20b044 100644 --- a/tests/PhpSpreadsheetTests/Style/StyleTest.php +++ b/tests/PhpSpreadsheetTests/Style/StyleTest.php @@ -55,6 +55,29 @@ class StyleTest extends TestCase self::assertFalse($sheet->getStyle('C3')->getFont()->getItalic()); } + public function testStyleIsReused(): void + { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $styleArray = [ + 'font' => [ + 'italic' => true, + ], + ]; + + $sheet->getStyle('A1')->getFont()->setBold(true); + $sheet->getStyle('A2')->getFont()->setBold(true); + $sheet->getStyle('A3')->getFont()->setBold(true); + $sheet->getStyle('A3')->getFont()->setItalic(true); + + $sheet->getStyle('A')->applyFromArray($styleArray); + + self::assertCount(4, $spreadsheet->getCellXfCollection()); + $spreadsheet->garbageCollect(); + + self::assertCount(3, $spreadsheet->getCellXfCollection()); + } + public function testStyleRow(): void { $spreadsheet = new Spreadsheet(); diff --git a/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterAverageTop10Test.php b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterAverageTop10Test.php new file mode 100644 index 00000000..79358823 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterAverageTop10Test.php @@ -0,0 +1,165 @@ +getSheet(); + $sheet->getCell('A1')->setValue('Header'); + $sheet->getCell('A2')->setValue(1); + $sheet->getCell('A3')->setValue(3); + $sheet->getCell('A4')->setValue(5); + $sheet->getCell('A5')->setValue(7); + $sheet->getCell('A6')->setValue(9); + $sheet->getCell('A7')->setValue(2); + $sheet->getCell('A8')->setValue(4); + $sheet->getCell('A9')->setValue(6); + $sheet->getCell('A10')->setValue(8); + $this->maxRow = 10; + + return $sheet; + } + + public function providerAverage(): array + { + return [ + [[5, 6, 9, 10], Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE], + [[2, 3, 7, 8], Rule::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE], + ]; + } + + /** + * @dataProvider providerAverage + */ + public function testAboveAverage(array $expectedVisible, string $rule): void + { + $sheet = $this->initSheet(); + $maxRow = $this->maxRow; + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange("A1:A$maxRow"); + $columnFilter = $autoFilter->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + '', + $rule + ) + ->setRuleType(Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER); + + self::assertEquals($expectedVisible, $this->getVisible()); + } + + public function providerTop10(): array + { + return [ + [[6, 10], Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE, Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP, 2], + [[2, 3, 7], Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE, Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM, 3], + [[6], Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT, Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP, 10], + [[2, 3, 7], Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT, Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM, 40], + ]; + } + + /** + * @dataProvider providerTop10 + */ + public function testTop10(array $expectedVisible, string $rule, string $ruleType, int $count): void + { + $sheet = $this->initSheet(); + $maxRow = $this->maxRow; + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange("A1:A$maxRow"); + $columnFilter = $autoFilter->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER); + $columnFilter->createRule() + ->setRule( + $rule, + $count, + $ruleType + ) + ->setRuleType(Rule::AUTOFILTER_RULETYPE_TOPTENFILTER); + + self::assertEquals($expectedVisible, $this->getVisible()); + } + + public function initsheetTies(): Worksheet + { + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue('Header'); + $sheet->getCell('A2')->setValue(1); + $sheet->getCell('A3')->setValue(3); + $sheet->getCell('A4')->setValue(3); + $sheet->getCell('A5')->setValue(7); + $sheet->getCell('A6')->setValue(9); + $sheet->getCell('A7')->setValue(4); + $sheet->getCell('A8')->setValue(4); + $sheet->getCell('A9')->setValue(8); + $sheet->getCell('A10')->setValue(8); + $this->maxRow = 10; + + return $sheet; + } + + public function providerTop10Ties(): array + { + return [ + [[2, 3, 4], Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE, Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM, 2], + [[2], Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE, Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM, 1], + [[5, 6, 7, 8, 9, 10], Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE, Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP, 5], + [[6], Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE, Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP, 1], + [[2, 3, 4], Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT, Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM, 25], + [[6, 9, 10], Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT, Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP, 25], + ]; + } + + /** + * @dataProvider providerTop10Ties + */ + public function testTop10Ties(array $expectedVisible, string $rule, string $ruleType, int $count): void + { + $sheet = $this->initSheetTies(); + $maxRow = $this->maxRow; + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange("A1:A$maxRow"); + $columnFilter = $autoFilter->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER); + $columnFilter->createRule() + ->setRule( + $rule, + $count, + $ruleType + ) + ->setRuleType(Rule::AUTOFILTER_RULETYPE_TOPTENFILTER); + + self::assertEquals($expectedVisible, $this->getVisible()); + } + + public function testTop10Exceeds500(): void + { + $sheet = $this->getSheet(); + $sheet->getCell('A1')->setValue('Heading'); + for ($row = 2; $row < 602; ++$row) { + $sheet->getCell("A$row")->setValue($row); + } + $maxRow = $this->maxRow = 601; + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange("A1:A$maxRow"); + $columnFilter = $autoFilter->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE, + 550, + Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP + ) + ->setRuleType(Rule::AUTOFILTER_RULETYPE_TOPTENFILTER); + + self::assertCount(500, $this->getVisible(), 'Top10 Filter limited to 500 items plus ties'); + } +} diff --git a/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterCustomTextTest.php b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterCustomTextTest.php new file mode 100644 index 00000000..643ffc0f --- /dev/null +++ b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterCustomTextTest.php @@ -0,0 +1,105 @@ +getSheet(); + $sheet->getCell('A1')->setValue('Header'); + $sheet->getCell('A2')->setValue('abc'); + $sheet->getCell('A3')->setValue('cba'); + $sheet->getCell('A4')->setValue('cab'); + // nothing in cell A5 + $sheet->getCell('A6')->setValue('c*b'); + $sheet->getCell('A7')->setValue('c?b'); + $sheet->getCell('A8')->setValue('a'); + $sheet->getCell('A9')->setValue('zzbc'); + $sheet->getCell('A10')->setValue('zzbcd'); + $sheet->getCell('A11')->setValue('~pqr'); + $sheet->getCell('A12')->setValue('pqr~'); + $this->maxRow = 12; + + return $sheet; + } + + public function providerCustomText(): array + { + return [ + 'begins with a' => [[2, 8], 'a*'], + 'ends with b' => [[4, 6, 7], '*b'], + 'contains c' => [[2, 3, 4, 6, 7, 9, 10], '*c*'], + 'empty' => [[5], ''], + 'contains asterisk' => [[6], '*~**'], + 'contains question mark' => [[7], '*~?*'], + 'c followed by character followed by b' => [[4, 6, 7], 'c?b'], + 'one character followed by bc' => [[2], '?bc'], + 'two characters followed by bc' => [[9], '??bc'], + 'starts with z ends with c' => [[9], 'z*c'], + 'starts with tilde' => [[11], '~~*'], + 'contains tilde' => [[11, 12], '*~~*'], + ]; + } + + /** + * @dataProvider providerCustomText + */ + public function testCustomTest(array $expectedVisible, string $pattern): void + { + $sheet = $this->initSheet(); + $maxRow = $this->maxRow; + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange("A1:A$maxRow"); + $columnFilter = $autoFilter->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + $pattern + ) + ->setRuleType(Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER); + + self::assertEquals($expectedVisible, $this->getVisible()); + } + + public function testCustomTestNotEqual(): void + { + $sheet = $this->initSheet(); + $maxRow = $this->maxRow; + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange("A1:A$maxRow"); + $columnFilter = $autoFilter->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL, + '' + ) + ->setRuleType(Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER); + + self::assertEquals([2, 3, 4, 6, 7, 8, 9, 10, 11, 12], $this->getVisible()); + } + + public function testCustomTestGreaterThan(): void + { + $sheet = $this->initSheet(); + $maxRow = $this->maxRow; + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange("A1:A$maxRow"); + $columnFilter = $autoFilter->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN, + '' + ) + ->setRuleType(Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER); + + self::assertEquals([2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], $this->getVisible()); + } +} diff --git a/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterMonthTest.php b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterMonthTest.php new file mode 100644 index 00000000..e17ccce9 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterMonthTest.php @@ -0,0 +1,86 @@ +getCell('A1')->setValue('Date'); + $sheet->getCell('A2')->setValue('=TODAY()'); + // cache result for consistency in later calculations + $sheet->getCell('A2')->getCalculatedValue(); + $sheet->getCell('A3')->setValue('=DATE(YEAR(A2), MONTH(A2), 1)'); + if ($startMonth === 12) { + $sheet->getCell('A4')->setValue('=DATE(YEAR(A2) + 1, 1, 1)'); + $sheet->getCell('A5')->setValue('=DATE(YEAR(A2) + 1, 2, 1)'); + } elseif ($startMonth === 11) { + $sheet->getCell('A4')->setValue('=DATE(YEAR(A2), MONTH(A2) + 1, 1)'); + $sheet->getCell('A5')->setValue('=DATE(YEAR(A2) + 1, 1, 1)'); + } else { + $sheet->getCell('A4')->setValue('=DATE(YEAR(A2), MONTH(A2) + 1, 1)'); + $sheet->getCell('A5')->setValue('=DATE(YEAR(A2), MONTH(A2) + 2, 1)'); + } + if ($startMonth === 1) { + $sheet->getCell('A6')->setValue('=DATE(YEAR(A2) - 1, 12, 1)'); + $sheet->getCell('A7')->setValue('=DATE(YEAR(A2) - 1, 10, 1)'); + } elseif ($startMonth === 2) { + $sheet->getCell('A6')->setValue('=DATE(YEAR(A2), 1, 1)'); + $sheet->getCell('A7')->setValue('=DATE(YEAR(A2) - 1, 12, 1)'); + } else { + $sheet->getCell('A6')->setValue('=DATE(YEAR(A2), MONTH(A2) - 1, 1)'); + $sheet->getCell('A7')->setValue('=DATE(YEAR(A2), MONTH(A2) - 2, 1)'); + } + $sheet->getCell('A8')->setValue('=DATE(YEAR(A2) + 1, MONTH(A2), 1)'); + $sheet->getCell('A9')->setValue('=DATE(YEAR(A2) - 1, MONTH(A2), 1)'); + $this->maxRow = 9; + } + + /** + * @dataProvider providerMonth + */ + public function testMonths(array $expectedVisible, string $rule): void + { + // Loop to avoid rare edge case where first calculation + // and second do not take place in same day. + do { + $sheet = $this->getSpreadsheet()->createSheet(); + $dtStart = new DateTimeImmutable(); + $startDay = (int) $dtStart->format('d'); + $startMonth = (int) $dtStart->format('m'); + $this->setCells($sheet, $startMonth); + + $maxRow = $this->maxRow; + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange("A1:A$maxRow"); + $columnFilter = $autoFilter->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + '', + $rule + ) + ->setRuleType(Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER); + $autoFilter->showHideRows(); + $dtEnd = new DateTimeImmutable(); + $endDay = (int) $dtEnd->format('d'); + } while ($startDay !== $endDay); + + self::assertEquals($expectedVisible, $this->getVisibleSheet($sheet)); + } +} diff --git a/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterQuarterTest.php b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterQuarterTest.php new file mode 100644 index 00000000..370158a0 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterQuarterTest.php @@ -0,0 +1,69 @@ +getCell('A1')->setValue('Date'); + $sheet->getCell('A2')->setValue('=TODAY()'); + // cache result for consistency in later calculations + $sheet->getCell('A2')->getCalculatedValue(); + $sheet->getCell('A3')->setValue('=DATE(YEAR(A2), MONTH(A2), 1)'); + $sheet->getCell('A4')->setValue('=DATE(YEAR(A2), MONTH(A2) + 3, 1)'); + $sheet->getCell('A5')->setValue('=DATE(YEAR(A2), MONTH(A2) + 6, 1)'); + $sheet->getCell('A6')->setValue('=DATE(YEAR(A2), MONTH(A2) - 3, 1)'); + $sheet->getCell('A7')->setValue('=DATE(YEAR(A2), MONTH(A2) - 6, 1)'); + $sheet->getCell('A8')->setValue('=DATE(YEAR(A2) + 1, MONTH(A2), 1)'); + $sheet->getCell('A9')->setValue('=DATE(YEAR(A2) - 1, MONTH(A2), 1)'); + $this->maxRow = 9; + } + + /** + * @dataProvider providerQuarter + */ + public function testQuarters(array $expectedVisible, string $rule): void + { + // Loop to avoid rare edge case where first calculation + // and second do not take place in same day. + do { + $sheet = $this->getSpreadsheet()->createSheet(); + $dtStart = new DateTimeImmutable(); + $startDay = (int) $dtStart->format('d'); + $this->setCells($sheet); + + $maxRow = $this->maxRow; + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange("A1:A$maxRow"); + $columnFilter = $autoFilter->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + '', + $rule + ) + ->setRuleType(Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER); + $autoFilter->showHideRows(); + $dtEnd = new DateTimeImmutable(); + $endDay = (int) $dtEnd->format('d'); + } while ($startDay !== $endDay); + + self::assertEquals($expectedVisible, $this->getVisibleSheet($sheet)); + } +} diff --git a/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterTest.php b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterTest.php new file mode 100644 index 00000000..28bbbb87 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterTest.php @@ -0,0 +1,443 @@ +getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + + // magic __toString should return the active autofilter range + $result = (string) $autoFilter; + self::assertEquals($expectedResult, $result); + } + + public function testGetParent(): void + { + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + $result = $autoFilter->getParent(); + self::assertSame($sheet, $result); + } + + public function testSetParent(): void + { + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + $spreadsheet = $this->getSpreadsheet(); + $sheet2 = $spreadsheet->createSheet(); + // Setters return the instance to implement the fluent interface + $result = $autoFilter->setParent($sheet2); + self::assertInstanceOf(AutoFilter::class, $result); + } + + public function testGetRange(): void + { + $expectedResult = self::INITIAL_RANGE; + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + + // Result should be the active autofilter range + $result = $autoFilter->getRange(); + self::assertEquals($expectedResult, $result); + } + + public function testSetRange(): void + { + $sheet = $this->getSheet(); + $title = $sheet->getTitle(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + $ranges = [ + 'G1:J512' => "$title!G1:J512", + 'K1:N20' => 'K1:N20', + ]; + + foreach ($ranges as $actualRange => $fullRange) { + // Setters return the instance to implement the fluent interface + $result = $autoFilter->setRange($fullRange); + self::assertInstanceOf(AutoFilter::class, $result); + + // Result should be the new autofilter range + $result = $autoFilter->getRange(); + self::assertEquals($actualRange, $result); + } + } + + public function testClearRange(): void + { + $expectedResult = ''; + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + + // Setters return the instance to implement the fluent interface + $result = $autoFilter->setRange(''); + self::assertInstanceOf(AutoFilter::class, $result); + + // Result should be a clear range + $result = $autoFilter->getRange(); + self::assertEquals($expectedResult, $result); + } + + public function testSetRangeInvalidRange(): void + { + $this->expectException(PhpSpreadsheetException::class); + + $expectedResult = 'A1'; + + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange($expectedResult); + } + + public function testGetColumnsEmpty(): void + { + // There should be no columns yet defined + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $result = $autoFilter->getColumns(); + self::assertIsArray($result); + self::assertCount(0, $result); + } + + public function testGetColumnOffset(): void + { + $columnIndexes = [ + 'H' => 0, + 'K' => 3, + 'M' => 5, + ]; + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + + // If we request a specific column by its column ID, we should get an + // integer returned representing the column offset within the range + foreach ($columnIndexes as $columnIndex => $columnOffset) { + $result = $autoFilter->getColumnOffset($columnIndex); + self::assertEquals($columnOffset, $result); + } + } + + public function testGetInvalidColumnOffset(): void + { + $this->expectException(PhpSpreadsheetException::class); + + $invalidColumn = 'G'; + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + + $autoFilter->getColumnOffset($invalidColumn); + } + + public function testSetColumnWithString(): void + { + $expectedResult = 'L'; + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + + // Setters return the instance to implement the fluent interface + $result = $autoFilter->setColumn($expectedResult); + self::assertInstanceOf(AutoFilter::class, $result); + + $result = $autoFilter->getColumns(); + // Result should be an array of \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\AutoFilter\Column + // objects for each column we set indexed by the column ID + self::assertIsArray($result); + self::assertCount(1, $result); + self::assertArrayHasKey($expectedResult, $result); + self::assertInstanceOf(Column::class, $result[$expectedResult]); + } + + public function testSetInvalidColumnWithString(): void + { + $this->expectException(PhpSpreadsheetException::class); + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + + $invalidColumn = 'A'; + + $autoFilter->setColumn($invalidColumn); + } + + public function testSetColumnWithColumnObject(): void + { + $expectedResult = 'M'; + $columnObject = new Column($expectedResult); + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + + // Setters return the instance to implement the fluent interface + $result = $autoFilter->setColumn($columnObject); + self::assertInstanceOf(AutoFilter::class, $result); + + $result = $autoFilter->getColumns(); + // Result should be an array of \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\AutoFilter\Column + // objects for each column we set indexed by the column ID + self::assertIsArray($result); + self::assertCount(1, $result); + self::assertArrayHasKey($expectedResult, $result); + self::assertInstanceOf(Column::class, $result[$expectedResult]); + } + + public function testSetInvalidColumnWithObject(): void + { + $this->expectException(PhpSpreadsheetException::class); + + $invalidColumn = 'E'; + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + $autoFilter->setColumn($invalidColumn); + } + + public function testSetColumnWithInvalidDataType(): void + { + $this->expectException(PhpSpreadsheetException::class); + + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + $invalidColumn = 123.456; + // @phpstan-ignore-next-line + $autoFilter->setColumn($invalidColumn); + } + + public function testGetColumns(): void + { + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + + $columnIndexes = ['L', 'M']; + + foreach ($columnIndexes as $columnIndex) { + $autoFilter->setColumn($columnIndex); + } + + $result = $autoFilter->getColumns(); + // Result should be an array of \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\AutoFilter\Column + // objects for each column we set indexed by the column ID + self::assertIsArray($result); + self::assertCount(count($columnIndexes), $result); + foreach ($columnIndexes as $columnIndex) { + self::assertArrayHasKey($columnIndex, $result); + self::assertInstanceOf(Column::class, $result[$columnIndex]); + } + + $autoFilter->setRange(''); + self::assertCount(0, $autoFilter->getColumns()); + self::assertSame('', $autoFilter->getRange()); + } + + public function testGetColumn(): void + { + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + + $columnIndexes = ['L', 'M']; + + foreach ($columnIndexes as $columnIndex) { + $autoFilter->setColumn($columnIndex); + } + + // If we request a specific column by its column ID, we should + // get a \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\AutoFilter\Column object returned + foreach ($columnIndexes as $columnIndex) { + $result = $autoFilter->getColumn($columnIndex); + self::assertInstanceOf(Column::class, $result); + } + } + + public function testGetColumnByOffset(): void + { + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + + $columnIndexes = [ + 0 => 'H', + 3 => 'K', + 5 => 'M', + ]; + + // If we request a specific column by its offset, we should + // get a \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\AutoFilter\Column object returned + foreach ($columnIndexes as $columnIndex => $columnID) { + $result = $autoFilter->getColumnByOffset($columnIndex); + self::assertInstanceOf(Column::class, $result); + self::assertEquals($result->getColumnIndex(), $columnID); + } + } + + public function testGetColumnIfNotSet(): void + { + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + // If we request a specific column by its column ID, we should + // get a \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\AutoFilter\Column object returned + $result = $autoFilter->getColumn('K'); + self::assertInstanceOf(Column::class, $result); + } + + public function testGetColumnWithoutRangeSet(): void + { + $this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class); + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + + // Clear the range + $autoFilter->setRange(''); + $autoFilter->getColumn('A'); + } + + public function testClearRangeWithExistingColumns(): void + { + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + $expectedResult = ''; + + $columnIndexes = ['L', 'M', 'N']; + foreach ($columnIndexes as $columnIndex) { + $autoFilter->setColumn($columnIndex); + } + + // Setters return the instance to implement the fluent interface + $result = $autoFilter->setRange(''); + self::assertInstanceOf(AutoFilter::class, $result); + + // Range should be cleared + $result = $autoFilter->getRange(); + self::assertEquals($expectedResult, $result); + + // Column array should be cleared + $result = $autoFilter->getColumns(); + self::assertIsArray($result); + self::assertCount(0, $result); + } + + public function testSetRangeWithExistingColumns(): void + { + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + $expectedResult = 'G1:J512'; + + // These columns should be retained + $columnIndexes1 = ['I', 'J']; + foreach ($columnIndexes1 as $columnIndex) { + $autoFilter->setColumn($columnIndex); + } + // These columns should be discarded + $columnIndexes2 = ['K', 'L', 'M']; + foreach ($columnIndexes2 as $columnIndex) { + $autoFilter->setColumn($columnIndex); + } + + // Setters return the instance to implement the fluent interface + $result = $autoFilter->setRange($expectedResult); + self::assertInstanceOf(AutoFilter::class, $result); + + // Range should be correctly set + $result = $autoFilter->getRange(); + self::assertEquals($expectedResult, $result); + + // Only columns that existed in the original range and that + // still fall within the new range should be retained + $result = $autoFilter->getColumns(); + self::assertIsArray($result); + self::assertCount(count($columnIndexes1), $result); + } + + public function testClone(): void + { + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + $columnIndexes = ['L', 'M']; + + foreach ($columnIndexes as $columnIndex) { + $autoFilter->setColumn($columnIndex); + } + + $result = clone $autoFilter; + self::assertInstanceOf(AutoFilter::class, $result); + self::assertSame($autoFilter->getRange(), $result->getRange()); + self::assertNull($result->getParent()); + self::assertNotNull($autoFilter->getParent()); + self::assertInstanceOf(Worksheet::class, $autoFilter->getParent()); + $autoColumns = $autoFilter->getColumns(); + $resultColumns = $result->getColumns(); + self::assertIsArray($autoColumns); + self::assertIsArray($resultColumns); + self::assertCount(2, $autoColumns); + self::assertCount(2, $resultColumns); + self::assertArrayHasKey('L', $autoColumns); + self::assertArrayHasKey('L', $resultColumns); + self::assertArrayHasKey('M', $autoColumns); + self::assertArrayHasKey('M', $resultColumns); + self::assertInstanceOf(Column::class, $autoColumns['L']); + self::assertInstanceOf(Column::class, $resultColumns['L']); + self::assertInstanceOf(Column::class, $autoColumns['M']); + self::assertInstanceOf(Column::class, $resultColumns['M']); + } + + public function testNoWorksheet(): void + { + $autoFilter = new AutoFilter(); + self::assertSame($autoFilter, $autoFilter->showHideRows()); + } + + public function testClearColumn(): void + { + $sheet = $this->getSheet(); + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange(self::INITIAL_RANGE); + $columnIndexes = ['J', 'K', 'L', 'M']; + + foreach ($columnIndexes as $columnIndex) { + $autoFilter->setColumn($columnIndex); + } + $columns = $autoFilter->getColumns(); + self::assertCount(4, $columns); + self::assertArrayHasKey('J', $columns); + self::assertArrayHasKey('K', $columns); + self::assertArrayHasKey('L', $columns); + self::assertArrayHasKey('M', $columns); + $autoFilter->clearColumn('K'); + $columns = $autoFilter->getColumns(); + self::assertCount(3, $columns); + self::assertArrayHasKey('J', $columns); + self::assertArrayHasKey('L', $columns); + self::assertArrayHasKey('M', $columns); + $autoFilter->shiftColumn('L', 'K'); + $columns = $autoFilter->getColumns(); + self::assertCount(3, $columns); + self::assertArrayHasKey('J', $columns); + self::assertArrayHasKey('K', $columns); + self::assertArrayHasKey('M', $columns); + } +} diff --git a/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterTodayTest.php b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterTodayTest.php new file mode 100644 index 00000000..6805ec77 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterTodayTest.php @@ -0,0 +1,61 @@ +getSpreadsheet()->createSheet(); + $dtStart = new DateTimeImmutable(); + $startDay = $dtStart->format('d'); + $sheet->getCell('A1')->setValue('Date'); + $sheet->getCell('A2')->setValue('=NOW()'); + // cache result for consistency in later calculations + $sheet->getCell('A2')->getCalculatedValue(); + $sheet->getCell('A3')->setValue('=A2+1'); + $sheet->getCell('A4')->setValue('=A2-1'); + $sheet->getCell('A5')->setValue('=TODAY()'); + // cache result for consistency in later calculations + $sheet->getCell('A5')->getCalculatedValue(); + $sheet->getCell('A6')->setValue('=A5+1'); + $sheet->getCell('A7')->setValue('=A5-1'); + $this->maxRow = $maxRow = 7; + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange("A1:A$maxRow"); + $columnFilter = $autoFilter->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + '', + $rule + ) + ->setRuleType(Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER); + $autoFilter->showHideRows(); + $dtEnd = new DateTimeImmutable(); + $endDay = $dtEnd->format('d'); + } while ($startDay !== $endDay); + + self::assertEquals($expectedVisible, $this->getVisibleSheet($sheet)); + } +} diff --git a/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterWeekTest.php b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterWeekTest.php new file mode 100644 index 00000000..ce506e54 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterWeekTest.php @@ -0,0 +1,70 @@ +getCell('A1')->setValue('Date'); + $sheet->getCell('A2')->setValue('=TODAY()'); + // cache result for consistency in later calculations + $sheet->getCell('A2')->getCalculatedValue(); + $sheet->getCell('B2')->setValue('=WEEKDAY(A2) - 1'); // subtract to get to Sunday + $sheet->getCell('A3')->setValue('=DATE(YEAR(A2), MONTH(A2), DAY(A2) - B2)'); + $sheet->getCell('A4')->setValue('=DATE(YEAR(A3), MONTH(A3), DAY(A3) + 8)'); + $sheet->getCell('A5')->setValue('=DATE(YEAR(A3), MONTH(A3), DAY(A3) + 19)'); + $sheet->getCell('A6')->setValue('=DATE(YEAR(A3), MONTH(A3), DAY(A3) - 6)'); + $sheet->getCell('A7')->setValue('=DATE(YEAR(A3), MONTH(A3), DAY(A3) - 12)'); + $sheet->getCell('A8')->setValue('=DATE(YEAR(A2) + 1, MONTH(A2), 1)'); + $sheet->getCell('A9')->setValue('=DATE(YEAR(A2) - 1, MONTH(A2), 1)'); + $this->maxRow = 9; + } + + /** + * @dataProvider providerWeek + */ + public function testWeek(array $expectedVisible, string $rule): void + { + // Loop to avoid rare edge case where first calculation + // and second do not take place in same day. + do { + $sheet = $this->getSpreadsheet()->createSheet(); + $dtStart = new DateTimeImmutable(); + $startDay = (int) $dtStart->format('d'); + $this->setCells($sheet); + + $maxRow = $this->maxRow; + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange("A1:A$maxRow"); + $columnFilter = $autoFilter->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + '', + $rule + ) + ->setRuleType(Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER); + $autoFilter->showHideRows(); + $dtEnd = new DateTimeImmutable(); + $endDay = (int) $dtEnd->format('d'); + } while ($startDay !== $endDay); + + self::assertEquals($expectedVisible, $this->getVisibleSheet($sheet)); + } +} diff --git a/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterYearTest.php b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterYearTest.php new file mode 100644 index 00000000..8f463671 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/AutoFilterYearTest.php @@ -0,0 +1,107 @@ +getSpreadsheet()->createSheet(); + $dtStart = new DateTimeImmutable(); + $startDay = (int) $dtStart->format('d'); + $sheet->getCell('A1')->setValue('Date'); + $year = (int) $dtStart->format('Y') - 1; + $row = 1; + $iteration = 0; + while ($iteration < 3) { + for ($month = 3; $month < 13; $month += 4) { + ++$row; + $sheet->getCell("A$row")->setValue("=DATE($year, $month, 1)"); + } + ++$year; + ++$iteration; + } + ++$row; + $sheet->getCell("A$row")->setValue('=DATE(2041, 1, 1)'); // beyond epoch + ++$row; // empty row at end + $this->maxRow = $maxRow = $row; + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange("A1:A$maxRow"); + $columnFilter = $autoFilter->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + '', + $rule + ) + ->setRuleType(Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER); + $autoFilter->showHideRows(); + $dtEnd = new DateTimeImmutable(); + $endDay = (int) $dtEnd->format('d'); + } while ($startDay !== $endDay); + + self::assertEquals($expectedVisible, $this->getVisibleSheet($sheet)); + } + + public function testYearToDate(): void + { + // Loop to avoid rare edge case where first calculation + // and second do not take place in same day. + do { + $sheet = $this->getSpreadsheet()->createSheet(); + $dtStart = new DateTimeImmutable(); + $startDay = (int) $dtStart->format('d'); + $startMonth = (int) $dtStart->format('m'); + $sheet->getCell('A1')->setValue('Date'); + $sheet->getCell('A2')->setValue('=TODAY()'); + // cache result for consistency in later calculations + $sheet->getCell('A2')->getCalculatedValue(); + $sheet->getCell('A3')->setValue('=DATE(YEAR(A2), 12, 31)'); + $sheet->getCell('A4')->setValue('=A3 + 1'); + $sheet->getCell('A5')->setValue('=DATE(YEAR(A2), 1, 1)'); + $sheet->getCell('A6')->setValue('=A5 - 1'); + + $this->maxRow = $maxRow = 6; + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange("A1:A$maxRow"); + $columnFilter = $autoFilter->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + '', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE + ) + ->setRuleType(Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER); + $autoFilter->showHideRows(); + $dtEnd = new DateTimeImmutable(); + $endDay = (int) $dtEnd->format('d'); + } while ($startDay !== $endDay); + + $expected = ($startMonth === 12 && $startDay === 31) ? [2, 3, 5] : [2, 5]; + self::assertEquals($expected, $this->getVisibleSheet($sheet)); + } +} diff --git a/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/Column/RuleTest.php b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/Column/RuleTest.php deleted file mode 100644 index 156a95de..00000000 --- a/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/Column/RuleTest.php +++ /dev/null @@ -1,103 +0,0 @@ -mockAutoFilterColumnObject = $this->getMockBuilder(Column::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->testAutoFilterRuleObject = new Column\Rule( - $this->mockAutoFilterColumnObject - ); - } - - public function testGetRuleType(): void - { - $result = $this->testAutoFilterRuleObject->getRuleType(); - self::assertEquals(Column\Rule::AUTOFILTER_RULETYPE_FILTER, $result); - } - - public function testSetRuleType(): void - { - $expectedResult = Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP; - - // Setters return the instance to implement the fluent interface - $result = $this->testAutoFilterRuleObject->setRuleType($expectedResult); - self::assertInstanceOf(Column\Rule::class, $result); - - $result = $this->testAutoFilterRuleObject->getRuleType(); - self::assertEquals($expectedResult, $result); - } - - public function testSetValue(): void - { - $expectedResult = 100; - - // Setters return the instance to implement the fluent interface - $result = $this->testAutoFilterRuleObject->setValue($expectedResult); - self::assertInstanceOf(Column\Rule::class, $result); - - $result = $this->testAutoFilterRuleObject->getValue(); - self::assertEquals($expectedResult, $result); - } - - public function testGetOperator(): void - { - $result = $this->testAutoFilterRuleObject->getOperator(); - self::assertEquals(Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL, $result); - } - - public function testSetOperator(): void - { - $expectedResult = Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN; - - // Setters return the instance to implement the fluent interface - $result = $this->testAutoFilterRuleObject->setOperator($expectedResult); - self::assertInstanceOf(Column\Rule::class, $result); - - $result = $this->testAutoFilterRuleObject->getOperator(); - self::assertEquals($expectedResult, $result); - } - - public function testSetGrouping(): void - { - $expectedResult = Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH; - - // Setters return the instance to implement the fluent interface - $result = $this->testAutoFilterRuleObject->setGrouping($expectedResult); - self::assertInstanceOf(Column\Rule::class, $result); - - $result = $this->testAutoFilterRuleObject->getGrouping(); - self::assertEquals($expectedResult, $result); - } - - public function testGetParent(): void - { - $result = $this->testAutoFilterRuleObject->getParent(); - self::assertInstanceOf(Column::class, $result); - } - - public function testSetParent(): void - { - // Setters return the instance to implement the fluent interface - $result = $this->testAutoFilterRuleObject->setParent($this->mockAutoFilterColumnObject); - self::assertInstanceOf(Column\Rule::class, $result); - } - - public function testClone(): void - { - $result = clone $this->testAutoFilterRuleObject; - self::assertInstanceOf(Column\Rule::class, $result); - } -} diff --git a/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/ColumnTest.php b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/ColumnTest.php index ef67b05d..c94cb3a4 100644 --- a/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/ColumnTest.php +++ b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/ColumnTest.php @@ -2,137 +2,174 @@ namespace PhpOffice\PhpSpreadsheetTests\Worksheet\AutoFilter; -use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter; -use PHPUnit\Framework\TestCase; +use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; +use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column; +use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule; +use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; -class ColumnTest extends TestCase +class ColumnTest extends SetupTeardown { - private $testInitialColumn = 'H'; - - private $testAutoFilterColumnObject; - - private $mockAutoFilterObject; - - protected function setUp(): void + protected function initSheet(): Worksheet { - $this->mockAutoFilterObject = $this->getMockBuilder(AutoFilter::class) - ->disableOriginalConstructor() - ->getMock(); + $sheet = $this->getSheet(); + $sheet->getCell('G1')->setValue('Heading'); + $sheet->getCell('G2')->setValue(2); + $sheet->getCell('G3')->setValue(3); + $sheet->getCell('G4')->setValue(4); + $sheet->getCell('H1')->setValue('Heading2'); + $sheet->getCell('H2')->setValue(1); + $sheet->getCell('H3')->setValue(2); + $sheet->getCell('H4')->setValue(3); + $this->maxRow = $maxRow = 4; + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange("G1:H$maxRow"); - $this->mockAutoFilterObject->expects(self::any()) - ->method('testColumnInRange') - ->willReturn(3); - - $this->testAutoFilterColumnObject = new AutoFilter\Column($this->testInitialColumn, $this->mockAutoFilterObject); + return $sheet; } - public function testGetColumnIndex(): void + public function testVariousGets(): void { - $result = $this->testAutoFilterColumnObject->getColumnIndex(); - self::assertEquals($this->testInitialColumn, $result); + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('H'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + 3 + ); + $result = $columnFilter->getColumnIndex(); + self::assertEquals('H', $result); + } + + public function testGetBadColumnIndex(): void + { + $this->expectException(PhpSpreadsheetException::class); + $this->expectExceptionMessage('Column is outside of current autofilter range.'); + $sheet = $this->initSheet(); + $sheet->getAutoFilter()->getColumn('B'); } public function testSetColumnIndex(): void { - $expectedResult = 'L'; + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('H'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + 3 + ); + $expectedResult = 'G'; - // Setters return the instance to implement the fluent interface - $result = $this->testAutoFilterColumnObject->setColumnIndex($expectedResult); - self::assertInstanceOf(AutoFilter\Column::class, $result); + $result = $columnFilter->setColumnIndex($expectedResult); + self::assertInstanceOf(Column::class, $result); - $result = $this->testAutoFilterColumnObject->getColumnIndex(); + $result = $result->getColumnIndex(); self::assertEquals($expectedResult, $result); } - public function testGetParent(): void - { - $result = $this->testAutoFilterColumnObject->getParent(); - self::assertInstanceOf(AutoFilter::class, $result); - } - public function testSetParent(): void { + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('H'); // Setters return the instance to implement the fluent interface - $result = $this->testAutoFilterColumnObject->setParent($this->mockAutoFilterObject); - self::assertInstanceOf(AutoFilter\Column::class, $result); + $result = $columnFilter->setParent(null); + self::assertInstanceOf(Column::class, $result); } - public function testGetFilterType(): void + public function testVariousSets(): void { - $result = $this->testAutoFilterColumnObject->getFilterType(); - self::assertEquals(AutoFilter\Column::AUTOFILTER_FILTERTYPE_FILTER, $result); - } + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('H'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + 3 + ); - public function testSetFilterType(): void - { - $result = $this->testAutoFilterColumnObject->setFilterType(AutoFilter\Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER); - self::assertInstanceOf(AutoFilter\Column::class, $result); + $result = $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER); + self::assertInstanceOf(Column::class, $result); - $result = $this->testAutoFilterColumnObject->getFilterType(); - self::assertEquals(AutoFilter\Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER, $result); + $result = $columnFilter->getFilterType(); + self::assertEquals(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER, $result); + + $result = $columnFilter->setJoin(Column::AUTOFILTER_COLUMN_JOIN_AND); + self::assertInstanceOf(Column::class, $result); + + $result = $columnFilter->getJoin(); + self::assertEquals(Column::AUTOFILTER_COLUMN_JOIN_AND, $result); } public function testSetInvalidFilterTypeThrowsException(): void { - $this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class); + $this->expectException(PhpSpreadsheetException::class); + $this->expectExceptionMessage('Invalid filter type for column AutoFilter.'); + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('H'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + 3 + ); $expectedResult = 'Unfiltered'; - $this->testAutoFilterColumnObject->setFilterType($expectedResult); - } - - public function testGetJoin(): void - { - $result = $this->testAutoFilterColumnObject->getJoin(); - self::assertEquals(AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_OR, $result); - } - - public function testSetJoin(): void - { - $result = $this->testAutoFilterColumnObject->setJoin(AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND); - self::assertInstanceOf(AutoFilter\Column::class, $result); - - $result = $this->testAutoFilterColumnObject->getJoin(); - self::assertEquals(AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND, $result); + $columnFilter->setFilterType($expectedResult); } public function testSetInvalidJoinThrowsException(): void { - $this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class); + $this->expectException(PhpSpreadsheetException::class); + $this->expectExceptionMessage('Invalid rule connection for column AutoFilter.'); + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('H'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + 3 + ); $expectedResult = 'Neither'; - $this->testAutoFilterColumnObject->setJoin($expectedResult); - } - - public function testSetAttributes(): void - { - $attributeSet = [ - 'val' => 100, - 'maxVal' => 200, - ]; - - // Setters return the instance to implement the fluent interface - $result = $this->testAutoFilterColumnObject->setAttributes($attributeSet); - self::assertInstanceOf(AutoFilter\Column::class, $result); + $columnFilter->setJoin($expectedResult); } public function testGetAttributes(): void { + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('H'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + 3 + ); $attributeSet = [ 'val' => 100, 'maxVal' => 200, ]; - $this->testAutoFilterColumnObject->setAttributes($attributeSet); + $result = $columnFilter->setAttributes($attributeSet); + self::assertInstanceOf(Column::class, $result); - $result = $this->testAutoFilterColumnObject->getAttributes(); - self::assertIsArray($result); - self::assertCount(count($attributeSet), $result); + $result = $columnFilter->getAttributes(); + self::assertSame($attributeSet, $result); } public function testSetAttribute(): void { + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('H'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + 3 + ); + $attributeSet = [ 'val' => 100, 'maxVal' => 200, @@ -140,37 +177,104 @@ class ColumnTest extends TestCase foreach ($attributeSet as $attributeName => $attributeValue) { // Setters return the instance to implement the fluent interface - $result = $this->testAutoFilterColumnObject->setAttribute($attributeName, $attributeValue); - self::assertInstanceOf(AutoFilter\Column::class, $result); + $result = $columnFilter->setAttribute($attributeName, $attributeValue); + self::assertInstanceOf(Column::class, $result); } + self::assertSame($attributeSet, $columnFilter->getAttributes()); } public function testGetAttribute(): void { + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('H'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + 3 + ); + $attributeSet = [ 'val' => 100, 'maxVal' => 200, ]; - $this->testAutoFilterColumnObject->setAttributes($attributeSet); + $columnFilter->setAttributes($attributeSet); foreach ($attributeSet as $attributeName => $attributeValue) { - $result = $this->testAutoFilterColumnObject->getAttribute($attributeName); - self::assertEquals($attributeValue, $result); + $result = $columnFilter->getAttribute($attributeName); + self::assertSame($attributeValue, $result); } - $result = $this->testAutoFilterColumnObject->getAttribute('nonExistentAttribute'); + $result = $columnFilter->getAttribute('nonExistentAttribute'); self::assertNull($result); } public function testClone(): void { - $originalRule = $this->testAutoFilterColumnObject->createRule(); - $result = clone $this->testAutoFilterColumnObject; - self::assertInstanceOf(AutoFilter\Column::class, $result); - self::assertCount(1, $result->getRules()); - self::assertContainsOnlyInstancesOf(AutoFilter\Column\Rule::class, $result->getRules()); - $clonedRule = $result->getRules()[0]; - self::assertNotSame($originalRule, $clonedRule); - self::assertSame($result, $clonedRule->getParent()); + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('H'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + 3 + ); + $originalRule = $columnFilter->getRules(); + $result = clone $columnFilter; + self::assertSame($columnFilter->getColumnIndex(), $result->getColumnIndex()); + self::assertSame($columnFilter->getFilterType(), $result->getFilterType()); + self::assertSame($columnFilter->getJoin(), $result->getJoin()); + self::assertNull($result->getParent()); + self::assertNotNull($columnFilter->getParent()); + self::assertContainsOnlyInstancesOf(Rule::class, $result->getRules()); + $clonedRule = $result->getRules(); + self::assertCount(1, $clonedRule); + self::assertCount(1, $originalRule); + self::assertNotSame($originalRule[0], $clonedRule[0]); + self::assertSame($originalRule[0]->getRuleType(), $clonedRule[0]->getRuleType()); + self::assertSame($originalRule[0]->getValue(), $clonedRule[0]->getValue()); + self::assertSame($originalRule[0]->getOperator(), $clonedRule[0]->getOperator()); + self::assertSame($originalRule[0]->getGrouping(), $clonedRule[0]->getGrouping()); + self::assertSame($result, $clonedRule[0]->getParent()); + } + + public function testRuleManipulation(): void + { + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('H'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + 3 + ); + $originalRules = $columnFilter->getRules(); + self::assertCount(1, $originalRules); + $rule0 = $columnFilter->getRule(0); + self::assertSame($originalRules[0], $rule0); + $rule1 = $columnFilter->getRule(1); + self::assertInstanceOf(Rule::class, $rule1); + self::assertNotEquals($originalRules[0], $rule1); + self::assertCount(2, $columnFilter->getRules()); + self::assertSame(Column::AUTOFILTER_COLUMN_JOIN_OR, $columnFilter->getJoin()); + $columnFilter->setJoin(Column::AUTOFILTER_COLUMN_JOIN_AND); + $rule2 = new Rule(); + $columnFilter->addRule($rule2); + self::assertCount(3, $columnFilter->getRules()); + self::assertSame(Column::AUTOFILTER_COLUMN_JOIN_AND, $columnFilter->getJoin()); + $columnFilter->deleteRule(2); + self::assertCount(2, $columnFilter->getRules()); + self::assertSame(Column::AUTOFILTER_COLUMN_JOIN_AND, $columnFilter->getJoin()); + $columnFilter->deleteRule(1); + self::assertCount(1, $columnFilter->getRules()); + self::assertSame(Column::AUTOFILTER_COLUMN_JOIN_OR, $columnFilter->getJoin()); + $columnFilter->addRule($rule1); + $columnFilter->addRule($rule2); + $columnFilter->setJoin(Column::AUTOFILTER_COLUMN_JOIN_AND); + self::assertCount(3, $columnFilter->getRules()); + self::assertSame(Column::AUTOFILTER_COLUMN_JOIN_AND, $columnFilter->getJoin()); + $columnFilter->clearRules(); + self::assertCount(0, $columnFilter->getRules()); + self::assertSame(Column::AUTOFILTER_COLUMN_JOIN_OR, $columnFilter->getJoin()); } } diff --git a/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/DateGroupTest.php b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/DateGroupTest.php new file mode 100644 index 00000000..a89ebd5b --- /dev/null +++ b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/DateGroupTest.php @@ -0,0 +1,223 @@ +getSheet(); + $sheet->getCell('A1')->setValue('Date'); + $sheet->getCell('B1')->setValue('Time'); + $sheet->getCell('C1')->setValue('DateTime'); + $sheet->getCell('C1')->setValue('Row*10'); + for ($row = 2; $row < 63; ++$row) { + $sheet->getCell("A$row")->setValue("=DATE($year,11,30)+$row"); + $hour = $row % 24; + $minute = $row % 10; + $second = $row % 20; + $sheet->getCell("B$row")->setValue("=TIME($hour,$minute,$second)"); + $sheet->getCell("C$row")->setValue("=A$row+B$row"); + $sheet->getCell("D$row")->setValue("=10*$row"); + } + $this->maxRow = $maxRow = 62; + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange("A1:C$maxRow"); + + return $sheet; + } + + public function testYearMonthDayGroup(): void + { + $year = 2011; + $sheet = $this->initSheet($year); + $columnFilter = $sheet->getAutoFilter()->getColumn('C'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + [ + 'year' => $year, + 'month' => 12, + 'day' => 6, + ] + ) + ->setRuleType( + Rule::AUTOFILTER_RULETYPE_DATEGROUP + ); + self::assertEquals([6], $this->getVisible()); + } + + public function testYearMonthDayHourMinuteSecond1Group(): void + { + $year = 2011; + $sheet = $this->initSheet($year); + $columnFilter = $sheet->getAutoFilter()->getColumn('C'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + [ + 'year' => $year, + 'month' => 12, + 'day' => 6, + 'hour' => 6, + 'minute' => 6, + 'second' => 6, + ] + ) + ->setRuleType( + Rule::AUTOFILTER_RULETYPE_DATEGROUP + ); + $sheet->getCell('C5')->setValue(''); // make an empty cell in range + self::assertEquals([6], $this->getVisible()); + } + + public function testYearMonthDayHourMinuteSecond2Group(): void + { + $year = 2011; + $sheet = $this->initSheet($year); + $columnFilter = $sheet->getAutoFilter()->getColumn('C'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + [ + 'year' => $year, + 'month' => 12, + 'day' => 6, + 'hour' => 6, + 'minute' => 6, + 'second' => 7, + ] + ) + ->setRuleType( + Rule::AUTOFILTER_RULETYPE_DATEGROUP + ); + self::assertEquals([], $this->getVisible()); + } + + public function testDayGroupEpoch(): void + { + $year = 2040; + $sheet = $this->initSheet($year); + $columnFilter = $sheet->getAutoFilter()->getColumn('C'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + [ + 'year' => $year, + 'month' => 12, + 'day' => 6, + ] + ) + ->setRuleType( + Rule::AUTOFILTER_RULETYPE_DATEGROUP + ); + self::assertEquals([6], $this->getVisible()); + } + + public function testDayGroupNonArray(): void + { + $year = 2011; + $sheet = $this->initSheet($year); + $cellA2 = $sheet->getCell('A2')->getCalculatedValue(); + $columnFilter = $sheet->getAutoFilter()->getColumn('C'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + $cellA2 + ) + ->setRuleType( + Rule::AUTOFILTER_RULETYPE_DATEGROUP + ); + self::assertEquals([], $this->getVisible()); + } + + public function testHourGroup(): void + { + $year = 2011; + $sheet = $this->initSheet($year); + $columnFilter = $sheet->getAutoFilter()->getColumn('B'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + [ + 'hour' => 14, + ] + ) + ->setRuleType( + Rule::AUTOFILTER_RULETYPE_DATEGROUP + ); + self::assertEquals([14, 38, 62], $this->getVisible()); + } + + public function testHourMinuteGroup(): void + { + $year = 2011; + $sheet = $this->initSheet($year); + $columnFilter = $sheet->getAutoFilter()->getColumn('B'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + [ + 'hour' => 14, + 'minute' => 8, + ] + ) + ->setRuleType( + Rule::AUTOFILTER_RULETYPE_DATEGROUP + ); + self::assertEquals([38], $this->getVisible()); + } + + public function testHourMinuteSecondGroup1(): void + { + $year = 2011; + $sheet = $this->initSheet($year); + $columnFilter = $sheet->getAutoFilter()->getColumn('B'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + [ + 'hour' => 14, + 'minute' => 8, + 'second' => 18, + ] + ) + ->setRuleType( + Rule::AUTOFILTER_RULETYPE_DATEGROUP + ); + self::assertEquals([38], $this->getVisible()); + } + + public function testHourMinuteSecondGroup2(): void + { + $year = 2011; + $sheet = $this->initSheet($year); + $columnFilter = $sheet->getAutoFilter()->getColumn('B'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + [ + 'hour' => 14, + 'minute' => 8, + 'second' => 19, + ] + ) + ->setRuleType( + Rule::AUTOFILTER_RULETYPE_DATEGROUP + ); + self::assertEquals([], $this->getVisible()); + } +} diff --git a/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/RuleCustomTest.php b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/RuleCustomTest.php new file mode 100644 index 00000000..9f6b48bb --- /dev/null +++ b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/RuleCustomTest.php @@ -0,0 +1,57 @@ +getSheet(); + $sheet->getCell('A1')->setValue('Heading'); + $sheet->getCell('A2')->setValue(2); + $sheet->getCell('A3')->setValue(3); + $sheet->getCell('A4')->setValue(4); + $sheet->getCell('B1')->setValue('Heading2'); + $sheet->getCell('B2')->setValue(1); + $sheet->getCell('B3')->setValue(2); + $sheet->getCell('B4')->setValue(3); + $this->maxRow = $maxRow = 4; + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange("A1:B$maxRow"); + + return $sheet; + } + + /** + * @dataProvider providerCondition + */ + public function testRuleCondition(array $expectedResult, string $condition): void + { + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER); + $columnFilter->createRule() + ->setRule( + $condition, + 3 + ) + ->setRuleType(Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER); + self::assertEquals($expectedResult, $this->getVisible()); + } + + public function providerCondition(): array + { + return [ + [[3], Rule::AUTOFILTER_COLUMN_RULE_EQUAL], + [[2, 4], Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL], + [[4], Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN], + [[3, 4], Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL], + [[2], Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN], + [[2, 3], Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/RuleDateGroupTest.php b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/RuleDateGroupTest.php new file mode 100644 index 00000000..3a32a9eb --- /dev/null +++ b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/RuleDateGroupTest.php @@ -0,0 +1,132 @@ +getSheet(); + $sheet->getCell('A1')->setValue('Date'); + $sheet->getCell('A2')->setValue('=DATE(2011,1,10)'); + $sheet->getCell('A3')->setValue('=DATE(2012,1,10)'); + $sheet->getCell('A4')->setValue('=DATE(2011,1,10)'); + $sheet->getCell('A5')->setValue('=DATE(2012,2,10)'); + $sheet->getCell('A6')->setValue('=DATE(2012,1,1)'); + $sheet->getCell('A7')->setValue('=DATE(2012,12,31)'); + $sheet->getCell('B1')->setValue('Heading2'); + $sheet->getCell('B2')->setValue(1); + $sheet->getCell('B3')->setValue(2); + $sheet->getCell('B4')->setValue(3); + $sheet->getCell('B5')->setValue(4); + $sheet->getCell('B6')->setValue(5); + $sheet->getCell('B7')->setValue(6); + $this->maxRow = $maxRow = 7; + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange("A1:B$maxRow"); + + return $sheet; + } + + public function testYearGroup(): void + { + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + [ + 'year' => 2012, + ] + ) + ->setRuleType( + Rule::AUTOFILTER_RULETYPE_DATEGROUP + ); + self::assertEquals([3, 5, 6, 7], $this->getVisible()); + } + + public function testYearGroupWithInvalidIndex(): void + { + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + [ + 'year' => 2012, + 'xyz' => 5, + ] + ) + ->setRuleType( + Rule::AUTOFILTER_RULETYPE_DATEGROUP + ); + self::assertEquals([3, 5, 6, 7], $this->getVisible()); + } + + public function testYearGroupNoValidIndexes(): void + { + $this->expectException(SpException::class); + $this->expectExceptionMessage('Invalid rule value for column AutoFilter Rule.'); + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + [ + 'zzyear' => 2012, + 'xyz' => 5, + ] + ) + ->setRuleType( + Rule::AUTOFILTER_RULETYPE_DATEGROUP + ); + self::assertEquals([3, 5, 6, 7], $this->getVisible()); + } + + public function testYearGroupBadRuleType(): void + { + $this->expectException(SpException::class); + $this->expectExceptionMessage('Invalid rule type for column AutoFilter Rule.'); + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + [ + 'year' => 2012, + ] + ) + ->setRuleType( + 'xyz' + ); + self::assertEquals([3, 5, 6, 7], $this->getVisible()); + } + + public function testYearMonthGroup(): void + { + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + [ + 'year' => 2012, + 'month' => 1, + ] + ) + ->setRuleType( + Rule::AUTOFILTER_RULETYPE_DATEGROUP + ); + self::assertEquals([3, 6], $this->getVisible()); + } +} diff --git a/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/RuleTest.php b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/RuleTest.php new file mode 100644 index 00000000..c9eaa4f2 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/RuleTest.php @@ -0,0 +1,122 @@ +getSheet(); + $sheet->getCell('A1')->setValue('Heading'); + $sheet->getCell('A2')->setValue(2); + $sheet->getCell('A3')->setValue(3); + $sheet->getCell('A4')->setValue(4); + $sheet->getCell('B1')->setValue('Heading2'); + $sheet->getCell('B2')->setValue(1); + $sheet->getCell('B3')->setValue(2); + $sheet->getCell('B4')->setValue(3); + $this->maxRow = $maxRow = 4; + $autoFilter = $sheet->getAutoFilter(); + $autoFilter->setRange("A1:B$maxRow"); + + return $sheet; + } + + public function testRule(): void + { + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + 3 + ); + $autoFilterRuleObject = new Rule($columnFilter); + self::assertEquals(Rule::AUTOFILTER_RULETYPE_FILTER, $autoFilterRuleObject->getRuleType()); + self::assertEquals([3], $this->getVisible()); + $ruleParent = $autoFilterRuleObject->getParent(); + if ($ruleParent === null) { + self::fail('Unexpected null parent'); + } else { + self::assertEquals('A', $ruleParent->getColumnIndex()); + self::assertSame($columnFilter, $ruleParent); + } + } + + public function testSetParent(): void + { + $sheet = $this->initSheet(); + $autoFilterRuleObject = new Rule(); + $autoFilterRuleObject->setParent($sheet->getAutoFilter()->getColumn('B')); + $columnFilter = $autoFilterRuleObject->getParent(); + if ($columnFilter === null) { + self::fail('Unexpected null parent'); + } else { + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + 3 + ); + self::assertEquals(Rule::AUTOFILTER_RULETYPE_FILTER, $autoFilterRuleObject->getRuleType()); + self::assertEquals([4], $this->getVisible()); + } + } + + public function testBadSetRule(): void + { + $this->expectException(SpException::class); + $this->expectExceptionMessage('Invalid operator for column AutoFilter Rule.'); + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + 'xyz', + 3 + ); + } + + public function testBadSetGrouping(): void + { + $this->expectException(SpException::class); + $this->expectExceptionMessage('Invalid grouping for column AutoFilter Rule.'); + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + '', + 3 + ); + $autoFilterRuleObject = new Rule($columnFilter); + $autoFilterRuleObject->setGrouping('xyz'); + } + + public function testClone(): void + { + $sheet = $this->initSheet(); + $columnFilter = $sheet->getAutoFilter()->getColumn('A'); + $columnFilter->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); + $columnFilter->createRule() + ->setRule( + Rule::AUTOFILTER_COLUMN_RULE_EQUAL, + 3 + ); + $autoFilterRuleObject = new Rule($columnFilter); + $result = clone $autoFilterRuleObject; + self::assertSame($autoFilterRuleObject->getRuleType(), $result->getRuleType()); + self::assertSame($autoFilterRuleObject->getValue(), $result->getValue()); + self::assertSame($autoFilterRuleObject->getRuleType(), $result->getRuleType()); + self::assertSame($autoFilterRuleObject->getOperator(), $result->getOperator()); + self::assertSame($autoFilterRuleObject->getGrouping(), $result->getGrouping()); + self::assertNotNull($autoFilterRuleObject->getParent()); + self::assertNull($result->getParent()); + } +} diff --git a/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/SetupTeardown.php b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/SetupTeardown.php new file mode 100644 index 00000000..3546bc32 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Worksheet/AutoFilter/SetupTeardown.php @@ -0,0 +1,72 @@ +sheet = null; + if ($this->spreadsheet !== null) { + $this->spreadsheet->disconnectWorksheets(); + $this->spreadsheet = null; + } + } + + protected function getSpreadsheet(): Spreadsheet + { + if ($this->spreadsheet !== null) { + return $this->spreadsheet; + } + $this->spreadsheet = new Spreadsheet(); + + return $this->spreadsheet; + } + + protected function getSheet(): Worksheet + { + if ($this->sheet !== null) { + return $this->sheet; + } + $this->sheet = $this->getSpreadsheet()->getActiveSheet(); + + return $this->sheet; + } + + public function getVisible(): array + { + return $this->getVisibleSheet($this->getSheet()); + } + + public function getVisibleSheet(Worksheet $sheet): array + { + $sheet->getAutoFilter()->showHideRows(); + $actualVisible = []; + for ($row = 2; $row <= $this->maxRow; ++$row) { + if ($sheet->getRowDimension($row)->getVisible()) { + $actualVisible[] = $row; + } + } + + return $actualVisible; + } +} diff --git a/tests/PhpSpreadsheetTests/Worksheet/AutoFilterTest.php b/tests/PhpSpreadsheetTests/Worksheet/AutoFilterTest.php deleted file mode 100644 index 17b4c022..00000000 --- a/tests/PhpSpreadsheetTests/Worksheet/AutoFilterTest.php +++ /dev/null @@ -1,336 +0,0 @@ -mockWorksheetObject = $this->getMockBuilder(Worksheet::class) - ->disableOriginalConstructor() - ->getMock(); - $this->cellCollection = $this->getMockBuilder(Cells::class) - ->disableOriginalConstructor() - ->getMock(); - $this->mockWorksheetObject->expects(self::any()) - ->method('getCellCollection') - ->willReturn($this->cellCollection); - - $this->testAutoFilterObject = new AutoFilter($this->testInitialRange, $this->mockWorksheetObject); - } - - public function testToString(): void - { - $expectedResult = $this->testInitialRange; - - // magic __toString should return the active autofilter range - $result = $this->testAutoFilterObject; - self::assertEquals($expectedResult, $result); - } - - public function testGetParent(): void - { - $result = $this->testAutoFilterObject->getParent(); - self::assertInstanceOf(Worksheet::class, $result); - } - - public function testSetParent(): void - { - // Setters return the instance to implement the fluent interface - $result = $this->testAutoFilterObject->setParent($this->mockWorksheetObject); - self::assertInstanceOf(AutoFilter::class, $result); - } - - public function testGetRange(): void - { - $expectedResult = $this->testInitialRange; - - // Result should be the active autofilter range - $result = $this->testAutoFilterObject->getRange(); - self::assertEquals($expectedResult, $result); - } - - public function testSetRange(): void - { - $ranges = [ - 'G1:J512' => 'Worksheet1!G1:J512', - 'K1:N20' => 'K1:N20', - ]; - - foreach ($ranges as $actualRange => $fullRange) { - // Setters return the instance to implement the fluent interface - $result = $this->testAutoFilterObject->setRange($fullRange); - self::assertInstanceOf(AutoFilter::class, $result); - - // Result should be the new autofilter range - $result = $this->testAutoFilterObject->getRange(); - self::assertEquals($actualRange, $result); - } - } - - public function testClearRange(): void - { - $expectedResult = ''; - - // Setters return the instance to implement the fluent interface - $result = $this->testAutoFilterObject->setRange(''); - self::assertInstanceOf(AutoFilter::class, $result); - - // Result should be a clear range - $result = $this->testAutoFilterObject->getRange(); - self::assertEquals($expectedResult, $result); - } - - public function testSetRangeInvalidRange(): void - { - $this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class); - - $expectedResult = 'A1'; - - $this->testAutoFilterObject->setRange($expectedResult); - } - - public function testGetColumnsEmpty(): void - { - // There should be no columns yet defined - $result = $this->testAutoFilterObject->getColumns(); - self::assertIsArray($result); - self::assertCount(0, $result); - } - - public function testGetColumnOffset(): void - { - $columnIndexes = [ - 'H' => 0, - 'K' => 3, - 'M' => 5, - ]; - - // If we request a specific column by its column ID, we should get an - // integer returned representing the column offset within the range - foreach ($columnIndexes as $columnIndex => $columnOffset) { - $result = $this->testAutoFilterObject->getColumnOffset($columnIndex); - self::assertEquals($columnOffset, $result); - } - } - - public function testGetInvalidColumnOffset(): void - { - $this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class); - - $invalidColumn = 'G'; - - $this->testAutoFilterObject->getColumnOffset($invalidColumn); - } - - public function testSetColumnWithString(): void - { - $expectedResult = 'L'; - - // Setters return the instance to implement the fluent interface - $result = $this->testAutoFilterObject->setColumn($expectedResult); - self::assertInstanceOf(AutoFilter::class, $result); - - $result = $this->testAutoFilterObject->getColumns(); - // Result should be an array of \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\AutoFilter\Column - // objects for each column we set indexed by the column ID - self::assertIsArray($result); - self::assertCount(1, $result); - self::assertArrayHasKey($expectedResult, $result); - self::assertInstanceOf(Column::class, $result[$expectedResult]); - } - - public function testSetInvalidColumnWithString(): void - { - $this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class); - - $invalidColumn = 'A'; - - $this->testAutoFilterObject->setColumn($invalidColumn); - } - - public function testSetColumnWithColumnObject(): void - { - $expectedResult = 'M'; - $columnObject = new AutoFilter\Column($expectedResult); - - // Setters return the instance to implement the fluent interface - $result = $this->testAutoFilterObject->setColumn($columnObject); - self::assertInstanceOf(AutoFilter::class, $result); - - $result = $this->testAutoFilterObject->getColumns(); - // Result should be an array of \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\AutoFilter\Column - // objects for each column we set indexed by the column ID - self::assertIsArray($result); - self::assertCount(1, $result); - self::assertArrayHasKey($expectedResult, $result); - self::assertInstanceOf(Column::class, $result[$expectedResult]); - } - - public function testSetInvalidColumnWithObject(): void - { - $this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class); - - $invalidColumn = 'E'; - $this->testAutoFilterObject->setColumn($invalidColumn); - } - - public function testSetColumnWithInvalidDataType(): void - { - $this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class); - - $invalidColumn = 123.456; - $this->testAutoFilterObject->setColumn($invalidColumn); - } - - public function testGetColumns(): void - { - $columnIndexes = ['L', 'M']; - - foreach ($columnIndexes as $columnIndex) { - $this->testAutoFilterObject->setColumn($columnIndex); - } - - $result = $this->testAutoFilterObject->getColumns(); - // Result should be an array of \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\AutoFilter\Column - // objects for each column we set indexed by the column ID - self::assertIsArray($result); - self::assertCount(count($columnIndexes), $result); - foreach ($columnIndexes as $columnIndex) { - self::assertArrayHasKey($columnIndex, $result); - self::assertInstanceOf(Column::class, $result[$columnIndex]); - } - } - - public function testGetColumn(): void - { - $columnIndexes = ['L', 'M']; - - foreach ($columnIndexes as $columnIndex) { - $this->testAutoFilterObject->setColumn($columnIndex); - } - - // If we request a specific column by its column ID, we should - // get a \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\AutoFilter\Column object returned - foreach ($columnIndexes as $columnIndex) { - $result = $this->testAutoFilterObject->getColumn($columnIndex); - self::assertInstanceOf(Column::class, $result); - } - } - - public function testGetColumnByOffset(): void - { - $columnIndexes = [ - 0 => 'H', - 3 => 'K', - 5 => 'M', - ]; - - // If we request a specific column by its offset, we should - // get a \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\AutoFilter\Column object returned - foreach ($columnIndexes as $columnIndex => $columnID) { - $result = $this->testAutoFilterObject->getColumnByOffset($columnIndex); - self::assertInstanceOf(Column::class, $result); - self::assertEquals($result->getColumnIndex(), $columnID); - } - } - - public function testGetColumnIfNotSet(): void - { - // If we request a specific column by its column ID, we should - // get a \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\AutoFilter\Column object returned - $result = $this->testAutoFilterObject->getColumn('K'); - self::assertInstanceOf(Column::class, $result); - } - - public function testGetColumnWithoutRangeSet(): void - { - $this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class); - - // Clear the range - $this->testAutoFilterObject->setRange(''); - $this->testAutoFilterObject->getColumn('A'); - } - - public function testClearRangeWithExistingColumns(): void - { - $expectedResult = ''; - - $columnIndexes = ['L', 'M', 'N']; - foreach ($columnIndexes as $columnIndex) { - $this->testAutoFilterObject->setColumn($columnIndex); - } - - // Setters return the instance to implement the fluent interface - $result = $this->testAutoFilterObject->setRange(''); - self::assertInstanceOf(AutoFilter::class, $result); - - // Range should be cleared - $result = $this->testAutoFilterObject->getRange(); - self::assertEquals($expectedResult, $result); - - // Column array should be cleared - $result = $this->testAutoFilterObject->getColumns(); - self::assertIsArray($result); - self::assertCount(0, $result); - } - - public function testSetRangeWithExistingColumns(): void - { - $expectedResult = 'G1:J512'; - - // These columns should be retained - $columnIndexes1 = ['I', 'J']; - foreach ($columnIndexes1 as $columnIndex) { - $this->testAutoFilterObject->setColumn($columnIndex); - } - // These columns should be discarded - $columnIndexes2 = ['K', 'L', 'M']; - foreach ($columnIndexes2 as $columnIndex) { - $this->testAutoFilterObject->setColumn($columnIndex); - } - - // Setters return the instance to implement the fluent interface - $result = $this->testAutoFilterObject->setRange($expectedResult); - self::assertInstanceOf(AutoFilter::class, $result); - - // Range should be correctly set - $result = $this->testAutoFilterObject->getRange(); - self::assertEquals($expectedResult, $result); - - // Only columns that existed in the original range and that - // still fall within the new range should be retained - $result = $this->testAutoFilterObject->getColumns(); - self::assertIsArray($result); - self::assertCount(count($columnIndexes1), $result); - } - - public function testClone(): void - { - $columnIndexes = ['L', 'M']; - - foreach ($columnIndexes as $columnIndex) { - $this->testAutoFilterObject->setColumn($columnIndex); - } - - $result = clone $this->testAutoFilterObject; - self::assertInstanceOf(AutoFilter::class, $result); - } -} diff --git a/tests/PhpSpreadsheetTests/Worksheet/ColumnCellIterator2Test.php b/tests/PhpSpreadsheetTests/Worksheet/ColumnCellIterator2Test.php index c542d89e..90280bd2 100644 --- a/tests/PhpSpreadsheetTests/Worksheet/ColumnCellIterator2Test.php +++ b/tests/PhpSpreadsheetTests/Worksheet/ColumnCellIterator2Test.php @@ -25,9 +25,11 @@ class ColumnCellIterator2Test extends TestCase $lastCoordinate = ''; $firstCoordinate = ''; foreach ($iterator as $cell) { - $lastCoordinate = $cell->getCoordinate(); - if (!$firstCoordinate) { - $firstCoordinate = $lastCoordinate; + if ($cell !== null) { + $lastCoordinate = $cell->getCoordinate(); + if (!$firstCoordinate) { + $firstCoordinate = $lastCoordinate; + } } } self::assertEquals($expectedResultFirst, $firstCoordinate); diff --git a/tests/PhpSpreadsheetTests/Worksheet/ColumnCellIteratorTest.php b/tests/PhpSpreadsheetTests/Worksheet/ColumnCellIteratorTest.php index 1fa25330..9d5f4977 100644 --- a/tests/PhpSpreadsheetTests/Worksheet/ColumnCellIteratorTest.php +++ b/tests/PhpSpreadsheetTests/Worksheet/ColumnCellIteratorTest.php @@ -5,13 +5,20 @@ namespace PhpOffice\PhpSpreadsheetTests\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Worksheet\ColumnCellIterator; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class ColumnCellIteratorTest extends TestCase { - public $mockWorksheet; + /** + * @var Worksheet&MockObject + */ + private $mockWorksheet; - public $mockCell; + /** + * @var Cell&MockObject + */ + private $mockCell; protected function setUp(): void { diff --git a/tests/PhpSpreadsheetTests/Worksheet/ColumnDimensionTest.php b/tests/PhpSpreadsheetTests/Worksheet/ColumnDimensionTest.php index b10875c2..1994fa81 100644 --- a/tests/PhpSpreadsheetTests/Worksheet/ColumnDimensionTest.php +++ b/tests/PhpSpreadsheetTests/Worksheet/ColumnDimensionTest.php @@ -2,6 +2,7 @@ namespace PhpOffice\PhpSpreadsheetTests\Worksheet; +use PhpOffice\PhpSpreadsheet\Helper\Dimension; use PhpOffice\PhpSpreadsheet\Worksheet\ColumnDimension; use PHPUnit\Framework\TestCase; @@ -29,9 +30,18 @@ class ColumnDimensionTest extends TestCase { $expected = 1.2; $columnDimension = new ColumnDimension(); + $columnDimension->setWidth($expected); $result = $columnDimension->getWidth(); self::assertSame($expected, $result); + + $expectedPx = 32.0; + $expectedPt = 24.0; + $columnDimension->setWidth($expectedPx, Dimension::UOM_PIXELS); + $resultPx = $columnDimension->getWidth(Dimension::UOM_PIXELS); + self::assertSame($expectedPx, $resultPx); + $resultPt = $columnDimension->getWidth(Dimension::UOM_POINTS); + self::assertSame($expectedPt, $resultPt); } public function testGetAndSetAutoSize(): void @@ -40,6 +50,6 @@ class ColumnDimensionTest extends TestCase $columnDimension = new ColumnDimension(); $columnDimension->setAutoSize($expected); $result = $columnDimension->getAutoSize(); - self::assertSame($expected, $result); + self::assertTrue($result); } } diff --git a/tests/PhpSpreadsheetTests/Worksheet/ColumnIteratorTest.php b/tests/PhpSpreadsheetTests/Worksheet/ColumnIteratorTest.php index de985cee..98a402fe 100644 --- a/tests/PhpSpreadsheetTests/Worksheet/ColumnIteratorTest.php +++ b/tests/PhpSpreadsheetTests/Worksheet/ColumnIteratorTest.php @@ -5,20 +5,18 @@ namespace PhpOffice\PhpSpreadsheetTests\Worksheet; use PhpOffice\PhpSpreadsheet\Worksheet\Column; use PhpOffice\PhpSpreadsheet\Worksheet\ColumnIterator; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class ColumnIteratorTest extends TestCase { - public $mockWorksheet; - - public $mockColumn; + /** + * @var Worksheet&MockObject + */ + private $mockWorksheet; protected function setUp(): void { - $this->mockColumn = $this->getMockBuilder(Column::class) - ->disableOriginalConstructor() - ->getMock(); - $this->mockWorksheet = $this->getMockBuilder(Worksheet::class) ->disableOriginalConstructor() ->getMock(); @@ -67,6 +65,22 @@ class ColumnIteratorTest extends TestCase } } + public function testIteratorResetStart(): void + { + $iterator = new ColumnIterator($this->mockWorksheet, 'B', 'D'); + $iterator->resetStart('E'); + + $key = $iterator->key(); + self::assertSame('E', $key); + + $lastColumn = $iterator->key(); + while ($iterator->valid() !== false) { + $iterator->next(); + $lastColumn = $iterator->key(); + } + self::assertSame('F', $lastColumn); + } + public function testSeekOutOfRange(): void { $this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class); @@ -81,4 +95,12 @@ class ColumnIteratorTest extends TestCase $iterator->prev(); self::assertFalse($iterator->valid()); } + + public function testResetStartOutOfRange(): void + { + $this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class); + + $iterator = new ColumnIterator($this->mockWorksheet, 'B', 'D'); + $iterator->resetStart('H'); + } } diff --git a/tests/PhpSpreadsheetTests/Worksheet/ColumnTest.php b/tests/PhpSpreadsheetTests/Worksheet/ColumnTest.php index 0abff0ec..7795b5ae 100644 --- a/tests/PhpSpreadsheetTests/Worksheet/ColumnTest.php +++ b/tests/PhpSpreadsheetTests/Worksheet/ColumnTest.php @@ -5,13 +5,15 @@ namespace PhpOffice\PhpSpreadsheetTests\Worksheet; use PhpOffice\PhpSpreadsheet\Worksheet\Column; use PhpOffice\PhpSpreadsheet\Worksheet\ColumnCellIterator; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class ColumnTest extends TestCase { - public $mockWorksheet; - - public $mockColumn; + /** + * @var Worksheet&MockObject + */ + private $mockWorksheet; protected function setUp(): void { diff --git a/tests/PhpSpreadsheetTests/Worksheet/RowCellIterator2Test.php b/tests/PhpSpreadsheetTests/Worksheet/RowCellIterator2Test.php index 20d10da9..52183168 100644 --- a/tests/PhpSpreadsheetTests/Worksheet/RowCellIterator2Test.php +++ b/tests/PhpSpreadsheetTests/Worksheet/RowCellIterator2Test.php @@ -25,9 +25,11 @@ class RowCellIterator2Test extends TestCase $lastCoordinate = ''; $firstCoordinate = ''; foreach ($iterator as $cell) { - $lastCoordinate = $cell->getCoordinate(); - if (!$firstCoordinate) { - $firstCoordinate = $lastCoordinate; + if ($cell !== null) { + $lastCoordinate = $cell->getCoordinate(); + if (!$firstCoordinate) { + $firstCoordinate = $lastCoordinate; + } } } self::assertEquals($expectedResultFirst, $firstCoordinate); diff --git a/tests/PhpSpreadsheetTests/Worksheet/RowCellIteratorTest.php b/tests/PhpSpreadsheetTests/Worksheet/RowCellIteratorTest.php index 4105c91c..85191746 100644 --- a/tests/PhpSpreadsheetTests/Worksheet/RowCellIteratorTest.php +++ b/tests/PhpSpreadsheetTests/Worksheet/RowCellIteratorTest.php @@ -5,13 +5,20 @@ namespace PhpOffice\PhpSpreadsheetTests\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Worksheet\RowCellIterator; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class RowCellIteratorTest extends TestCase { - public $mockWorksheet; + /** + * @var Worksheet&MockObject + */ + private $mockWorksheet; - public $mockCell; + /** + * @var Cell&MockObject + */ + private $mockCell; protected function setUp(): void { diff --git a/tests/PhpSpreadsheetTests/Worksheet/RowDimensionTest.php b/tests/PhpSpreadsheetTests/Worksheet/RowDimensionTest.php new file mode 100644 index 00000000..a5b5a04d --- /dev/null +++ b/tests/PhpSpreadsheetTests/Worksheet/RowDimensionTest.php @@ -0,0 +1,55 @@ +getRowIndex(); + self::assertEquals($expected, $result); + } + + public function testGetAndSetColumnIndex(): void + { + $expected = 2; + $rowDimension = new RowDimension(); + $rowDimension->setRowIndex($expected); + $result = $rowDimension->getRowIndex(); + self::assertSame($expected, $result); + } + + public function testGetAndSetHeight(): void + { + $expected = 1.2; + $columnDimension = new RowDimension(); + + $columnDimension->setRowHeight($expected); + $result = $columnDimension->getRowHeight(); + self::assertSame($expected, $result); + + $expectedPx = 32.0; + $expectedPt = 24.0; + $columnDimension->setRowHeight($expectedPx, Dimension::UOM_PIXELS); + $resultPx = $columnDimension->getRowHeight(Dimension::UOM_PIXELS); + self::assertSame($expectedPx, $resultPx); + $resultPt = $columnDimension->getRowHeight(Dimension::UOM_POINTS); + self::assertSame($expectedPt, $resultPt); + } + + public function testRowZeroHeight(): void + { + $expected = true; + $rowDimension = new RowDimension(); + $rowDimension->setZeroHeight($expected); + $result = $rowDimension->getZeroHeight(); + self::assertTrue($result); + } +} diff --git a/tests/PhpSpreadsheetTests/Worksheet/RowIteratorTest.php b/tests/PhpSpreadsheetTests/Worksheet/RowIteratorTest.php index 919da9ef..6228a320 100644 --- a/tests/PhpSpreadsheetTests/Worksheet/RowIteratorTest.php +++ b/tests/PhpSpreadsheetTests/Worksheet/RowIteratorTest.php @@ -5,20 +5,18 @@ namespace PhpOffice\PhpSpreadsheetTests\Worksheet; use PhpOffice\PhpSpreadsheet\Worksheet\Row; use PhpOffice\PhpSpreadsheet\Worksheet\RowIterator; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class RowIteratorTest extends TestCase { - public $mockWorksheet; - - public $mockRow; + /** + * @var Worksheet&MockObject + */ + private $mockWorksheet; protected function setUp(): void { - $this->mockRow = $this->getMockBuilder(Row::class) - ->disableOriginalConstructor() - ->getMock(); - $this->mockWorksheet = $this->getMockBuilder(Worksheet::class) ->disableOriginalConstructor() ->getMock(); @@ -65,6 +63,22 @@ class RowIteratorTest extends TestCase } } + public function testIteratorResetStart(): void + { + $iterator = new RowIterator($this->mockWorksheet, 2, 4); + $iterator->resetStart(5); + + $key = $iterator->key(); + self::assertSame(5, $key); + + $lastRow = $iterator->key(); + while ($iterator->valid() !== false) { + $iterator->next(); + $lastRow = $iterator->key(); + } + self::assertSame(6, $lastRow); + } + public function testSeekOutOfRange(): void { $this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class); @@ -79,4 +93,12 @@ class RowIteratorTest extends TestCase $iterator->prev(); self::assertFalse($iterator->valid()); } + + public function testResetStartOutOfRange(): void + { + $this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class); + + $iterator = new RowIterator($this->mockWorksheet, 2, 4); + $iterator->resetStart(10); + } } diff --git a/tests/PhpSpreadsheetTests/Worksheet/RowTest.php b/tests/PhpSpreadsheetTests/Worksheet/RowTest.php index 93ff589c..9dea36aa 100644 --- a/tests/PhpSpreadsheetTests/Worksheet/RowTest.php +++ b/tests/PhpSpreadsheetTests/Worksheet/RowTest.php @@ -5,13 +5,15 @@ namespace PhpOffice\PhpSpreadsheetTests\Worksheet; use PhpOffice\PhpSpreadsheet\Worksheet\Row; use PhpOffice\PhpSpreadsheet\Worksheet\RowCellIterator; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class RowTest extends TestCase { - public $mockWorksheet; - - public $mockRow; + /** + * @var Worksheet&MockObject + */ + private $mockWorksheet; protected function setUp(): void { diff --git a/tests/PhpSpreadsheetTests/Worksheet/WorksheetNamedRangesTest.php b/tests/PhpSpreadsheetTests/Worksheet/WorksheetNamedRangesTest.php new file mode 100644 index 00000000..b367583b --- /dev/null +++ b/tests/PhpSpreadsheetTests/Worksheet/WorksheetNamedRangesTest.php @@ -0,0 +1,144 @@ +spreadsheet = $reader->load('tests/data/Worksheet/namedRangeTest.xlsx'); + } + + public function testCellExists(): void + { + $namedCell = 'GREETING'; + + $worksheet = $this->spreadsheet->getActiveSheet(); + $cellExists = $worksheet->cellExists($namedCell); + self::assertTrue($cellExists); + } + + public function testCellNotExists(): void + { + $namedCell = 'GOODBYE'; + + $worksheet = $this->spreadsheet->getActiveSheet(); + $cellExists = $worksheet->cellExists($namedCell); + self::assertFalse($cellExists); + } + + public function testCellExistsInvalidScope(): void + { + $namedCell = 'Result'; + + $worksheet = $this->spreadsheet->getActiveSheet(); + $cellExists = $worksheet->cellExists($namedCell); + self::assertFalse($cellExists); + } + + public function testCellExistsRange(): void + { + $namedRange = 'Range1'; + + $this->expectException(Exception::class); + $this->expectExceptionMessage('Cell coordinate string can not be a range of cells'); + + $worksheet = $this->spreadsheet->getActiveSheet(); + $worksheet->cellExists($namedRange); + } + + public function testGetCell(): void + { + $namedCell = 'GREETING'; + + $worksheet = $this->spreadsheet->getActiveSheet(); + $cell = $worksheet->getCell($namedCell); + self::assertSame('Hello', $cell->getValue()); + } + + public function testGetCellNotExists(): void + { + $namedCell = 'GOODBYE'; + + $this->expectException(Exception::class); + $this->expectExceptionMessage("Invalid cell coordinate {$namedCell}"); + + $worksheet = $this->spreadsheet->getActiveSheet(); + $worksheet->getCell($namedCell); + } + + public function testGetCellInvalidScope(): void + { + $namedCell = 'Result'; + $ucNamedCell = strtoupper($namedCell); + + $this->expectException(Exception::class); + $this->expectExceptionMessage("Invalid cell coordinate {$ucNamedCell}"); + + $worksheet = $this->spreadsheet->getActiveSheet(); + $worksheet->getCell($namedCell); + } + + public function testGetCellLocalScoped(): void + { + $namedCell = 'Result'; + + $this->spreadsheet->setActiveSheetIndexByName('Sheet2'); + $worksheet = $this->spreadsheet->getActiveSheet(); + $cell = $worksheet->getCell($namedCell); + self::assertSame(8, $cell->getCalculatedValue()); + } + + public function testGetCellNamedFormula(): void + { + $namedCell = 'Result'; + + $this->spreadsheet->setActiveSheetIndexByName('Sheet2'); + $worksheet = $this->spreadsheet->getActiveSheet(); + $cell = $worksheet->getCell($namedCell); + self::assertSame(8, $cell->getCalculatedValue()); + } + + public function testGetCellWithNamedRange(): void + { + $namedCell = 'Range1'; + + $this->expectException(Exception::class); + $this->expectExceptionMessage('Cell coordinate string can not be a range of cells'); + + $worksheet = $this->spreadsheet->getActiveSheet(); + $worksheet->getCell($namedCell); + } + + public function testNamedRangeToArray(): void + { + $namedRange = 'Range1'; + + $worksheet = $this->spreadsheet->getActiveSheet(); + $rangeData = $worksheet->namedRangeToArray($namedRange); + self::assertSame([[1, 2, 3]], $rangeData); + } + + public function testInvalidNamedRangeToArray(): void + { + $namedRange = 'Range2'; + + $this->expectException(Exception::class); + $this->expectExceptionMessage("Named Range {$namedRange} does not exist"); + + $worksheet = $this->spreadsheet->getActiveSheet(); + $rangeData = $worksheet->namedRangeToArray($namedRange); + self::assertSame([[1, 2, 3]], $rangeData); + } +} diff --git a/tests/PhpSpreadsheetTests/Worksheet/WorksheetTest.php b/tests/PhpSpreadsheetTests/Worksheet/WorksheetTest.php index 46c848ba..5377444d 100644 --- a/tests/PhpSpreadsheetTests/Worksheet/WorksheetTest.php +++ b/tests/PhpSpreadsheetTests/Worksheet/WorksheetTest.php @@ -18,7 +18,7 @@ class WorksheetTest extends TestCase self::assertSame($testTitle, $worksheet->getTitle()); } - public function setTitleInvalidProvider() + public function setTitleInvalidProvider(): array { return [ [str_repeat('a', 32), 'Maximum 31 characters allowed in sheet title.'], @@ -76,7 +76,7 @@ class WorksheetTest extends TestCase self::assertSame($testCodeName, $worksheet->getCodeName()); } - public function setCodeNameInvalidProvider() + public function setCodeNameInvalidProvider(): array { return [ [str_repeat('a', 32), 'Maximum 31 characters allowed in sheet code name.'], @@ -132,7 +132,7 @@ class WorksheetTest extends TestCase self::assertSame('B2', $worksheet->getTopLeftCell()); } - public function extractSheetTitleProvider() + public function extractSheetTitleProvider(): array { return [ ['B2', '', '', 'B2'], @@ -274,7 +274,7 @@ class WorksheetTest extends TestCase self::assertSame($expectedData, $worksheet->toArray()); } - public function removeRowsProvider() + public function removeRowsProvider(): array { return [ 'Remove all rows except first one' => [ diff --git a/tests/PhpSpreadsheetTests/Writer/Csv/CsvEnclosureTest.php b/tests/PhpSpreadsheetTests/Writer/Csv/CsvEnclosureTest.php index d048183c..383f83ab 100644 --- a/tests/PhpSpreadsheetTests/Writer/Csv/CsvEnclosureTest.php +++ b/tests/PhpSpreadsheetTests/Writer/Csv/CsvEnclosureTest.php @@ -10,32 +10,37 @@ use PhpOffice\PhpSpreadsheetTests\Functional; class CsvEnclosureTest extends Functional\AbstractFunctional { - private static $cellValues = [ + private const CELL_VALUES = [ 'A1' => '2020-06-03', 'B1' => '000123', 'C1' => '06.53', - 'D1' => '14.22', + 'D1' => 14.22, 'A2' => '2020-06-04', 'B2' => '000234', 'C2' => '07.12', 'D2' => '15.44', ]; + private static function getFileData(string $filename): string + { + return file_get_contents($filename) ?: ''; + } + public function testNormalEnclosure(): void { $delimiter = ';'; $enclosure = '"'; $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); - foreach (self::$cellValues as $key => $value) { + foreach (self::CELL_VALUES as $key => $value) { $sheet->setCellValue($key, $value); } $writer = new CsvWriter($spreadsheet); $writer->setDelimiter($delimiter); $writer->setEnclosure($enclosure); - $filename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); + $filename = File::temporaryFilename(); $writer->save($filename); - $filedata = file_get_contents($filename); + $filedata = self::getFileData($filename); $filedata = preg_replace('/\\r?\\n/', $delimiter, $filedata); $reader = new CsvReader(); $reader->setDelimiter($delimiter); @@ -44,11 +49,13 @@ class CsvEnclosureTest extends Functional\AbstractFunctional unlink($filename); $sheet = $newspreadsheet->getActiveSheet(); $expected = ''; - foreach (self::$cellValues as $key => $value) { + foreach (self::CELL_VALUES as $key => $value) { self::assertEquals($value, $sheet->getCell($key)->getValue()); $expected .= "$enclosure$value$enclosure$delimiter"; } self::assertEquals($expected, $filedata); + $spreadsheet->disconnectWorksheets(); + $newspreadsheet->disconnectWorksheets(); } public function testNoEnclosure(): void @@ -57,16 +64,16 @@ class CsvEnclosureTest extends Functional\AbstractFunctional $enclosure = ''; $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); - foreach (self::$cellValues as $key => $value) { + foreach (self::CELL_VALUES as $key => $value) { $sheet->setCellValue($key, $value); } $writer = new CsvWriter($spreadsheet); $writer->setDelimiter($delimiter); $writer->setEnclosure($enclosure); self::assertEquals('', $writer->getEnclosure()); - $filename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); + $filename = File::temporaryFilename(); $writer->save($filename); - $filedata = file_get_contents($filename); + $filedata = self::getFileData($filename); $filedata = preg_replace('/\\r?\\n/', $delimiter, $filedata); $reader = new CsvReader(); $reader->setDelimiter($delimiter); @@ -76,11 +83,13 @@ class CsvEnclosureTest extends Functional\AbstractFunctional unlink($filename); $sheet = $newspreadsheet->getActiveSheet(); $expected = ''; - foreach (self::$cellValues as $key => $value) { + foreach (self::CELL_VALUES as $key => $value) { self::assertEquals($value, $sheet->getCell($key)->getValue()); $expected .= "$enclosure$value$enclosure$delimiter"; } self::assertEquals($expected, $filedata); + $spreadsheet->disconnectWorksheets(); + $newspreadsheet->disconnectWorksheets(); } public function testNotRequiredEnclosure1(): void @@ -89,15 +98,15 @@ class CsvEnclosureTest extends Functional\AbstractFunctional $enclosure = '"'; $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); - foreach (self::$cellValues as $key => $value) { + foreach (self::CELL_VALUES as $key => $value) { $sheet->setCellValue($key, $value); } $writer = new CsvWriter($spreadsheet); self::assertTrue($writer->getEnclosureRequired()); $writer->setEnclosureRequired(false)->setDelimiter($delimiter)->setEnclosure($enclosure); - $filename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); + $filename = File::temporaryFilename(); $writer->save($filename); - $filedata = file_get_contents($filename); + $filedata = self::getFileData($filename); $filedata = preg_replace('/\\r?\\n/', $delimiter, $filedata); $reader = new CsvReader(); $reader->setDelimiter($delimiter); @@ -106,11 +115,13 @@ class CsvEnclosureTest extends Functional\AbstractFunctional unlink($filename); $sheet = $newspreadsheet->getActiveSheet(); $expected = ''; - foreach (self::$cellValues as $key => $value) { + foreach (self::CELL_VALUES as $key => $value) { self::assertEquals($value, $sheet->getCell($key)->getValue()); $expected .= "$value$delimiter"; } self::assertEquals($expected, $filedata); + $spreadsheet->disconnectWorksheets(); + $newspreadsheet->disconnectWorksheets(); } public function testNotRequiredEnclosure2(): void @@ -123,7 +134,7 @@ class CsvEnclosureTest extends Functional\AbstractFunctional 'A2' => 'has space', 'B2' => "has\nnewline", 'C2' => '', - 'D2' => '15.44', + 'D2' => 15.44, 'A3' => ' leadingspace', 'B3' => 'trailingspace ', 'C3' => '=D2*2', @@ -132,13 +143,18 @@ class CsvEnclosureTest extends Functional\AbstractFunctional 'B4' => 'unused', 'C4' => 'unused', 'D4' => 'unused', + 'A5' => false, + 'B5' => true, + 'C5' => null, + 'D5' => 0, ]; $calcc3 = '30.88'; $expected1 = '2020-06-03,"has,separator",has;non-separator,"has""enclosure"'; $expected2 = 'has space,"has' . "\n" . 'newline",,15.44'; $expected3 = ' leadingspace,trailingspace ,' . $calcc3 . ',",leadingcomma"'; $expected4 = '"trailingquote""",unused,unused,unused'; - $expectedfile = "$expected1\n$expected2\n$expected3\n$expected4\n"; + $expected5 = 'FALSE,TRUE,,0'; + $expectedfile = "$expected1\n$expected2\n$expected3\n$expected4\n$expected5\n"; $delimiter = ','; $enclosure = '"'; $spreadsheet = new Spreadsheet(); @@ -149,9 +165,9 @@ class CsvEnclosureTest extends Functional\AbstractFunctional $writer = new CsvWriter($spreadsheet); self::assertTrue($writer->getEnclosureRequired()); $writer->setEnclosureRequired(false)->setDelimiter($delimiter)->setEnclosure($enclosure); - $filename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); + $filename = File::temporaryFilename(); $writer->save($filename); - $filedata = file_get_contents($filename); + $filedata = self::getFileData($filename); $filedata = preg_replace('/\\r/', '', $filedata); $reader = new CsvReader(); $reader->setDelimiter($delimiter); @@ -160,9 +176,70 @@ class CsvEnclosureTest extends Functional\AbstractFunctional unlink($filename); $sheet = $newspreadsheet->getActiveSheet(); foreach ($cellValues2 as $key => $value) { - self::assertEquals(($key === 'C3') ? $calcc3 : $value, $sheet->getCell($key)->getValue()); + self::assertEquals(($key === 'C3') ? $calcc3 : $value, $sheet->getCell($key)->getValue(), "Failure for cell $key"); } self::assertEquals($expectedfile, $filedata); + $spreadsheet->disconnectWorksheets(); + $newspreadsheet->disconnectWorksheets(); + } + + public function testRequiredEnclosure2(): void + { + $cellValues2 = [ + 'A1' => '2020-06-03', + 'B1' => 'has,separator', + 'C1' => 'has;non-separator', + 'D1' => 'has"enclosure', + 'A2' => 'has space', + 'B2' => "has\nnewline", + 'C2' => '', + 'D2' => 15.44, + 'A3' => ' leadingspace', + 'B3' => 'trailingspace ', + 'C3' => '=D2*2', + 'D3' => ',leadingcomma', + 'A4' => 'trailingquote"', + 'B4' => 'unused', + 'C4' => 'unused', + 'D4' => 'unused', + 'A5' => false, + 'B5' => true, + 'C5' => null, + 'D5' => 0, + ]; + $calcc3 = '30.88'; + $expected1 = '"2020-06-03","has,separator","has;non-separator","has""enclosure"'; + $expected2 = '"has space","has' . "\n" . 'newline","","15.44"'; + $expected3 = '" leadingspace","trailingspace ","' . $calcc3 . '",",leadingcomma"'; + $expected4 = '"trailingquote""","unused","unused","unused"'; + $expected5 = '"FALSE","TRUE","","0"'; + $expectedfile = "$expected1\n$expected2\n$expected3\n$expected4\n$expected5\n"; + $delimiter = ','; + $enclosure = '"'; + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + foreach ($cellValues2 as $key => $value) { + $sheet->setCellValue($key, $value); + } + $writer = new CsvWriter($spreadsheet); + self::assertTrue($writer->getEnclosureRequired()); + $writer->setEnclosureRequired(true)->setDelimiter($delimiter)->setEnclosure($enclosure); + $filename = File::temporaryFilename(); + $writer->save($filename); + $filedata = self::getFileData($filename); + $filedata = preg_replace('/\\r/', '', $filedata); + $reader = new CsvReader(); + $reader->setDelimiter($delimiter); + $reader->setEnclosure($enclosure); + $newspreadsheet = $reader->load($filename); + unlink($filename); + $sheet = $newspreadsheet->getActiveSheet(); + foreach ($cellValues2 as $key => $value) { + self::assertEquals(($key === 'C3') ? $calcc3 : $value, $sheet->getCell($key)->getValue(), "Failure for cell $key"); + } + self::assertEquals($expectedfile, $filedata); + $spreadsheet->disconnectWorksheets(); + $newspreadsheet->disconnectWorksheets(); } public function testGoodReread(): void @@ -176,7 +253,7 @@ class CsvEnclosureTest extends Functional\AbstractFunctional $sheet->setCellValue('C1', '4'); $writer = new CsvWriter($spreadsheet); $writer->setEnclosureRequired(false)->setDelimiter($delimiter)->setEnclosure($enclosure); - $filename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); + $filename = File::temporaryFilename(); $writer->save($filename); $reader = new CsvReader(); $reader->setDelimiter($delimiter); @@ -187,6 +264,8 @@ class CsvEnclosureTest extends Functional\AbstractFunctional self::assertEquals('1', $sheet->getCell('A1')->getValue()); self::assertEquals('2,3', $sheet->getCell('B1')->getValue()); self::assertEquals('4', $sheet->getCell('C1')->getValue()); + $spreadsheet->disconnectWorksheets(); + $newspreadsheet->disconnectWorksheets(); } public function testBadReread(): void @@ -200,7 +279,7 @@ class CsvEnclosureTest extends Functional\AbstractFunctional $sheet->setCellValue('C1', '4'); $writer = new CsvWriter($spreadsheet); $writer->setDelimiter($delimiter)->setEnclosure($enclosure); - $filename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); + $filename = File::temporaryFilename(); $writer->save($filename); $reader = new CsvReader(); $reader->setDelimiter($delimiter); @@ -212,5 +291,7 @@ class CsvEnclosureTest extends Functional\AbstractFunctional self::assertEquals('2', $sheet->getCell('B1')->getValue()); self::assertEquals('3', $sheet->getCell('C1')->getValue()); self::assertEquals('4', $sheet->getCell('D1')->getValue()); + $spreadsheet->disconnectWorksheets(); + $newspreadsheet->disconnectWorksheets(); } } diff --git a/tests/PhpSpreadsheetTests/Writer/Csv/CsvExcelCompatibilityTest.php b/tests/PhpSpreadsheetTests/Writer/Csv/CsvExcelCompatibilityTest.php new file mode 100644 index 00000000..9b7d16aa --- /dev/null +++ b/tests/PhpSpreadsheetTests/Writer/Csv/CsvExcelCompatibilityTest.php @@ -0,0 +1,49 @@ +getActiveSheet(); + $sheet->setCellValue('A1', '1'); + $sheet->setCellValue('B1', '2'); + $sheet->setCellValue('C1', '3'); + $sheet->setCellValue('A2', '4'); + $sheet->setCellValue('B2', '5'); + $sheet->setCellValue('C2', '6'); + $writer = new CsvWriter($spreadsheet); + $writer->setExcelCompatibility(true); + self::assertSame('', $writer->getOutputEncoding()); + $filename = File::temporaryFilename(); + $writer->save($filename); + $reader = new CsvReader(); + $spreadsheet2 = $reader->load($filename); + $contents = file_get_contents($filename); + unlink($filename); + self::assertEquals(1, $spreadsheet2->getActiveSheet()->getCell('A1')->getValue()); + self::assertEquals(6, $spreadsheet2->getActiveSheet()->getCell('C2')->getValue()); + self::assertStringContainsString(CsvReader::UTF8_BOM, $contents); + self::assertStringContainsString("\r\n", $contents); + self::assertStringContainsString('sep=;', $contents); + self::assertStringContainsString('"1";"2";"3"', $contents); + self::assertStringContainsString('"4";"5";"6"', $contents); + } +} diff --git a/tests/PhpSpreadsheetTests/Writer/Csv/CsvOutputEncodingTest.php b/tests/PhpSpreadsheetTests/Writer/Csv/CsvOutputEncodingTest.php new file mode 100644 index 00000000..81e4428e --- /dev/null +++ b/tests/PhpSpreadsheetTests/Writer/Csv/CsvOutputEncodingTest.php @@ -0,0 +1,31 @@ +getActiveSheet(); + $sheet->setCellValue('A1', 'こんにちは!'); + $sheet->setCellValue('B1', 'Hello!'); + + $writer = new CsvWriter($spreadsheet); + + $filename = File::temporaryFilename(); + $writer->setUseBOM(false); + $writer->setOutputEncoding('SJIS-win'); + $writer->save($filename); + $contents = file_get_contents($filename); + unlink($filename); + + // self::assertStringContainsString(mb_convert_encoding('こんにちは!', 'SJIS-win'), $contents); + self::assertStringContainsString("\x82\xb1\x82\xf1\x82\xc9\x82\xbf\x82\xcd\x81\x49", $contents); + } +} diff --git a/tests/PhpSpreadsheetTests/Writer/Csv/CsvWriteTest.php b/tests/PhpSpreadsheetTests/Writer/Csv/CsvWriteTest.php index 7fe1902b..aa9a8fc3 100644 --- a/tests/PhpSpreadsheetTests/Writer/Csv/CsvWriteTest.php +++ b/tests/PhpSpreadsheetTests/Writer/Csv/CsvWriteTest.php @@ -23,7 +23,7 @@ class CsvWriteTest extends Functional\AbstractFunctional $writer = new CsvWriter($spreadsheet); $writer->setSheetIndex(1); self::assertEquals(1, $writer->getSheetIndex()); - $filename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); + $filename = File::temporaryFilename(); $writer->save($filename); $reader = new CsvReader(); $newspreadsheet = $reader->load($filename); diff --git a/tests/PhpSpreadsheetTests/Writer/Html/CallbackTest.php b/tests/PhpSpreadsheetTests/Writer/Html/CallbackTest.php index 94c201a7..ae71ca55 100644 --- a/tests/PhpSpreadsheetTests/Writer/Html/CallbackTest.php +++ b/tests/PhpSpreadsheetTests/Writer/Html/CallbackTest.php @@ -42,7 +42,7 @@ EOF; self::assertEquals($html3, $html1); $writer->setEditHtmlCallback([$this, 'yellowBody']); - $oufil = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); + $oufil = File::temporaryFilename(); $writer->save($oufil); $html4 = file_get_contents($oufil); unlink($oufil); diff --git a/tests/PhpSpreadsheetTests/Writer/Html/HtmlCommentsTest.php b/tests/PhpSpreadsheetTests/Writer/Html/HtmlCommentsTest.php index 0d43d7eb..a4f474fa 100644 --- a/tests/PhpSpreadsheetTests/Writer/Html/HtmlCommentsTest.php +++ b/tests/PhpSpreadsheetTests/Writer/Html/HtmlCommentsTest.php @@ -8,9 +8,12 @@ use PhpOffice\PhpSpreadsheetTests\Functional; class HtmlCommentsTest extends Functional\AbstractFunctional { + /** + * @var Spreadsheet + */ private $spreadsheet; - public function providerCommentRichText() + public function providerCommentRichText(): array { $valueSingle = 'I am comment.'; $valueMulti = 'I am ' . PHP_EOL . 'multi-line' . PHP_EOL . 'comment.'; diff --git a/tests/PhpSpreadsheetTests/Writer/Html/HtmlNumberFormatTest.php b/tests/PhpSpreadsheetTests/Writer/Html/HtmlNumberFormatTest.php index 340e820b..056ffc71 100644 --- a/tests/PhpSpreadsheetTests/Writer/Html/HtmlNumberFormatTest.php +++ b/tests/PhpSpreadsheetTests/Writer/Html/HtmlNumberFormatTest.php @@ -3,6 +3,7 @@ namespace PhpOffice\PhpSpreadsheetTests\Writer\Html; use DOMDocument; +use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Html; @@ -10,10 +11,19 @@ use PhpOffice\PhpSpreadsheetTests\Functional; class HtmlNumberFormatTest extends Functional\AbstractFunctional { + /** + * @var string + */ private $currency; + /** + * @var string + */ private $decsep; + /** + * @var string + */ private $thosep; protected function setUp(): void @@ -166,13 +176,13 @@ class HtmlNumberFormatTest extends Functional\AbstractFunctional $rows = $tbod[0]->getElementsByTagName('tr'); $tds = $rows[0]->getElementsByTagName('td'); - $nbsp = html_entity_decode(' '); + $nbsp = html_entity_decode(' ', Settings::htmlEntityFlags()); self::assertEquals($expectedResult, str_replace($nbsp, ' ', $tds[0]->textContent)); $this->writeAndReload($spreadsheet, 'Html'); } - public function providerNumberFormat() + public function providerNumberFormat(): array { return require __DIR__ . '/../../../data/Style/NumberFormat.php'; } @@ -202,13 +212,13 @@ class HtmlNumberFormatTest extends Functional\AbstractFunctional $rows = $tbod[0]->getElementsByTagName('tr'); $tds = $rows[0]->getElementsByTagName('td'); - $nbsp = html_entity_decode(' '); + $nbsp = html_entity_decode(' ', Settings::htmlEntityFlags()); self::assertEquals($expectedResult, str_replace($nbsp, ' ', $tds[0]->textContent)); $this->writeAndReload($spreadsheet, 'Html'); } - public function providerNumberFormatDates() + public function providerNumberFormatDates(): array { return require __DIR__ . '/../../../data/Style/NumberFormatDates.php'; } diff --git a/tests/PhpSpreadsheetTests/Writer/Html/ImagesRootTest.php b/tests/PhpSpreadsheetTests/Writer/Html/ImagesRootTest.php index 6cc7f18f..b36a87c0 100644 --- a/tests/PhpSpreadsheetTests/Writer/Html/ImagesRootTest.php +++ b/tests/PhpSpreadsheetTests/Writer/Html/ImagesRootTest.php @@ -9,11 +9,19 @@ use PhpOffice\PhpSpreadsheetTests\Functional; class ImagesRootTest extends Functional\AbstractFunctional { - private $curdir; + /** + * @var string + */ + private $curdir = ''; protected function setUp(): void { - $this->curdir = getcwd(); + $curdir = getcwd(); + if ($curdir === false) { + self::fail('Unable to obtain current directory'); + } else { + $this->curdir = $curdir; + } } protected function tearDown(): void @@ -61,5 +69,6 @@ class ImagesRootTest extends Functional\AbstractFunctional self::assertCount(1, $img); self::assertEquals("$root/$stub", $img[0]->getAttribute('src')); self::assertEquals($desc, $img[0]->getAttribute('alt')); + $spreadsheet->disconnectWorksheets(); } } diff --git a/tests/PhpSpreadsheetTests/Writer/Html/XssVulnerabilityTest.php b/tests/PhpSpreadsheetTests/Writer/Html/XssVulnerabilityTest.php index 48aced02..4d8b03a5 100644 --- a/tests/PhpSpreadsheetTests/Writer/Html/XssVulnerabilityTest.php +++ b/tests/PhpSpreadsheetTests/Writer/Html/XssVulnerabilityTest.php @@ -10,7 +10,7 @@ use PhpOffice\PhpSpreadsheetTests\Functional; class XssVulnerabilityTest extends Functional\AbstractFunctional { - public function providerAcceptableMarkupRichText() + public function providerAcceptableMarkupRichText(): array { return [ 'basic text' => ['Hello, I am safely viewing your site', 'Hello, I am safely viewing your site'], @@ -37,17 +37,18 @@ class XssVulnerabilityTest extends Functional\AbstractFunctional ->getComment('A1') ->setText($richText); - $filename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); + $filename = File::temporaryFilename(); $writer = IOFactory::createWriter($spreadsheet, 'Html'); $writer->save($filename); $verify = file_get_contents($filename); + unlink($filename); // Ensure that executable js has been stripped from the comments self::assertStringContainsString($adjustedTextString, $verify); } - public function providerXssRichText() + public function providerXssRichText(): array { return [ 'script tag' => ["Hello, I am trying to your site"], @@ -58,8 +59,6 @@ class XssVulnerabilityTest extends Functional\AbstractFunctional ]; } - private static $counter = 0; - /** * @dataProvider providerXssRichText * @@ -78,14 +77,13 @@ class XssVulnerabilityTest extends Functional\AbstractFunctional ->getComment('A1') ->setText($richText); - $filename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); + $filename = File::temporaryFilename(); $writer = IOFactory::createWriter($spreadsheet, 'Html'); $writer->save($filename); $verify = file_get_contents($filename); - $counter = self::$counter++; - file_put_contents("verify{$counter}.html", $verify); + unlink($filename); // Ensure that executable js has been stripped from the comments self::assertStringNotContainsString($xssTextString, $verify); } diff --git a/tests/PhpSpreadsheetTests/Writer/Ods/AutoFilterTest.php b/tests/PhpSpreadsheetTests/Writer/Ods/AutoFilterTest.php new file mode 100644 index 00000000..4368ef76 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Writer/Ods/AutoFilterTest.php @@ -0,0 +1,33 @@ +getActiveSheet(); + + $dataSet = [ + ['Year', 'Quarter', 'Sales'], + [2020, 'Q1', 100], + [2020, 'Q2', 120], + [2020, 'Q3', 140], + [2020, 'Q4', 160], + [2021, 'Q1', 180], + [2021, 'Q2', 75], + [2021, 'Q3', 0], + [2021, 'Q4', 0], + ]; + $worksheet->fromArray($dataSet, null, 'A1'); + $worksheet->getAutoFilter()->setRange('A1:C9'); + + $reloaded = $this->writeAndReload($spreadsheet, 'Ods'); + + self::assertSame('A1:C9', $reloaded->getActiveSheet()->getAutoFilter()->getRange()); + } +} diff --git a/tests/PhpSpreadsheetTests/Writer/Ods/ContentTest.php b/tests/PhpSpreadsheetTests/Writer/Ods/ContentTest.php index 4086914d..917a0410 100644 --- a/tests/PhpSpreadsheetTests/Writer/Ods/ContentTest.php +++ b/tests/PhpSpreadsheetTests/Writer/Ods/ContentTest.php @@ -16,8 +16,15 @@ use PHPUnit\Framework\TestCase; class ContentTest extends TestCase { + /** + * @var string + */ private $samplesPath = 'tests/data/Writer/Ods'; + /** + * @var string + */ + /** * @var string */ @@ -59,6 +66,7 @@ class ContentTest extends TestCase $worksheet1->setCellValue('A2', true); // Boolean $worksheet1->setCellValue('B2', false); // Boolean + $worksheet1->setCellValueExplicit( 'C2', '=IF(A3, CONCATENATE(A1, " ", A2), CONCATENATE(A2, " ", A1))', @@ -70,6 +78,9 @@ class ContentTest extends TestCase ->getNumberFormat() ->setFormatCode(NumberFormat::FORMAT_DATE_DATETIME); + $worksheet1->setCellValueExplicit('F1', null, DataType::TYPE_ERROR); + $worksheet1->setCellValueExplicit('G1', 'Lorem ipsum', DataType::TYPE_INLINE); + // Styles $worksheet1->getStyle('A1')->getFont()->setBold(true); $worksheet1->getStyle('B1')->getFont()->setItalic(true); diff --git a/tests/PhpSpreadsheetTests/Writer/Ods/DefinedNamesTest.php b/tests/PhpSpreadsheetTests/Writer/Ods/DefinedNamesTest.php new file mode 100644 index 00000000..1b2e30b2 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Writer/Ods/DefinedNamesTest.php @@ -0,0 +1,33 @@ +getActiveSheet(); + + $dataSet = [ + [7, 'x', 5], + ['=', '=FORMULA'], + ]; + $worksheet->fromArray($dataSet, null, 'A1'); + + $spreadsheet->addDefinedName(new NamedRange('FIRST', $worksheet, '$A$1')); + $spreadsheet->addDefinedName(new NamedRange('SECOND', $worksheet, '$C$1')); + $spreadsheet->addDefinedName(new NamedFormula('FORMULA', $worksheet, '=FIRST*SECOND')); + + $reloaded = $this->writeAndReload($spreadsheet, 'Ods'); + + self::assertSame(7, $reloaded->getActiveSheet()->getCell('FIRST')->getValue()); + self::assertSame(5, $reloaded->getActiveSheet()->getCell('SECOND')->getValue()); + self::assertSame(35, $reloaded->getActiveSheet()->getCell('B2')->getCalculatedValue()); + } +} diff --git a/tests/PhpSpreadsheetTests/Writer/PreCalcTest.php b/tests/PhpSpreadsheetTests/Writer/PreCalcTest.php new file mode 100644 index 00000000..2db372c4 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Writer/PreCalcTest.php @@ -0,0 +1,208 @@ +outfile !== '') { + unlink($this->outfile); + $this->outfile = ''; + } + } + + public function providerPreCalc(): array + { + return [ + [true, 'Xlsx'], + [false, 'Xlsx'], + [null, 'Xlsx'], + [true, 'Xls'], + [false, 'Xls'], + [null, 'Xls'], + [true, 'Ods'], + [false, 'Ods'], + [null, 'Ods'], + [true, 'Html'], + [false, 'Html'], + [null, 'Html'], + [true, 'Csv'], + [false, 'Csv'], + [null, 'Csv'], + ]; + } + + private static function autoSize(?ColumnDimension $columnDimension): void + { + if ($columnDimension === null) { + self::fail('Unable to getColumnDimension'); + } else { + $columnDimension->setAutoSize(true); + } + } + + private static function verifyA2(Calculation $calculation, string $title, ?bool $preCalc): void + { + $cellValue = 0; + // A2 has no cached calculation value if preCalc is false + if ($preCalc === false) { + self::assertFalse($calculation->getValueFromCache("$title!A2", $cellValue)); + } else { + self::assertTrue($calculation->getValueFromCache("$title!A2", $cellValue)); + self::assertSame(3, $cellValue); + } + } + + private const AUTOSIZE_TYPES = ['Xlsx', 'Xls', 'Html']; + + private static function verifyA3B2(Calculation $calculation, string $title, ?bool $preCalc, string $type): void + { + $cellValue = 0; + if (in_array($type, self::AUTOSIZE_TYPES) || $preCalc !== false) { + // These 3 types support auto-sizing. + // A3 has cached calculation value because it is used in B2 calculation + self::assertTrue($calculation->getValueFromCache("$title!A3", $cellValue)); + self::assertSame(11, $cellValue); + // B2 has cached calculation value because its column is auto-sized + self::assertTrue($calculation->getValueFromCache("$title!B2", $cellValue)); + self::assertSame(14, $cellValue); + } else { + self::assertFalse($calculation->getValueFromCache("$title!A3", $cellValue)); + self::assertFalse($calculation->getValueFromCache("$title!B2", $cellValue)); + } + } + + private static function readFile(string $file): string + { + $dataOut = ''; + $data = file_get_contents($file); + // confirm that file contains B2 pre-calculated or not as appropriate + if ($data === false) { + self::fail("Unable to read $file"); + } else { + $dataOut = $data; + } + + return $dataOut; + } + + private function verifyXlsx(?bool $preCalc, string $type): void + { + if ($type === 'Xlsx') { + $file = 'zip://'; + $file .= $this->outfile; + $file .= '#xl/worksheets/sheet1.xml'; + $data = self::readFile($file); + // confirm that file contains B2 pre-calculated or not as appropriate + if ($preCalc === false) { + self::assertStringContainsString('3+A30', $data); + } else { + self::assertStringContainsString('3+A314', $data); + } + $file = 'zip://'; + $file .= $this->outfile; + $file .= '#xl/workbook.xml'; + $data = self::readFile($file); + // confirm whether workbook is set to recalculate + if ($preCalc === false) { + self::assertStringContainsString('', $data); + } else { + self::assertStringContainsString('', $data); + } + } + } + + private function verifyOds(?bool $preCalc, string $type): void + { + if ($type === 'Ods') { + $file = 'zip://'; + $file .= $this->outfile; + $file .= '#content.xml'; + $data = self::readFile($file); + // confirm that file contains B2 pre-calculated or not as appropriate + if ($preCalc === false) { + self::assertStringContainsString('table:formula="of:=3+[.A3]" office:value-type="string" office:value="=3+A3"', $data); + } else { + self::assertStringContainsString(' table:formula="of:=3+[.A3]" office:value-type="float" office:value="14"', $data); + } + } + } + + private function verifyHtml(?bool $preCalc, string $type): void + { + if ($type === 'Html') { + $data = self::readFile($this->outfile); + // confirm that file contains B2 pre-calculated or not as appropriate + if ($preCalc === false) { + self::assertStringContainsString('>=1+2', $data); + self::assertStringContainsString('>=3+A3', $data); + self::assertStringContainsString('>=5+6', $data); + } else { + self::assertStringContainsString('>3', $data); + self::assertStringContainsString('>14', $data); + self::assertStringContainsString('>11', $data); + } + } + } + + private function verifyCsv(?bool $preCalc, string $type): void + { + if ($type === 'Csv') { + $data = self::readFile($this->outfile); + // confirm that file contains B2 pre-calculated or not as appropriate + if ($preCalc === false) { + self::assertStringContainsString('"=1+2"', $data); + self::assertStringContainsString('"=3+A3"', $data); + self::assertStringContainsString('"=5+6"', $data); + } else { + self::assertStringContainsString('"3"', $data); + self::assertStringContainsString('"14"', $data); + self::assertStringContainsString('"11"', $data); + } + } + } + + /** + * @dataProvider providerPreCalc + */ + public function testPreCalc(?bool $preCalc, string $type): void + { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->getCell('A1')->setValue('Column not set to autoSize'); + $sheet->getCell('B1')->setValue('Column set to autoSize'); + $sheet->getCell('A2')->setValue('=1+2'); + $sheet->getCell('A3')->setValue('=5+6'); + $sheet->getCell('B2')->setValue('=3+A3'); + $columnDimension = $sheet->getColumnDimension('B'); + self::autoSize($columnDimension); + + $writer = IOFactory::createWriter($spreadsheet, $type); + if ($preCalc !== null) { + $writer->setPreCalculateFormulas($preCalc); + } + $this->outfile = File::temporaryFilename(); + $writer->save($this->outfile); + $title = $sheet->getTitle(); + $calculation = Calculation::getInstance($spreadsheet); + // verify values in Calculation cache + self::verifyA2($calculation, $title, $preCalc); + self::verifyA3B2($calculation, $title, $preCalc, $type); + // verify values in output file + $this->verifyXlsx($preCalc, $type); + $this->verifyOds($preCalc, $type); + $this->verifyHtml($preCalc, $type); + $this->verifyCsv($preCalc, $type); + } +} diff --git a/tests/PhpSpreadsheetTests/Writer/RetainSelectedCellsTest.php b/tests/PhpSpreadsheetTests/Writer/RetainSelectedCellsTest.php new file mode 100644 index 00000000..59f480fd --- /dev/null +++ b/tests/PhpSpreadsheetTests/Writer/RetainSelectedCellsTest.php @@ -0,0 +1,77 @@ +getActiveSheet(); + $sheet->setCellValue('A1', '=SIN(1)') + ->setCellValue('A2', '=SIN(2)') + ->setCellValue('A3', '=SIN(3)') + ->setCellValue('B1', '=SIN(4)') + ->setCellValue('B2', '=SIN(5)') + ->setCellValue('B3', '=SIN(6)') + ->setCellValue('C1', '=SIN(7)') + ->setCellValue('C2', '=SIN(8)') + ->setCellValue('C3', '=SIN(9)'); + $sheet->setSelectedCell('A3'); + $sheet = $spreadsheet->createSheet(); + $sheet->setCellValue('A1', '=SIN(1)') + ->setCellValue('A2', '=SIN(2)') + ->setCellValue('A3', '=SIN(3)') + ->setCellValue('B1', '=SIN(4)') + ->setCellValue('B2', '=SIN(5)') + ->setCellValue('B3', '=SIN(6)') + ->setCellValue('C1', '=SIN(7)') + ->setCellValue('C2', '=SIN(8)') + ->setCellValue('C3', '=SIN(9)'); + $sheet->setSelectedCell('B1'); + $sheet = $spreadsheet->createSheet(); + $sheet->setCellValue('A1', '=SIN(1)') + ->setCellValue('A2', '=SIN(2)') + ->setCellValue('A3', '=SIN(3)') + ->setCellValue('B1', '=SIN(4)') + ->setCellValue('B2', '=SIN(5)') + ->setCellValue('B3', '=SIN(6)') + ->setCellValue('C1', '=SIN(7)') + ->setCellValue('C2', '=SIN(8)') + ->setCellValue('C3', '=SIN(9)'); + $sheet->setSelectedCell('C2'); + $spreadsheet->setActiveSheetIndex(1); + + $reloaded = $this->writeAndReload($spreadsheet, $format); + self::assertEquals('A3', $spreadsheet->getSheet(0)->getSelectedCells()); + self::assertEquals('B1', $spreadsheet->getSheet(1)->getSelectedCells()); + self::assertEquals('C2', $spreadsheet->getSheet(2)->getSelectedCells()); + self::assertEquals(1, $spreadsheet->getActiveSheetIndex()); + // SelectedCells and ActiveSheet don't make sense for Html, Csv. + if ($format === 'Xlsx' || $format === 'Xls' || $format === 'Ods') { + self::assertEquals('A3', $reloaded->getSheet(0)->getSelectedCells()); + self::assertEquals('B1', $reloaded->getSheet(1)->getSelectedCells()); + self::assertEquals('C2', $reloaded->getSheet(2)->getSelectedCells()); + self::assertEquals(1, $reloaded->getActiveSheetIndex()); + } + } +} diff --git a/tests/PhpSpreadsheetTests/Writer/Xls/FormulaErrTest.php b/tests/PhpSpreadsheetTests/Writer/Xls/FormulaErrTest.php index bbb00d89..3965db62 100644 --- a/tests/PhpSpreadsheetTests/Writer/Xls/FormulaErrTest.php +++ b/tests/PhpSpreadsheetTests/Writer/Xls/FormulaErrTest.php @@ -19,7 +19,7 @@ class FormulaErrTest extends TestCase $sheet0->setCellValue('C1', '=DEFNAM=2'); $sheet0->setCellValue('D1', '=CONCAT("X",DEFNAM)'); $writer = IOFactory::createWriter($obj, 'Xls'); - $filename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); + $filename = File::temporaryFilename(); $writer->save($filename); $reader = IOFactory::createReader('Xls'); $robj = $reader->load($filename); diff --git a/tests/PhpSpreadsheetTests/Writer/Xls/Sample19Test.php b/tests/PhpSpreadsheetTests/Writer/Xls/Sample19Test.php new file mode 100644 index 00000000..13fa9fa1 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Writer/Xls/Sample19Test.php @@ -0,0 +1,28 @@ +setActiveSheetIndex(0); + $spreadsheet->getActiveSheet()->setCellValue('A1', 'Firstname:') + ->setCellValue('A2', 'Lastname:') + ->setCellValue('A3', 'Fullname:') + ->setCellValue('B1', 'Maarten') + ->setCellValue('B2', 'Balliauw') + ->setCellValue('B3', '=B1 & " " & B2') + ->setCellValue('C1', '=A2&A3&A3&A2&B1'); + + $robj = $this->writeAndReload($spreadsheet, 'Xls'); + $sheet0 = $robj->setActiveSheetIndex(0); + // Xls parser eliminates unneeded whitespace + self::assertEquals('=B1&" "&B2', $sheet0->getCell('B3')->getValue()); + self::assertEquals('Maarten Balliauw', $sheet0->getCell('B3')->getCalculatedValue()); + self::assertEquals('Lastname:Fullname:Fullname:Lastname:Maarten', $sheet0->getCell('C1')->getCalculatedValue()); + } +} diff --git a/tests/PhpSpreadsheetTests/Writer/Xls/VisibilityTest.php b/tests/PhpSpreadsheetTests/Writer/Xls/VisibilityTest.php new file mode 100644 index 00000000..7de39328 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Writer/Xls/VisibilityTest.php @@ -0,0 +1,99 @@ +getActiveSheet(); + foreach ($visibleRows as $row => $visibility) { + $worksheet->setCellValue("A{$row}", $row); + $worksheet->getRowDimension($row)->setVisible($visibility); + } + + $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xls'); + $reloadedWorksheet = $reloadedSpreadsheet->getActiveSheet(); + foreach ($visibleRows as $row => $visibility) { + self::assertSame($visibility, $reloadedWorksheet->getRowDimension($row)->getVisible()); + } + } + + public function dataProviderRowVisibility(): array + { + return [ + [ + [1 => true, 2 => false, 3 => false, 4 => true, 5 => true, 6 => false], + ], + ]; + } + + /** + * @dataProvider dataProviderColumnVisibility + */ + public function testColumnVisibility(array $visibleColumns): void + { + $spreadsheet = new Spreadsheet(); + $worksheet = $spreadsheet->getActiveSheet(); + foreach ($visibleColumns as $column => $visibility) { + $worksheet->setCellValue("{$column}1", $column); + $worksheet->getColumnDimension($column)->setVisible($visibility); + } + + $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xls'); + $reloadedWorksheet = $reloadedSpreadsheet->getActiveSheet(); + foreach ($visibleColumns as $column => $visibility) { + self::assertSame($visibility, $reloadedWorksheet->getColumnDimension($column)->getVisible()); + } + } + + public function dataProviderColumnVisibility(): array + { + return [ + [ + ['A' => true, 'B' => false, 'C' => false, 'D' => true, 'E' => true, 'F' => false], + ], + ]; + } + + /** + * @dataProvider dataProviderSheetVisibility + */ + public function testSheetVisibility(array $visibleSheets): void + { + $spreadsheet = new Spreadsheet(); + $spreadsheet->removeSheetByIndex(0); + foreach ($visibleSheets as $sheetName => $visibility) { + $worksheet = $spreadsheet->addSheet(new Worksheet($spreadsheet, $sheetName)); + $worksheet->setCellValue('A1', $sheetName); + $worksheet->setSheetState($visibility); + } + + $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xls'); + foreach ($visibleSheets as $sheetName => $visibility) { + $reloadedWorksheet = $reloadedSpreadsheet->getSheetByName($sheetName) ?? new Worksheet(); + self::assertSame($visibility, $reloadedWorksheet->getSheetState()); + } + } + + public function dataProviderSheetVisibility(): array + { + return [ + [ + [ + 'Worksheet 1' => Worksheet::SHEETSTATE_HIDDEN, + 'Worksheet 2' => Worksheet::SHEETSTATE_VERYHIDDEN, + 'Worksheet 3' => Worksheet::SHEETSTATE_VISIBLE, + ], + ], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Writer/Xls/WorkbookTest.php b/tests/PhpSpreadsheetTests/Writer/Xls/WorkbookTest.php index 5ebe645f..160a665a 100644 --- a/tests/PhpSpreadsheetTests/Writer/Xls/WorkbookTest.php +++ b/tests/PhpSpreadsheetTests/Writer/Xls/WorkbookTest.php @@ -47,7 +47,7 @@ class WorkbookTest extends TestCase self::assertEquals($expectedResult, $palette); } - public function providerAddColor() + public function providerAddColor(): array { $this->setUp(); diff --git a/tests/PhpSpreadsheetTests/Writer/Xls/XlsGifBmpTest.php b/tests/PhpSpreadsheetTests/Writer/Xls/XlsGifBmpTest.php index ceba7e54..d1353fa3 100644 --- a/tests/PhpSpreadsheetTests/Writer/Xls/XlsGifBmpTest.php +++ b/tests/PhpSpreadsheetTests/Writer/Xls/XlsGifBmpTest.php @@ -2,6 +2,7 @@ namespace PhpOffice\PhpSpreadsheetTests\Writer\Xls; +use DateTime; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Drawing; use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; @@ -9,6 +10,9 @@ use PhpOffice\PhpSpreadsheetTests\Functional\AbstractFunctional; class XlsGifBmpTest extends AbstractFunctional { + /** + * @var string + */ private $filename = ''; protected function tearDown(): void @@ -21,7 +25,7 @@ class XlsGifBmpTest extends AbstractFunctional public function testBmp(): void { - $pgmstart = time(); + $pgmstart = (float) (new DateTime())->format('U'); $spreadsheet = new Spreadsheet(); $filstart = $spreadsheet->getProperties()->getModified(); self::assertLessThanOrEqual($filstart, $pgmstart); @@ -38,15 +42,15 @@ class XlsGifBmpTest extends AbstractFunctional $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xls'); $creationDatestamp = $reloadedSpreadsheet->getProperties()->getCreated(); $filstart = $creationDatestamp; - $pSheet = $reloadedSpreadsheet->getActiveSheet(); - $drawings = $pSheet->getDrawingCollection(); + $worksheet = $reloadedSpreadsheet->getActiveSheet(); + $drawings = $worksheet->getDrawingCollection(); self::assertCount(1, $drawings); - foreach ($pSheet->getDrawingCollection() as $drawing) { + foreach ($worksheet->getDrawingCollection() as $drawing) { // See if Scrutinizer approves this $mimeType = ($drawing instanceof MemoryDrawing) ? $drawing->getMimeType() : 'notmemorydrawing'; self::assertEquals('image/png', $mimeType); } - $pgmend = time(); + $pgmend = (float) (new DateTime())->format('U'); self::assertLessThanOrEqual($pgmend, $pgmstart); self::assertLessThanOrEqual($pgmend, $filstart); @@ -67,10 +71,10 @@ class XlsGifBmpTest extends AbstractFunctional $drawing->setCoordinates('A1'); $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xls'); - $pSheet = $reloadedSpreadsheet->getActiveSheet(); - $drawings = $pSheet->getDrawingCollection(); + $worksheet = $reloadedSpreadsheet->getActiveSheet(); + $drawings = $worksheet->getDrawingCollection(); self::assertCount(1, $drawings); - foreach ($pSheet->getDrawingCollection() as $drawing) { + foreach ($worksheet->getDrawingCollection() as $drawing) { $mimeType = ($drawing instanceof MemoryDrawing) ? $drawing->getMimeType() : 'notmemorydrawing'; self::assertEquals('image/png', $mimeType); } diff --git a/tests/PhpSpreadsheetTests/Writer/Xlsx/ConditionalTest.php b/tests/PhpSpreadsheetTests/Writer/Xlsx/ConditionalTest.php new file mode 100644 index 00000000..21659dad --- /dev/null +++ b/tests/PhpSpreadsheetTests/Writer/Xlsx/ConditionalTest.php @@ -0,0 +1,41 @@ +getActiveSheet(); + + $condition = new Conditional(); + $condition->setConditionType(Conditional::CONDITION_NOTCONTAINSTEXT); + $condition->setOperatorType(Conditional::OPERATOR_NOTCONTAINS); + $condition->setText('C'); + $condition->getStyle()->applyFromArray([ + 'fill' => [ + 'color' => ['argb' => 'FFFFC000'], + 'fillType' => Fill::FILL_SOLID, + ], + ]); + $worksheet->setConditionalStyles('A1:A5', [$condition]); + + $writer = new Xlsx($spreadsheet); + $writerWorksheet = new Xlsx\Worksheet($writer); + $data = $writerWorksheet->writeWorksheet($worksheet, []); + $needle = <<ISERROR(SEARCH("C",A1:A5))
+xml; + self::assertStringContainsString($needle, $data); + } +} diff --git a/tests/PhpSpreadsheetTests/Writer/Xlsx/DrawingsTest.php b/tests/PhpSpreadsheetTests/Writer/Xlsx/DrawingsTest.php index d6ad77c6..012cdbcd 100644 --- a/tests/PhpSpreadsheetTests/Writer/Xlsx/DrawingsTest.php +++ b/tests/PhpSpreadsheetTests/Writer/Xlsx/DrawingsTest.php @@ -2,30 +2,13 @@ namespace PhpOffice\PhpSpreadsheetTests\Writer\Xlsx; +use PhpOffice\PhpSpreadsheet\IOFactory; use PhpOffice\PhpSpreadsheet\Reader\Xlsx; -use PhpOffice\PhpSpreadsheet\Settings; +use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheetTests\Functional\AbstractFunctional; class DrawingsTest extends AbstractFunctional { - /** - * @var int - */ - protected $prevValue; - - protected function setUp(): void - { - $this->prevValue = Settings::getLibXmlLoaderOptions(); - - // Disable validating XML with the DTD - Settings::setLibXmlLoaderOptions($this->prevValue & ~LIBXML_DTDVALID & ~LIBXML_DTDATTR & ~LIBXML_DTDLOAD); - } - - protected function tearDown(): void - { - Settings::setLibXmlLoaderOptions($this->prevValue); - } - /** * Test save and load XLSX file with drawing on 2nd worksheet. */ @@ -42,4 +25,35 @@ class DrawingsTest extends AbstractFunctional // Fake assert. The only thing we need is to ensure the file is loaded without exception self::assertNotNull($reloadedSpreadsheet); } + + /** + * Test save and load XLSX file with drawing with the same file name. + */ + public function testSaveLoadWithDrawingWithSamePath(): void + { + // Read spreadsheet from file + $originalFileName = 'tests/data/Writer/XLSX/saving_drawing_with_same_path.xlsx'; + + $originalFile = file_get_contents($originalFileName); + + $tempFileName = File::sysGetTempDir() . '/saving_drawing_with_same_path'; + + file_put_contents($tempFileName, $originalFile); + + $reader = new Xlsx(); + $spreadsheet = $reader->load($tempFileName); + + $spreadsheet->getActiveSheet()->setCellValue('D5', 'foo'); + // Save spreadsheet to file to the same path. Success test case won't + // throw exception here + $writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); + $writer->save($tempFileName); + + $reloadedSpreadsheet = $reader->load($tempFileName); + + unlink($tempFileName); + + // Fake assert. The only thing we need is to ensure the file is loaded without exception + self::assertNotNull($reloadedSpreadsheet); + } } diff --git a/tests/PhpSpreadsheetTests/Writer/Xlsx/FloatsRetainedTest.php b/tests/PhpSpreadsheetTests/Writer/Xlsx/FloatsRetainedTest.php index 746b9846..6ba8316b 100644 --- a/tests/PhpSpreadsheetTests/Writer/Xlsx/FloatsRetainedTest.php +++ b/tests/PhpSpreadsheetTests/Writer/Xlsx/FloatsRetainedTest.php @@ -3,7 +3,6 @@ namespace PhpOffice\PhpSpreadsheetTests\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\Xlsx as Reader; -use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx as Writer; @@ -18,8 +17,7 @@ class FloatsRetainedTest extends TestCase */ public function testIntyFloatsRetainedByWriter($value): void { - $outputFilename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); - Settings::setLibXmlLoaderOptions(null); + $outputFilename = File::temporaryFilename(); $sheet = new Spreadsheet(); $sheet->getActiveSheet()->getCell('A1')->setValue($value); @@ -33,7 +31,7 @@ class FloatsRetainedTest extends TestCase self::assertSame($value, $sheet->getActiveSheet()->getCell('A1')->getValue()); } - public function providerIntyFloatsRetainedByWriter() + public function providerIntyFloatsRetainedByWriter(): array { return [ [-1.0], diff --git a/tests/PhpSpreadsheetTests/Writer/Xlsx/Issue2082Test.php b/tests/PhpSpreadsheetTests/Writer/Xlsx/Issue2082Test.php new file mode 100644 index 00000000..1f72a382 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Writer/Xlsx/Issue2082Test.php @@ -0,0 +1,40 @@ +getActiveSheet(); + $worksheet->fromArray(['A', 'B', 'C', 'D']); + $worksheet->getCell('A2')->setValue('=A1<>"A"'); + $worksheet->getCell('A3')->setValue('=A1="A"'); + $worksheet->getCell('B2')->setValue('=LEFT(B1, 0)'); + $worksheet->getCell('B3')->setValue('=B2=""'); + + $writer = new Writer($spreadsheet); + $writer->save($outputFilename); + $zipfile = "zip://$outputFilename#xl/worksheets/sheet1.xml"; + $contents = file_get_contents($zipfile); + unlink($outputFilename); + if ($contents === false) { + self::fail('Unable to open file'); + } else { + self::assertStringContainsString('A1<>"A"0', $contents); + self::assertStringContainsString('A1="A"1', $contents); + self::assertStringContainsString('LEFT(B1, 0)', $contents); + self::assertStringContainsString('B2=""1', $contents); + } + } +} diff --git a/tests/PhpSpreadsheetTests/Writer/Xlsx/Issue2266Test.php b/tests/PhpSpreadsheetTests/Writer/Xlsx/Issue2266Test.php new file mode 100644 index 00000000..68583be0 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Writer/Xlsx/Issue2266Test.php @@ -0,0 +1,46 @@ +load('tests/data/Writer/XLSX/issue.2266f.xlsx'); + self::assertCount(2, $spreadsheet->getAllSheets()); + self::assertCount(1, $spreadsheet->getDefinedNames()); + $index = 1; + $sheet = $spreadsheet->getSheet($index); + self::assertSame('Sheet2', $sheet->getTitle()); + $definedName = $spreadsheet->getDefinedName('LocalName', $sheet); + self::assertNotNull($definedName); + self::assertTrue($definedName->getLocalOnly()); + $spreadsheet->removeSheetByIndex($index); + + $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $type); + $spreadsheet->disconnectWorksheets(); + + self::assertCount(1, $reloadedSpreadsheet->getAllSheets()); + self::assertCount(0, $reloadedSpreadsheet->getDefinedNames()); + self::assertNotEquals('Sheet2', $reloadedSpreadsheet->getSheet(0)->getTitle()); + + $reloadedSpreadsheet->disconnectWorksheets(); + } + + public function providerType(): array + { + return [ + ['Xlsx'], + ['Xls'], + ['Ods'], + ]; + } +} diff --git a/tests/PhpSpreadsheetTests/Writer/Xlsx/LocaleFloatsTest.php b/tests/PhpSpreadsheetTests/Writer/Xlsx/LocaleFloatsTest.php index 373ef37f..13a13bc9 100644 --- a/tests/PhpSpreadsheetTests/Writer/Xlsx/LocaleFloatsTest.php +++ b/tests/PhpSpreadsheetTests/Writer/Xlsx/LocaleFloatsTest.php @@ -6,9 +6,15 @@ use PHPUnit\Framework\TestCase; class LocaleFloatsTest extends TestCase { - protected $localeAdjusted; + /** + * @var bool + */ + private $localeAdjusted; - protected $currentLocale; + /** + * @var false|string + */ + private $currentLocale; protected function setUp(): void { @@ -25,7 +31,7 @@ class LocaleFloatsTest extends TestCase protected function tearDown(): void { - if ($this->localeAdjusted) { + if ($this->localeAdjusted && is_string($this->currentLocale)) { setlocale(LC_ALL, $this->currentLocale); } } @@ -49,12 +55,7 @@ class LocaleFloatsTest extends TestCase $result = $spreadsheet->getActiveSheet()->getCell('A1')->getValue(); - ob_start(); - var_dump($result); - preg_match('/(?:double|float)\(([^\)]+)\)/mui', ob_get_clean(), $matches); - self::assertArrayHasKey(1, $matches); - $actual = $matches[1]; - // From PHP8, https://wiki.php.net/rfc/locale_independent_float_to_string applies - self::assertEquals('1,1', $actual); + $actual = sprintf('%f', $result); + self::assertStringContainsString('1,1', $actual); } } diff --git a/tests/PhpSpreadsheetTests/Writer/Xlsx/StartsWithHashTest.php b/tests/PhpSpreadsheetTests/Writer/Xlsx/StartsWithHashTest.php index d4fe5b22..ebc3c92f 100644 --- a/tests/PhpSpreadsheetTests/Writer/Xlsx/StartsWithHashTest.php +++ b/tests/PhpSpreadsheetTests/Writer/Xlsx/StartsWithHashTest.php @@ -4,7 +4,6 @@ namespace PhpOffice\PhpSpreadsheetTests\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Reader\Xlsx as Reader; -use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx as Writer; @@ -15,8 +14,7 @@ class StartsWithHashTest extends TestCase { public function testStartWithHash(): void { - $outputFilename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); - Settings::setLibXmlLoaderOptions(null); + $outputFilename = File::temporaryFilename(); $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->setCellValueExplicit('A1', '#define M', DataType::TYPE_STRING); @@ -40,8 +38,7 @@ class StartsWithHashTest extends TestCase public function testStartWithHashReadRaw(): void { // Make sure raw data indicates A3 is an error, but A2 isn't. - $outputFilename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); - Settings::setLibXmlLoaderOptions(null); + $outputFilename = File::temporaryFilename(); $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->setCellValueExplicit('A1', '#define M', DataType::TYPE_STRING); diff --git a/tests/PhpSpreadsheetTests/Writer/Xlsx/UnparsedDataCloneTest.php b/tests/PhpSpreadsheetTests/Writer/Xlsx/UnparsedDataCloneTest.php index 660e40fe..9a801015 100644 --- a/tests/PhpSpreadsheetTests/Writer/Xlsx/UnparsedDataCloneTest.php +++ b/tests/PhpSpreadsheetTests/Writer/Xlsx/UnparsedDataCloneTest.php @@ -2,7 +2,6 @@ namespace PhpOffice\PhpSpreadsheetTests\Writer\Xlsx; -use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Shared\File; use PHPUnit\Framework\TestCase; use ZipArchive; @@ -15,8 +14,7 @@ class UnparsedDataCloneTest extends TestCase public function testLoadSaveXlsxWithUnparsedDataClone(): void { $sampleFilename = 'tests/data/Writer/XLSX/drawing_on_2nd_page.xlsx'; - $resultFilename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); - Settings::setLibXmlLoaderOptions(null); // reset to default options + $resultFilename = File::temporaryFilename(); $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); $spreadsheet = $reader->load($sampleFilename); $spreadsheet->setActiveSheetIndex(1); @@ -60,10 +58,9 @@ class UnparsedDataCloneTest extends TestCase public function testSaveTwice(): void { $sampleFilename = 'tests/data/Writer/XLSX/drawing_on_2nd_page.xlsx'; - $resultFilename1 = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test1'); - $resultFilename2 = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test2'); + $resultFilename1 = File::temporaryFilename(); + $resultFilename2 = File::temporaryFilename(); self::assertNotEquals($resultFilename1, $resultFilename2); - Settings::setLibXmlLoaderOptions(null); // reset to default options $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); $spreadsheet = $reader->load($sampleFilename); $sheet = $spreadsheet->setActiveSheetIndex(1); diff --git a/tests/PhpSpreadsheetTests/Writer/Xlsx/UnparsedDataTest.php b/tests/PhpSpreadsheetTests/Writer/Xlsx/UnparsedDataTest.php index 4ea6f955..981962bc 100644 --- a/tests/PhpSpreadsheetTests/Writer/Xlsx/UnparsedDataTest.php +++ b/tests/PhpSpreadsheetTests/Writer/Xlsx/UnparsedDataTest.php @@ -16,8 +16,7 @@ class UnparsedDataTest extends TestCase public function testLoadSaveXlsxWithUnparsedData(): void { $sampleFilename = 'tests/data/Writer/XLSX/form_pass_print.xlsm'; - $resultFilename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test'); - Settings::setLibXmlLoaderOptions(null); // reset to default options + $resultFilename = File::temporaryFilename(); $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); $excel = $reader->load($sampleFilename); @@ -66,13 +65,16 @@ class UnparsedDataTest extends TestCase // xl/workbook.xml $xmlWorkbook = simplexml_load_string($resultWorkbookRaw, 'SimpleXMLElement', Settings::getLibXmlLoaderOptions()); + self::assertNotFalse($xmlWorkbook); if (!$xmlWorkbook->workbookProtection) { self::fail('workbook.xml/workbookProtection not found!'); } else { self::assertEquals($xmlWorkbook->workbookProtection['workbookPassword'], 'CBEB', 'workbook.xml/workbookProtection[workbookPassword] is wrong!'); self::assertEquals($xmlWorkbook->workbookProtection['lockStructure'], 'true', 'workbook.xml/workbookProtection[lockStructure] is wrong!'); + self::assertNotNull($xmlWorkbook->sheets->sheet[0]); self::assertEquals($xmlWorkbook->sheets->sheet[0]['state'], '', 'workbook.xml/sheets/sheet[0][state] is wrong!'); + self::assertNotNull($xmlWorkbook->sheets->sheet[1]); self::assertEquals($xmlWorkbook->sheets->sheet[1]['state'], 'hidden', 'workbook.xml/sheets/sheet[1][state] is wrong!'); } unset($xmlWorkbook); diff --git a/tests/PhpSpreadsheetTests/Writer/Xlsx/VisibilityTest.php b/tests/PhpSpreadsheetTests/Writer/Xlsx/VisibilityTest.php new file mode 100644 index 00000000..7e1ca967 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Writer/Xlsx/VisibilityTest.php @@ -0,0 +1,99 @@ +getActiveSheet(); + foreach ($visibleRows as $row => $visibility) { + $worksheet->setCellValue("A{$row}", $row); + $worksheet->getRowDimension($row)->setVisible($visibility); + } + + $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xlsx'); + $reloadedWorksheet = $reloadedSpreadsheet->getActiveSheet(); + foreach ($visibleRows as $row => $visibility) { + self::assertSame($visibility, $reloadedWorksheet->getRowDimension($row)->getVisible()); + } + } + + public function dataProviderRowVisibility(): array + { + return [ + [ + [1 => false, 2 => false, 3 => true, 4 => false, 5 => true, 6 => false], + ], + ]; + } + + /** + * @dataProvider dataProviderColumnVisibility + */ + public function testColumnVisibility(array $visibleColumns): void + { + $spreadsheet = new Spreadsheet(); + $worksheet = $spreadsheet->getActiveSheet(); + foreach ($visibleColumns as $column => $visibility) { + $worksheet->setCellValue("{$column}1", $column); + $worksheet->getColumnDimension($column)->setVisible($visibility); + } + + $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xlsx'); + $reloadedWorksheet = $reloadedSpreadsheet->getActiveSheet(); + foreach ($visibleColumns as $column => $visibility) { + self::assertSame($visibility, $reloadedWorksheet->getColumnDimension($column)->getVisible()); + } + } + + public function dataProviderColumnVisibility(): array + { + return [ + [ + ['A' => false, 'B' => false, 'C' => true, 'D' => false, 'E' => true, 'F' => false], + ], + ]; + } + + /** + * @dataProvider dataProviderSheetVisibility + */ + public function testSheetVisibility(array $visibleSheets): void + { + $spreadsheet = new Spreadsheet(); + $spreadsheet->removeSheetByIndex(0); + foreach ($visibleSheets as $sheetName => $visibility) { + $worksheet = $spreadsheet->addSheet(new Worksheet($spreadsheet, $sheetName)); + $worksheet->setCellValue('A1', $sheetName); + $worksheet->setSheetState($visibility); + } + + $reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xlsx'); + foreach ($visibleSheets as $sheetName => $visibility) { + $reloadedWorksheet = $reloadedSpreadsheet->getSheetByName($sheetName) ?? new Worksheet(); + self::assertSame($visibility, $reloadedWorksheet->getSheetState()); + } + } + + public function dataProviderSheetVisibility(): array + { + return [ + [ + [ + 'Worksheet 1' => Worksheet::SHEETSTATE_HIDDEN, + 'Worksheet 2' => Worksheet::SHEETSTATE_VERYHIDDEN, + 'Worksheet 3' => Worksheet::SHEETSTATE_VISIBLE, + ], + ], + ]; + } +} diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 77cd5228..9ebd3f26 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -3,4 +3,4 @@ setlocale(LC_ALL, 'en_US.utf8'); // PHP 5.3 Compat -date_default_timezone_set('Europe/London'); +//date_default_timezone_set('Europe/London'); diff --git a/tests/data/Calculation/Calculation.php b/tests/data/Calculation/Calculation.php index 2f9e0a0c..e49bed9f 100644 --- a/tests/data/Calculation/Calculation.php +++ b/tests/data/Calculation/Calculation.php @@ -1,6 +1,6 @@ [ - 6890, // '11th November 1918' - 18, 11, 11, - ], - 'Excel 1900 Calendar Base Date' => [ - 1, - 1900, 1, 1, - ], - 'Day before Excel mythical 1900 leap day' => [ - 59, - 1900, 2, 28, - ], - 'Excel mythical 1900 leap day' => [ - 60, - 1900, 2, 29, - ], - 'Day after Excel mythical 1900 leap day' => [ - 61, - 1900, 3, 1, - ], - 'Day after Excel actual 1904 leap day' => [ - 713, - 1901, 12, 13, - ], - 'signed 32-bit Unix Timestamp Earliest Date' => [ - 714, - 1901, 12, 14, - ], - 'Day before Excel 1904 Calendar Base Date' => [ - 1461, - 1903, 12, 31, - ], - 'Excel 1904 Calendar Base Date' => [ - 1462, - 1904, 1, 1, - ], - 'Day after Excel 1904 Calendar Base Date' => [ - 1463, - 1904, 1, 2, - ], - [ - 22269, - 1960, 12, 19, - ], - 'Unix Timestamp Base Date' => [ - 25569, - 1970, 1, 1, - ], - [ - 30292, - 1982, 12, 7, - ], - [ - 39611, - 2008, 6, 12, - ], - '32-bit signed Unix Timestamp Latest Date' => [ - 50424, - 2038, 1, 19, - ], - 'Day after 32-bit signed Unix Timestamp Latest Date' => [ - 50425, - 2038, 1, 20, - ], - [ - 39448, - 2008, 1, 1, - ], - [ - 39447, - 2008, 1, null, - ], - [ - 39446, - 2008, 1, -1, - ], - [ - 39417, - 2008, 1, -30, - ], - [ - 39416, - 2008, 1, -31, - ], - [ - 39082, - 2008, 1, -365, - ], - [ - 39508, - 2008, 3, 1, - ], - [ - 39507, - 2008, 3, null, - ], - [ - 39506, - 2008, 3, -1, - ], - [ - 39142, - 2008, 3, -365, - ], - [ - 39417, - 2008, null, 1, - ], - [ - 39387, - 2008, -1, 1, - ], - [ - 39083, - 2008, -11, 1, - ], - [ - 39052, - 2008, -12, 1, - ], - [ - 39022, - 2008, -13, 1, - ], - [ - 39051, - 2008, -13, 30, - ], - [ - 39021, - 2008, -13, null, - ], - [ - 38991, - 2008, -13, -30, - ], - [ - 38990, - 2008, -13, -31, - ], - [ - 39814, - 2008, 13, 1, - ], - [ - 39507, - 2007, 15, null, - ], - [ - 40210, - 2008, 26, 1, - ], - [ - 40199, - 2008, 26, -10, - ], - [ - 38686, - 2008, -26, 61, - ], - [ - 39641, - 2010, -15, -50, - ], - [ - 39741, - 2010, -15, 50, - ], - [ - 40552, - 2010, 15, -50, - ], - [ - 40652, - 2010, 15, 50, - ], - [ - 40179, - 2010, 1.5, 1, - ], - [ - 40178, - 2010, 1.5, 0, - ], - [ - 40148, - 2010, 0, 1.5, - ], - [ - 40179, - 2010, 1, 1.5, - ], - [ - 41075, - 2012, 6, 15, - ], - [ - 41060, - 2012, 6, null, - ], - [ - 40892, - 2012, null, 15, - ], - [ - 167, - null, 6, 15, - ], - [ - 3819, - 10, 6, 15, - ], - [ - 3622, - 10, null, null, - ], - [ - 274, - null, 10, null, - ], - [ - '#NUM!', - null, null, 10, - ], - [ - '#NUM!', - -20, null, null, - ], - [ - '#NUM!', - -20, 6, 15, - ], - 'Excel Maximum Date' => [ - 2958465, - 9999, 12, 31, - ], - 'Exceeded Excel Maximum Date' => [ - '#NUM!', - 10000, 1, 1, - ], - [ - 39670, - 2008, 8, 10, - ], - [ - 39813, - 2008, 12, 31, - ], - [ - 39692, - 2008, 8, 32, - ], - [ - 39844, - 2008, 13, 31, - ], - [ - 39813, - 2009, 1, 0, - ], - [ - 39812, - 2009, 1, -1, - ], - [ - 39782, - 2009, 0, 0, - ], - [ - 39781, - 2009, 0, -1, - ], - [ - 39752, - 2009, -1, 0, - ], - [ - 39751, - 2009, -1, -1, - ], - [ - 40146, - 2010, 0, -1, - ], - [ - 40329, - 2010, 5, 31, - ], + [6890, '18, 11, 11'], // year without centure + [1, '1900, 1, 1'], // Excel 1900 Calendar BaseDate + [59, '1900, 2, 28'], // Day before Excel mythical 1900 leap day + [60, '1900, 2, 29'], // Excel mythical 1900 leap day + [61, '1900, 3, 1'], // Day after Excel mythical 1900 leap day + [713, '1901, 12, 13'], // Day after actual 1904 leap day + [714, '1901, 12, 14'], // signed 32-bit Unix Timestamp Earliest Date + [1461, '1903, 12, 31'], // Day before Excel 1904 Calendar Base Date + [1462, '1904, 1, 1'], // Excel 1904 Calendar Base Date + [1463, '1904, 1, 2'], // Day after Excel 1904 Calendar Base Date + [22269, '1960, 12, 19'], + [25569, '1970, 1, 1'], // Unix Timestamp Base Date + [30292, '1982, 12, 7'], + [39611, '2008, 6, 12'], + [50424, '2038, 1, 19'], // 32-bit signed Unix Timestamp Latest Date + [50425, '2038, 1, 20'], // Day after 32-bit signed Unix Timestamp Latest Date + [39448, '2008, 1, 1'], + [39447, '2008, 1, Q15'], + [39446, '2008, 1, -1'], + [39417, '2008, 1, -30'], + [39416, '2008, 1, -31'], + [39082, '2008, 1, -365'], + [39508, '2008, 3, 1'], + [39507, '2008, 3, Q15'], + [39506, '2008, 3, -1'], + [39142, '2008, 3, -365'], + [39417, '2008, Q15, 1'], + [39387, '2008, -1, 1'], + [39083, '2008, -11, 1'], + [39052, '2008, -12, 1'], + [39022, '2008, -13, 1'], + [39051, '2008, -13, 30'], + [39021, '2008, -13, Q15'], + [38991, '2008, -13, -30'], + [38990, '2008, -13, -31'], + [39814, '2008, 13, 1'], + [39507, '2007, 15, Q15'], + [40210, '2008, 26, 1'], + [40199, '2008, 26, -10'], + [38686, '2008, -26, 61'], + [39641, '2010, -15, -50'], + [39741, '2010, -15, 50'], + [40552, '2010, 15, -50'], + [40652, '2010, 15, 50'], + [40179, '2010, 1.5, 1'], + [40178, '2010, 1.5, 0'], + [40148, '2010, 0, 1.5'], + [40179, '2010, 1, 1.5'], + [41075, '2012, 6, 15'], + [41060, '2012, 6, Q15'], + [40892, '2012, Q15, 15'], + [167, 'Q15, 6, 15'], + [3819, '10, 6, 15'], + [3622, '10, Q15, Q16'], + [274, 'Q14, 10, Q15'], + ['#NUM!', 'Q14, Q15, 10'], + ['#NUM!', '-20, Q14, Q15'], + ['#NUM!', '-20, 6, 15'], + [2958465, '9999, 12, 31'], // Excel maximum date + ['#NUM!', '10000, 1, 1'], // Exceeded Excel maximum date + [39670, '2008, 8, 10'], + [39813, '2008, 12, 31'], + [39692, '2008, 8, 32'], + [39844, '2008, 13, 31'], + [39813, '2009, 1, 0'], + [39812, '2009, 1, -1'], + [39782, '2009, 0, 0'], + [39781, '2009, 0, -1'], + [39752, '2009, -1, 0'], + [39751, '2009, -1, -1'], + [40146, '2010, 0, -1'], + [40329, '2010, 5, 31'], + [40199, '2010, 1, "21st"'], // Excel can't parse ordinal, PhpSpreadsheet can + [40258, '2010, "March", "21st"'], // ordinal and month name // MS Excel will fail with a #VALUE return, but PhpSpreadsheet can parse this date - [ - 40199, - 2010, 1, '21st', - ], - // MS Excel will fail with a #VALUE return, but PhpSpreadsheet can parse this date - [ - 40258, - 2010, 'March', '21st', - ], - // MS Excel will fail with a #VALUE return, but PhpSpreadsheet can parse this date - [ - 40258, - 2010, 'March', 21, - ], - [ - '#VALUE!', - 'ABC', 1, 21, - ], - [ - '#VALUE!', - 2010, 'DEF', 21, - ], - [ - '#VALUE!', - 2010, 3, 'GHI', - ], + [40258, '2010, "March", 21'], // Excel can't parse month name, PhpSpreadsheet can + ['#VALUE!', '"ABC", 1, 21'], + ['#VALUE!', '2010, "DEF", 21'], + ['#VALUE!', '2010, 3, "GHI"'], + ['exception', '2010, 3'], ]; diff --git a/tests/data/Calculation/DateTime/DATEDIF.php b/tests/data/Calculation/DateTime/DATEDIF.php index a6d2d761..5ba0bd3c 100644 --- a/tests/data/Calculation/DateTime/DATEDIF.php +++ b/tests/data/Calculation/DateTime/DATEDIF.php @@ -1,424 +1,112 @@ = 2**48 + ['#NUM!', '1, power(2, 50)'], // argument >= 2**48 + ['#NUM!', '-2, 1'], // negative argument + ['#NUM!', '2, -1'], // negative argument + ['#NUM!', '-2, -1'], // negative argument + ['#NUM!', '3.1, 1'], // non-integer argument + ['#NUM!', '3, 1.1'], // non-integer argument + [0, '4, Q15'], + [0, '4, null'], + [0, '4, false'], + [1, '3, true'], + ['exception', ''], + ['exception', '2'], + [0, ', 4'], + [0, 'Q15, 4'], + [0, 'false, 4'], + [1, 'true, 5'], + [8, 'A2, 9'], ]; diff --git a/tests/data/Calculation/Engineering/BITLSHIFT.php b/tests/data/Calculation/Engineering/BITLSHIFT.php index ceaf9a33..fee922e4 100644 --- a/tests/data/Calculation/Engineering/BITLSHIFT.php +++ b/tests/data/Calculation/Engineering/BITLSHIFT.php @@ -1,20 +1,34 @@ 2**32 + [16000000000, '8000000000, 1'], // argument > 2**32 + ['#NUM!', 'power(2,50), 1'], // argument >= 2**48 + ['1', 'power(2, 47), -47'], ]; diff --git a/tests/data/Calculation/Engineering/BITOR.php b/tests/data/Calculation/Engineering/BITOR.php index 01640c9f..a98ce380 100644 --- a/tests/data/Calculation/Engineering/BITOR.php +++ b/tests/data/Calculation/Engineering/BITOR.php @@ -1,24 +1,34 @@ = 2**48 + ['#NUM!', '1, power(2, 50)'], // argument >= 2**48 + ['#NUM!', '-2, 1'], // negative argument + ['#NUM!', '2, -1'], // negative argument + ['#NUM!', '-2, -1'], // negative argument + ['#NUM!', '3.1, 1'], // non-integer argument + ['#NUM!', '3, 1.1'], // non-integer argument + [4, '4, Q15'], + [4, '4, null'], + [4, '4, false'], + [5, '4, true'], + ['exception', ''], + ['exception', '2'], + [4, ', 4'], + [4, 'Q15, 4'], + [4, 'false, 4'], + [5, 'true, 4'], + [9, 'A2, 1'], ]; diff --git a/tests/data/Calculation/Engineering/BITRSHIFT.php b/tests/data/Calculation/Engineering/BITRSHIFT.php index 78cacf37..343ccb5c 100644 --- a/tests/data/Calculation/Engineering/BITRSHIFT.php +++ b/tests/data/Calculation/Engineering/BITRSHIFT.php @@ -1,16 +1,35 @@ 2**32 + [8000000000, '16000000000, 1'], // argument > 2**32 + ['#NUM!', 'power(2,50), 1'], // argument >= 2**48 + ['1', 'power(2, 47), 47'], ]; diff --git a/tests/data/Calculation/Engineering/BITXOR.php b/tests/data/Calculation/Engineering/BITXOR.php index 40972c1c..836f327a 100644 --- a/tests/data/Calculation/Engineering/BITXOR.php +++ b/tests/data/Calculation/Engineering/BITXOR.php @@ -1,24 +1,32 @@ = 2**48 + ['#NUM!', '1, power(2, 50)'], // argument >= 2**48 + ['#NUM!', '-2, 1'], // negative argument + ['#NUM!', '2, -1'], // negative argument + ['#NUM!', '-2, -1'], // negative argument + ['#NUM!', '3.1, 1'], // non-integer argument + ['#NUM!', '3, 1.1'], // non-integer argument + [4, '4, Q15'], + [4, '4, null'], + [4, '4, false'], + [5, '4, true'], + ['exception', ''], + ['exception', '2'], + [4, ', 4'], + [4, 'Q15, 4'], + [4, 'false, 4'], + [5, 'true, 4'], + [9, 'A2, 1'], ]; diff --git a/tests/data/Calculation/Engineering/COMPLEX.php b/tests/data/Calculation/Engineering/COMPLEX.php index 6b3e137c..22e21a8f 100644 --- a/tests/data/Calculation/Engineering/COMPLEX.php +++ b/tests/data/Calculation/Engineering/COMPLEX.php @@ -1,5 +1,7 @@ [ + 1.942559385723E-03, + 1.0, + 'ozm', + 'sg', + ], + 'Same prefixed metric UoM' => [ + 5.0, + 5.0, + 'kg', + 'kg', + ], + 'Imperial to prefixed metric' => [ + 4.5359237E-01, 1.0, 'lbm', 'kg', ], - [ - 123.45, - 123.45, - 'kg', + 'Prefixed metric to prefixed metric, same unit' => [ + 0.2, + 2.0, + 'hg', 'kg', ], + 'Unprefixed metric to prefixed metric, same unit' => [ + 12.345000000000001, + 12345, + 'm', + 'km', + ], + 'Prefixed metric to unprefixed metric, same unit' => [ + 12345, + 12.345000000000001, + 'km', + 'm', + ], + 'Prefixed metric to imperial' => [ + 0.62137119223732995, + 1, + 'km', + 'mi', + ], + 'Prefixed metric to alternative metric' => [ + 1.23450000000000E+05, + 12.345, + 'um', + 'ang', + ], + 'Prefixed metric to alternative prefixed metric' => [ + 1.23450000000000E+02, + 12.345, + 'um', + 'kang', + ], + 'Prefixed metric to 2-character prefixed metric, same unit' => [ + 1000.0, + 100.0, + 'hl', + 'dal', + ], + 'Imperial to Imperial (distance)' => [ + 1.0, + 3.0, + 'ft', + 'yd', + ], [ 20, 68, @@ -38,111 +92,171 @@ return [ 'F', ], [ - 295.14999999999998, + -273.15, + 0, + 'K', + 'C', + ], + [ + -459.67, + 0, + 'K', + 'F', + ], + [ + 295.15, 22, 'C', 'K', ], [ 22.5, - 295.64999999999998, + 295.65, 'K', 'C', ], - [ - '#N/A', - 2.5, - 'ft', - 'sec', + 'Melting Point of Titanium (K to C)' => [ + 1667.85, + 1941, + 'K', + 'C', ], - [ - 12.345000000000001, - 12345, - 'm', - 'km', + 'Melting Point of Titanium (K to F)' => [ + 3034.13, + 1941, + 'K', + 'F', ], - [ - 12345, - 12.345000000000001, - 'km', - 'm', + 'Melting Point of Titanium (K to Rankine)' => [ + 3493.8, + 1941, + 'K', + 'Rank', ], - [ - 0.62137119223732995, - 1, - 'km', - 'mi', + 'Melting Point of Titanium (K to Réaumur)' => [ + 1334.28, + 1941, + 'K', + 'Reau', ], - [ - '#VALUE!', - 'three', - 'ft', - 'yds', + 'Melting Point of Titanium (Rankine to K)' => [ + 1941, + 3493.8, + 'Rank', + 'K', ], - [ + 'Melting Point of Titanium (Réaumur to K)' => [ + 1941, + 1334.28, + 'Reau', + 'K', + ], + 'Temperature synonyms (K)' => [ 123.45, 123.45, 'K', 'kel', ], - [ + 'Temperature synonyms (C)' => [ 123.45, 123.45, 'C', 'cel', ], - [ + 'Temperature synonyms (F)' => [ 123.45, 123.45, 'F', 'fah', ], - [ + 'Invalid value to convert' => [ + '#VALUE!', + 'three', + 'ft', + 'yds', + ], + 'Imperial to 2-character prefixed imperial, same unit' => [ + '#N/A', + 100.0, + 'pt', + 'dapt', + ], + 'Prefixed metric to binary prefixed metric' => [ + '#N/A', + 12.345, + 'um', + 'kiang', + ], + 'Mismatched categories' => [ '#N/A', 1, 'ft', 'day', ], - [ - 123.45, - 123.45, - 'm', - 'm', - ], - [ - 234.56, - 234.56, - 'km', - 'km', - ], - [ + 'From prefixed Imperial (Invalid)' => [ '#N/A', 234.56, 'kpt', 'lt', ], - [ - '#N/A', - 234.56, - 'sm', - 'm', - ], - [ + 'To prefixed Imperial (Invalid)' => [ '#N/A', 234.56, 'lt', 'kpt', ], - [ + 'From binary prefixed Imperial (Invalid)' => [ + '#N/A', + 234.56, + 'kiqt', + 'pt', + ], + 'To binary prefixed Imperial (Invalid)' => [ + '#N/A', + 234.56, + 'pt', + 'kiqt', + ], + 'From prefixed Imperial 2 (Invalid)' => [ + '#N/A', + 12345.6, + 'baton', + 'cwt', + ], + 'To prefixed Imperial 2 (Invalid)' => [ + '#N/A', + 12345.6, + 'cwt', + 'baton', + ], + 'Invalid from unit' => [ + '#N/A', + 234.56, + 'xxxx', + 'm', + ], + 'Invalid to unit' => [ '#N/A', 234.56, 'm', - 'sm', + 'xxxx', ], - [ - 12345000, - 12.345000000000001, - 'km', - 'mm', + 'Basic Information conversion' => [ + 2, + 16, + 'bit', + 'byte', + ], + 'Information with standard metric prefix' => [ + 1000, + 1, + 'kbyte', + 'byte', + ], + 'Information with binary prefix' => [ + 1024, + 1, + 'kibyte', + 'byte', ], ]; diff --git a/tests/data/Calculation/Engineering/DEC2BIN.php b/tests/data/Calculation/Engineering/DEC2BIN.php index a88b69a8..317c9b5b 100644 --- a/tests/data/Calculation/Engineering/DEC2BIN.php +++ b/tests/data/Calculation/Engineering/DEC2BIN.php @@ -1,91 +1,36 @@ [ '#VALUE!', - '2008-03-01', - '2008-08-31', - '2008-05-01', - 0.10000000000000001, - 1000, - 2, - 'ABC', + '2008-03-01', '2008-08-31', '2008-05-01', 'NaN', 1000, 2, 0, + ], + 'Invalid Rate' => [ + '#NUM!', + '2008-03-01', '2008-08-31', '2008-05-01', -0.10, 1000, 2, 0, + ], + 'Non-numeric Par Value' => [ + '#VALUE!', + '2008-03-01', '2008-08-31', '2008-05-01', 0.10, 'NaN', 2, 0, + ], + 'Invalid Par Value' => [ + '#NUM!', + '2008-03-01', '2008-08-31', '2008-05-01', 0.10, -1000, 2, 0, + ], + 'Non-numeric Frequency' => [ + '#VALUE!', + '2008-03-01', '2008-08-31', '2008-05-01', 0.10, 1000, 'NaN', 0, + ], + 'Invalid Frequency' => [ + '#NUM!', + '2008-03-01', '2008-08-31', '2008-05-01', 0.10, -1000, 3, 0, + ], + 'Non-numeric Basis' => [ + '#VALUE!', + '2008-03-01', '2008-08-31', '2008-05-01', 0.10, 1000, 2, 'ABC', + ], + 'Invalid Basis' => [ + '#NUM!', + '2008-03-01', '2008-08-31', '2008-05-01', 0.10, 1000, 2, -2, ], ]; diff --git a/tests/data/Calculation/Financial/ACCRINTM.php b/tests/data/Calculation/Financial/ACCRINTM.php index 7949b1ad..444e41f9 100644 --- a/tests/data/Calculation/Financial/ACCRINTM.php +++ b/tests/data/Calculation/Financial/ACCRINTM.php @@ -5,41 +5,54 @@ return [ [ 20.547945205478999, - '2008-04-01', - '2008-06-15', - 0.10000000000000001, - 1000, - 3, + '2008-04-01', '2008-06-15', 0.10, 1000, 3, ], [ 800, - '2010-01-01', - '2010-12-31', - 0.080000000000000002, - 10000, + '2010-01-01', '2010-12-31', 0.08, 10000, + ], + [ + 800, + '2010-01-01', '2010-12-31', 0.08, 10000, null, + ], + [ + 365.958904109589, + '2012-01-01', '2013-02-15', 0.065, 5000, 3, + ], + [ + 73.1917808219178, + '2012-01-01', '2013-02-15', 0.065, 1000, 3, ], [ '#NUM!', - '2008-03-05', - '2008-08-31', - -0.10000000000000001, - 1000, - 2, + '2008-03-05', '2008-08-31', -0.10, 1000, 2, ], [ '#VALUE!', - 'Invalid Date', - '2008-08-31', - 0.10000000000000001, - 1000, - 2, + 'Invalid Date', '2008-08-31', 0.10, 1000, 2, ], - [ + 'Non-numeric Rate' => [ '#VALUE!', - '2008-03-01', - '2008-08-31', - 'ABC', - 1000, - 2, + '2008-03-01', '2008-08-31', 'NaN', 1000, 2, + ], + 'Invalid Rate' => [ + '#NUM!', + '2008-03-01', '2008-08-31', -0.10, 1000, 2, + ], + 'Non-numeric Par Value' => [ + '#VALUE!', + '2008-03-01', '2008-08-31', 0.10, 'NaN', 2, + ], + 'Invalid Par Value' => [ + '#NUM!', + '2008-03-01', '2008-08-31', 0.10, -1000, 2, + ], + 'Non-numeric Basis' => [ + '#VALUE!', + '2008-03-01', '2008-08-31', 0.10, 1000, 'NaN', + ], + 'Invalid Basis' => [ + '#NUM!', + '2008-03-01', '2008-08-31', 0.10, 1000, 99, ], ]; diff --git a/tests/data/Calculation/Financial/AMORDEGRC.php b/tests/data/Calculation/Financial/AMORDEGRC.php index 1e959141..fa546c8c 100644 --- a/tests/data/Calculation/Financial/AMORDEGRC.php +++ b/tests/data/Calculation/Financial/AMORDEGRC.php @@ -5,22 +5,94 @@ return [ [ 776, - 2400, - '2008-08-19', - '2008-12-31', - 300, - 1, - 0.14999999999999999, - 1, + 2400, '2008-08-19', '2008-12-31', 300, 1, 0.15, 1, + ], + [ + 776, + 2400, '2008-08-19', '2008-12-31', 300, 1, 0.15, 0, + ], + [ + 776, + 2400, '2008-08-19', '2008-12-31', 300, 1, 0.15, null, + ], + [ + 820, + 2400, '2008-08-19', '2008-12-31', 300, 1, 0.2, 1, + ], + [ + 492, + 2400, '2008-08-19', '2008-12-31', 300, 2, 0.2, 1, + ], + [ + 886, + 2400, '2008-08-19', '2008-12-31', 300, 1, 0.22, 1, + ], + [ + 949, + 2400, '2008-08-19', '2008-12-31', 300, 1, 0.24, 1, + ], + [ + 494, + 2400, '2008-08-19', '2008-12-31', 300, 2, 0.24, 1, + ], + [ + 902, + 2400, '2008-08-19', '2008-12-31', 300, 1, 0.3, 1, ], [ 42, - 150, - '2011-01-01', - '2011-09-30', - 20, - 1, - 0.20000000000000001, - 4, + 150, '2011-01-01', '2011-09-30', 20, 1, 0.2, 4, + ], + [ + 25, + 150, '2011-01-01', '2011-09-30', 20, 2, 0.2, 4, + ], + [ + 16, + 150, '2011-01-01', '2011-09-30', 20, 3, 0.15, 4, + ], + [ + 42, + 150, '2011-01-01', '2011-09-30', 20, 1, 0.4, 4, + ], + [ + 2813, + 10000, '2012-03-01', '2012-12-31', 1500, 1, 0.3, 1, + ], + [ + 0.0, + 500, '2012-03-01', '2012-12-31', 500, 3, 0.3, 1, + ], + [ + '#VALUE!', + 'NaN', '2012-03-01', '2020-12-25', 20, 1, 0.2, 4, + ], + [ + '#VALUE!', + 550, 'notADate', '2020-12-25', 20, 1, 0.2, 4, + ], + [ + '#VALUE!', + 550, '2011-01-01', 'notADate', 20, 1, 0.2, 4, + ], + [ + '#VALUE!', + 550, '2012-03-01', '2020-12-25', 'NaN', 1, 0.2, 4, + ], + [ + '#VALUE!', + 550, '2012-03-01', '2020-12-25', 20, 'NaN', 0.2, 4, + ], + [ + '#VALUE!', + 550, '2012-03-01', '2020-12-25', 20, 1, 'NaN', 4, + ], + [ + '#VALUE!', + 550, '2012-03-01', '2020-12-25', 20, 1, 0.2, 'NaN', + ], + [ + '#NUM!', + 550, '2012-03-01', '2020-12-25', 20, 1, 0.2, 99, ], ]; diff --git a/tests/data/Calculation/Financial/AMORLINC.php b/tests/data/Calculation/Financial/AMORLINC.php index 92adbe13..c0175536 100644 --- a/tests/data/Calculation/Financial/AMORLINC.php +++ b/tests/data/Calculation/Financial/AMORLINC.php @@ -5,22 +5,66 @@ return [ [ 360, - 2400, - '2008-08-19', - '2008-12-31', - 300, - 1, - 0.14999999999999999, - 1, + 2400, '2008-08-19', '2008-12-31', 300, 1, 0.15, 1, + ], + [ + 576, + 2400, '2008-08-19', '2008-12-31', 300, 2, 0.24, 1, + ], + [ + 576, + 2400, '2008-08-19', '2008-12-31', 300, 2, 0.24, 0, + ], + [ + 576, + 2400, '2008-08-19', '2008-12-31', 300, 2, 0.24, null, ], [ 30, - 150, - '2011-01-01', - '2011-09-30', - 20, - 1, - 0.20000000000000001, - 4, + 150, '2011-01-01', '2011-09-30', 20, 1, 0.2, 4, + ], + [ + 22.41666667, + 150, '2011-01-01', '2011-09-30', 20, 0, 0.2, 4, + ], + [ + 17.58333333, + 150, '2011-01-01', '2011-09-30', 20, 4, 0.2, 4, + ], + [ + 0.0, + 150, '2011-01-01', '2011-09-30', 20, 5, 0.2, 4, + ], + [ + '#VALUE!', + 'NaN', '2011-01-01', '2011-09-30', 20, 1, 0.2, 4, + ], + [ + '#VALUE!', + 150, '2011-01-01', 'notADate', 20, 1, 0.2, 4, + ], + [ + '#VALUE!', + 150, 'notADate', '2011-09-30', 20, 1, 0.2, 4, + ], + [ + '#VALUE!', + 150, '2011-01-01', '2011-09-30', 'NaN', 1, 0.2, 4, + ], + [ + '#VALUE!', + 150, '2011-01-01', '2011-09-30', 20, 'NaN', 0.2, 4, + ], + [ + '#VALUE!', + 150, '2011-01-01', '2011-09-30', 20, 1, 'NaN', 4, + ], + [ + '#VALUE!', + 150, '2011-01-01', '2011-09-30', 20, 1, 0.2, 'NaN', + ], + [ + '#NUM!', + 550, '2012-03-01', '2020-12-25', 20, 1, 0.2, 99, ], ]; diff --git a/tests/data/Calculation/Financial/COUPDAYBS.php b/tests/data/Calculation/Financial/COUPDAYBS.php index ea93d427..f41d3620 100644 --- a/tests/data/Calculation/Financial/COUPDAYBS.php +++ b/tests/data/Calculation/Financial/COUPDAYBS.php @@ -16,6 +16,20 @@ return [ '2012-10-25', 4, ], + [ + 66, + '2011-01-01', + '2012-10-25', + 4, + null, + ], + [ + 71, + '2011-01-25', + '2011-11-15', + 2, + 1, + ], [ '#VALUE!', 'Invalid Date', @@ -30,11 +44,179 @@ return [ 2, 1, ], - [ + 'Invalid Frequency' => [ '#NUM!', '25-Jan-2007', '15-Nov-2008', 3, 1, ], + 'Non-Numeric Frequency' => [ + '#VALUE!', + '25-Jan-2007', + '15-Nov-2008', + 'NaN', + 1, + ], + 'Invalid Basis' => [ + '#NUM!', + '25-Jan-2007', + '15-Nov-2008', + 4, + -1, + ], + 'Non-Numeric Basis' => [ + '#VALUE!', + '25-Jan-2007', + '15-Nov-2008', + 4, + 'NaN', + ], + 'Same Date' => [ + '#NUM!', + '24-Dec-2000', + '24-Dec-2000', + 4, + 0, + ], + [ + 311, + '31-Jan-2021', + '20-Mar-2021', + 1, + 0, + ], + [ + 317, + '31-Jan-2021', + '20-Mar-2021', + 1, + 1, + ], + [ + 317, + '31-Jan-2020', + '20-Mar-2021', + 1, + 1, + ], + [ + 317, + '31-Jan-2021', + '20-Mar-2021', + 1, + 2, + ], + [ + 317, + '31-Jan-2021', + '20-Mar-2021', + 1, + 3, + ], + [ + 310, + '31-Jan-2021', + '20-Mar-2021', + 1, + 4, + ], + [ + 131, + '31-Jan-2021', + '20-Mar-2021', + 2, + 0, + ], + [ + 133, + '31-Jan-2021', + '20-Mar-2021', + 2, + 1, + ], + [ + 133, + '31-Jan-2020', + '20-Mar-2021', + 2, + 1, + ], + [ + 133, + '31-Jan-2021', + '20-Mar-2021', + 2, + 2, + ], + [ + 133, + '31-Jan-2021', + '20-Mar-2021', + 2, + 3, + ], + [ + 130, + '31-Jan-2021', + '20-Mar-2021', + 2, + 4, + ], + [ + 41, + '31-Jan-2021', + '20-Mar-2021', + 4, + 0, + ], + [ + 42, + '31-Jan-2021', + '20-Mar-2021', + 4, + 1, + ], + [ + 42, + '31-Jan-2020', + '20-Mar-2021', + 4, + 1, + ], + [ + 42, + '31-Jan-2021', + '20-Mar-2021', + 4, + 2, + ], + [ + 42, + '31-Jan-2021', + '20-Mar-2021', + 4, + 3, + ], + [ + 40, + '31-Jan-2021', + '20-Mar-2021', + 4, + 4, + ], + [ + 5, + '05-Apr-2019', + '30-Sep-2021', + 2, + 0, + ], + [ + 5, + '05-Oct-2019', + '31-Mar-2022', + 2, + 0, + ], ]; diff --git a/tests/data/Calculation/Financial/COUPDAYS.php b/tests/data/Calculation/Financial/COUPDAYS.php index 384df0f1..caba56e5 100644 --- a/tests/data/Calculation/Financial/COUPDAYS.php +++ b/tests/data/Calculation/Financial/COUPDAYS.php @@ -16,6 +16,13 @@ return [ '2012-10-25', 4, ], + [ + 90, + '2011-01-01', + '2012-10-25', + 4, + null, + ], [ 182.5, '25-Jan-2007', @@ -51,11 +58,179 @@ return [ 2, 1, ], - [ + 'Invalid Frequency' => [ '#NUM!', '25-Jan-2007', '15-Nov-2008', 3, 1, ], + 'Non-Numeric Frequency' => [ + '#VALUE!', + '25-Jan-2007', + '15-Nov-2008', + 'NaN', + 1, + ], + 'Invalid Basis' => [ + '#NUM!', + '25-Jan-2007', + '15-Nov-2008', + 4, + -1, + ], + 'Non-Numeric Basis' => [ + '#VALUE!', + '25-Jan-2007', + '15-Nov-2008', + 4, + 'NaN', + ], + 'Same Date' => [ + '#NUM!', + '24-Dec-2000', + '24-Dec-2000', + 4, + 0, + ], + [ + 360, + '31-Jan-2021', + '20-Mar-2021', + 1, + 0, + ], + [ + 365, + '31-Jan-2021', + '20-Mar-2021', + 1, + 1, + ], + [ + 366, + '31-Jan-2020', + '20-Mar-2021', + 1, + 1, + ], + [ + 360, + '31-Jan-2021', + '20-Mar-2021', + 1, + 2, + ], + [ + 365, + '31-Jan-2021', + '20-Mar-2021', + 1, + 3, + ], + [ + 360, + '31-Jan-2021', + '20-Mar-2021', + 1, + 4, + ], + [ + 180, + '31-Jan-2021', + '20-Mar-2021', + 2, + 0, + ], + [ + 181, + '31-Jan-2021', + '20-Mar-2021', + 2, + 1, + ], + [ + 182, + '31-Jan-2020', + '20-Mar-2021', + 2, + 1, + ], + [ + 180, + '31-Jan-2021', + '20-Mar-2021', + 2, + 2, + ], + [ + 182.5, + '31-Jan-2021', + '20-Mar-2021', + 2, + 3, + ], + [ + 180, + '31-Jan-2021', + '20-Mar-2021', + 2, + 4, + ], + [ + 90, + '31-Jan-2021', + '20-Mar-2021', + 4, + 0, + ], + [ + 90, + '31-Jan-2021', + '20-Mar-2021', + 4, + 1, + ], + [ + 91, + '31-Jan-2020', + '20-Mar-2021', + 4, + 1, + ], + [ + 90, + '31-Jan-2021', + '20-Mar-2021', + 4, + 2, + ], + [ + 91.25, + '31-Jan-2021', + '20-Mar-2021', + 4, + 3, + ], + [ + 90, + '31-Jan-2021', + '20-Mar-2021', + 4, + 4, + ], + [ + 180, + '05-Apr-2019', + '30-Sep-2021', + 2, + 0, + ], + [ + 180, + '05-Oct-2019', + '31-Mar-2022', + 2, + 0, + ], ]; diff --git a/tests/data/Calculation/Financial/COUPDAYSNC.php b/tests/data/Calculation/Financial/COUPDAYSNC.php index 2b249cb8..e8500263 100644 --- a/tests/data/Calculation/Financial/COUPDAYSNC.php +++ b/tests/data/Calculation/Financial/COUPDAYSNC.php @@ -16,6 +16,13 @@ return [ '2012-10-25', 4, ], + [ + 24, + '2011-01-01', + '2012-10-25', + 4, + null, + ], [ '#VALUE!', 'Invalid Date', @@ -30,11 +37,203 @@ return [ 2, 1, ], - [ + 'Invalid Frequency' => [ '#NUM!', '25-Jan-2007', '15-Nov-2008', 3, 1, ], + 'Non-Numeric Frequency' => [ + '#VALUE!', + '25-Jan-2007', + '15-Nov-2008', + 'NaN', + 1, + ], + 'Invalid Basis' => [ + '#NUM!', + '25-Jan-2007', + '15-Nov-2008', + 4, + -1, + ], + 'Non-Numeric Basis' => [ + '#VALUE!', + '25-Jan-2007', + '15-Nov-2008', + 4, + 'NaN', + ], + 'Same Date' => [ + '#NUM!', + '24-Dec-2000', + '24-Dec-2000', + 4, + 0, + ], + [ + 49, + '31-Jan-2021', + '20-Mar-2021', + 1, + 0, + ], + [ + 49, + '01-Feb-2021', + '20-Mar-2021', + 1, + 0, + ], + [ + 48, + '31-Jan-2021', + '20-Mar-2021', + 1, + 1, + ], + [ + 49, + '31-Jan-2020', + '20-Mar-2021', + 1, + 1, + ], + [ + 48, + '31-Jan-2021', + '20-Mar-2021', + 1, + 2, + ], + [ + 48, + '31-Jan-2021', + '20-Mar-2021', + 1, + 3, + ], + [ + 50, + '31-Jan-2021', + '20-Mar-2021', + 1, + 4, + ], + [ + 49, + '31-Jan-2021', + '20-Mar-2021', + 2, + 0, + ], + [ + 49, + '01-Feb-2021', + '20-Mar-2021', + 2, + 0, + ], + [ + 48, + '31-Jan-2021', + '20-Mar-2021', + 2, + 1, + ], + [ + 49, + '31-Jan-2020', + '20-Mar-2021', + 2, + 1, + ], + [ + 48, + '31-Jan-2021', + '20-Mar-2021', + 2, + 2, + ], + [ + 48, + '31-Jan-2021', + '20-Mar-2021', + 2, + 3, + ], + [ + 50, + '31-Jan-2021', + '20-Mar-2021', + 2, + 4, + ], + [ + 49, + '31-Jan-2021', + '20-Mar-2021', + 4, + 0, + ], + [ + 49, + '01-Feb-2021', + '20-Mar-2021', + 4, + 0, + ], + [ + 48, + '31-Jan-2021', + '20-Mar-2021', + 4, + 1, + ], + [ + 49, + '31-Jan-2020', + '20-Mar-2021', + 4, + 1, + ], + [ + 48, + '31-Jan-2021', + '20-Mar-2021', + 4, + 2, + ], + [ + 48, + '31-Jan-2021', + '20-Mar-2021', + 4, + 3, + ], + [ + 50, + '31-Jan-2021', + '20-Mar-2021', + 4, + 4, + ], + [ + 175, + '05-Apr-2019', + '30-Sep-2021', + 2, + 0, + ], + // Excel and LibreOffice return 175 for the following calculation. + // Gnumeric returns 176. + // My hand calculation, hardly guaranteed, agrees with Gnumeric. + [ + 176, + '05-Oct-2019', + '31-Mar-2022', + 2, + 0, + ], ]; diff --git a/tests/data/Calculation/Financial/COUPNCD.php b/tests/data/Calculation/Financial/COUPNCD.php index eea6ad13..d690525c 100644 --- a/tests/data/Calculation/Financial/COUPNCD.php +++ b/tests/data/Calculation/Financial/COUPNCD.php @@ -16,6 +16,13 @@ return [ '2012-10-25', 4, ], + [ + 40568, + '2011-01-01', + '2012-10-25', + 4, + null, + ], [ '#VALUE!', 'Invalid Date', @@ -30,14 +37,35 @@ return [ 2, 1, ], - [ + 'Invalid Frequency' => [ '#NUM!', '25-Jan-2007', '15-Nov-2008', 3, 1, ], - [ + 'Non-Numeric Frequency' => [ + '#VALUE!', + '25-Jan-2007', + '15-Nov-2008', + 'NaN', + 1, + ], + 'Invalid Basis' => [ + '#NUM!', + '25-Jan-2007', + '15-Nov-2008', + 4, + -1, + ], + 'Non-Numeric Basis' => [ + '#VALUE!', + '25-Jan-2007', + '15-Nov-2008', + 4, + 'NaN', + ], + 'Same Date' => [ '#NUM!', '24-Dec-2000', '24-Dec-2000', @@ -65,4 +93,158 @@ return [ 4, 0, ], + [ + 44275, + '31-Jan-2021', + '20-Mar-2021', + 1, + 0, + ], + [ + 44275, + '31-Jan-2021', + '20-Mar-2021', + 1, + 1, + ], + [ + 43910, + '31-Jan-2020', + '20-Mar-2021', + 1, + 1, + ], + [ + 44275, + '31-Jan-2021', + '20-Mar-2021', + 1, + 2, + ], + [ + 44275, + '31-Jan-2021', + '20-Mar-2021', + 1, + 3, + ], + [ + 44275, + '31-Jan-2021', + '20-Mar-2021', + 1, + 4, + ], + [ + 44275, + '31-Jan-2021', + '20-Mar-2021', + 2, + 0, + ], + [ + 44275, + '31-Jan-2021', + '20-Mar-2021', + 2, + 1, + ], + [ + 43910, + '31-Jan-2020', + '20-Mar-2021', + 2, + 1, + ], + [ + 44275, + '31-Jan-2021', + '20-Mar-2021', + 2, + 2, + ], + [ + 44275, + '31-Jan-2021', + '20-Mar-2021', + 2, + 3, + ], + [ + 44275, + '31-Jan-2021', + '20-Mar-2021', + 2, + 4, + ], + [ + 44275, + '31-Jan-2021', + '20-Mar-2021', + 4, + 0, + ], + [ + 44275, + '31-Jan-2021', + '20-Mar-2021', + 4, + 1, + ], + [ + 43910, + '31-Jan-2020', + '20-Mar-2021', + 4, + 1, + ], + [ + 44275, + '31-Jan-2021', + '20-Mar-2021', + 4, + 2, + ], + [ + 44275, + '31-Jan-2021', + '20-Mar-2021', + 4, + 3, + ], + [ + 44275, + '31-Jan-2021', + '20-Mar-2021', + 4, + 4, + ], + [ + 44651, + '30-Sep-2021', + '31-Mar-2022', + 2, + 0, + ], + [ + 44834, + '31-Mar-2022', + '30-Sep-2022', + 2, + 0, + ], + [ + 43738, + '05-Apr-2019', + '30-Sep-2021', + 2, + 0, + ], + [ + 43921, + '05-Oct-2019', + '31-Mar-2022', + 2, + 0, + ], ]; diff --git a/tests/data/Calculation/Financial/COUPNUM.php b/tests/data/Calculation/Financial/COUPNUM.php index 719ad733..4cf0cc29 100644 --- a/tests/data/Calculation/Financial/COUPNUM.php +++ b/tests/data/Calculation/Financial/COUPNUM.php @@ -17,6 +17,13 @@ return [ 4, 0, ], + [ + 8, + '2011-01-01', + '2012-10-25', + 4, + null, + ], [ '#VALUE!', 'Invalid Date', @@ -31,13 +38,41 @@ return [ 2, 1, ], - [ + 'Invalid Frequency' => [ '#NUM!', '25-Jan-2007', '15-Nov-2008', 3, 1, ], + 'Non-Numeric Frequency' => [ + '#VALUE!', + '25-Jan-2007', + '15-Nov-2008', + 'NaN', + 1, + ], + 'Invalid Basis' => [ + '#NUM!', + '25-Jan-2007', + '15-Nov-2008', + 4, + -1, + ], + 'Non-Numeric Basis' => [ + '#VALUE!', + '25-Jan-2007', + '15-Nov-2008', + 4, + 'NaN', + ], + 'Same Date' => [ + '#NUM!', + '24-Dec-2000', + '24-Dec-2000', + 4, + 0, + ], [ 5, '01-Jan-2008', @@ -108,4 +143,130 @@ return [ 2, 4, ], + [ + 1, + '31-Jan-2021', + '20-Mar-2021', + 1, + 0, + ], + [ + 1, + '31-Jan-2021', + '20-Mar-2021', + 1, + 1, + ], + [ + 2, + '31-Jan-2020', + '20-Mar-2021', + 1, + 1, + ], + [ + 1, + '31-Jan-2021', + '20-Mar-2021', + 1, + 2, + ], + [ + 1, + '31-Jan-2021', + '20-Mar-2021', + 1, + 3, + ], + [ + 1, + '31-Jan-2021', + '20-Mar-2021', + 1, + 4, + ], + [ + 1, + '31-Jan-2021', + '20-Mar-2021', + 2, + 0, + ], + [ + 1, + '31-Jan-2021', + '20-Mar-2021', + 2, + 1, + ], + [ + 3, + '31-Jan-2020', + '20-Mar-2021', + 2, + 1, + ], + [ + 1, + '31-Jan-2021', + '20-Mar-2021', + 2, + 2, + ], + [ + 1, + '31-Jan-2021', + '20-Mar-2021', + 2, + 3, + ], + [ + 1, + '31-Jan-2021', + '20-Mar-2021', + 2, + 4, + ], + [ + 1, + '31-Jan-2021', + '20-Mar-2021', + 4, + 0, + ], + [ + 1, + '31-Jan-2021', + '20-Mar-2021', + 4, + 1, + ], + [ + 5, + '31-Jan-2020', + '20-Mar-2021', + 4, + 1, + ], + [ + 1, + '31-Jan-2021', + '20-Mar-2021', + 4, + 2, + ], + [ + 1, + '31-Jan-2021', + '20-Mar-2021', + 4, + 3, + ], + [ + 1, + '31-Jan-2021', + '20-Mar-2021', + 4, + 4, + ], ]; diff --git a/tests/data/Calculation/Financial/COUPPCD.php b/tests/data/Calculation/Financial/COUPPCD.php index 911637d6..88b93af5 100644 --- a/tests/data/Calculation/Financial/COUPPCD.php +++ b/tests/data/Calculation/Financial/COUPPCD.php @@ -16,6 +16,13 @@ return [ '2012-10-25', 4, ], + [ + 40476, + '2011-01-01', + '2012-10-25', + 4, + null, + ], [ '#VALUE!', 'Invalid Date', @@ -30,14 +37,35 @@ return [ 2, 1, ], - [ + 'Invalid Frequency' => [ '#NUM!', '25-Jan-2007', '15-Nov-2008', 3, 1, ], - [ + 'Non-Numeric Frequency' => [ + '#VALUE!', + '25-Jan-2007', + '15-Nov-2008', + 'NaN', + 1, + ], + 'Invalid Basis' => [ + '#NUM!', + '25-Jan-2007', + '15-Nov-2008', + 4, + -1, + ], + 'Non-Numeric Basis' => [ + '#VALUE!', + '25-Jan-2007', + '15-Nov-2008', + 4, + 'NaN', + ], + 'Same Date' => [ '#NUM!', '24-Dec-2000', '24-Dec-2000', @@ -65,4 +93,144 @@ return [ 4, 0, ], + [ + 43910, + '31-Jan-2021', + '20-Mar-2021', + 1, + 0, + ], + [ + 43910, + '31-Jan-2021', + '20-Mar-2021', + 1, + 1, + ], + [ + 43544, + '31-Jan-2020', + '20-Mar-2021', + 1, + 1, + ], + [ + 43910, + '31-Jan-2021', + '20-Mar-2021', + 1, + 2, + ], + [ + 43910, + '31-Jan-2021', + '20-Mar-2021', + 1, + 3, + ], + [ + 43910, + '31-Jan-2021', + '20-Mar-2021', + 1, + 4, + ], + [ + 44094, + '31-Jan-2021', + '20-Mar-2021', + 2, + 0, + ], + [ + 44094, + '31-Jan-2021', + '20-Mar-2021', + 2, + 1, + ], + [ + 43728, + '31-Jan-2020', + '20-Mar-2021', + 2, + 1, + ], + [ + 44094, + '31-Jan-2021', + '20-Mar-2021', + 2, + 2, + ], + [ + 44094, + '31-Jan-2021', + '20-Mar-2021', + 2, + 3, + ], + [ + 44094, + '31-Jan-2021', + '20-Mar-2021', + 2, + 4, + ], + [ + 44185, + '31-Jan-2021', + '20-Mar-2021', + 4, + 0, + ], + [ + 44185, + '31-Jan-2021', + '20-Mar-2021', + 4, + 1, + ], + [ + 43819, + '31-Jan-2020', + '20-Mar-2021', + 4, + 1, + ], + [ + 44185, + '31-Jan-2021', + '20-Mar-2021', + 4, + 2, + ], + [ + 44185, + '31-Jan-2021', + '20-Mar-2021', + 4, + 3, + ], + [ + 44185, + '31-Jan-2021', + '20-Mar-2021', + 4, + 4, + ], + [ + 43555, + '05-Apr-2019', + '30-Sep-2021', + 2, + 0, + ], + [ + 43738, + '05-Oct-2019', + '31-Mar-2022', + 2, + 0, + ], ]; diff --git a/tests/data/Calculation/Financial/CUMIPMT.php b/tests/data/Calculation/Financial/CUMIPMT.php index bc14d92a..2ccc5ff2 100644 --- a/tests/data/Calculation/Financial/CUMIPMT.php +++ b/tests/data/Calculation/Financial/CUMIPMT.php @@ -5,7 +5,7 @@ return [ [ -11135.232130750999, - 0.0074999999999999997, + 0.0075, 360, 125000, 13, @@ -14,7 +14,7 @@ return [ ], [ -937.5, - 0.0074999999999999997, + 0.0075, 360, 125000, 1, @@ -22,8 +22,17 @@ return [ 0, ], [ - -2294.9775375120998, - 0.0041666666669999998, + -937.5, + 0.0075, + 360, + 125000, + 1, + 1, + null, + ], + [ + -2299.6141712553544, + 0.004175, 60, 50000, 1, @@ -31,8 +40,8 @@ return [ 0, ], [ - -1833.1000667254, - 0.0041666666669999998, + -1836.8883999349455, + 0.004175, 60, 50000, 13, @@ -40,8 +49,8 @@ return [ 0, ], [ - -1347.5920679425001, - 0.0041666666669999998, + -1350.4402595996685, + 0.004175, 60, 50000, 25, @@ -49,8 +58,8 @@ return [ 0, ], [ - -837.24455850309005, - 0.0041666666669999998, + -839.0535854569902, + 0.004175, 60, 50000, 37, @@ -58,8 +67,8 @@ return [ 0, ], [ - -300.78670189938998, - 0.0041666666669999998, + -301.4498641014851, + 0.004175, 60, 50000, 49, @@ -68,7 +77,7 @@ return [ ], [ '#VALUE!', - 0.0074999999999999997, + 'NaN', 360, 125000, 24, @@ -76,12 +85,66 @@ return [ 0, ], [ - '#NUM!', - 0.0074999999999999997, + '#VALUE!', + 0.0075, + 'NaN', + 125000, + 24, + 13, + 0, + ], + [ + '#VALUE!', + 0.0075, + 360, + 'NaN', + 24, + 13, + 0, + ], + [ + '#VALUE!', + 0.0075, + 360, + 125000, + 'NaN', + 13, + 0, + ], + [ + '#VALUE!', + 0.0075, + 360, + 125000, + 24, + 'NaN', + 0, + ], + [ + '#VALUE!', + 0.0075, 360, 125000, 24, 13, + 'NaN', + ], + [ + '#NUM!', + 0.0075, + 360, + 125000, + 13, + 24, 2, ], + [ + '#NUM!', + 0.0075, + 10, + 125000, + 24, + 13, + 0, + ], ]; diff --git a/tests/data/Calculation/Financial/CUMPRINC.php b/tests/data/Calculation/Financial/CUMPRINC.php index 63392c52..e14d5adc 100644 --- a/tests/data/Calculation/Financial/CUMPRINC.php +++ b/tests/data/Calculation/Financial/CUMPRINC.php @@ -5,7 +5,7 @@ return [ [ -934.10712342088004, - 0.0074999999999999997, + 0.0075, 360, 125000, 13, @@ -14,7 +14,7 @@ return [ ], [ -68.278271180977001, - 0.0074999999999999997, + 0.0075, 360, 125000, 1, @@ -22,8 +22,17 @@ return [ 0, ], [ - -9027.7626490046005, - 0.0041666666669999998, + -68.278271180977001, + 0.0075, + 360, + 125000, + 1, + 1, + null, + ], + [ + -9025.875084814226, + 0.004175, 60, 50000, 1, @@ -31,8 +40,8 @@ return [ 0, ], [ - -9489.6401197913001, - 0.0041666666669999998, + -9488.600856134633, + 0.004175, 60, 50000, 13, @@ -40,8 +49,8 @@ return [ 0, ], [ - -9975.1481185740995, - 0.0041666666669999998, + -9975.04899646991, + 0.004175, 60, 50000, 25, @@ -49,8 +58,8 @@ return [ 0, ], [ - -10485.495628014, - 0.0041666666669999998, + -10486.435670612591, + 0.004175, 60, 50000, 37, @@ -58,8 +67,8 @@ return [ 0, ], [ - -11021.953484617001, - 0.0041666666669999998, + -11024.039391968092, + 0.004175, 60, 50000, 49, @@ -68,7 +77,61 @@ return [ ], [ '#VALUE!', - 0.0074999999999999997, + 'NaN', + 360, + 125000, + 13, + 24, + 0, + ], + [ + '#VALUE!', + 0.0075, + 'NaN', + 125000, + 13, + 24, + 0, + ], + [ + '#VALUE!', + 0.0075, + 360, + 'NaN', + 13, + 24, + 0, + ], + [ + '#VALUE!', + 0.0075, + 360, + 125000, + 'NaN', + 24, + 0, + ], + [ + '#VALUE!', + 0.0075, + 360, + 125000, + 13, + 'NaN', + 0, + ], + [ + '#VALUE!', + 0.0075, + 360, + 125000, + 13, + 24, + 'NaN', + ], + [ + '#VALUE!', + 0.0075, 360, 125000, 24, @@ -77,11 +140,20 @@ return [ ], [ '#NUM!', - 0.0074999999999999997, + 0.0075, 360, 125000, 24, 13, 2, ], + [ + '#NUM!', + 0.0075, + 10, + 125000, + 13, + 24, + 0, + ], ]; diff --git a/tests/data/Calculation/Financial/DB.php b/tests/data/Calculation/Financial/DB.php index 7f8fc6fa..89bd22f2 100644 --- a/tests/data/Calculation/Financial/DB.php +++ b/tests/data/Calculation/Financial/DB.php @@ -115,6 +115,47 @@ return [ 6, 6, ], + [ + 4651.199, + 12000, + 2000, + 3.5, + 2, + 1, + ], + [ + 3521.399, + 12000, + 2000, + 5, + 2.5, + 1, + ], + [ + 3521.399, + 12000, + 2000, + 5, + 2.5, + 1.2, + ], + // Period value between 0 and 1 not yet handled in code + // [ + // 301.0, + // 12000, + // 2000, + // 5, + // 0.5, + // 1, + // ], + [ + -554.116, + 12000, + 15000, + 5, + 2, + 1, + ], [ '#NUM!', -1000, @@ -125,10 +166,82 @@ return [ ], [ '#VALUE!', - 'ABC', - 100, + 'Invalid', + 1000, 5, - 6, - 6, + 2, + 1, + ], + [ + '#VALUE!', + 12000, + 'Invalid', + 5, + 2, + 1, + ], + [ + '#VALUE!', + 12000, + 1000, + 'Invalid', + 2, + 1, + ], + [ + '#VALUE!', + 12000, + 1000, + 5, + 'Invalid', + 1, + ], + [ + '#VALUE!', + 12000, + 1000, + 5, + 2, + 'Invalid', + ], + [ + '#NUM!', + -12000, + 1000, + 5, + 2, + 1, + ], + [ + '#NUM!', + 12000, + -1000, + 5, + 2, + 1, + ], + [ + '#NUM!', + 12000, + 1000, + 5, + 0, + 1, + ], + [ + '#NUM!', + 12000, + 1000, + 5, + -2, + 1, + ], + [ + '#NUM!', + 12000, + 1000, + 5, + 2, + 0, ], ]; diff --git a/tests/data/Calculation/Financial/DDB.php b/tests/data/Calculation/Financial/DDB.php index 879224ca..67962ea2 100644 --- a/tests/data/Calculation/Financial/DDB.php +++ b/tests/data/Calculation/Financial/DDB.php @@ -98,6 +98,47 @@ return [ 5, 5, ], + [ + 972.0, + 12000, + 1000, + 5, + 3, + 0.5, + ], + [ + 1259.4752186588921, + 12000, + 1000, + 3.5, + 3, + 0.5, + ], + [ + 1080.00, + 12000, + 1000, + 5, + 2, + 0.5, + ], + [ + 0.0, + 12000, + 15000, + 5, + 2, + 0.5, + ], + // Code does not yet handle fractional period values for DDB, only integer + // [ + // 1024.58, + // 12000, + // 1000, + // 5, + // 2.5, + // 0.5, + // ], [ '#NUM!', -2400, @@ -112,4 +153,76 @@ return [ 36500, 1, ], + [ + '#VALUE!', + 12000, + 'INVALID', + 5, + 3, + 0.5, + ], + [ + '#VALUE!', + 12000, + 1000, + 'INVALID', + 3, + 0.5, + ], + [ + '#VALUE!', + 12000, + 1000, + 5, + 'INVALID', + 0.5, + ], + [ + '#VALUE!', + 12000, + 1000, + 5, + 3, + 'INVALID', + ], + [ + '#NUM!', + 12000, + -1000, + 5, + 3, + 0.5, + ], + [ + '#NUM!', + 12000, + 1000, + 5, + -3, + 0.5, + ], + [ + '#NUM!', + 12000, + 1000, + 5, + 3, + -0.5, + ], + [ + '#NUM!', + 12000, + 1000, + 5, + 0, + 0.5, + ], + [ + '#NUM!', + 12000, + 1000, + 2, + 3, + 0.5, + ], ]; diff --git a/tests/data/Calculation/Financial/DISC.php b/tests/data/Calculation/Financial/DISC.php index d77b0a81..f33ed21b 100644 --- a/tests/data/Calculation/Financial/DISC.php +++ b/tests/data/Calculation/Financial/DISC.php @@ -18,6 +18,14 @@ return [ 95, 100, ], + [ + 0.01, + '2010-04-01', + '2015-03-31', + 95, + 100, + null, + ], [ '#NUM!', '2010-04-01', diff --git a/tests/data/Calculation/Financial/DaysPerYear.php b/tests/data/Calculation/Financial/DaysPerYear.php new file mode 100644 index 00000000..d8adb1c5 --- /dev/null +++ b/tests/data/Calculation/Financial/DaysPerYear.php @@ -0,0 +1,15 @@ + 0, 2 > 0, + true, true, ], [ true, @@ -15,23 +15,23 @@ return [ ], [ true, - 1 > 0, 0 > 1, + true, false, ], [ true, - 0 > 1, 2 > 0, + false, true, ], [ false, - 0 > 1, 0 > 2, + false, false, ], [ false, - 1 > 0, 2 > 0, 0 > 1, 0 > 2, + true, true, false, false, ], [ true, - 1 > 0, 2 > 0, 3 > 0, 0 > 1, + true, true, true, false, ], [ false, diff --git a/tests/data/Calculation/LookupRef/ADDRESS.php b/tests/data/Calculation/LookupRef/ADDRESS.php new file mode 100644 index 00000000..b9e170d5 --- /dev/null +++ b/tests/data/Calculation/LookupRef/ADDRESS.php @@ -0,0 +1,64 @@ + 'B5', 'C' => 'C5', 'D' => 'D5'], + ], + [ + [2, 3, 4], + 'B2:D3', + ], + [ + [2, 3, 4], + 'Sheet1!B2:D2', + ], + [ + [2, 3, 4], + '"WorkSheet #1"!B2:D2', + ], + [1, []], +]; diff --git a/tests/data/Calculation/LookupRef/COLUMNSonSpreadsheet.php b/tests/data/Calculation/LookupRef/COLUMNSonSpreadsheet.php new file mode 100644 index 00000000..4002c2f1 --- /dev/null +++ b/tests/data/Calculation/LookupRef/COLUMNSonSpreadsheet.php @@ -0,0 +1,19 @@ + [1, 'namedrangex'], + 'global $f$2:$h$2' => [3, 'namedrangey'], + 'global $f$4:$h$4' => [3, 'namedrange3'], + 'local in scope $f$5:$i$5' => [4, 'namedrange5'], + 'local out of scope' => ['#NAME?', 'localname'], + 'non-existent sheet' => [10, 'UnknownSheet!B2:K6'], + 'not enough arguments' => ['exception', 'omitted'], + 'other existing sheet' => [6, 'OtherSheet!B1:G1'], + 'qualified in scope $f$5:$i$5' => [4, 'ThisSheet!namedrange5'], + 'single cell absolute' => [1, '$C$15'], + 'single cell relative' => [1, 'C7'], + 'unknown name' => ['#NAME?', 'namedrange2'], + 'unknown name as first part of range' => ['#NAME?', 'Invalid:A2'], + 'unknown name as second part of range' => ['#NAME?', 'A2:Invalid'], + //'qualified out of scope $f$6:$h$6' => [3, 'OtherSheet!localname'], // needs investigation +]; diff --git a/tests/data/Calculation/LookupRef/COLUMNonSpreadsheet.php b/tests/data/Calculation/LookupRef/COLUMNonSpreadsheet.php new file mode 100644 index 00000000..cc93653e --- /dev/null +++ b/tests/data/Calculation/LookupRef/COLUMNonSpreadsheet.php @@ -0,0 +1,17 @@ + [2, 'omitted'], + 'global name $E$2:$E$6' => [5, 'namedrangex'], + 'global name $F$2:$H$2' => [6, 'namedrange3'], + 'global name $F$4:$H$4' => [6, 'namedrangey'], + 'out of scope name' => ['#NAME?', 'localname'], + 'qualified cell existing sheet' => [1, 'OtherSheet!A1'], + 'qualified cell non-existent sheet' => [1, 'UnknownSheet!A1'], + 'single cell absolute' => [3, '$C$15'], + 'single cell relative' => [3, 'C7'], + 'unknown name' => ['#NAME?', 'namedrange2'], + 'unknown name as first part of range' => ['#NAME?', 'Invalid:A2'], + 'unknown name as second part of range' => ['#NAME?', 'A2:Invalid'], + //'qualified name' => [6, 'OtherSheet!localname'], // Never reaches function +]; diff --git a/tests/data/Calculation/LookupRef/HLOOKUP.php b/tests/data/Calculation/LookupRef/HLOOKUP.php index b880f247..078ed007 100644 --- a/tests/data/Calculation/LookupRef/HLOOKUP.php +++ b/tests/data/Calculation/LookupRef/HLOOKUP.php @@ -1,276 +1,94 @@ ['R' => 1]], ], - [ + 'Negative Row' => [ '#VALUE!', // Expected // Input [ @@ -15,7 +15,7 @@ return [ ], -1, ], - [ + 'Row > matrix rows' => [ '#REF!', // Expected // Input [ @@ -24,7 +24,25 @@ return [ ], 10, ], - [ + 'Row is not a number' => [ + '#VALUE!', // Expected + // Input + [ + 20 => ['R' => 1], + 21 => ['R' => 2], + ], + 'NaN', + ], + 'Row is Error' => [ + '#N/A', // Expected + // Input + [ + 20 => ['R' => 1], + 21 => ['R' => 2], + ], + '#N/A', + ], + 'Return row 2' => [ [21 => ['R' => 2]], // Expected // Input [ @@ -33,7 +51,7 @@ return [ ], 2, ], - [ + 'Return row 2 from larger matrix' => [ [21 => ['R' => 2, 'S' => 4]], // Expected // Input [ @@ -43,18 +61,18 @@ return [ 2, 0, ], - [ + 'Negative Column' => [ '#VALUE!', // Expected // Input [ '20' => ['R' => 1, 'S' => 3], '21' => ['R' => 2, 'S' => 4], ], - 2, + 0, -1, ], - [ - '#VALUE!', // Expected + 'Column > matrix columns' => [ + '#REF!', // Expected // Input [ '20' => ['R' => 1, 'S' => 3], @@ -63,6 +81,26 @@ return [ 2, 10, ], + 'Column is not a number' => [ + '#VALUE!', // Expected + // Input + [ + 20 => ['R' => 1], + 21 => ['R' => 2], + ], + 1, + 'NaN', + ], + 'Column is Error' => [ + '#N/A', // Expected + // Input + [ + 20 => ['R' => 1], + 21 => ['R' => 2], + ], + 1, + '#N/A', + ], [ 4, // Expected // Input @@ -87,4 +125,73 @@ return [ '21' => ['R' => 2], ], ], + [ + 'Pears', + [ + ['Apples', 'Lemons'], + ['Bananas', 'Pears'], + ], + 2, + 2, + ], + [ + 'Bananas', + [ + ['Apples', 'Lemons'], + ['Bananas', 'Pears'], + ], + 2, + 1, + ], + [ + [1 => ['Bananas', 'Pears']], + [ + ['Apples', 'Lemons'], + ['Bananas', 'Pears'], + ], + 2, + 0, + ], + [ + 3, + [ + [4, 6], + [5, 3], + [6, 9], + [7, 5], + [8, 3], + ], + 5, + 2, + ], + [ + [4 => [8, 3]], + [ + [4, 6], + [5, 3], + [6, 9], + [7, 5], + [8, 3], + ], + 5, + 0, + ], + [ + [ + [6], + [3], + [9], + [5], + [3], + ], + [ + [4, 6], + [5, 3], + [6, 9], + [7, 5], + [8, 3], + ], + 0, + 2, + ], ]; diff --git a/tests/data/Calculation/LookupRef/INDIRECT.php b/tests/data/Calculation/LookupRef/INDIRECT.php new file mode 100644 index 00000000..b8519657 --- /dev/null +++ b/tests/data/Calculation/LookupRef/INDIRECT.php @@ -0,0 +1,37 @@ + [600, '$A$1:$A$3'], + 'cell range on different sheet' => [30, 'OtherSheet!A1:A2'], + 'cell range on different sheet absolute' => [60, 'OtherSheet!$A$1:$A$3'], + 'cell range relative' => [500, 'A2:A3'], + 'global name qualified with correct sheet' => [90, 'OtherSheet!newnr'], + 'global name qualified with incorrect sheet' => [90, 'ThisSheet!newnr'], + 'global name qualified with non-existent sheet' => ['#REF!', 'UnknownSheet!newnr'], + 'invalid address' => ['#REF!', 'InvalidCellAddress'], + 'invalid address as first part of range' => ['#REF!', 'Invalid:A2'], + 'invalid address as second part of range' => ['#REF!', 'A2:Invalid'], + 'local name out of scope' => ['#REF!', 'localname'], + 'named range' => [90, 'newnr'], + 'named range a1 arg ignored' => [90, 'newnr', false], + 'named range case-insensitive' => [90, 'newNr'], + 'null address' => ['#REF!', null], + 'omit a1 argument' => [900, 'A2:A4'], + 'qualified name correct sheet even out of scope' => [9, 'OtherSheet!localname'], + 'qualified name incorrect sheet' => ['#REF!', 'ThisSheet!localname'], + 'qualified name non-existent sheet' => ['#REF!', 'OtherSheetx!localname'], + 'r1c1 cell on different sheet' => [40, 'OtherSheet!R4C1', false], + 'r1c1 format a1 as string not permitted' => ['#VALUE!', 'R2C1', '0'], + 'r1c1 format a1 is bool' => [200, 'R2C1', false], + 'r1c1 format a1 is int' => [200, 'R2C1', 0], + 'r1c1 range' => [600, 'R1C1:R3C1', false], + 'r1c1 range on different sheet' => [90, 'OtherSheet!R4C1:R5C1', false], + 'single cell absolute' => [200, '$A$2'], + 'single cell relative' => [100, 'A1'], + 'single cell on different sheet absolute' => [30, 'OtherSheet!$A$3'], + 'single cell on different sheet relative' => [10, 'OtherSheet!A1'], + 'supply a1 argument as bool' => [900, 'A2:A4', true], + 'supply a1 argument as int' => [900, 'A2:A4', 1], + 'supply a1 argument as float' => [900, 'A2:A4', 7.3], + 'supply a1 argument as string not permitted' => ['#VALUE!', 'A2:A4', '1'], +]; diff --git a/tests/data/Calculation/LookupRef/IndirectDefinedName.xlsx b/tests/data/Calculation/LookupRef/IndirectDefinedName.xlsx new file mode 100644 index 00000000..d351aa60 Binary files /dev/null and b/tests/data/Calculation/LookupRef/IndirectDefinedName.xlsx differ diff --git a/tests/data/Calculation/LookupRef/IndirectFormulaSelection.xlsx b/tests/data/Calculation/LookupRef/IndirectFormulaSelection.xlsx new file mode 100644 index 00000000..0095a29a Binary files /dev/null and b/tests/data/Calculation/LookupRef/IndirectFormulaSelection.xlsx differ diff --git a/tests/data/Calculation/LookupRef/LOOKUP.php b/tests/data/Calculation/LookupRef/LOOKUP.php index ab322d57..9c7d96eb 100644 --- a/tests/data/Calculation/LookupRef/LOOKUP.php +++ b/tests/data/Calculation/LookupRef/LOOKUP.php @@ -1,7 +1,6 @@ ['B' => 'B5', 'C' => 'C5', 'D' => 'D5'], + 5 => ['B' => 'B5', 'C' => 'C5', 'D' => 'D5'], + ], + ], + [ + [[10], [11], [12]], + 'Sheet1!C10:C12', + ], + [ + [[10], [11], [12]], + '"WorkSheet #1"!C10:C12', + ], + [1, []], +]; diff --git a/tests/data/Calculation/LookupRef/ROWSonSpreadsheet.php b/tests/data/Calculation/LookupRef/ROWSonSpreadsheet.php new file mode 100644 index 00000000..117885bc --- /dev/null +++ b/tests/data/Calculation/LookupRef/ROWSonSpreadsheet.php @@ -0,0 +1,19 @@ + [5, 'namedrangex'], + 'global $F$2:$H$2' => [1, 'namedrangey'], + 'global $F$4:$H$4' => [1, 'namedrange3'], + 'local in scope $F$5:$H$5' => [1, 'namedrange5'], + 'local out of scope' => ['#NAME?', 'localname'], + 'non-existent sheet' => [5, 'UnknownSheet!B2:K6'], + 'not enough arguments' => ['exception', 'omitted'], + 'other existing sheet' => [6, 'OtherSheet!A1:H6'], + 'qualified in scope $F$5:$H$5' => [1, 'ThisSheet!namedrange5'], + 'single cell absolute' => [1, '$C$7'], + 'single cell relative' => [1, 'C7'], + 'unknown name' => ['#NAME?', 'InvalidCellAddress'], + 'unknown name as first part of range' => ['#NAME?', 'Invalid:A2'], + 'unknown name as second part of range' => ['#NAME?', 'A2:Invalid'], + //'qualified out of scope $F$6:$H$6' => [1, 'OtherSheet!localname'], // needs investigation +]; diff --git a/tests/data/Calculation/LookupRef/ROWonSpreadsheet.php b/tests/data/Calculation/LookupRef/ROWonSpreadsheet.php new file mode 100644 index 00000000..f2395e6b --- /dev/null +++ b/tests/data/Calculation/LookupRef/ROWonSpreadsheet.php @@ -0,0 +1,18 @@ + [3, 'omitted'], + 'global name $E$2:$E$6' => [2, 'namedrangex'], + 'global name $F$2:$H$2' => [2, 'namedrangey'], + 'global name $F$4:$H$4' => [4, 'namedrange3'], + 'local name $F$5:$H$5' => [5, 'namedrange5'], + 'out of scope name' => ['#NAME?', 'localname'], + 'qualified cell existing sheet' => [1, 'OtherSheet!A1'], + 'qualified cell non-existent sheet' => [1, 'UnknownSheet!A1'], + 'single cell absolute' => [7, '$C$7'], + 'single cell relative' => [7, 'C7'], + 'unknown name' => ['#NAME?', 'namedrange2'], + 'unknown name as first part of range' => ['#NAME?', 'InvalidCell:A2'], + 'unknown name as second part of range' => ['#NAME?', 'A2:InvalidCell'], + //'qualified name' => [6, 'OtherSheet!localname'], // Never reaches function +]; diff --git a/tests/data/Calculation/LookupRef/TRANSPOSE.php b/tests/data/Calculation/LookupRef/TRANSPOSE.php new file mode 100644 index 00000000..a5ca45f4 --- /dev/null +++ b/tests/data/Calculation/LookupRef/TRANSPOSE.php @@ -0,0 +1,32 @@ + 36 + ['#NUM!', 2 ** 54, 16], // number > 2 ** 53 + ['00000120', 15, 3, 8.1], + ['exception'], + ['exception', 1], ]; diff --git a/tests/data/Calculation/MathTrig/CEILING.php b/tests/data/Calculation/MathTrig/CEILING.php index 4005f12b..a4af7df1 100644 --- a/tests/data/Calculation/MathTrig/CEILING.php +++ b/tests/data/Calculation/MathTrig/CEILING.php @@ -1,104 +1,34 @@ ['A' => 0], - 2 => ['A' => 1], - 3 => ['A' => 1], - 4 => ['A' => 2], - 5 => ['A' => 3], - 6 => ['A' => 5], - 7 => ['A' => 8], - 8 => ['A' => 13], - 9 => ['A' => 21], - 10 => ['A' => 34], - 11 => ['A' => 55], - 12 => ['A' => 89], -]; - return [ - [ - 19.3333333333333, - 1, - $baseTestData, - ], - [ - 12, - 2, - $baseTestData, - ], - [ - 12, - 3, - $baseTestData, - ], - [ - 89, - 4, - $baseTestData, - ], - [ - 0, - 5, - $baseTestData, - ], - [ - 0, - 6, - $baseTestData, - ], - [ - 27.5196899207337, - 7, - $baseTestData, - ], - [ - 26.3480971271593, - 8, - $baseTestData, - ], - [ - 232, - 9, - $baseTestData, - ], - [ - 757.3333333333330, - 10, - $baseTestData, - ], - [ - 694.2222222222220, - 11, - $baseTestData, - ], + [19.3333333333333, 1], + [12, 2], + [12, 3], + [89, 4], + [0, 5], + [0, 6], + [27.5196899207337, 7], + [26.3480971271593, 8], + [232, 9], + [757.3333333333330, '10'], + [694.2222222222220, 11.1], + ['#VALUE!', 0], + ['#VALUE!', -1], + ['#VALUE!', 12], + ['#VALUE!', '"X"'], ]; diff --git a/tests/data/Calculation/MathTrig/SUBTOTALHIDDEN.php b/tests/data/Calculation/MathTrig/SUBTOTALHIDDEN.php index 001531f8..df6375dc 100644 --- a/tests/data/Calculation/MathTrig/SUBTOTALHIDDEN.php +++ b/tests/data/Calculation/MathTrig/SUBTOTALHIDDEN.php @@ -1,74 +1,15 @@ ['A' => 0], - 2 => ['A' => 1], - 3 => ['A' => 1], - 4 => ['A' => 2], - 5 => ['A' => 3], - 6 => ['A' => 5], - 7 => ['A' => 8], - 8 => ['A' => 13], - 9 => ['A' => 21], - 10 => ['A' => 34], - 11 => ['A' => 55], - 12 => ['A' => 89], -]; - return [ - [ - 21, - 101, - $baseTestData, - ], - [ - 5, - 102, - $baseTestData, - ], - [ - 5, - 103, - $baseTestData, - ], - [ - 55, - 104, - $baseTestData, - ], - [ - 1, - 105, - $baseTestData, - ], - [ - 48620, - 106, - $baseTestData, - ], - [ - 23.1840462387393, - 107, - $baseTestData, - ], - [ - 20.7364413533277, - 108, - $baseTestData, - ], - [ - 105, - 109, - $baseTestData, - ], - [ - 537.5, - 110, - $baseTestData, - ], - [ - 430, - 111, - $baseTestData, - ], + [21, 101], + [5, 102], + [5, 103], + [55, 104], + [1, 105], + [48620, 106], + [23.1840462387393, 107], + [20.7364413533277, 108], + [105, 109], + [537.5, 110], + [430, 111], ]; diff --git a/tests/data/Calculation/MathTrig/SUBTOTALNESTED.php b/tests/data/Calculation/MathTrig/SUBTOTALNESTED.php deleted file mode 100644 index e1ae38f8..00000000 --- a/tests/data/Calculation/MathTrig/SUBTOTALNESTED.php +++ /dev/null @@ -1,18 +0,0 @@ - ['A' => 123], - 2 => ['A' => 234], - 3 => ['A' => '=SUBTOTAL(1, A1:A2)'], - 4 => ['A' => '=ROMAN(SUBTOTAL(1, A1:A2))'], - 5 => ['A' => 'This is text containing "=" and "SUBTOTAL("'], - 6 => ['A' => '=AGGREGATE(1, A1:A2)'], -]; - -return [ - [ - 357, - 9, - $baseTestData, - ], -]; diff --git a/tests/data/Calculation/MathTrig/SUM.php b/tests/data/Calculation/MathTrig/SUM.php new file mode 100644 index 00000000..0c54613e --- /dev/null +++ b/tests/data/Calculation/MathTrig/SUM.php @@ -0,0 +1,12 @@ +2', + ['Jeff', 'Chris', 'Carol', 'Jeff', 'Chris', 'Carol', 'Jeff', 'Chris', 'Carol', 'Jeff', 'Chris', 'Carol'], + 'Jeff', + ], ]; diff --git a/tests/data/Calculation/MathTrig/SUMLITERALS.php b/tests/data/Calculation/MathTrig/SUMLITERALS.php new file mode 100644 index 00000000..fd184ebd --- /dev/null +++ b/tests/data/Calculation/MathTrig/SUMLITERALS.php @@ -0,0 +1,12 @@ +true', + [2, 4, 6, 8, 10], + ], + [ + (1 + 2 + 5 + 6) / 4, + ['North', 'South', 'East', 'West', 'North', 'South', 'East', 'West'], + '???th', + [1, 2, 3, 4, 5, 6, 7, 8], + ], + [ + 16733.5, + ['East', 'West', 'North', 'South (New Office)', 'Midwest'], + '=*West', + [45678, 23789, -4789, 0, 9678], + ], + [ + 18589, + ['East', 'West', 'North', 'South (New Office)', 'Midwest'], + '<>*(New Office)', + [45678, 23789, -4789, 0, 9678], ], ]; diff --git a/tests/data/Calculation/Statistical/AVERAGEIFS.php b/tests/data/Calculation/Statistical/AVERAGEIFS.php new file mode 100644 index 00000000..d5bc6dad --- /dev/null +++ b/tests/data/Calculation/Statistical/AVERAGEIFS.php @@ -0,0 +1,45 @@ +70', + [75, 94, 86, 'incomplete'], + '<90', + ], + [ + '#DIV/0!', + [85, 80, 93, 75], + [85, 80, 93, 75], + '>95', + ], + [ + 87.5, + [87, 88, 'incomplete', 75], + [87, 88, 'incomplete', 75], + '<>incomplete', + [87, 88, 'incomplete', 75], + '>80', + ], + [ + 174000, + [223000, 125000, 456000, 322000, 340000, 198000, 310000, 250000, 460000, 261000, 389000, 305000], + [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], + 1, + ['North', 'North', 'South', 'North', 'North', 'South', 'North', 'North', 'South', 'North', 'North', 'South'], + 'North', + ], + [ + 285500, + [223000, 125000, 456000, 322000, 340000, 198000, 310000, 250000, 460000, 261000, 389000, 305000], + [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], + '>2', + ['Jeff', 'Chris', 'Carol', 'Jeff', 'Chris', 'Carol', 'Jeff', 'Chris', 'Carol', 'Jeff', 'Chris', 'Carol'], + 'Jeff', + ], +]; diff --git a/tests/data/Calculation/Statistical/BETADIST.php b/tests/data/Calculation/Statistical/BETADIST.php index f489429c..ef89575f 100644 --- a/tests/data/Calculation/Statistical/BETADIST.php +++ b/tests/data/Calculation/Statistical/BETADIST.php @@ -13,6 +13,10 @@ return [ 0.960370937542, 3, 7.5, 9, 1, 4, ], + [ + 0.960370937542, + 3, 7.5, 9, 4, 1, + ], [ 0.598190307617, 7.5, 8, 9, 5, 10, @@ -21,12 +25,60 @@ return [ 0.685470581054, 2, 8, 10, 1, 3, ], + [ + 0.4059136, + 0.4, 4, 5, + ], + [ + 0.4059136, + 0.4, 4, 5, null, null, + ], + [ + '#VALUE!', + 'NAN', 8, 10, 1, 3, + ], [ '#VALUE!', 2, 'NAN', 10, 1, 3, ], [ + '#VALUE!', + 2, 8, 'NAN', 1, 3, + ], + [ + '#VALUE!', + 2, 8, 10, 'NAN', 3, + ], + [ + '#VALUE!', + 2, 8, 10, 1, 'NAN', + ], + 'alpha < 0' => [ '#NUM!', 2, -8, 10, 1, 3, ], + 'alpha = 0' => [ + '#NUM!', + 2, 0, 10, 1, 3, + ], + 'beta < 0' => [ + '#NUM!', + 2, 8, -10, 1, 3, + ], + 'beta = 0' => [ + '#NUM!', + 2, 8, 0, 1, 3, + ], + 'value < Min' => [ + '#NUM!', + 0.5, 8, 10, 1, 3, + ], + 'value > Max' => [ + '#NUM!', + 3.5, 8, 10, 1, 3, + ], + 'Min = Max' => [ + '#NUM!', + 2, 8, 10, 2, 2, + ], ]; diff --git a/tests/data/Calculation/Statistical/BETAINV.php b/tests/data/Calculation/Statistical/BETAINV.php index d62c1c35..609c2804 100644 --- a/tests/data/Calculation/Statistical/BETAINV.php +++ b/tests/data/Calculation/Statistical/BETAINV.php @@ -9,6 +9,10 @@ return [ 2.164759759129, 0.3, 7.5, 9, 1, 4, ], + [ + 2.164759759129, + 0.3, 7.5, 9, 4, 1, + ], [ 7.761240188783, 0.75, 8, 9, 5, 10, @@ -21,12 +25,60 @@ return [ 0.303225844664, 0.2, 4, 5, 0, 1, ], + [ + 0.303225844664, + 0.2, 4, 5, null, null, + ], + [ + '#VALUE!', + 'NAN', 4, 5, 0, 1, + ], [ '#VALUE!', 0.2, 'NAN', 5, 0, 1, ], [ + '#VALUE!', + 0.2, 4, 'NAN', 0, 1, + ], + [ + '#VALUE!', + 0.2, 4, 5, 'NAN', 1, + ], + [ + '#VALUE!', + 0.2, 4, 5, 0, 'NAN', + ], + 'alpha < 0' => [ '#NUM!', 0.2, -4, 5, 0, 1, ], + 'alpha = 0' => [ + '#NUM!', + 0.2, 0, 5, 0, 1, + ], + 'beta < 0' => [ + '#NUM!', + 0.2, 4, -5, 0, 1, + ], + 'beta = 0' => [ + '#NUM!', + 0.2, 4, 0, 0, 1, + ], + 'Probability < 0' => [ + '#NUM!', + -0.5, 4, 5, 1, 3, + ], + 'Probability = 0' => [ + '#NUM!', + 0.0, 4, 5, 1, 3, + ], + 'Probability > 1' => [ + '#NUM!', + 1.5, 4, 5, 1, 3, + ], + 'Min = Max' => [ + '#NUM!', + 1, 4, 5, 1, 1, + ], ]; diff --git a/tests/data/Calculation/Statistical/BINOMDIST.php b/tests/data/Calculation/Statistical/BINOMDIST.php index 47e8a3f3..3606bced 100644 --- a/tests/data/Calculation/Statistical/BINOMDIST.php +++ b/tests/data/Calculation/Statistical/BINOMDIST.php @@ -49,12 +49,32 @@ return [ '#VALUE!', 'NAN', 100, 0.5, true, ], + [ + '#VALUE!', + 65, 'NAN', 0.5, true, + ], + [ + '#VALUE!', + 65, 100, 'NAN', true, + ], + [ + '#VALUE!', + 65, 100, 0.5, 'NAN', + ], [ '#NUM!', -5, 100, 0.5, true, ], [ '#NUM!', - 5, 100, 1.5, true, + 105, 100, 0.5, true, + ], + [ + '#NUM!', + 65, 100, -0.5, true, + ], + [ + '#NUM!', + 65, 100, 1.5, true, ], ]; diff --git a/tests/data/Calculation/Statistical/BINOMDISTRANGE.php b/tests/data/Calculation/Statistical/BINOMDISTRANGE.php new file mode 100644 index 00000000..153706d1 --- /dev/null +++ b/tests/data/Calculation/Statistical/BINOMDISTRANGE.php @@ -0,0 +1,76 @@ + [ + '#NUM!', + -8, 3, true, + ], + 'Degrees < 1' => [ + '#NUM!', + 8, 0, true, + ], +]; diff --git a/tests/data/Calculation/Statistical/CHIDIST.php b/tests/data/Calculation/Statistical/CHIDISTRightTail.php similarity index 84% rename from tests/data/Calculation/Statistical/CHIDIST.php rename to tests/data/Calculation/Statistical/CHIDISTRightTail.php index 5cfdc664..24ddab9f 100644 --- a/tests/data/Calculation/Statistical/CHIDIST.php +++ b/tests/data/Calculation/Statistical/CHIDISTRightTail.php @@ -35,14 +35,18 @@ return [ ], [ '#VALUE!', - 'NAN', 3, + 'NaN', 3, ], [ - '#NUM!', - 8, 0, + '#VALUE!', + 8, 'NaN', ], - [ + 'Value < 0' => [ '#NUM!', -8, 3, ], + 'Degrees < 1' => [ + '#NUM!', + 8, 0, + ], ]; diff --git a/tests/data/Calculation/Statistical/CHIINVLeftTail.php b/tests/data/Calculation/Statistical/CHIINVLeftTail.php new file mode 100644 index 00000000..bc64721e --- /dev/null +++ b/tests/data/Calculation/Statistical/CHIINVLeftTail.php @@ -0,0 +1,64 @@ + [ + '#NUM!', + -0.1, 3, + ], + 'Probability > 1' => [ + '#NUM!', + 1.1, 3, + ], + 'Freedom > 1' => [ + '#NUM!', + 0.1, 0.5, + ], +]; diff --git a/tests/data/Calculation/Statistical/CHIINV.php b/tests/data/Calculation/Statistical/CHIINVRightTail.php similarity index 51% rename from tests/data/Calculation/Statistical/CHIINV.php rename to tests/data/Calculation/Statistical/CHIINVRightTail.php index 2384cda6..58b317e5 100644 --- a/tests/data/Calculation/Statistical/CHIINV.php +++ b/tests/data/Calculation/Statistical/CHIINVRightTail.php @@ -10,13 +10,21 @@ return [ 0.75, 10, ], [ - 18.30697345702, - 0.050001, 10, + 0.007716715545, + 0.93, 1, + ], + [ + 1.021651247532, + 0.6, 2, ], [ 0.45493642312, 0.5, 1, ], + [ + 4.351460191096, + 0.5, 5, + ], [ 0.101531044268, 0.75, 1, @@ -35,6 +43,22 @@ return [ ], [ '#VALUE!', - 0.25, 'NAN', + 'NaN', 3, + ], + [ + '#VALUE!', + 0.25, 'NaN', + ], + 'Probability < 0' => [ + '#NUM!', + -0.1, 3, + ], + 'Probability > 1' => [ + '#NUM!', + 1.1, 3, + ], + 'Freedom > 1' => [ + '#NUM!', + 0.1, 0.5, ], ]; diff --git a/tests/data/Calculation/Statistical/CHITEST.php b/tests/data/Calculation/Statistical/CHITEST.php new file mode 100644 index 00000000..6f5cd05c --- /dev/null +++ b/tests/data/Calculation/Statistical/CHITEST.php @@ -0,0 +1,39 @@ +true', + ], + [ + 4, + ['apples', 'oranges', 'peaches', 'apples'], + '*', + ], + [ + 3, + ['apples', 'oranges', 'peaches', 'apples'], + '*p*s*', + ], + [ + 4, + [ + ['apples', 'oranges', 'peaches', 'apples'], + ['bananas', 'mangoes', 'grapes', 'cherries'], + ], + '*p*e*', + ], + [ + 2, + ['apples', 'oranges', 'peaches', 'apples'], + '?????es', + ], + [ + 2, + ['great * ratings', 'bad * ratings', 'films * wars', 'films * trek', 'music * radio'], + '*~* ra*s', + ], ]; diff --git a/tests/data/Calculation/Statistical/COUNTIFS.php b/tests/data/Calculation/Statistical/COUNTIFS.php index 32f64d71..3ed1634a 100644 --- a/tests/data/Calculation/Statistical/COUNTIFS.php +++ b/tests/data/Calculation/Statistical/COUNTIFS.php @@ -1,6 +1,9 @@ 60%', + ], [ 2, - [1, 2, 3, 'B', '', false], - '<=2', + ['Maths', 'English', 'Science', 'Maths', 'English', 'Science', 'Maths', 'English', 'Science', 'Maths', 'English', 'Science'], + 'Science', + [0.63, 0.78, 0.39, 0.55, 0.71, 0.51, 0.78, 0.81, 0.49, 0.35, 0.69, 0.65], + '<50%', ], ]; diff --git a/tests/data/Calculation/Statistical/COVAR.php b/tests/data/Calculation/Statistical/COVAR.php index d361a352..b1cd2908 100644 --- a/tests/data/Calculation/Statistical/COVAR.php +++ b/tests/data/Calculation/Statistical/COVAR.php @@ -16,4 +16,14 @@ return [ [2, 7, 8, 3, 4, 1, 6, 5], [22.9, 33.49, 34.5, 27.61, 19.5, 10.11, 37.9, 31.08], ], + [ + '#N/A', + [1, 2, 3], + [4, 5], + ], + [ + '#DIV/0!', + [1, 2, 3], + [4, null, null], + ], ]; diff --git a/tests/data/Calculation/Statistical/CRITBINOM.php b/tests/data/Calculation/Statistical/CRITBINOM.php deleted file mode 100644 index 8e59bf51..00000000 --- a/tests/data/Calculation/Statistical/CRITBINOM.php +++ /dev/null @@ -1,24 +0,0 @@ - ['#NUM!', 0.0], + 'Negative integer value' => ['#NUM!', -1], ['#VALUE!', 'NAN'], ]; diff --git a/tests/data/Calculation/Statistical/GAMMADIST.php b/tests/data/Calculation/Statistical/GAMMADIST.php index e79b3869..2a1bfa14 100644 --- a/tests/data/Calculation/Statistical/GAMMADIST.php +++ b/tests/data/Calculation/Statistical/GAMMADIST.php @@ -17,12 +17,44 @@ return [ 0.576809918873, 6, 3, 2, true, ], + 'Boolean as numeric' => [ + 0.576809918873, + 6, 3, 2, 1, + ], + [ + '#VALUE!', + 'NAN', 3, 2, true, + ], [ '#VALUE!', 6, 'NAN', 2, true, ], [ + '#VALUE!', + 6, 3, 'NAN', true, + ], + [ + '#VALUE!', + 6, 3, 2, 'NAN', + ], + 'Value < 0' => [ '#NUM!', -6, 3, 2, true, ], + 'A < 0' => [ + '#NUM!', + 6, -3, 2, true, + ], + 'A = 0' => [ + '#NUM!', + 6, 0, 2, true, + ], + 'B < 0' => [ + '#NUM!', + 6, 3, -2, true, + ], + 'B = 0' => [ + '#NUM!', + 6, 3, 0, true, + ], ]; diff --git a/tests/data/Calculation/Statistical/GAMMAINV.php b/tests/data/Calculation/Statistical/GAMMAINV.php index 3b3604b4..c35c4219 100644 --- a/tests/data/Calculation/Statistical/GAMMAINV.php +++ b/tests/data/Calculation/Statistical/GAMMAINV.php @@ -11,10 +11,38 @@ return [ ], [ '#VALUE!', - 'NAN', 3, 2, + 'NaN', 3, 2, ], [ + '#VALUE!', + 0.5, 'NaN', 2, + ], + [ + '#VALUE!', + 0.5, 3, 'NaN', + ], + 'Probability < 0' => [ '#NUM!', -0.5, 3, 2, ], + 'Probability > 1' => [ + '#NUM!', + 1.5, 3, 2, + ], + 'Alpha < 0' => [ + '#NUM!', + 0.5, -3, 2, + ], + 'Alpha = 0' => [ + '#NUM!', + 0.5, 0, 2, + ], + 'Beta < 0' => [ + '#NUM!', + 0.5, 3, -2, + ], + 'Beta = 0' => [ + '#NUM!', + 0.5, 3, 0, + ], ]; diff --git a/tests/data/Calculation/Statistical/GAMMALN.php b/tests/data/Calculation/Statistical/GAMMALN.php index a415f559..7b43eea8 100644 --- a/tests/data/Calculation/Statistical/GAMMALN.php +++ b/tests/data/Calculation/Statistical/GAMMALN.php @@ -13,8 +13,12 @@ return [ '#VALUE!', 'NAN', ], - [ + 'Value < 0' => [ '#NUM!', -4.5, ], + 'Value = 0' => [ + '#NUM!', + 0.0, + ], ]; diff --git a/tests/data/Calculation/Statistical/GROWTH.php b/tests/data/Calculation/Statistical/GROWTH.php new file mode 100644 index 00000000..25596e30 --- /dev/null +++ b/tests/data/Calculation/Statistical/GROWTH.php @@ -0,0 +1,25 @@ + [ + // [ + // [-234.2371645, 2553.21066, 12529.76817, 27.64138737, 52317.83051], + // [13.26801148, 530.6691519, 400.0668382, 5.429374042, 12237.3616], + // [0.996747993, 970.5784629, '#N/A', '#N/A', '#N/A'], + // [459.7536742, 6, '#N/A', '#N/A', '#N/A'], + // [1732393319, 5652135.316, '#N/A', '#N/A', '#N/A'], + // ], + // [142000, 144000, 151000, 150000, 139000, 169000, 126000, 142900, 163000, 169000, 149000], + // [ + // [2310, 2, 2, 20], + // [2333, 2, 2, 12], + // [2356, 3, 1.5, 33], + // [2379, 3, 2, 43], + // [2402, 2, 3, 53], + // [2425, 4, 2, 23], + // [2448, 2, 1.5, 99], + // [2471, 2, 2, 34], + // [2494, 3, 3, 23], + // [2517, 4, 4, 55], + // [2540, 2, 3, 22], + // ], + // true, + // true, + // ], ]; diff --git a/tests/data/Calculation/Statistical/LOGEST.php b/tests/data/Calculation/Statistical/LOGEST.php index e74db005..bba7487b 100644 --- a/tests/data/Calculation/Statistical/LOGEST.php +++ b/tests/data/Calculation/Statistical/LOGEST.php @@ -1,6 +1,20 @@ 2', + ['Jeff', 'Chris', 'Carol', 'Jeff', 'Chris', 'Carol', 'Jeff', 'Chris', 'Carol', 'Jeff', 'Chris', 'Carol'], + 'Jeff', + ], ]; diff --git a/tests/data/Calculation/Statistical/MINA.php b/tests/data/Calculation/Statistical/MINA.php index 754f9aad..5f1fbd2a 100644 --- a/tests/data/Calculation/Statistical/MINA.php +++ b/tests/data/Calculation/Statistical/MINA.php @@ -25,4 +25,8 @@ return [ 0, null, 'STRING', '', 'xl95', ], + [ + 0, + null, null, null, null, + ], ]; diff --git a/tests/data/Calculation/Statistical/MINIFS.php b/tests/data/Calculation/Statistical/MINIFS.php index a00f25b7..5a1de173 100644 --- a/tests/data/Calculation/Statistical/MINIFS.php +++ b/tests/data/Calculation/Statistical/MINIFS.php @@ -1,6 +1,9 @@ 2', + ['Jeff', 'Chris', 'Carol', 'Jeff', 'Chris', 'Carol', 'Jeff', 'Chris', 'Carol', 'Jeff', 'Chris', 'Carol'], + 'Jeff', + ], ]; diff --git a/tests/data/Calculation/Statistical/NEGBINOMDIST.php b/tests/data/Calculation/Statistical/NEGBINOMDIST.php new file mode 100644 index 00000000..fd983cc1 --- /dev/null +++ b/tests/data/Calculation/Statistical/NEGBINOMDIST.php @@ -0,0 +1,52 @@ + [ + '#NUM!', + -35, 40, true, + ], + 'Mean < 0' => [ + '#NUM!', + 35, -40, true, + ], +]; diff --git a/tests/data/Calculation/Statistical/QUARTILE.php b/tests/data/Calculation/Statistical/QUARTILE.php new file mode 100644 index 00000000..26a7902f --- /dev/null +++ b/tests/data/Calculation/Statistical/QUARTILE.php @@ -0,0 +1,52 @@ + ['exception'], + 'non-printable' => ["\x02", 2], + 'bool argument' => ["\x01", true], + 'null argument' => ['#VALUE!', null], + 'ascii 1 is 49' => ['1', 49], + 'ascii 0 is 48' => ['0', 48], ]; diff --git a/tests/data/Calculation/TextData/CLEAN.php b/tests/data/Calculation/TextData/CLEAN.php index aab0fe3a..ad668271 100644 --- a/tests/data/Calculation/TextData/CLEAN.php +++ b/tests/data/Calculation/TextData/CLEAN.php @@ -5,6 +5,10 @@ return [ 'HELLO ', 'HELLO ', ], + [ + ' HELLO ', + ' HELLO ', + ], [ 'HELLO', ' HELLO', @@ -21,4 +25,5 @@ return [ null, null, ], + 'omitted argument' => ['exception'], ]; diff --git a/tests/data/Calculation/TextData/CODE.php b/tests/data/Calculation/TextData/CODE.php index 1b74b699..8ab92726 100644 --- a/tests/data/Calculation/TextData/CODE.php +++ b/tests/data/Calculation/TextData/CODE.php @@ -69,4 +69,5 @@ return [ 0x2020, '†', ], + 'omitted argument' => ['exception'], ]; diff --git a/tests/data/Calculation/TextData/CONCATENATE.php b/tests/data/Calculation/TextData/CONCATENATE.php index f17b024b..c6b583eb 100644 --- a/tests/data/Calculation/TextData/CONCATENATE.php +++ b/tests/data/Calculation/TextData/CONCATENATE.php @@ -18,4 +18,5 @@ return [ '-', true, ], + 'no arguments' => ['exception'], ]; diff --git a/tests/data/Calculation/TextData/DOLLAR.php b/tests/data/Calculation/TextData/DOLLAR.php index 67f394bb..78fcc1b5 100644 --- a/tests/data/Calculation/TextData/DOLLAR.php +++ b/tests/data/Calculation/TextData/DOLLAR.php @@ -16,7 +16,7 @@ return [ 2, ], [ - '($123.32)', + '-$123.32', -123.321, 2, ], @@ -31,7 +31,7 @@ return [ -5, ], [ - '($1,200,000)', + '-$1,200,000', -1234567, -5, ], @@ -45,4 +45,10 @@ return [ 123.456, 'ABC', ], + 'omitted amount' => ['exception'], + 'omitted decimals' => ['$123.46', 123.456], + 'null decimals' => ['$123', 123.456, null], + 'boolean decimals' => ['$123.5', 123.456, true], + 'boolean value' => ['$1.00', true], + 'null value' => ['$0.00', null], ]; diff --git a/tests/data/Calculation/TextData/EXACT.php b/tests/data/Calculation/TextData/EXACT.php index f760a58f..f392b0b0 100644 --- a/tests/data/Calculation/TextData/EXACT.php +++ b/tests/data/Calculation/TextData/EXACT.php @@ -36,4 +36,6 @@ return [ ' ', '', ], + 'no arguments' => ['exception'], + 'one argument1' => ['exception', 'abc'], ]; diff --git a/tests/data/Calculation/TextData/FIND.php b/tests/data/Calculation/TextData/FIND.php index 7420841a..1ae6d730 100644 --- a/tests/data/Calculation/TextData/FIND.php +++ b/tests/data/Calculation/TextData/FIND.php @@ -31,6 +31,36 @@ return [ 'A', 'MARK BAKER', ], + [ + 1, + 'Ενα', + 'Ενα δύο τρία τέσσερα πέντε', + ], + [ + 9, + 'τρία', + 'Ενα δύο τρία τέσσερα πέντε', + ], + [ + 22, + 'πέντε', + 'Ενα δύο τρία τέσσερα πέντε', + ], + [ + 1, + 'ΕΝΑ', + 'ΕΝΑ ΔΎΟ ΤΡΊΑ ΤΈΣΣΕΡΑ ΠΈΝΤΕ', + ], + [ + 9, + 'ΤΡΊΑ', + 'ΕΝΑ ΔΎΟ ΤΡΊΑ ΤΈΣΣΕΡΑ ΠΈΝΤΕ', + ], + [ + 22, + 'ΠΈΝΤΕ', + 'ΕΝΑ ΔΎΟ ΤΡΊΑ ΤΈΣΣΕΡΑ ΠΈΝΤΕ', + ], [ 2, 'a', @@ -71,4 +101,11 @@ return [ 'Mark Baker', 8, ], + 'Boolean Needle' => [ + '#VALUE!', + true, + 'Mark Baker', + ], + 'no arguments' => ['exception'], + 'one argument' => ['exception', 'a'], ]; diff --git a/tests/data/Calculation/TextData/FIXED.php b/tests/data/Calculation/TextData/FIXED.php index 2083ecce..29734404 100644 --- a/tests/data/Calculation/TextData/FIXED.php +++ b/tests/data/Calculation/TextData/FIXED.php @@ -59,4 +59,9 @@ return [ 'ABC', null, ], + 'no arguments' => ['exception'], + 'just one argument is okay' => ['123.00', 123], + 'null second argument' => ['123', 123, null], + 'false second argument' => ['123', 123, false], + 'true second argument' => ['123.0', 123, true], ]; diff --git a/tests/data/Calculation/TextData/LEFT.php b/tests/data/Calculation/TextData/LEFT.php index 914d16be..17d3fcf7 100644 --- a/tests/data/Calculation/TextData/LEFT.php +++ b/tests/data/Calculation/TextData/LEFT.php @@ -11,16 +11,50 @@ return [ '', 1, ], + [ + '', + 'ABC', + 0, + ], [ '#VALUE!', 'QWERTYUIOP', -1, ], + [ + '#VALUE!', + 'QWERTYUIOP', + 'NaN', + ], + 'null length defaults to 0' => [ + '', + 'QWERTYUIOP', + null, + ], + 'omitted length defaults to 1' => [ + 'Q', + 'QWERTYUIOP', + ], [ 'ABC', 'ABCDEFGHI', 3, ], + [ + 'Ενα', + 'Ενα δύο τρία τέσσερα πέντε', + 3, + ], + [ + 'Ενα δύο', + 'Ενα δύο τρία τέσσερα πέντε', + 7, + ], + [ + 'Ενα δύο τρία', + 'Ενα δύο τρία τέσσερα πέντε', + 12, + ], [ 'TR', true, @@ -31,4 +65,7 @@ return [ false, 2, ], + 'string not specified' => [ + 'exception', + ], ]; diff --git a/tests/data/Calculation/TextData/LEN.php b/tests/data/Calculation/TextData/LEN.php index 6bf44fc9..babf3535 100644 --- a/tests/data/Calculation/TextData/LEN.php +++ b/tests/data/Calculation/TextData/LEN.php @@ -25,4 +25,5 @@ return [ 5, false, ], + 'no arguments' => ['exception'], ]; diff --git a/tests/data/Calculation/TextData/LOWER.php b/tests/data/Calculation/TextData/LOWER.php index 2a4064bf..23825546 100644 --- a/tests/data/Calculation/TextData/LOWER.php +++ b/tests/data/Calculation/TextData/LOWER.php @@ -9,6 +9,18 @@ return [ 'mark baker', 'MARK BAKER', ], + [ + 'buenos días', + 'BUENOS DÍAS', + ], + [ + 'καλημερα', + 'ΚΑΛΗΜΕΡΑ', + ], + [ + 'доброе утро', + 'ДОБРОЕ УТРО', + ], [ 'true', true, @@ -17,4 +29,5 @@ return [ 'false', false, ], + 'no argument' => ['exception'], ]; diff --git a/tests/data/Calculation/TextData/MID.php b/tests/data/Calculation/TextData/MID.php index 2a59373b..45e0ceab 100644 --- a/tests/data/Calculation/TextData/MID.php +++ b/tests/data/Calculation/TextData/MID.php @@ -16,7 +16,7 @@ return [ [ '#VALUE!', 'QWERTYUIOP', - -1, + 0, 1, ], [ @@ -26,22 +26,71 @@ return [ -1, ], [ + '#VALUE!', + 'QWERTYUIOP', + 'NaN', + 1, + ], + [ + '#VALUE!', + 'QWERTYUIOP', + 2, + 'NaN', + ], + 'length null treated as zero' => [ '', 'QWERTYUIOP', + 2, + null, + ], + 'length not specified' => [ + 'exception', + 'QWERTYUIOP', 5, ], + 'start not specified' => [ + 'exception', + 'QWERTYUIOP', + ], + 'string not specified' => [ + 'exception', + ], [ 'IOP', 'QWERTYUIOP', 8, 20, ], + [ + '', + 'QWERTYUIOP', + 999, + 2, + ], [ 'DEF', 'ABCDEFGHI', 4, 3, ], + [ + 'δύο', + 'Ενα δύο τρία τέσσερα πέντε', + 5, + 3, + ], + [ + 'δύο τρία', + 'Ενα δύο τρία τέσσερα πέντε', + 5, + 8, + ], + [ + 'τρία τέσσερα', + 'Ενα δύο τρία τέσσερα πέντε', + 9, + 12, + ], [ 'R', true, diff --git a/tests/data/Calculation/TextData/NUMBERVALUE.php b/tests/data/Calculation/TextData/NUMBERVALUE.php index 3a6510b8..791e61cf 100644 --- a/tests/data/Calculation/TextData/NUMBERVALUE.php +++ b/tests/data/Calculation/TextData/NUMBERVALUE.php @@ -3,50 +3,52 @@ return [ [ 1234567.89, - ['1,234,567.890'], + '1,234,567.890', ], [ 1234567.89, - ['1 234 567,890', ',', ' '], + '1 234 567,890', ',', ' ', ], [ -1234567.89, - ['-1 234 567,890', ',', ' '], + '-1 234 567,890', ',', ' ', ], [ '#VALUE!', - ['1 234 567,890-', ',', ' '], + '1 234 567,890-', ',', ' ', ], [ '#VALUE!', - ['1,234,567.890,123'], + '1,234,567.890,123', ], [ '#VALUE!', - ['1.234.567.890,123'], + '1.234.567.890,123', ], [ 1234567.890, - ['1.234.567,890', ',', '.'], + '1.234.567,890', ',', '.', ], [ '#VALUE!', - ['1.234.567,89'], + '1.234.567,89', ], [ 12345.6789, - ['1,234,567.89%'], + '1,234,567.89%', ], [ 123.456789, - ['1,234,567.89%%'], + '1,234,567.89%%', ], [ 1.23456789, - ['1,234,567.89%%%'], + '1,234,567.89%%%', ], [ '#VALUE!', - ['1,234,567.89-%'], + '1,234,567.89-%', ], + 'no arguments' => ['exception'], + 'boolean argument' => ['#VALUE!', true], ]; diff --git a/tests/data/Calculation/TextData/OpenOffice.php b/tests/data/Calculation/TextData/OpenOffice.php new file mode 100644 index 00000000..fc79d5f1 --- /dev/null +++ b/tests/data/Calculation/TextData/OpenOffice.php @@ -0,0 +1,28 @@ + ["\x00", '=CHAR(0)'], + 'OO treats CODE(bool) as 0/1' => ['48', '=CODE(FALSE)'], + 'OO treats bool as string as 0/1 to REPT' => ['111', '=REPT(true, 3)'], + 'OO treats bool as string as 0/1 to CLEAN' => ['0', '=CLEAN(false)'], + 'OO treats bool as string as 0/1 to TRIM' => ['1', '=TRIM(true)'], + 'OO treats bool as string as 0/1 to LEN' => ['1', '=LEN(false)'], + 'OO treats bool as string as 0/1 to EXACT parm 1' => [true, '=EXACT(true, 1)'], + 'OO treats bool as string as 0/1 to EXACT parm 2' => [true, '=EXACT(0, false)'], + 'OO treats bool as string as 0/1 to FIND parm 1' => [2, '=FIND(true, "210")'], + 'OO treats bool as string as 0/1 to FIND parm 2' => [1, '=FIND(0, false)'], + 'OO treats true as int 1 to FIND parm 3' => [1, '=FIND("a", "aba", true)'], + 'OO treats false as int 0 to FIND parm 3' => ['#VALUE!', '=FIND("a", "aba", false)'], + 'OO treats bool as string as 0/1 to SEARCH parm 1' => [2, '=SEARCH(true, "210")'], + 'OO treats bool as string as 0/1 to SEARCH parm 2' => [1, '=SEARCH(0, false)'], + 'OO treats true as int 1 to SEARCH parm 3' => [1, '=SEARCH("a", "aba", true)'], + 'OO treats false as int 0 to SEARCH parm 3' => ['#VALUE!', '=SEARCH("a", "aba", false)'], + 'OO treats true as 1 to REPLACE parm 1' => ['10', '=REPLACE(true, 3, 1, false)'], + 'OO treats false as 0 to REPLACE parm 4' => ['he0lo', '=REPLACE("hello", 3, 1, false)'], + 'OO treats false as 0 SUBSTITUTE parm 1' => ['6', '=SUBSTITUTE(true, "1", "6")'], + 'OO treats true as 1 SUBSTITUTE parm 4' => ['zbcade', '=SUBSTITUTE("abcade", "a", "z", true)'], + 'OO TEXT boolean in lieu of string' => ['0', '=TEXT(false, "@")'], + 'OO VALUE boolean in lieu of string' => ['0', '=VALUE(false)'], + 'OO NUMBERVALUE boolean in lieu of string' => ['1', '=NUMBERVALUE(true)'], + 'OO TEXTJOIN boolean in lieu of string' => ['1-0-1', '=TEXTJOIN("-", true, true, false, true)'], +]; diff --git a/tests/data/Calculation/TextData/PROPER.php b/tests/data/Calculation/TextData/PROPER.php index 84c29096..e9a5d4ce 100644 --- a/tests/data/Calculation/TextData/PROPER.php +++ b/tests/data/Calculation/TextData/PROPER.php @@ -5,6 +5,18 @@ return [ 'Mark Baker', 'MARK BAKER', ], + [ + 'Buenos Días', + 'BUENOS DÍAS', + ], + [ + 'Καλημερα', + 'ΚΑΛΗΜΕΡΑ', + ], + [ + 'Доброе Утро', + 'ДОБРОЕ УТРО', + ], [ 'True', true, @@ -13,4 +25,5 @@ return [ 'False', false, ], + 'no argument' => ['exception'], ]; diff --git a/tests/data/Calculation/TextData/REPLACE.php b/tests/data/Calculation/TextData/REPLACE.php index 086d1290..8f02e2e3 100644 --- a/tests/data/Calculation/TextData/REPLACE.php +++ b/tests/data/Calculation/TextData/REPLACE.php @@ -29,4 +29,40 @@ return [ 0, 'DFG', ], + [ + 'Ενα δύοτρίατέσσεραπέντε', + 'Εναδύοτρίατέσσεραπέντε', + 4, + 0, + ' ', + ], + [ + 'Ενα δύο τρίατέσσεραπέντε', + 'Ενα δύοτρίατέσσεραπέντε', + 8, + 0, + ' ', + ], + [ + 'Ενα δύο τρία τέσσεραπέντε', + 'Ενα δύο τρίατέσσεραπέντε', + 13, + 0, + ' ', + ], + [ + 'Ενα δύο τρία τέσσερα πέντε', + 'Ενα δύο τρία τέσσεραπέντε', + 21, + 0, + ' ', + ], + 'no arguments' => ['exception'], + 'one argument' => ['exception', 'hello'], + 'two arguments' => ['exception', 'hello', 2], + 'three arguments' => ['exception', 'hello', 2, 2], + 'position zero' => ['#VALUE!', 'hello', 0, 2, 'xyz'], + 'negative length' => ['#VALUE!', 'hello', 3, -1, 'xyz'], + 'boolean 1st parm' => ['TRDFGE', true, 3, 1, 'DFG'], + 'boolean 4th parm' => ['heFALSElo', 'hello', 3, 1, false], ]; diff --git a/tests/data/Calculation/TextData/REPT.php b/tests/data/Calculation/TextData/REPT.php new file mode 100644 index 00000000..f8aef72c --- /dev/null +++ b/tests/data/Calculation/TextData/REPT.php @@ -0,0 +1,14 @@ + ['exception'], + 'one argument' => ['exception', 'ABC'], + ['#VALUE!', 'ABC', 'DEF'], + ['ABCABCABC', 'ABC', 3], + ['ABCABC', 'ABC', 2.2], + ['', 'ABC', 0], + ['TRUETRUE', true, 2], + ['111', 1, 3], + ['δύο δύο ', 'δύο ', 2], + ['#VALUE!', 'ABC', -1], +]; diff --git a/tests/data/Calculation/TextData/RIGHT.php b/tests/data/Calculation/TextData/RIGHT.php index 78ea6a69..77ea64bf 100644 --- a/tests/data/Calculation/TextData/RIGHT.php +++ b/tests/data/Calculation/TextData/RIGHT.php @@ -16,11 +16,45 @@ return [ 'QWERTYUIOP', -1, ], + [ + '#VALUE!', + 'QWERTYUIOP', + 'NaN', + ], + 'null length defaults to 0' => [ + '', + 'QWERTYUIOP', + null, + ], + 'omitted length defaults to 1' => [ + 'P', + 'QWERTYUIOP', + ], [ 'GHI', 'ABCDEFGHI', 3, ], + [ + '', + 'ABCDEFGHI', + 0, + ], + [ + 'πέντε', + 'Ενα δύο τρία τέσσερα πέντε', + 5, + ], + [ + 'τέσσερα πέντε', + 'Ενα δύο τρία τέσσερα πέντε', + 13, + ], + [ + 'τρία τέσσερα πέντε', + 'Ενα δύο τρία τέσσερα πέντε', + 18, + ], [ 'UE', true, @@ -31,4 +65,7 @@ return [ false, 2, ], + 'string not specified' => [ + 'exception', + ], ]; diff --git a/tests/data/Calculation/TextData/SEARCH.php b/tests/data/Calculation/TextData/SEARCH.php index 28cd98f8..335a7f12 100644 --- a/tests/data/Calculation/TextData/SEARCH.php +++ b/tests/data/Calculation/TextData/SEARCH.php @@ -59,9 +59,46 @@ return [ '', 'Mark Baker', ], + [ + 1, + 'Ενα', + 'Ενα δύο τρία τέσσερα πέντε', + ], + [ + 9, + 'τρία', + 'Ενα δύο τρία τέσσερα πέντε', + ], + [ + 22, + 'πέντε', + 'Ενα δύο τρία τέσσερα πέντε', + ], + [ + 1, + 'Ενα', + 'ΕΝΑ ΔΥΟ ΤΡΙΑ ΤΕΣΣΕΡΑ ΠΕΝΤΕ', + ], + [ + 9, + 'τρία', + 'ΕΝΑ ΔΎΟ ΤΡΊΑ ΤΈΣΣΕΡΑ ΠΈΝΤΕ', + ], + [ + 22, + 'πέντε', + 'ΕΝΑ ΔΎΟ ΤΡΊΑ ΤΈΣΣΕΡΑ ΠΈΝΤΕ', + ], [ '#VALUE!', 'BITE', 'BIT', ], + 'Boolean Needle' => [ + '#VALUE!', + true, + 'Mark Baker', + ], + 'no arguments' => ['exception'], + 'one argument' => ['exception', 'string'], ]; diff --git a/tests/data/Calculation/TextData/SUBSTITUTE.php b/tests/data/Calculation/TextData/SUBSTITUTE.php index 23f66a18..9b695a71 100644 --- a/tests/data/Calculation/TextData/SUBSTITUTE.php +++ b/tests/data/Calculation/TextData/SUBSTITUTE.php @@ -20,6 +20,20 @@ return [ 'x', 1, ], + [ + 'Mark Bxker', + 'Mark Baker', + 'a', + 'x', + 2, + ], + [ + 'Mark Bakker', + 'Mark Baker', + 'k', + 'kk', + 2, + ], [ 'Mark Baker', 'Mark Baker', @@ -27,6 +41,26 @@ return [ 'a', 1, ], + [ + 'Ενα δύο αρία αέσσερα πέναε', + 'Ενα δύο τρία τέσσερα πέντε', + 'τ', + 'α', + ], + [ + 'Ενα δύο τρία αέσσερα πέντε', + 'Ενα δύο τρία τέσσερα πέντε', + 'τ', + 'α', + 2, + ], + [ + 'Ενα δύο τρία ατέσσερα πέντε', + 'Ενα δύο τρία τέσσερα πέντε', + 'τ', + 'ατ', + 2, + ], 'Unicode equivalence is not supported' => [ "\u{0061}\u{030A}", "\u{0061}\u{030A}", @@ -39,4 +73,16 @@ return [ "\u{00E5}", 'x', ], + 'no arguments' => ['exception'], + 'one argument' => ['exception', 'a'], + 'two arguments' => ['exception', 'a', 'b'], + 'negative instance' => ['#VALUE!', 'abcdefg', 'def', 123, -1], + 'non-numeric instance' => ['#VALUE!', 'abcdefg', 'def', 123, 'xyz'], + 'null instance' => ['abc123g', 'abcdefg', 'def', 123], + '0 instance' => ['#VALUE!', 'abcdefg', 'def', 123, 0], + '1 instance' => ['abc123g', 'abcdefg', 'def', 123, 1], + 'past last instance' => ['abcdefg', 'abcdefg', 'def', 123, 2], + 'bool false instance' => ['#VALUE!', 'abcdefg', 'def', '123', false], + 'bool true instance' => ['#VALUE!', 'abcdefg', 'def', '123', true], + 'bool text' => ['FA-SE', false, 'L', '-'], ]; diff --git a/tests/data/Calculation/TextData/TEXT.php b/tests/data/Calculation/TextData/TEXT.php index fcb05191..1c7c338a 100644 --- a/tests/data/Calculation/TextData/TEXT.php +++ b/tests/data/Calculation/TextData/TEXT.php @@ -66,4 +66,7 @@ return [ 1.75, '# ?/?', ], + 'no arguments' => ['exception'], + 'one argument' => ['exception', 1.75], + 'boolean in lieu of string' => ['TRUE', true, '@'], ]; diff --git a/tests/data/Calculation/TextData/TEXTJOIN.php b/tests/data/Calculation/TextData/TEXTJOIN.php index 9ad85e94..e345f7c1 100644 --- a/tests/data/Calculation/TextData/TEXTJOIN.php +++ b/tests/data/Calculation/TextData/TEXTJOIN.php @@ -5,10 +5,22 @@ return [ 'ABCDE,FGHIJ', [',', true, 'ABCDE', 'FGHIJ'], ], + [ + 'ABCDEFGHIJ', + ['', true, 'ABCDE', 'FGHIJ'], + ], [ '1-2-3', ['-', true, 1, 2, 3], ], + [ + '<<::>>', + ['::', true, '<<', '>>'], + ], + [ + 'Καλό απόγευμα', + [' ', true, 'Καλό', 'απόγευμα'], + ], [ 'Boolean-TRUE', ['-', true, 'Boolean', '', true], @@ -25,4 +37,9 @@ return [ 'C:\\Users\\Mark\\Documents\\notes.doc', ['\\', true, 'C:', 'Users', 'Mark', 'Documents', 'notes.doc'], ], + 'no argument' => ['exception', []], + 'one argument' => ['exception', ['-']], + 'two arguments' => ['exception', ['-', true]], + 'three arguments' => ['a', ['-', true, 'a']], + 'boolean as string' => ['TRUE-FALSE-TRUE', ['-', true, true, false, true]], ]; diff --git a/tests/data/Calculation/TextData/TRIM.php b/tests/data/Calculation/TextData/TRIM.php index f400f187..882dc824 100644 --- a/tests/data/Calculation/TextData/TRIM.php +++ b/tests/data/Calculation/TextData/TRIM.php @@ -29,4 +29,5 @@ return [ null, null, ], + 'no arguments' => ['exception'], ]; diff --git a/tests/data/Calculation/TextData/UPPER.php b/tests/data/Calculation/TextData/UPPER.php index b43163be..21b04ae4 100644 --- a/tests/data/Calculation/TextData/UPPER.php +++ b/tests/data/Calculation/TextData/UPPER.php @@ -9,6 +9,18 @@ return [ 'MARK BAKER', 'mark baker', ], + [ + 'BUENOS DÍAS', + 'buenos días', + ], + [ + 'ΚΑΛΗΜΕΡΑ', + 'Καλημερα', + ], + [ + 'ДОБРОЕ УТРО', + 'доброе утро', + ], [ 'TRUE', true, @@ -17,4 +29,5 @@ return [ 'FALSE', false, ], + 'no arguments' => ['exception'], ]; diff --git a/tests/data/Calculation/TextData/VALUE.php b/tests/data/Calculation/TextData/VALUE.php index d859c087..666f12d1 100644 --- a/tests/data/Calculation/TextData/VALUE.php +++ b/tests/data/Calculation/TextData/VALUE.php @@ -41,4 +41,7 @@ return [ '0.11527777777778', '2:46 AM', ], + 'no arguments' => ['exception'], + 'bool argument' => ['#VALUE!', false], + 'null argument' => ['0', null], ]; diff --git a/tests/data/Calculation/Translations.php b/tests/data/Calculation/Translations.php new file mode 100644 index 00000000..f510e262 --- /dev/null +++ b/tests/data/Calculation/Translations.php @@ -0,0 +1,48 @@ + ['=D3+F7+G4+C6+5', '=R3C4+R7C6+R4C7+R6C3+5'], + 'Basic subtraction' => ['=D3-F7-G4-C6-5', '=R3C4-R7C6-R4C7-R6C3-5'], + 'Basic multiplication' => ['=D3*F7*G4*C6*5', '=R3C4*R7C6*R4C7*R6C3*5'], + 'Basic division' => ['=D3/F7/G4/C6/5', '=R3C4/R7C6/R4C7/R6C3/5'], + 'Simple formula' => ['=SUM(E1:E5)', '=SUM(R1C5:R5C5)'], + 'Formula with range and cell' => ['=SUM(E1:E5, D5)', '=SUM(R1C5:R5C5, R5C4)'], + 'Formula arithmetic' => ['=SUM(E1:E5, D5)-C5', '=SUM(R1C5:R5C5, R5C4)-R5C3'], + 'Formula with comparison' => ['=IF(E1>E2, E3, E4)', '=IF(R1C5>R2C5, R3C5, R4C5)'], + 'String literal' => ['=CONCAT("Result of formula expression =R3C3+R4C3 is: ", C3+C4)', '=CONCAT("Result of formula expression =R3C3+R4C3 is: ", R3C3+R4C3)'], +]; diff --git a/tests/data/Cell/ConvertFormulaToA1FromR1C1Relative.php b/tests/data/Cell/ConvertFormulaToA1FromR1C1Relative.php new file mode 100644 index 00000000..d6df418c --- /dev/null +++ b/tests/data/Cell/ConvertFormulaToA1FromR1C1Relative.php @@ -0,0 +1,17 @@ + ['=D3+F7+G4+C6+5', '=R[-2]C[-1]+R[2]C[1]+R[-1]C[2]+R[1]C[-2]+5', 5, 5], + 'Basic subtraction' => ['=D3-F7-G4-C6-5', '=R[-2]C[-1]-R[2]C[1]-R[-1]C[2]-R[1]C[-2]-5', 5, 5], + 'Basic multiplication' => ['=D3*F7*G4*C6*5', '=R[-2]C[-1]*R[2]C[1]*R[-1]C[2]*R[1]C[-2]*5', 5, 5], + 'Basic division' => ['=D3/F7/G4/C6/5', '=R[-2]C[-1]/R[2]C[1]/R[-1]C[2]/R[1]C[-2]/5', 5, 5], + 'Basic addition with current row/column' => ['=E3+E7+G5+C5+E5+5', '=R[-2]C+R[2]C+RC[2]+RC[-2]+RC+5', 5, 5], + 'Basic subtraction with current row/column' => ['=E3-E7-G5-C5-E5-5', '=R[-2]C-R[2]C-RC[2]-RC[-2]-RC-5', 5, 5], + 'Basic multiplication with current row/column' => ['=E3*E7*G5*C5*E5*5', '=R[-2]C*R[2]C*RC[2]*RC[-2]*RC*5', 5, 5], + 'Basic division with current row/column' => ['=E3/E7/G5/C5/E5/5', '=R[-2]C/R[2]C/RC[2]/RC[-2]/RC/5', 5, 5], + 'Simple formula' => ['=SUM(E1:E5)', '=SUM(R[-4]C:RC)', 5, 5], + 'Formula with range and cell' => ['=SUM(E1:E5, D5)', '=SUM(R[-4]C:RC, RC[-1])', 5, 5], + 'Formula arithmetic' => ['=SUM(E1:E5, D5)-C5', '=SUM(R[-4]C:RC, RC[-1])-RC[-2]', 5, 5], + 'Formula with comparison' => ['=IF(E1>E2, E3, E4)', '=IF(R[-4]C>R[-3]C, R[-2]C, R[-1]C)', 5, 5], + 'String literal' => ['=CONCAT("Result of formula expression =R[-2]C[-2]+R[-1]C[-2] is: ", C3+C4)', '=CONCAT("Result of formula expression =R[-2]C[-2]+R[-1]C[-2] is: ", R[-2]C[-2]+R[-1]C[-2])', 5, 5], +]; diff --git a/tests/data/Cell/ConvertFormulaToA1FromSpreadsheetXml.php b/tests/data/Cell/ConvertFormulaToA1FromSpreadsheetXml.php new file mode 100644 index 00000000..d350c07b --- /dev/null +++ b/tests/data/Cell/ConvertFormulaToA1FromSpreadsheetXml.php @@ -0,0 +1,15 @@ + ['=D3+F7+G4+C6+5', 'of:=[.D3]+[.F7]+[.G4]+[.C6]+5'], + 'Basic subtraction' => ['=D3-F7-G4-C6-5', 'of:=[.D3]-[.F7]-[.G4]-[.C6]-5'], + 'Basic multiplication' => ['=D3*F7*G4*C6*5', 'of:=[.D3]*[.F7]*[.G4]*[.C6]*5'], + 'Basic division' => ['=D3/F7/G4/C6/5', 'of:=[.D3]/[.F7]/[.G4]/[.C6]/5'], + 'Simple formula' => ['=SUM(E1:E5)', 'of:=SUM([.E1:.E5])'], + 'Formula with range and cell' => ['=SUM(E1:E5, D5)', 'of:=SUM([.E1:.E5], [.D5])'], + 'Formula arithmetic' => ['=SUM(E1:E5, D5)-C5', 'of:=SUM([.E1:.E5], [.D5])-[.C5]'], + 'Formula with comparison' => ['=IF(E1>E2, E3, E4)', 'of:=IF([.E1]>[.E2], [.E3], [.E4])'], + 'String literal' => ['=CONCAT("Result of formula expression =[.C3]+[.C4] is: ", C3+C4)', 'of:=CONCAT("Result of formula expression =[.C3]+[.C4] is: ", [.C3]+[.C4])'], + 'Simple numeric addition' => ['=1.23+2.34', 'of:=1.23+2.34'], + 'More complex formula with cells and numeric literals' => ['=D3+F7+G4+C6+5.67', 'of:=[.D3]+[.F7]+[.G4]+[.C6]+5.67'], +]; diff --git a/tests/data/Cell/DefaultValueBinder.php b/tests/data/Cell/DefaultValueBinder.php index 1f0c40e0..f5dafc7b 100644 --- a/tests/data/Cell/DefaultValueBinder.php +++ b/tests/data/Cell/DefaultValueBinder.php @@ -77,4 +77,8 @@ return [ 's', '123456\n', ], + 'Numeric that exceeds PHP MAX_INT Size' => [ + 's', + '1234567890123459012345689012345690', + ], ]; diff --git a/tests/data/Cell/IndexesFromString.php b/tests/data/Cell/IndexesFromString.php new file mode 100644 index 00000000..c2fe1c09 --- /dev/null +++ b/tests/data/Cell/IndexesFromString.php @@ -0,0 +1,74 @@ + + + + + diff --git a/tests/data/Shared/CodePage.php b/tests/data/Shared/CodePage.php index 82bb23e4..ccb59f24 100644 --- a/tests/data/Shared/CodePage.php +++ b/tests/data/Shared/CodePage.php @@ -233,7 +233,7 @@ return [ ], // Macintosh Central Europe [ - 'MACCENTRALEUROPE', + ['MACCENTRALEUROPE', 'MAC-CENTRALEUROPE'], 10029, ], // Macintosh Icelandic @@ -271,4 +271,9 @@ return [ 'UTF-8', 65001, ], + // invalid + [ + 'exception', + 99999, + ], ]; diff --git a/tests/data/Shared/Date/ExcelToTimestamp1900.php b/tests/data/Shared/Date/ExcelToTimestamp1900.php index ab79731e..ffcd194f 100644 --- a/tests/data/Shared/Date/ExcelToTimestamp1900.php +++ b/tests/data/Shared/Date/ExcelToTimestamp1900.php @@ -72,4 +72,11 @@ return [ 10666, 0.12345, ], + // 29-Apr-2038 00:00:00 beyond PHP 32-bit Latest Date + [ + 2156112000, + 50524, + ], + [-2147483648, -2147483648 / 86400], // Okay on 64- and 32-bit systems + [-2147483649, -2147483649 / 86400], // Skipped test on 32-bit ]; diff --git a/tests/data/Shared/Date/ExcelToTimestamp1904.php b/tests/data/Shared/Date/ExcelToTimestamp1904.php index e0f30754..fc55238a 100644 --- a/tests/data/Shared/Date/ExcelToTimestamp1904.php +++ b/tests/data/Shared/Date/ExcelToTimestamp1904.php @@ -29,17 +29,22 @@ return [ ], // 06:00:00 [ - 21600, + gmmktime(6, 0, 0, 1, 1, 1904), // 32-bit safe - no Y2038 problem 0.25, ], // 08:00.00 [ - 28800, + gmmktime(8, 0, 0, 1, 1, 1904), // 32-bit safe - no Y2038 problem 0.3333333333333333333, ], - // 02:57:46 + // 13:02:13 [ - 46933, + gmmktime(13, 02, 13, 1, 1, 1904), // 32-bit safe - no Y2038 problem 0.54321, ], + // 29-Apr-2038 00:00:00 beyond PHP 32-bit Latest Date + [ + 2156112000, + 49062, + ], ]; diff --git a/tests/data/Shared/PasswordHashes.php b/tests/data/Shared/PasswordHashes.php index 34c25cef..c46adf14 100644 --- a/tests/data/Shared/PasswordHashes.php +++ b/tests/data/Shared/PasswordHashes.php @@ -51,4 +51,9 @@ return [ 'Symbols_salt', 100000, ], + // Additional tests suggested by Issue #1897 + ['DCDF', 'ABCDEFGHIJKLMNOPQRSTUVW'], + ['ECD1', 'ABCDEFGHIJKLMNOPQRSTUVWX'], + ['88D2', 'ABCDEFGHIJKLMNOPQRSTUVWXY'], + 'password too long' => ['exception', str_repeat('x', 256)], ]; diff --git a/tests/data/Shared/Trend/ExponentialBestFit.php b/tests/data/Shared/Trend/ExponentialBestFit.php new file mode 100644 index 00000000..ac1da739 --- /dev/null +++ b/tests/data/Shared/Trend/ExponentialBestFit.php @@ -0,0 +1,12 @@ + [0.8, 0.813512072856517], + 'intersect' => [20.7, 20.671878197177865], + 'goodnessOfFit' => [0.904868, 0.9048681877346413], + 'equation' => 'Y = 20.67 * 0.81^X', + [3, 10, 3, 6, 8, 12, 1, 4, 9, 14], + [8, 2, 11, 6, 5, 4, 12, 9, 6, 1], + ], +]; diff --git a/tests/data/Shared/Trend/LinearBestFit.php b/tests/data/Shared/Trend/LinearBestFit.php new file mode 100644 index 00000000..b1be2f9a --- /dev/null +++ b/tests/data/Shared/Trend/LinearBestFit.php @@ -0,0 +1,20 @@ + [-1.1, -1.1064189189190], + 'intersect' => [14.1, 14.081081081081], + 'goodnessOfFit' => [0.873138, 0.8731378215564962], + 'equation' => 'Y = 14.08 + -1.11 * X', + [3, 10, 3, 6, 8, 12, 1, 4, 9, 14], + [8, 2, 11, 6, 5, 4, 12, 9, 6, 1], + ], + [ + 'slope' => [1.0, 1.0], + 'intersect' => [-2.0, -2.0], + 'goodnessOfFit' => [1.0, 1.0], + 'equation' => 'Y = -2 + 1 * X', + [1, 2, 3, 4, 5], + [3, 4, 5, 6, 7], + ], +]; diff --git a/tests/data/Style/NumberFormat.php b/tests/data/Style/NumberFormat.php index 5038d6da..0124c324 100644 --- a/tests/data/Style/NumberFormat.php +++ b/tests/data/Style/NumberFormat.php @@ -88,6 +88,26 @@ return [ 12345.678900000001, '#,##0.000', ], + [ + '12.34 kg', + 12.34, + '0.00 "kg"', + ], + [ + 'kg 12.34', + 12.34, + '"kg" 0.00', + ], + [ + '12.34 kg.', + 12.34, + '0.00 "kg."', + ], + [ + 'kg. 12.34', + 12.34, + '"kg." 0.00', + ], [ '£ 12,345.68', 12345.678900000001, @@ -108,6 +128,11 @@ return [ 12345.678900000001, '#,##0.000\ [$]', ], + 'Spacing Character' => [ + '826.00 €', + 826, + '#,##0.00 __€', + ], [ '5.68', 5.6788999999999996, @@ -165,6 +190,81 @@ return [ -125.73999999999999, '$0.00" Surplus";$0.00" Shortage"', ], + [ + '12%', + 0.123, + '0%', + ], + [ + '10%', + 0.1, + '0%', + ], + [ + '10.0%', + 0.1, + '0.0%', + ], + [ + '-12%', + -0.123, + '0%', + ], + [ + '12.3 %', + 0.123, + '0.?? %', + ], + [ + '12.35 %', + 0.12345, + '0.?? %', + ], + [ + '12.345 %', + 0.12345, + '0.00?? %', + ], + [ + '12.3457 %', + 0.123456789, + '0.00?? %', + ], + [ + '-12.3 %', + -0.123, + '0.?? %', + ], + [ + '12.30 %age', + 0.123, + '0.00 %"age"', + ], + [ + '-12.30 %age', + -0.123, + '0.00 %"age"', + ], + [ + '12.30%', + 0.123, + '0.00%;(0.00%)', + ], + [ + '(12.30%)', + -0.123, + '0.00%;(0.00%)', + ], + [ + '12.30% ', + 0.123, + '0.00%_;( 0.00% )', + ], + [ + '( 12.30% )', + -0.123, + '_(0.00%_;( 0.00% )', + ], // Fraction [ '5 1/4', @@ -197,6 +297,36 @@ return [ 0.75, '? ??/???', ], + [ + ' 3/4', + '0.75000', + '? ??/???', + ], + [ + '5 1/16', + 5.0625, + '? ??/???', + ], + [ + '- 5/8', + -0.625, + '? ??/???', + ], + [ + '0', + 0, + '? ??/???', + ], + [ + '0', + '0.000', + '? ??/???', + ], + [ + '-16', + '-016.0', + '? ??/???', + ], // Complex formats [ '(001) 2-3456-789', @@ -279,10 +409,30 @@ return [ '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)', ], [ - ' € 13.03 ', - 13.0316, + ' € (13.03)', + -13.0316, '_("€"* #,##0.00_);_("€"* \(#,##0.00\);_("€"* "-"??_);_(@_)', ], + [ + ' € 11.70 ', + 11.7, + '_-€* #,##0.00_-;"-€"* #,##0.00_-;_-€* -??_-;_-@_-', + ], + [ + '-€ 12.14 ', + -12.14, + '_-€* #,##0.00_-;"-€"* #,##0.00_-;_-€* -??_-;_-@_-', + ], + [ + ' € - ', + 0, + '_-€* #,##0.00_-;"-€"* #,##0.00_-;_-€* -??_-;_-@_-', + ], + [ + 'test', + 'test', + '_-€* #,##0.00_-;"-€"* #,##0.00_-;_-€* -??_-;_-@_-', + ], // Named colours // Simple color [ @@ -290,6 +440,11 @@ return [ 12345, '[Green]General', ], + [ + '12345', + 12345, + '[GrEeN]General', + ], [ '-70', -70, @@ -304,14 +459,24 @@ return [ [ '12345', 12345, - '[Blue]0;[Red]0', + '[Blue]0;[Red]0-', ], + [ + '12345-', + -12345, + '[BLUE]0;[red]0-', + ], + [ + '12345-', + -12345, + '[blue]0;[RED]0-', + ], + // Multiple colors with text substitution [ 'Positive', 12, '[Green]"Positive";[Red]"Negative";[Blue]"Zero"', ], - // Multiple colors with text substitution [ 'Zero', 0, @@ -322,6 +487,7 @@ return [ -2, '[Green]"Positive";[Red]"Negative";[Blue]"Zero"', ], + // Value break points [ '<=3500 red', 3500, @@ -342,4 +508,35 @@ return [ 25, '[Green][<>25]"<>25 green";[Red]"else red"', ], + // Leading/trailing quotes in mask + [ + '$12.34 ', + 12.34, + '$#,##0.00_;[RED]"($"#,##0.00")"', + ], + [ + '($12.34)', + -12.34, + '$#,##0.00_;[RED]"($"#,##0.00")"', + ], + [ + 'pfx. 25.00', + 25, + '"pfx." 0.00;"pfx." -0.00;"pfx." 0.00;', + ], + [ + 'pfx. 25.20', + 25.2, + '"pfx." 0.00;"pfx." -0.00;"pfx." 0.00;', + ], + [ + 'pfx. -25.20', + -25.2, + '"pfx." 0.00;"pfx." -0.00;"pfx." 0.00;', + ], + [ + 'pfx. 25.26', + 25.255555555555555, + '"pfx." 0.00;"pfx." -0.00;"pfx." 0.00;', + ], ]; diff --git a/tests/data/Style/NumberFormatDates.php b/tests/data/Style/NumberFormatDates.php index 9e476042..331a080c 100644 --- a/tests/data/Style/NumberFormatDates.php +++ b/tests/data/Style/NumberFormatDates.php @@ -36,22 +36,6 @@ return [ 22269.0625, '"y-m-d "yyyy-mm-dd" h:m:s "hh:mm:ss', ], - // Chinese date format - [ - '1960年12月19日', - 22269.0625, - '[DBNum1][$-804]yyyy"年"m"月"d"日";@', - ], - [ - '1960年12月', - 22269.0625, - '[DBNum1][$-804]yyyy"年"m"月";@', - ], - [ - '12月19日', - 22269.0625, - '[DBNum1][$-804]m"月"d"日";@', - ], [ '07:35:00 AM', 43270.315972222, @@ -77,4 +61,15 @@ return [ 1.1354166666667, '[h]:mm', ], + [ + '19331018', + 12345.6789, + '[DBNum4][$-804]yyyymmdd;@', + ], + // Technically should be 19331018 + [ + '19331018', + 12345.6789, + '[DBNum3][$-zh-CN]yyyymmdd;@', + ], ]; diff --git a/tests/data/Worksheet/namedRangeTest.xlsx b/tests/data/Worksheet/namedRangeTest.xlsx new file mode 100644 index 00000000..a4383bb0 Binary files /dev/null and b/tests/data/Worksheet/namedRangeTest.xlsx differ diff --git a/tests/data/Writer/Ods/content-empty.xml b/tests/data/Writer/Ods/content-empty.xml index 87f756db..c9620060 100644 --- a/tests/data/Writer/Ods/content-empty.xml +++ b/tests/data/Writer/Ods/content-empty.xml @@ -4,8 +4,9 @@ + + - diff --git a/tests/data/Writer/Ods/content-with-data.xml b/tests/data/Writer/Ods/content-with-data.xml index a9048047..a707d197 100644 --- a/tests/data/Writer/Ods/content-with-data.xml +++ b/tests/data/Writer/Ods/content-with-data.xml @@ -1,105 +1,124 @@ - - - - + + + + - - - + + + + - - - + + + + - - - + + + + - - - + + + + - - - + + + + - - - + + + + - - - + + + + - - - + + + + - - - + + + + - - - + + + + - - - + + + + - + - - + + - + 1 - + 12345.6789 - + 1 - + 01234 - + Lorem ipsum - + + #NULL! + + + Lorem ipsum + + - + 1 - - + + - + 1 1 - + 42798.572060185 - - + + + + - - + + - + 2 - + - + - \ No newline at end of file + diff --git a/tests/data/Writer/XLSX/issue.2266f.xlsx b/tests/data/Writer/XLSX/issue.2266f.xlsx new file mode 100644 index 00000000..c0d0e5a9 Binary files /dev/null and b/tests/data/Writer/XLSX/issue.2266f.xlsx differ diff --git a/tests/data/Writer/XLSX/saving_drawing_with_same_path.xlsx b/tests/data/Writer/XLSX/saving_drawing_with_same_path.xlsx new file mode 100644 index 00000000..a88d43d3 Binary files /dev/null and b/tests/data/Writer/XLSX/saving_drawing_with_same_path.xlsx differ