diff --git a/.editorconfig b/.editorconfig
deleted file mode 100644
index 1485c5e..0000000
--- a/.editorconfig
+++ /dev/null
@@ -1,15 +0,0 @@
-root = true
-
-[*]
-charset = utf-8
-end_of_line = lf
-indent_style = space
-indent_size = 4
-trim_trailing_whitespace = true
-insert_final_newline = true
-
-[{.travis.yml}]
-indent_size = 2
-
-[*.md]
-trim_trailing_whitespace = false
diff --git a/.gitattributes b/.gitattributes
deleted file mode 100644
index 5305c97..0000000
--- a/.gitattributes
+++ /dev/null
@@ -1,11 +0,0 @@
-# Ignore all test and documentation for archive
-/tests export-ignore
-/.editorconfig export-ignore
-/.gitattributes export-ignore
-/.gitignore export-ignore
-/.scrutinizer.yml export-ignore
-/.travis.yml export-ignore
-/composer.lock export-ignore
-/CONTRIBUTING.md export-ignore
-/logo.png export-ignore
-/phpunit.xml export-ignore
diff --git a/.gitignore b/.gitignore
deleted file mode 100644
index 68715b4..0000000
--- a/.gitignore
+++ /dev/null
@@ -1,5 +0,0 @@
-/tests/resources/generated
-/tests/coverage
-/vendor
-/.idea
-*.iml
diff --git a/.scrutinizer.yml b/.scrutinizer.yml
deleted file mode 100644
index 42f2492..0000000
--- a/.scrutinizer.yml
+++ /dev/null
@@ -1,57 +0,0 @@
-filter:
- excluded_paths: [vendor/*, tests/*]
-
-tools:
- external_code_coverage:
- timeout: 600 # Wait 10 minutes for results
- runs: 3 # Merge results for 5.4, 5.5 and 5.6 jobs
- php_mess_detector: true
- php_code_sniffer:
- config:
- standard: PSR4
- filter:
- paths: ['src']
- sensiolabs_security_checker: true
- php_pdepend: true
- php_loc:
- enabled: true
- filter:
- paths: ['src']
- php_cpd: false # Must be disabled to use php_sim instead
- php_sim:
- enabled: true
- filter:
- paths: ['src']
-
-build_failure_conditions:
- - 'project.metric("scrutinizer.quality", < 9)' # Code Quality Rating drops below 9
- - 'project.metric_change("scrutinizer.test_coverage", < -0.005)' # Code Coverage decreased by more than 0.5%
- - 'project.metric("scrutinizer.test_coverage", < 0.97)' # Code Coverage drops below 97%
-
-checks:
- php:
- remove_extra_empty_lines: true
- remove_php_closing_tag: true
- remove_trailing_whitespace: true
- fix_use_statements:
- remove_unused: true
- preserve_multiple: false
- preserve_blanklines: true
- fix_php_opening_tag: true
- fix_linefeed: true
- fix_line_ending: true
- fix_identation_4spaces: true
- fix_doc_comments: true
- uppercase_constants: true
- use_self_instead_of_fqcn: true
- simplify_boolean_return: true
- return_doc_comments: true
- return_doc_comment_if_not_inferrable: true
- phpunit_assertions: true
- parameters_in_camelcaps: true
- parameter_doc_comments: true
- param_doc_comment_if_not_inferrable: true
- optional_parameters_at_the_end: true
- newline_at_end_of_file: true
- encourage_single_quotes: true
-
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index b23c7fd..0000000
--- a/.travis.yml
+++ /dev/null
@@ -1,23 +0,0 @@
-language: php
-
-php:
- - 5.4
- - 5.5
- - 5.6
- - 7.0
- - hhvm
-
-cache:
- directories:
- - $HOME/.composer/cache
-
-install:
- - composer install --no-interaction --prefer-source
-
-script:
- - mkdir -p build/logs
- - php vendor/bin/phpunit --coverage-clover=build/logs/coverage.clover
-
-after_script:
- - if [[ $TRAVIS_PHP_VERSION != 'hhvm' && $TRAVIS_PHP_VERSION != '7.0' ]]; then wget https://scrutinizer-ci.com/ocular.phar; fi
- - if [[ $TRAVIS_PHP_VERSION != 'hhvm' && $TRAVIS_PHP_VERSION != '7.0' ]]; then php ocular.phar code-coverage:upload --format=php-clover build/logs/coverage.clover; fi
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
deleted file mode 100644
index 4cbf577..0000000
--- a/CONTRIBUTING.md
+++ /dev/null
@@ -1,75 +0,0 @@
-# Contributing
-
-All contributions are welcome to this project.
-
-## Contributor License Agreement
-
-Before a contribution can be merged into this project, please fill out the Contributor License Agreement (CLA) located at:
-
-http://opensource.box.com/cla
-
-To learn more about CLAs and why they are important to open source projects, please see the [Wikipedia entry](http://en.wikipedia.org/wiki/Contributor_License_Agreement).
-
-## How to contribute
-
-* **File an issue** - if you found a bug, want to request an enhancement, or want to implement something (bug fix or feature).
-* **Send a pull request** - if you want to contribute code. Please be sure to file an issue first.
-
-## Pull request best practices
-
-We want to accept your pull requests. Please follow these steps:
-
-### Step 1: File an issue
-
-Before writing any code, please file an issue stating the problem you want to solve or the feature you want to implement. This allows us to give you feedback before you spend any time writing code. There may be a known limitation that can't be addressed, or a bug that has already been fixed in a different way. The issue allows us to communicate and figure out if it's worth your time to write a bunch of code for the project.
-
-### Step 2: Fork this repository in GitHub
-
-This will create your own copy of our repository.
-
-### Step 3: Add the upstream source
-
-The upstream source is the project under the Box organization on GitHub. To add an upstream source for this project, type:
-
-```
-git remote add upstream git@github.com:box/spout.git
-```
-
-This will come in useful later.
-
-### Step 4: Create a feature branch
-
-Create a branch with a descriptive name, such as `add-search`.
-
-### Step 5: Push your feature branch to your fork
-
-As you develop code, continue to push code to your remote feature branch. Please make sure to include the issue number you're addressing in your commit message, such as:
-
-```
-git commit -m "Adding search (fixes #123)"
-```
-
-This helps us out by allowing us to track which issue your commit relates to.
-
-Keep a separate feature branch for each issue you want to address.
-
-### Step 6: Rebase
-
-Before sending a pull request, rebase against upstream, such as:
-
-```
-git fetch upstream
-git rebase upstream/master
-```
-
-This will add your changes on top of what's already in upstream, minimizing merge issues.
-
-### Step 7: Run the tests
-
-Make sure that all tests are passing before submitting a pull request.
-
-### Step 8: Send the pull request
-
-Send the pull request from your feature branch to us. Be sure to include a description that lets us know what work you did.
-
-Keep in mind that we like to see one issue addressed per pull request, as this helps keep our git history clean and we can more easily track down issues.
diff --git a/LICENSE b/LICENSE
deleted file mode 100644
index 167ec4d..0000000
--- a/LICENSE
+++ /dev/null
@@ -1,166 +0,0 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
-TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-1. Definitions.
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
-2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
-3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
-4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
-5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
-6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
-7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
-8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
-9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
-END OF TERMS AND CONDITIONS
diff --git a/README.md b/README.md
deleted file mode 100644
index a0fb2bf..0000000
--- a/README.md
+++ /dev/null
@@ -1,407 +0,0 @@
-# Spout
-
-[](https://packagist.org/packages/box/spout)
-[](http://opensource.box.com/badges)
-[](https://travis-ci.org/box/spout)
-[](https://scrutinizer-ci.com/g/box/spout/?branch=master)
-[](https://scrutinizer-ci.com/g/box/spout/?branch=master)
-[](https://packagist.org/packages/box/spout)
-
-Spout is a PHP library to read and write spreadsheet files (CSV, XLSX and ODS), in a fast and scalable way.
-Contrary to other file readers or writers, it is capable of processing very large files while keeping the memory usage really low (less than 3MB).
-
-Join the community and come discuss about Spout: [](https://gitter.im/box/spout?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
-
-## Installation
-
-### Composer (recommended)
-
-Spout can be installed directly from [Composer](https://getcomposer.org/).
-
-Run the following command:
-```
-$ composer require box/spout
-```
-
-### Manual installation
-
-If you can't use Composer, no worries! You can still install Spout manually.
-
-> Before starting, make sure your system meets the [requirements](#requirements).
-
-1. Download the source code from the [Releases page](https://github.com/box/spout/releases)
-2. Extract the downloaded content into your project.
-3. Add this code to the top controller (index.php) or wherever it may be more appropriate:
-```php
-require_once '[PATH/TO]/src/Spout/Autoloader/autoload.php'; // don't forget to change the path!
-```
-
-
-## Requirements
-
-* PHP version 5.4.0 or higher
-* PHP extension `php_zip` enabled
-* PHP extension `php_xmlreader` enabled
-
-
-## Basic usage
-
-### Reader
-
-Regardless of the file type, the interface to read a file is always the same:
-
-```php
-use Box\Spout\Reader\ReaderFactory;
-use Box\Spout\Common\Type;
-
-$reader = ReaderFactory::create(Type::XLSX); // for XLSX files
-//$reader = ReaderFactory::create(Type::CSV); // for CSV files
-//$reader = ReaderFactory::create(Type::ODS); // for ODS files
-
-$reader->open($filePath);
-
-foreach ($reader->getSheetIterator() as $sheet) {
- foreach ($sheet->getRowIterator() as $row) {
- // do stuff with the row
- }
-}
-
-$reader->close();
-```
-
-If there are multiple sheets in the file, the reader will read all of them sequentially.
-
-### Writer
-
-As with the reader, there is one common interface to write data to a file:
-
-```php
-use Box\Spout\Writer\WriterFactory;
-use Box\Spout\Common\Type;
-
-$writer = WriterFactory::create(Type::XLSX); // for XLSX files
-//$writer = WriterFactory::create(Type::CSV); // for CSV files
-//$writer = WriterFactory::create(Type::ODS); // for ODS files
-
-$writer->openToFile($filePath); // write data to a file or to a PHP stream
-//$writer->openToBrowser($fileName); // stream data directly to the browser
-
-$writer->addRow($singleRow); // add a row at a time
-$writer->addRows($multipleRows); // add multiple rows at a time
-
-$writer->close();
-```
-
-For XLSX and ODS files, the number of rows per sheet is limited to 1,048,576. By default, once this limit is reached, the writer will automatically create a new sheet and continue writing data into it.
-
-
-## Advanced usage
-
-If you are looking for how to perform some common, more advanced tasks with Spout, please take a look at the [Wiki](https://github.com/box/spout/wiki). It contains code snippets, ready to be used.
-
-### Configuring the CSV reader and writer
-
-It is possible to configure both the CSV reader and writer to specify the field separator as well as the field enclosure:
-```php
-use Box\Spout\Reader\ReaderFactory;
-use Box\Spout\Common\Type;
-
-$reader = ReaderFactory::create(Type::CSV);
-$reader->setFieldDelimiter('|');
-$reader->setFieldEnclosure('@');
-$reader->setEndOfLineCharacter("\r");
-```
-
-Additionally, if you need to read non UTF-8 files, you can specify the encoding of your file this way:
-```php
-$reader->setEncoding('UTF-16LE');
-```
-
-By default, the writer generates CSV files encoded in UTF-8, with a BOM.
-It is however possible to not include the BOM:
-```php
-use Box\Spout\Writer\WriterFactory;
-use Box\Spout\Common\Type;
-
-$writer = WriterFactory::create(Type::CSV);
-$writer->setShouldAddBOM(false);
-```
-
-
-### Configuring the XLSX and ODS readers and writers
-
-#### Row styling
-
-It is possible to apply some formatting options to a row. Spout supports fonts, background, borders as well as alignment styles.
-
-```php
-use Box\Spout\Common\Type;
-use Box\Spout\Writer\WriterFactory;
-use Box\Spout\Writer\Style\StyleBuilder;
-use Box\Spout\Writer\Style\Color;
-
-$style = (new StyleBuilder())
- ->setFontBold()
- ->setFontSize(15)
- ->setFontColor(Color::BLUE)
- ->setShouldWrapText()
- ->setBackgroundColor(Color::YELLOW)
- ->build();
-
-$writer = WriterFactory::create(Type::XLSX);
-$writer->openToFile($filePath);
-
-$writer->addRowWithStyle($singleRow, $style); // style will only be applied to this row
-$writer->addRow($otherSingleRow); // no style will be applied
-$writer->addRowsWithStyle($multipleRows, $style); // style will be applied to all given rows
-
-$writer->close();
-```
-
-Adding borders to a row requires a ```Border``` object.
-
-```php
-use Box\Spout\Common\Type;
-use Box\Spout\Writer\Style\Border;
-use Box\Spout\Writer\Style\BorderBuilder;
-use Box\Spout\Writer\Style\Color;
-use Box\Spout\Writer\Style\StyleBuilder;
-use Box\Spout\Writer\WriterFactory;
-
-$border = (new BorderBuilder())
- ->setBorderBottom(Color::GREEN, Border::WIDTH_THIN, Border::STYLE_DASHED)
- ->build();
-
-$style = (new StyleBuilder())
- ->setBorder($border)
- ->build();
-
-$writer = WriterFactory::create(Type::XLSX);
-$writer->openToFile($filePath);
-
-$writer->addRowWithStyle(['Border Bottom Green Thin Dashed'], $style);
-
-$writer->close();
-```
-
-Spout will use a default style for all created rows. This style can be overridden this way:
-
-```php
-$defaultStyle = (new StyleBuilder())
- ->setFontName('Arial')
- ->setFontSize(11)
- ->build();
-
-$writer = WriterFactory::create(Type::XLSX);
-$writer->setDefaultRowStyle($defaultStyle)
- ->openToFile($filePath);
-```
-
-Unfortunately, Spout does not support all the possible formatting options yet. But you can find the most important ones:
-
-| Category | Property | API
-|-----------|---------------|---------------------------------------
-| Font | Bold | `StyleBuilder::setFontBold()`
-| | Italic | `StyleBuilder::setFontItalic()`
-| | Underline | `StyleBuilder::setFontUnderline()`
-| | Strikethrough | `StyleBuilder::setFontStrikethrough()`
-| | Font name | `StyleBuilder::setFontName('Arial')`
-| | Font size | `StyleBuilder::setFontSize(14)`
-| | Font color | `StyleBuilder::setFontColor(Color::BLUE)`
`StyleBuilder::setFontColor(Color::rgb(0, 128, 255))`
-| Alignment | Wrap text | `StyleBuilder::setShouldWrapText(true|false)`
-
-#### New sheet creation
-
-It is also possible to change the behavior of the writer when the maximum number of rows (1,048,576) have been written in the current sheet:
-```php
-use Box\Spout\Writer\WriterFactory;
-use Box\Spout\Common\Type;
-
-$writer = WriterFactory::create(Type::ODS);
-$writer->setShouldCreateNewSheetsAutomatically(true); // default value
-$writer->setShouldCreateNewSheetsAutomatically(false); // will stop writing new data when limit is reached
-```
-
-#### Using custom temporary folder
-
-Processing XLSX and ODS files require temporary files to be created. By default, Spout will use the system default temporary folder (as returned by `sys_get_temp_dir()`). It is possible to override this by explicitly setting it on the reader or writer:
-```php
-use Box\Spout\Writer\WriterFactory;
-use Box\Spout\Common\Type;
-
-$writer = WriterFactory::create(Type::XLSX);
-$writer->setTempFolder($customTempFolderPath);
-```
-
-#### Strings storage (XLSX writer)
-
-XLSX files support different ways to store the string values:
-* Shared strings are meant to optimize file size by separating strings from the sheet representation and ignoring strings duplicates (if a string is used three times, only one string will be stored)
-* Inline strings are less optimized (as duplicate strings are all stored) but is faster to process
-
-In order to keep the memory usage really low, Spout does not optimize strings when using shared strings. It is nevertheless possible to use this mode.
-```php
-use Box\Spout\Writer\WriterFactory;
-use Box\Spout\Common\Type;
-
-$writer = WriterFactory::create(Type::XLSX);
-$writer->setShouldUseInlineStrings(true); // default (and recommended) value
-$writer->setShouldUseInlineStrings(false); // will use shared strings
-```
-
-> ##### Note on Apple Numbers and iOS support
->
-> Apple's products (Numbers and the iOS previewer) don't support inline strings and display empty cells instead. Therefore, if these platforms need to be supported, make sure to use shared strings!
-
-
-#### Date/Time formatting
-
-When reading a spreadsheet containing dates or times, Spout returns the values by default as DateTime objects.
-It is possible to change this behavior and have a formatted date returned instead (e.g. "2016-11-29 1:22 AM"). The format of the date corresponds to what is specified in the spreadsheet.
-
-```php
-use Box\Spout\Reader\ReaderFactory;
-use Box\Spout\Common\Type;
-
-$reader = ReaderFactory::create(Type::XLSX);
-$reader->setShouldFormatDates(false); // default value
-$reader->setShouldFormatDates(true); // will return formatted dates
-```
-
-### Playing with sheets
-
-When creating a XLSX or ODS file, it is possible to control which sheet the data will be written into. At any time, you can retrieve or set the current sheet:
-```php
-$firstSheet = $writer->getCurrentSheet();
-$writer->addRow($rowForSheet1); // writes the row to the first sheet
-
-$newSheet = $writer->addNewSheetAndMakeItCurrent();
-$writer->addRow($rowForSheet2); // writes the row to the new sheet
-
-$writer->setCurrentSheet($firstSheet);
-$writer->addRow($anotherRowForSheet1); // append the row to the first sheet
-```
-
-It is also possible to retrieve all the sheets currently created:
-```php
-$sheets = $writer->getSheets();
-```
-
-If you rely on the sheet's name in your application, you can access it and customize it this way:
-```php
-// Accessing the sheet name when reading
-foreach ($reader->getSheetIterator() as $sheet) {
- $sheetName = $sheet->getName();
-}
-
-// Accessing the sheet name when writing
-$sheet = $writer->getCurrentSheet();
-$sheetName = $sheet->getName();
-
-// Customizing the sheet name when writing
-$sheet = $writer->getCurrentSheet();
-$sheet->setName('My custom name');
-```
-
-> Please note that Excel has some restrictions on the sheet's name:
-> * it must not be blank
-> * it must not exceed 31 characters
-> * it must not contain these characters: \ / ? * : [ or ]
-> * it must not start or end with a single quote
-> * it must be unique
->
-> Handling these restrictions is the developer's responsibility. Spout does not try to automatically change the sheet's name, as one may rely on this name to be exactly what was passed in.
-
-Finally, it is possible to know which sheet was active when the spreadsheet was last saved. This can be useful if you are only interested in processing the one sheet that was last focused.
-```php
-foreach ($reader->getSheetIterator() as $sheet) {
- // only process data for the active sheet
- if ($sheet->isActive()) {
- // do something...
- }
-}
-```
-
-### Fluent interface
-
-Because fluent interfaces are great, you can use them with Spout:
-```php
-use Box\Spout\Writer\WriterFactory;
-use Box\Spout\Common\Type;
-
-$writer = WriterFactory::create(Type::XLSX);
-$writer->setTempFolder($customTempFolderPath)
- ->setShouldUseInlineStrings(true)
- ->openToFile($filePath)
- ->addRow($headerRow)
- ->addRows($dataRows)
- ->close();
-```
-
-
-## Running tests
-
-On the `master` branch, only unit and functional tests are included. The performance tests require very large files and have been excluded.
-If you just want to check that everything is working as expected, executing the tests of the `master` branch is enough.
-
-If you want to run performance tests, you will need to checkout the `perf-tests` branch. Multiple test suites can then be run, depending on the expected output:
-
-* `phpunit` - runs the whole test suite (unit + functional + performance tests)
-* `phpunit --exclude-group perf-tests` - only runs the unit and functional tests
-* `phpunit --group perf-tests` - only runs the performance tests
-
-For information, the performance tests take about 30 minutes to run (processing 1 million rows files is not a quick thing).
-
-> Performance tests status: [](https://travis-ci.org/box/spout)
-
-
-## Frequently Asked Questions
-
-#### How can Spout handle such large data sets and still use less than 3MB of memory?
-
-When writing data, Spout is streaming the data to files, one or few lines at a time. That means that it only keeps in memory the few rows that it needs to write. Once written, the memory is freed.
-
-Same goes with reading. Only one row at a time is stored in memory. A special technique is used to handle shared strings in XLSX, storing them - if needed - into several small temporary files that allows fast access.
-
-#### How long does it take to generate a file with X rows?
-
-Here are a few numbers regarding the performance of Spout:
-
-| Type | Action | 2,000 rows (6,000 cells) | 200,000 rows (600,000 cells) | 2,000,000 rows (6,000,000 cells) |
-|------|-------------------------------|--------------------------|------------------------------|----------------------------------|
-| CSV | Read | < 1 second | 4 seconds | 2-3 minutes |
-| | Write | < 1 second | 2 seconds | 2-3 minutes |
-| XLSX | Read
*inline strings* | < 1 second | 35-40 seconds | 18-20 minutes |
-| | Read
*shared strings* | 1 second | 1-2 minutes | 35-40 minutes |
-| | Write | 1 second | 20-25 seconds | 8-10 minutes |
-| ODS | Read | 1 second | 1-2 minutes | 5-6 minutes |
-| | Write | < 1 second | 35-40 seconds | 5-6 minutes |
-
-#### Does Spout support charts or formulas?
-
-No. This is a compromise to keep memory usage low. Charts and formulas requires data to be kept in memory in order to be used.
-So the larger the file would be, the more memory would be consumed, preventing your code to scale well.
-
-
-## Support
-
-Need to contact us directly? Email oss@box.com and be sure to include the name of this project in the subject.
-
-You can also ask questions, submit new features ideas or discuss about Spout in the chat room:
-[](https://gitter.im/box/spout?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
-
-## Copyright and License
-
-Copyright 2017 Box, Inc. All rights reserved.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
diff --git a/composer.json b/composer.json
deleted file mode 100644
index 76485c9..0000000
--- a/composer.json
+++ /dev/null
@@ -1,37 +0,0 @@
-{
- "name": "box/spout",
- "description": "PHP Library to read and write spreadsheet files (CSV, XLSX and ODS), in a fast and scalable way",
- "type": "library",
- "keywords": ["php","read","write","csv","xlsx","ods","odf","open","office","excel","spreadsheet","scale","memory","stream","ooxml"],
- "license": "Apache-2.0",
- "homepage": "https://www.github.com/box/spout",
- "authors": [
- {
- "name": "Adrien Loison",
- "email": "adrien@box.com"
- }
- ],
- "require": {
- "php": ">=5.4.0",
- "ext-zip": "*",
- "ext-xmlreader" : "*"
- },
- "require-dev": {
- "phpunit/phpunit": "^4.8.0"
- },
- "suggest": {
- "ext-iconv": "To handle non UTF-8 CSV files (if \"php-intl\" is not already installed or is too limited)",
- "ext-intl": "To handle non UTF-8 CSV files (if \"iconv\" is not already installed)"
- },
- "autoload": {
- "psr-4": {
- "Box\\Spout\\": "src/Spout"
- }
- },
- "extra": {
- "branch-alias": {
- "dev-master": "2.8.x-dev"
- }
- }
-
-}
diff --git a/composer.lock b/composer.lock
deleted file mode 100644
index df7690a..0000000
--- a/composer.lock
+++ /dev/null
@@ -1,980 +0,0 @@
-{
- "_readme": [
- "This file locks the dependencies of your project to a known state",
- "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
- "This file is @generated automatically"
- ],
- "hash": "8957b9da742e28d7250c02fca8f9a5a7",
- "content-hash": "973b8a4a1d8c520dd99fcd32cb5e022f",
- "packages": [],
- "packages-dev": [
- {
- "name": "doctrine/instantiator",
- "version": "1.0.5",
- "source": {
- "type": "git",
- "url": "https://github.com/doctrine/instantiator.git",
- "reference": "8e884e78f9f0eb1329e445619e04456e64d8051d"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/doctrine/instantiator/zipball/8e884e78f9f0eb1329e445619e04456e64d8051d",
- "reference": "8e884e78f9f0eb1329e445619e04456e64d8051d",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3,<8.0-DEV"
- },
- "require-dev": {
- "athletic/athletic": "~0.1.8",
- "ext-pdo": "*",
- "ext-phar": "*",
- "phpunit/phpunit": "~4.0",
- "squizlabs/php_codesniffer": "~2.0"
- },
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "1.0.x-dev"
- }
- },
- "autoload": {
- "psr-4": {
- "Doctrine\\Instantiator\\": "src/Doctrine/Instantiator/"
- }
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Marco Pivetta",
- "email": "ocramius@gmail.com",
- "homepage": "http://ocramius.github.com/"
- }
- ],
- "description": "A small, lightweight utility to instantiate objects in PHP without invoking their constructors",
- "homepage": "https://github.com/doctrine/instantiator",
- "keywords": [
- "constructor",
- "instantiate"
- ],
- "time": "2015-06-14 21:17:01"
- },
- {
- "name": "phpdocumentor/reflection-docblock",
- "version": "2.0.4",
- "source": {
- "type": "git",
- "url": "https://github.com/phpDocumentor/ReflectionDocBlock.git",
- "reference": "d68dbdc53dc358a816f00b300704702b2eaff7b8"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/d68dbdc53dc358a816f00b300704702b2eaff7b8",
- "reference": "d68dbdc53dc358a816f00b300704702b2eaff7b8",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.3"
- },
- "require-dev": {
- "phpunit/phpunit": "~4.0"
- },
- "suggest": {
- "dflydev/markdown": "~1.0",
- "erusev/parsedown": "~1.0"
- },
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "2.0.x-dev"
- }
- },
- "autoload": {
- "psr-0": {
- "phpDocumentor": [
- "src/"
- ]
- }
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Mike van Riel",
- "email": "mike.vanriel@naenius.com"
- }
- ],
- "time": "2015-02-03 12:10:50"
- },
- {
- "name": "phpspec/prophecy",
- "version": "v1.6.0",
- "source": {
- "type": "git",
- "url": "https://github.com/phpspec/prophecy.git",
- "reference": "3c91bdf81797d725b14cb62906f9a4ce44235972"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/phpspec/prophecy/zipball/3c91bdf81797d725b14cb62906f9a4ce44235972",
- "reference": "3c91bdf81797d725b14cb62906f9a4ce44235972",
- "shasum": ""
- },
- "require": {
- "doctrine/instantiator": "^1.0.2",
- "php": "^5.3|^7.0",
- "phpdocumentor/reflection-docblock": "~2.0",
- "sebastian/comparator": "~1.1",
- "sebastian/recursion-context": "~1.0"
- },
- "require-dev": {
- "phpspec/phpspec": "~2.0"
- },
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "1.5.x-dev"
- }
- },
- "autoload": {
- "psr-0": {
- "Prophecy\\": "src/"
- }
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Konstantin Kudryashov",
- "email": "ever.zet@gmail.com",
- "homepage": "http://everzet.com"
- },
- {
- "name": "Marcello Duarte",
- "email": "marcello.duarte@gmail.com"
- }
- ],
- "description": "Highly opinionated mocking framework for PHP 5.3+",
- "homepage": "https://github.com/phpspec/prophecy",
- "keywords": [
- "Double",
- "Dummy",
- "fake",
- "mock",
- "spy",
- "stub"
- ],
- "time": "2016-02-15 07:46:21"
- },
- {
- "name": "phpunit/php-code-coverage",
- "version": "2.2.4",
- "source": {
- "type": "git",
- "url": "https://github.com/sebastianbergmann/php-code-coverage.git",
- "reference": "eabf68b476ac7d0f73793aada060f1c1a9bf8979"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/eabf68b476ac7d0f73793aada060f1c1a9bf8979",
- "reference": "eabf68b476ac7d0f73793aada060f1c1a9bf8979",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.3",
- "phpunit/php-file-iterator": "~1.3",
- "phpunit/php-text-template": "~1.2",
- "phpunit/php-token-stream": "~1.3",
- "sebastian/environment": "^1.3.2",
- "sebastian/version": "~1.0"
- },
- "require-dev": {
- "ext-xdebug": ">=2.1.4",
- "phpunit/phpunit": "~4"
- },
- "suggest": {
- "ext-dom": "*",
- "ext-xdebug": ">=2.2.1",
- "ext-xmlwriter": "*"
- },
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "2.2.x-dev"
- }
- },
- "autoload": {
- "classmap": [
- "src/"
- ]
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "BSD-3-Clause"
- ],
- "authors": [
- {
- "name": "Sebastian Bergmann",
- "email": "sb@sebastian-bergmann.de",
- "role": "lead"
- }
- ],
- "description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.",
- "homepage": "https://github.com/sebastianbergmann/php-code-coverage",
- "keywords": [
- "coverage",
- "testing",
- "xunit"
- ],
- "time": "2015-10-06 15:47:00"
- },
- {
- "name": "phpunit/php-file-iterator",
- "version": "1.4.1",
- "source": {
- "type": "git",
- "url": "https://github.com/sebastianbergmann/php-file-iterator.git",
- "reference": "6150bf2c35d3fc379e50c7602b75caceaa39dbf0"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/6150bf2c35d3fc379e50c7602b75caceaa39dbf0",
- "reference": "6150bf2c35d3fc379e50c7602b75caceaa39dbf0",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.3"
- },
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "1.4.x-dev"
- }
- },
- "autoload": {
- "classmap": [
- "src/"
- ]
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "BSD-3-Clause"
- ],
- "authors": [
- {
- "name": "Sebastian Bergmann",
- "email": "sb@sebastian-bergmann.de",
- "role": "lead"
- }
- ],
- "description": "FilterIterator implementation that filters files based on a list of suffixes.",
- "homepage": "https://github.com/sebastianbergmann/php-file-iterator/",
- "keywords": [
- "filesystem",
- "iterator"
- ],
- "time": "2015-06-21 13:08:43"
- },
- {
- "name": "phpunit/php-text-template",
- "version": "1.2.1",
- "source": {
- "type": "git",
- "url": "https://github.com/sebastianbergmann/php-text-template.git",
- "reference": "31f8b717e51d9a2afca6c9f046f5d69fc27c8686"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/31f8b717e51d9a2afca6c9f046f5d69fc27c8686",
- "reference": "31f8b717e51d9a2afca6c9f046f5d69fc27c8686",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.3"
- },
- "type": "library",
- "autoload": {
- "classmap": [
- "src/"
- ]
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "BSD-3-Clause"
- ],
- "authors": [
- {
- "name": "Sebastian Bergmann",
- "email": "sebastian@phpunit.de",
- "role": "lead"
- }
- ],
- "description": "Simple template engine.",
- "homepage": "https://github.com/sebastianbergmann/php-text-template/",
- "keywords": [
- "template"
- ],
- "time": "2015-06-21 13:50:34"
- },
- {
- "name": "phpunit/php-timer",
- "version": "1.0.8",
- "source": {
- "type": "git",
- "url": "https://github.com/sebastianbergmann/php-timer.git",
- "reference": "38e9124049cf1a164f1e4537caf19c99bf1eb260"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/38e9124049cf1a164f1e4537caf19c99bf1eb260",
- "reference": "38e9124049cf1a164f1e4537caf19c99bf1eb260",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.3"
- },
- "require-dev": {
- "phpunit/phpunit": "~4|~5"
- },
- "type": "library",
- "autoload": {
- "classmap": [
- "src/"
- ]
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "BSD-3-Clause"
- ],
- "authors": [
- {
- "name": "Sebastian Bergmann",
- "email": "sb@sebastian-bergmann.de",
- "role": "lead"
- }
- ],
- "description": "Utility class for timing",
- "homepage": "https://github.com/sebastianbergmann/php-timer/",
- "keywords": [
- "timer"
- ],
- "time": "2016-05-12 18:03:57"
- },
- {
- "name": "phpunit/php-token-stream",
- "version": "1.4.8",
- "source": {
- "type": "git",
- "url": "https://github.com/sebastianbergmann/php-token-stream.git",
- "reference": "3144ae21711fb6cac0b1ab4cbe63b75ce3d4e8da"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/3144ae21711fb6cac0b1ab4cbe63b75ce3d4e8da",
- "reference": "3144ae21711fb6cac0b1ab4cbe63b75ce3d4e8da",
- "shasum": ""
- },
- "require": {
- "ext-tokenizer": "*",
- "php": ">=5.3.3"
- },
- "require-dev": {
- "phpunit/phpunit": "~4.2"
- },
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "1.4-dev"
- }
- },
- "autoload": {
- "classmap": [
- "src/"
- ]
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "BSD-3-Clause"
- ],
- "authors": [
- {
- "name": "Sebastian Bergmann",
- "email": "sebastian@phpunit.de"
- }
- ],
- "description": "Wrapper around PHP's tokenizer extension.",
- "homepage": "https://github.com/sebastianbergmann/php-token-stream/",
- "keywords": [
- "tokenizer"
- ],
- "time": "2015-09-15 10:49:45"
- },
- {
- "name": "phpunit/phpunit",
- "version": "4.8.26",
- "source": {
- "type": "git",
- "url": "https://github.com/sebastianbergmann/phpunit.git",
- "reference": "fc1d8cd5b5de11625979125c5639347896ac2c74"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/fc1d8cd5b5de11625979125c5639347896ac2c74",
- "reference": "fc1d8cd5b5de11625979125c5639347896ac2c74",
- "shasum": ""
- },
- "require": {
- "ext-dom": "*",
- "ext-json": "*",
- "ext-pcre": "*",
- "ext-reflection": "*",
- "ext-spl": "*",
- "php": ">=5.3.3",
- "phpspec/prophecy": "^1.3.1",
- "phpunit/php-code-coverage": "~2.1",
- "phpunit/php-file-iterator": "~1.4",
- "phpunit/php-text-template": "~1.2",
- "phpunit/php-timer": "^1.0.6",
- "phpunit/phpunit-mock-objects": "~2.3",
- "sebastian/comparator": "~1.1",
- "sebastian/diff": "~1.2",
- "sebastian/environment": "~1.3",
- "sebastian/exporter": "~1.2",
- "sebastian/global-state": "~1.0",
- "sebastian/version": "~1.0",
- "symfony/yaml": "~2.1|~3.0"
- },
- "suggest": {
- "phpunit/php-invoker": "~1.1"
- },
- "bin": [
- "phpunit"
- ],
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "4.8.x-dev"
- }
- },
- "autoload": {
- "classmap": [
- "src/"
- ]
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "BSD-3-Clause"
- ],
- "authors": [
- {
- "name": "Sebastian Bergmann",
- "email": "sebastian@phpunit.de",
- "role": "lead"
- }
- ],
- "description": "The PHP Unit Testing framework.",
- "homepage": "https://phpunit.de/",
- "keywords": [
- "phpunit",
- "testing",
- "xunit"
- ],
- "time": "2016-05-17 03:09:28"
- },
- {
- "name": "phpunit/phpunit-mock-objects",
- "version": "2.3.8",
- "source": {
- "type": "git",
- "url": "https://github.com/sebastianbergmann/phpunit-mock-objects.git",
- "reference": "ac8e7a3db35738d56ee9a76e78a4e03d97628983"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/phpunit-mock-objects/zipball/ac8e7a3db35738d56ee9a76e78a4e03d97628983",
- "reference": "ac8e7a3db35738d56ee9a76e78a4e03d97628983",
- "shasum": ""
- },
- "require": {
- "doctrine/instantiator": "^1.0.2",
- "php": ">=5.3.3",
- "phpunit/php-text-template": "~1.2",
- "sebastian/exporter": "~1.2"
- },
- "require-dev": {
- "phpunit/phpunit": "~4.4"
- },
- "suggest": {
- "ext-soap": "*"
- },
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "2.3.x-dev"
- }
- },
- "autoload": {
- "classmap": [
- "src/"
- ]
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "BSD-3-Clause"
- ],
- "authors": [
- {
- "name": "Sebastian Bergmann",
- "email": "sb@sebastian-bergmann.de",
- "role": "lead"
- }
- ],
- "description": "Mock Object library for PHPUnit",
- "homepage": "https://github.com/sebastianbergmann/phpunit-mock-objects/",
- "keywords": [
- "mock",
- "xunit"
- ],
- "time": "2015-10-02 06:51:40"
- },
- {
- "name": "sebastian/comparator",
- "version": "1.2.0",
- "source": {
- "type": "git",
- "url": "https://github.com/sebastianbergmann/comparator.git",
- "reference": "937efb279bd37a375bcadf584dec0726f84dbf22"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/937efb279bd37a375bcadf584dec0726f84dbf22",
- "reference": "937efb279bd37a375bcadf584dec0726f84dbf22",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.3",
- "sebastian/diff": "~1.2",
- "sebastian/exporter": "~1.2"
- },
- "require-dev": {
- "phpunit/phpunit": "~4.4"
- },
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "1.2.x-dev"
- }
- },
- "autoload": {
- "classmap": [
- "src/"
- ]
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "BSD-3-Clause"
- ],
- "authors": [
- {
- "name": "Jeff Welch",
- "email": "whatthejeff@gmail.com"
- },
- {
- "name": "Volker Dusch",
- "email": "github@wallbash.com"
- },
- {
- "name": "Bernhard Schussek",
- "email": "bschussek@2bepublished.at"
- },
- {
- "name": "Sebastian Bergmann",
- "email": "sebastian@phpunit.de"
- }
- ],
- "description": "Provides the functionality to compare PHP values for equality",
- "homepage": "http://www.github.com/sebastianbergmann/comparator",
- "keywords": [
- "comparator",
- "compare",
- "equality"
- ],
- "time": "2015-07-26 15:48:44"
- },
- {
- "name": "sebastian/diff",
- "version": "1.4.1",
- "source": {
- "type": "git",
- "url": "https://github.com/sebastianbergmann/diff.git",
- "reference": "13edfd8706462032c2f52b4b862974dd46b71c9e"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/13edfd8706462032c2f52b4b862974dd46b71c9e",
- "reference": "13edfd8706462032c2f52b4b862974dd46b71c9e",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.3"
- },
- "require-dev": {
- "phpunit/phpunit": "~4.8"
- },
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "1.4-dev"
- }
- },
- "autoload": {
- "classmap": [
- "src/"
- ]
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "BSD-3-Clause"
- ],
- "authors": [
- {
- "name": "Kore Nordmann",
- "email": "mail@kore-nordmann.de"
- },
- {
- "name": "Sebastian Bergmann",
- "email": "sebastian@phpunit.de"
- }
- ],
- "description": "Diff implementation",
- "homepage": "https://github.com/sebastianbergmann/diff",
- "keywords": [
- "diff"
- ],
- "time": "2015-12-08 07:14:41"
- },
- {
- "name": "sebastian/environment",
- "version": "1.3.7",
- "source": {
- "type": "git",
- "url": "https://github.com/sebastianbergmann/environment.git",
- "reference": "4e8f0da10ac5802913afc151413bc8c53b6c2716"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/4e8f0da10ac5802913afc151413bc8c53b6c2716",
- "reference": "4e8f0da10ac5802913afc151413bc8c53b6c2716",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.3"
- },
- "require-dev": {
- "phpunit/phpunit": "~4.4"
- },
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "1.3.x-dev"
- }
- },
- "autoload": {
- "classmap": [
- "src/"
- ]
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "BSD-3-Clause"
- ],
- "authors": [
- {
- "name": "Sebastian Bergmann",
- "email": "sebastian@phpunit.de"
- }
- ],
- "description": "Provides functionality to handle HHVM/PHP environments",
- "homepage": "http://www.github.com/sebastianbergmann/environment",
- "keywords": [
- "Xdebug",
- "environment",
- "hhvm"
- ],
- "time": "2016-05-17 03:18:57"
- },
- {
- "name": "sebastian/exporter",
- "version": "1.2.1",
- "source": {
- "type": "git",
- "url": "https://github.com/sebastianbergmann/exporter.git",
- "reference": "7ae5513327cb536431847bcc0c10edba2701064e"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/7ae5513327cb536431847bcc0c10edba2701064e",
- "reference": "7ae5513327cb536431847bcc0c10edba2701064e",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.3",
- "sebastian/recursion-context": "~1.0"
- },
- "require-dev": {
- "phpunit/phpunit": "~4.4"
- },
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "1.2.x-dev"
- }
- },
- "autoload": {
- "classmap": [
- "src/"
- ]
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "BSD-3-Clause"
- ],
- "authors": [
- {
- "name": "Jeff Welch",
- "email": "whatthejeff@gmail.com"
- },
- {
- "name": "Volker Dusch",
- "email": "github@wallbash.com"
- },
- {
- "name": "Bernhard Schussek",
- "email": "bschussek@2bepublished.at"
- },
- {
- "name": "Sebastian Bergmann",
- "email": "sebastian@phpunit.de"
- },
- {
- "name": "Adam Harvey",
- "email": "aharvey@php.net"
- }
- ],
- "description": "Provides the functionality to export PHP variables for visualization",
- "homepage": "http://www.github.com/sebastianbergmann/exporter",
- "keywords": [
- "export",
- "exporter"
- ],
- "time": "2015-06-21 07:55:53"
- },
- {
- "name": "sebastian/global-state",
- "version": "1.1.1",
- "source": {
- "type": "git",
- "url": "https://github.com/sebastianbergmann/global-state.git",
- "reference": "bc37d50fea7d017d3d340f230811c9f1d7280af4"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/bc37d50fea7d017d3d340f230811c9f1d7280af4",
- "reference": "bc37d50fea7d017d3d340f230811c9f1d7280af4",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.3"
- },
- "require-dev": {
- "phpunit/phpunit": "~4.2"
- },
- "suggest": {
- "ext-uopz": "*"
- },
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "1.0-dev"
- }
- },
- "autoload": {
- "classmap": [
- "src/"
- ]
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "BSD-3-Clause"
- ],
- "authors": [
- {
- "name": "Sebastian Bergmann",
- "email": "sebastian@phpunit.de"
- }
- ],
- "description": "Snapshotting of global state",
- "homepage": "http://www.github.com/sebastianbergmann/global-state",
- "keywords": [
- "global state"
- ],
- "time": "2015-10-12 03:26:01"
- },
- {
- "name": "sebastian/recursion-context",
- "version": "1.0.2",
- "source": {
- "type": "git",
- "url": "https://github.com/sebastianbergmann/recursion-context.git",
- "reference": "913401df809e99e4f47b27cdd781f4a258d58791"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/913401df809e99e4f47b27cdd781f4a258d58791",
- "reference": "913401df809e99e4f47b27cdd781f4a258d58791",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.3"
- },
- "require-dev": {
- "phpunit/phpunit": "~4.4"
- },
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "1.0.x-dev"
- }
- },
- "autoload": {
- "classmap": [
- "src/"
- ]
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "BSD-3-Clause"
- ],
- "authors": [
- {
- "name": "Jeff Welch",
- "email": "whatthejeff@gmail.com"
- },
- {
- "name": "Sebastian Bergmann",
- "email": "sebastian@phpunit.de"
- },
- {
- "name": "Adam Harvey",
- "email": "aharvey@php.net"
- }
- ],
- "description": "Provides functionality to recursively process PHP variables",
- "homepage": "http://www.github.com/sebastianbergmann/recursion-context",
- "time": "2015-11-11 19:50:13"
- },
- {
- "name": "sebastian/version",
- "version": "1.0.6",
- "source": {
- "type": "git",
- "url": "https://github.com/sebastianbergmann/version.git",
- "reference": "58b3a85e7999757d6ad81c787a1fbf5ff6c628c6"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/58b3a85e7999757d6ad81c787a1fbf5ff6c628c6",
- "reference": "58b3a85e7999757d6ad81c787a1fbf5ff6c628c6",
- "shasum": ""
- },
- "type": "library",
- "autoload": {
- "classmap": [
- "src/"
- ]
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "BSD-3-Clause"
- ],
- "authors": [
- {
- "name": "Sebastian Bergmann",
- "email": "sebastian@phpunit.de",
- "role": "lead"
- }
- ],
- "description": "Library that helps with managing the version number of Git-hosted PHP projects",
- "homepage": "https://github.com/sebastianbergmann/version",
- "time": "2015-06-21 13:59:46"
- },
- {
- "name": "symfony/yaml",
- "version": "v2.8.6",
- "source": {
- "type": "git",
- "url": "https://github.com/symfony/yaml.git",
- "reference": "e4fbcc65f90909c999ac3b4dfa699ee6563a9940"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/symfony/yaml/zipball/e4fbcc65f90909c999ac3b4dfa699ee6563a9940",
- "reference": "e4fbcc65f90909c999ac3b4dfa699ee6563a9940",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.9"
- },
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "2.8-dev"
- }
- },
- "autoload": {
- "psr-4": {
- "Symfony\\Component\\Yaml\\": ""
- },
- "exclude-from-classmap": [
- "/Tests/"
- ]
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Fabien Potencier",
- "email": "fabien@symfony.com"
- },
- {
- "name": "Symfony Community",
- "homepage": "https://symfony.com/contributors"
- }
- ],
- "description": "Symfony Yaml Component",
- "homepage": "https://symfony.com",
- "time": "2016-03-29 19:00:15"
- }
- ],
- "aliases": [],
- "minimum-stability": "stable",
- "stability-flags": [],
- "prefer-stable": false,
- "prefer-lowest": false,
- "platform": {
- "php": ">=5.4.0",
- "ext-zip": "*",
- "ext-xmlreader": "*",
- "ext-simplexml": "*"
- },
- "platform-dev": []
-}
diff --git a/logo.png b/logo.png
deleted file mode 100644
index 1319250..0000000
Binary files a/logo.png and /dev/null differ
diff --git a/phpunit.xml b/phpunit.xml
deleted file mode 100644
index 06ddf63..0000000
--- a/phpunit.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
-
- tests/
-
-
-
-
-
- src/
-
- src/Spout/Autoloader
-
-
-
-
-
diff --git a/src/Spout/Autoloader/Psr4Autoloader.php b/src/Spout/Autoloader/Psr4Autoloader.php
deleted file mode 100644
index 67cccc3..0000000
--- a/src/Spout/Autoloader/Psr4Autoloader.php
+++ /dev/null
@@ -1,150 +0,0 @@
-prefixes[$prefix]) === false) {
- $this->prefixes[$prefix] = array();
- }
-
- // retain the base directory for the namespace prefix
- if ($prepend) {
- array_unshift($this->prefixes[$prefix], $baseDir);
- } else {
- array_push($this->prefixes[$prefix], $baseDir);
- }
- }
-
- /**
- * Loads the class file for a given class name.
- *
- * @param string $class The fully-qualified class name.
- * @return mixed The mapped file name on success, or boolean false on
- * failure.
- */
- public function loadClass($class)
- {
- // the current namespace prefix
- $prefix = $class;
-
- // work backwards through the namespace names of the fully-qualified
- // class name to find a mapped file name
- while (false !== $pos = strrpos($prefix, '\\')) {
-
- // retain the trailing namespace separator in the prefix
- $prefix = substr($class, 0, $pos + 1);
-
- // the rest is the relative class name
- $relativeClass = substr($class, $pos + 1);
-
- // try to load a mapped file for the prefix and relative class
- $mappedFile = $this->loadMappedFile($prefix, $relativeClass);
- if ($mappedFile !== false) {
- return $mappedFile;
- }
-
- // remove the trailing namespace separator for the next iteration
- // of strrpos()
- $prefix = rtrim($prefix, '\\');
- }
-
- // never found a mapped file
- return false;
- }
-
- /**
- * Load the mapped file for a namespace prefix and relative class.
- *
- * @param string $prefix The namespace prefix.
- * @param string $relativeClass The relative class name.
- * @return mixed Boolean false if no mapped file can be loaded, or the
- * name of the mapped file that was loaded.
- */
- protected function loadMappedFile($prefix, $relativeClass)
- {
- // are there any base directories for this namespace prefix?
- if (isset($this->prefixes[$prefix]) === false) {
- return false;
- }
-
- // look through base directories for this namespace prefix
- foreach ($this->prefixes[$prefix] as $baseDir) {
-
- // replace the namespace prefix with the base directory,
- // replace namespace separators with directory separators
- // in the relative class name, append with .php
- $file = $baseDir
- . str_replace('\\', '/', $relativeClass)
- . '.php';
-
- // if the mapped file exists, require it
- if ($this->requireFile($file)) {
- // yes, we're done
- return $file;
- }
- }
-
- // never found it
- return false;
- }
-
- /**
- * If a file exists, require it from the file system.
- *
- * @param string $file The file to require.
- * @return bool True if the file exists, false if not.
- */
- protected function requireFile($file)
- {
- if (file_exists($file)) {
- require $file;
- return true;
- }
- return false;
- }
-}
diff --git a/src/Spout/Autoloader/autoload.php b/src/Spout/Autoloader/autoload.php
deleted file mode 100644
index 73ee519..0000000
--- a/src/Spout/Autoloader/autoload.php
+++ /dev/null
@@ -1,15 +0,0 @@
-register();
-$loader->addNamespace('Box\Spout', $srcBaseDirectory);
diff --git a/src/Spout/Common/Escaper/CSV.php b/src/Spout/Common/Escaper/CSV.php
deleted file mode 100644
index 4bc2d1a..0000000
--- a/src/Spout/Common/Escaper/CSV.php
+++ /dev/null
@@ -1,38 +0,0 @@
-', '&') need to be encoded.
- // Single and double quotes can be left as is.
- $escapedString = htmlspecialchars($string, ENT_NOQUOTES);
-
- // control characters values are from 0 to 1F (hex values) in the ASCII table
- // some characters should not be escaped though: "\t", "\r" and "\n".
- $regexPattern = '[\x00-\x08' .
- // skipping "\t" (0x9) and "\n" (0xA)
- '\x0B-\x0C' .
- // skipping "\r" (0xD)
- '\x0E-\x1F]';
- $replacedString = preg_replace("/$regexPattern/", '�', $escapedString);
- }
-
- return $replacedString;
- }
-
- /**
- * Unescapes the given string to make it compatible with XLSX
- *
- * @param string $string The string to unescape
- * @return string The unescaped string
- */
- public function unescape($string)
- {
- // ==============
- // = WARNING =
- // ==============
- // It is assumed that the given string has already had its XML entities decoded.
- // This is true if the string is coming from a DOMNode (as DOMNode already decode XML entities on creation).
- // Therefore there is no need to call "htmlspecialchars_decode()".
- return $string;
- }
-}
diff --git a/src/Spout/Common/Escaper/XLSX.php b/src/Spout/Common/Escaper/XLSX.php
deleted file mode 100644
index 7c6c61b..0000000
--- a/src/Spout/Common/Escaper/XLSX.php
+++ /dev/null
@@ -1,185 +0,0 @@
-escapableControlCharactersPattern = $this->getEscapableControlCharactersPattern();
- $this->controlCharactersEscapingMap = $this->getControlCharactersEscapingMap();
- $this->controlCharactersEscapingReverseMap = array_flip($this->controlCharactersEscapingMap);
- }
-
- /**
- * Escapes the given string to make it compatible with XLSX
- *
- * @param string $string The string to escape
- * @return string The escaped string
- */
- public function escape($string)
- {
- $escapedString = $this->escapeControlCharacters($string);
- // @NOTE: Using ENT_NOQUOTES as only XML entities ('<', '>', '&') need to be encoded.
- // Single and double quotes can be left as is.
- $escapedString = htmlspecialchars($escapedString, ENT_NOQUOTES);
-
- return $escapedString;
- }
-
- /**
- * Unescapes the given string to make it compatible with XLSX
- *
- * @param string $string The string to unescape
- * @return string The unescaped string
- */
- public function unescape($string)
- {
- // ==============
- // = WARNING =
- // ==============
- // It is assumed that the given string has already had its XML entities decoded.
- // This is true if the string is coming from a DOMNode (as DOMNode already decode XML entities on creation).
- // Therefore there is no need to call "htmlspecialchars_decode()".
- $unescapedString = $this->unescapeControlCharacters($string);
-
- return $unescapedString;
- }
-
- /**
- * @return string Regex pattern containing all escapable control characters
- */
- protected function getEscapableControlCharactersPattern()
- {
- // control characters values are from 0 to 1F (hex values) in the ASCII table
- // some characters should not be escaped though: "\t", "\r" and "\n".
- return '[\x00-\x08' .
- // skipping "\t" (0x9) and "\n" (0xA)
- '\x0B-\x0C' .
- // skipping "\r" (0xD)
- '\x0E-\x1F]';
- }
-
- /**
- * Builds the map containing control characters to be escaped
- * mapped to their escaped values.
- * "\t", "\r" and "\n" don't need to be escaped.
- *
- * NOTE: the logic has been adapted from the XlsxWriter library (BSD License)
- * @link https://github.com/jmcnamara/XlsxWriter/blob/f1e610f29/xlsxwriter/sharedstrings.py#L89
- *
- * @return string[]
- */
- protected function getControlCharactersEscapingMap()
- {
- $controlCharactersEscapingMap = [];
-
- // control characters values are from 0 to 1F (hex values) in the ASCII table
- for ($charValue = 0x00; $charValue <= 0x1F; $charValue++) {
- $character = chr($charValue);
- if (preg_match("/{$this->escapableControlCharactersPattern}/", $character)) {
- $charHexValue = dechex($charValue);
- $escapedChar = '_x' . sprintf('%04s' , strtoupper($charHexValue)) . '_';
- $controlCharactersEscapingMap[$escapedChar] = $character;
- }
- }
-
- return $controlCharactersEscapingMap;
- }
-
- /**
- * Converts PHP control characters from the given string to OpenXML escaped control characters
- *
- * Excel escapes control characters with _xHHHH_ and also escapes any
- * literal strings of that type by encoding the leading underscore.
- * So "\0" -> _x0000_ and "_x0000_" -> _x005F_x0000_.
- *
- * NOTE: the logic has been adapted from the XlsxWriter library (BSD License)
- * @link https://github.com/jmcnamara/XlsxWriter/blob/f1e610f29/xlsxwriter/sharedstrings.py#L89
- *
- * @param string $string String to escape
- * @return string
- */
- protected function escapeControlCharacters($string)
- {
- $escapedString = $this->escapeEscapeCharacter($string);
-
- // if no control characters
- if (!preg_match("/{$this->escapableControlCharactersPattern}/", $escapedString)) {
- return $escapedString;
- }
-
- return preg_replace_callback("/({$this->escapableControlCharactersPattern})/", function($matches) {
- return $this->controlCharactersEscapingReverseMap[$matches[0]];
- }, $escapedString);
- }
-
- /**
- * Escapes the escape character: "_x0000_" -> "_x005F_x0000_"
- *
- * @param string $string String to escape
- * @return string The escaped string
- */
- protected function escapeEscapeCharacter($string)
- {
- return preg_replace('/_(x[\dA-F]{4})_/', '_x005F_$1_', $string);
- }
-
- /**
- * Converts OpenXML escaped control characters from the given string to PHP control characters
- *
- * Excel escapes control characters with _xHHHH_ and also escapes any
- * literal strings of that type by encoding the leading underscore.
- * So "_x0000_" -> "\0" and "_x005F_x0000_" -> "_x0000_"
- *
- * NOTE: the logic has been adapted from the XlsxWriter library (BSD License)
- * @link https://github.com/jmcnamara/XlsxWriter/blob/f1e610f29/xlsxwriter/sharedstrings.py#L89
- *
- * @param string $string String to unescape
- * @return string
- */
- protected function unescapeControlCharacters($string)
- {
- $unescapedString = $string;
-
- foreach ($this->controlCharactersEscapingMap as $escapedCharValue => $charValue) {
- // only unescape characters that don't contain the escaped escape character for now
- $unescapedString = preg_replace("/(?unescapeEscapeCharacter($unescapedString);
- }
-
- /**
- * Unecapes the escape character: "_x005F_x0000_" => "_x0000_"
- *
- * @param string $string String to unescape
- * @return string The unescaped string
- */
- protected function unescapeEscapeCharacter($string)
- {
- return preg_replace('/_x005F(_x[\dA-F]{4}_)/', '$1', $string);
- }
-}
diff --git a/src/Spout/Common/Exception/EncodingConversionException.php b/src/Spout/Common/Exception/EncodingConversionException.php
deleted file mode 100644
index 6dcc0a8..0000000
--- a/src/Spout/Common/Exception/EncodingConversionException.php
+++ /dev/null
@@ -1,13 +0,0 @@
-globalFunctionsHelper = $globalFunctionsHelper;
-
- $this->supportedEncodingsWithBom = [
- self::ENCODING_UTF8 => self::BOM_UTF8,
- self::ENCODING_UTF16_LE => self::BOM_UTF16_LE,
- self::ENCODING_UTF16_BE => self::BOM_UTF16_BE,
- self::ENCODING_UTF32_LE => self::BOM_UTF32_LE,
- self::ENCODING_UTF32_BE => self::BOM_UTF32_BE,
- ];
- }
-
- /**
- * Returns the number of bytes to use as offset in order to skip the BOM.
- *
- * @param resource $filePointer Pointer to the file to check
- * @param string $encoding Encoding of the file to check
- * @return int Bytes offset to apply to skip the BOM (0 means no BOM)
- */
- public function getBytesOffsetToSkipBOM($filePointer, $encoding)
- {
- $byteOffsetToSkipBom = 0;
-
- if ($this->hasBOM($filePointer, $encoding)) {
- $bomUsed = $this->supportedEncodingsWithBom[$encoding];
-
- // we skip the N first bytes
- $byteOffsetToSkipBom = strlen($bomUsed);
- }
-
- return $byteOffsetToSkipBom;
- }
-
- /**
- * Returns whether the file identified by the given pointer has a BOM.
- *
- * @param resource $filePointer Pointer to the file to check
- * @param string $encoding Encoding of the file to check
- * @return bool TRUE if the file has a BOM, FALSE otherwise
- */
- protected function hasBOM($filePointer, $encoding)
- {
- $hasBOM = false;
-
- $this->globalFunctionsHelper->rewind($filePointer);
-
- if (array_key_exists($encoding, $this->supportedEncodingsWithBom)) {
- $potentialBom = $this->supportedEncodingsWithBom[$encoding];
- $numBytesInBom = strlen($potentialBom);
-
- $hasBOM = ($this->globalFunctionsHelper->fgets($filePointer, $numBytesInBom + 1) === $potentialBom);
- }
-
- return $hasBOM;
- }
-
- /**
- * Attempts to convert a non UTF-8 string into UTF-8.
- *
- * @param string $string Non UTF-8 string to be converted
- * @param string $sourceEncoding The encoding used to encode the source string
- * @return string The converted, UTF-8 string
- * @throws \Box\Spout\Common\Exception\EncodingConversionException If conversion is not supported or if the conversion failed
- */
- public function attemptConversionToUTF8($string, $sourceEncoding)
- {
- return $this->attemptConversion($string, $sourceEncoding, self::ENCODING_UTF8);
- }
-
- /**
- * Attempts to convert a UTF-8 string into the given encoding.
- *
- * @param string $string UTF-8 string to be converted
- * @param string $targetEncoding The encoding the string should be re-encoded into
- * @return string The converted string, encoded with the given encoding
- * @throws \Box\Spout\Common\Exception\EncodingConversionException If conversion is not supported or if the conversion failed
- */
- public function attemptConversionFromUTF8($string, $targetEncoding)
- {
- return $this->attemptConversion($string, self::ENCODING_UTF8, $targetEncoding);
- }
-
- /**
- * Attempts to convert the given string to the given encoding.
- * Depending on what is installed on the server, we will try to iconv or mbstring.
- *
- * @param string $string string to be converted
- * @param string $sourceEncoding The encoding used to encode the source string
- * @param string $targetEncoding The encoding the string should be re-encoded into
- * @return string The converted string, encoded with the given encoding
- * @throws \Box\Spout\Common\Exception\EncodingConversionException If conversion is not supported or if the conversion failed
- */
- protected function attemptConversion($string, $sourceEncoding, $targetEncoding)
- {
- // if source and target encodings are the same, it's a no-op
- if ($sourceEncoding === $targetEncoding) {
- return $string;
- }
-
- $convertedString = null;
-
- if ($this->canUseIconv()) {
- $convertedString = $this->globalFunctionsHelper->iconv($string, $sourceEncoding, $targetEncoding);
- } else if ($this->canUseMbString()) {
- $convertedString = $this->globalFunctionsHelper->mb_convert_encoding($string, $sourceEncoding, $targetEncoding);
- } else {
- throw new EncodingConversionException("The conversion from $sourceEncoding to $targetEncoding is not supported. Please install \"iconv\" or \"PHP Intl\".");
- }
-
- if ($convertedString === false) {
- throw new EncodingConversionException("The conversion from $sourceEncoding to $targetEncoding failed.");
- }
-
- return $convertedString;
- }
-
- /**
- * Returns whether "iconv" can be used.
- *
- * @return bool TRUE if "iconv" is available and can be used, FALSE otherwise
- */
- protected function canUseIconv()
- {
- return $this->globalFunctionsHelper->function_exists('iconv');
- }
-
- /**
- * Returns whether "mb_string" functions can be used.
- * These functions come with the PHP Intl package.
- *
- * @return bool TRUE if "mb_string" functions are available and can be used, FALSE otherwise
- */
- protected function canUseMbString()
- {
- return $this->globalFunctionsHelper->function_exists('mb_convert_encoding');
- }
-}
diff --git a/src/Spout/Common/Helper/FileSystemHelper.php b/src/Spout/Common/Helper/FileSystemHelper.php
deleted file mode 100644
index 3145be7..0000000
--- a/src/Spout/Common/Helper/FileSystemHelper.php
+++ /dev/null
@@ -1,133 +0,0 @@
-baseFolderRealPath = realpath($baseFolderPath);
- }
-
- /**
- * Creates an empty folder with the given name under the given parent folder.
- *
- * @param string $parentFolderPath The parent folder path under which the folder is going to be created
- * @param string $folderName The name of the folder to create
- * @return string Path of the created folder
- * @throws \Box\Spout\Common\Exception\IOException If unable to create the folder or if the folder path is not inside of the base folder
- */
- public function createFolder($parentFolderPath, $folderName)
- {
- $this->throwIfOperationNotInBaseFolder($parentFolderPath);
-
- $folderPath = $parentFolderPath . '/' . $folderName;
-
- $wasCreationSuccessful = mkdir($folderPath, 0777, true);
- if (!$wasCreationSuccessful) {
- throw new IOException("Unable to create folder: $folderPath");
- }
-
- return $folderPath;
- }
-
- /**
- * Creates a file with the given name and content in the given folder.
- * The parent folder must exist.
- *
- * @param string $parentFolderPath The parent folder path where the file is going to be created
- * @param string $fileName The name of the file to create
- * @param string $fileContents The contents of the file to create
- * @return string Path of the created file
- * @throws \Box\Spout\Common\Exception\IOException If unable to create the file or if the file path is not inside of the base folder
- */
- public function createFileWithContents($parentFolderPath, $fileName, $fileContents)
- {
- $this->throwIfOperationNotInBaseFolder($parentFolderPath);
-
- $filePath = $parentFolderPath . '/' . $fileName;
-
- $wasCreationSuccessful = file_put_contents($filePath, $fileContents);
- if ($wasCreationSuccessful === false) {
- throw new IOException("Unable to create file: $filePath");
- }
-
- return $filePath;
- }
-
- /**
- * Delete the file at the given path
- *
- * @param string $filePath Path of the file to delete
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If the file path is not inside of the base folder
- */
- public function deleteFile($filePath)
- {
- $this->throwIfOperationNotInBaseFolder($filePath);
-
- if (file_exists($filePath) && is_file($filePath)) {
- unlink($filePath);
- }
- }
-
- /**
- * Delete the folder at the given path as well as all its contents
- *
- * @param string $folderPath Path of the folder to delete
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If the folder path is not inside of the base folder
- */
- public function deleteFolderRecursively($folderPath)
- {
- $this->throwIfOperationNotInBaseFolder($folderPath);
-
- $itemIterator = new \RecursiveIteratorIterator(
- new \RecursiveDirectoryIterator($folderPath, \RecursiveDirectoryIterator::SKIP_DOTS),
- \RecursiveIteratorIterator::CHILD_FIRST
- );
-
- foreach ($itemIterator as $item) {
- if ($item->isDir()) {
- rmdir($item->getPathname());
- } else {
- unlink($item->getPathname());
- }
- }
-
- rmdir($folderPath);
- }
-
- /**
- * All I/O operations must occur inside the base folder, for security reasons.
- * This function will throw an exception if the folder where the I/O operation
- * should occur is not inside the base folder.
- *
- * @param string $operationFolderPath The path of the folder where the I/O operation should occur
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If the folder where the I/O operation should occur is not inside the base folder
- */
- protected function throwIfOperationNotInBaseFolder($operationFolderPath)
- {
- $operationFolderRealPath = realpath($operationFolderPath);
- $isInBaseFolder = (strpos($operationFolderRealPath, $this->baseFolderRealPath) === 0);
- if (!$isInBaseFolder) {
- throw new IOException("Cannot perform I/O operation outside of the base folder: {$this->baseFolderRealPath}");
- }
- }
-}
diff --git a/src/Spout/Common/Helper/GlobalFunctionsHelper.php b/src/Spout/Common/Helper/GlobalFunctionsHelper.php
deleted file mode 100644
index c5d6e31..0000000
--- a/src/Spout/Common/Helper/GlobalFunctionsHelper.php
+++ /dev/null
@@ -1,318 +0,0 @@
-convertToUseRealPath($filePath);
- return file_get_contents($realFilePath);
- }
-
- /**
- * Updates the given file path to use a real path.
- * This is to avoid issues on some Windows setup.
- *
- * @param string $filePath File path
- * @return string The file path using a real path
- */
- protected function convertToUseRealPath($filePath)
- {
- $realFilePath = $filePath;
-
- if ($this->isZipStream($filePath)) {
- if (preg_match('/zip:\/\/(.*)#(.*)/', $filePath, $matches)) {
- $documentPath = $matches[1];
- $documentInsideZipPath = $matches[2];
- $realFilePath = 'zip://' . realpath($documentPath) . '#' . $documentInsideZipPath;
- }
- } else {
- $realFilePath = realpath($filePath);
- }
-
- return $realFilePath;
- }
-
- /**
- * Returns whether the given path is a zip stream.
- *
- * @param string $path Path pointing to a document
- * @return bool TRUE if path is a zip stream, FALSE otherwise
- */
- protected function isZipStream($path)
- {
- return (strpos($path, 'zip://') === 0);
- }
-
- /**
- * Wrapper around global function feof()
- * @see feof()
- *
- * @param resource
- * @return bool
- */
- public function feof($handle)
- {
- return feof($handle);
- }
-
- /**
- * Wrapper around global function is_readable()
- * @see is_readable()
- *
- * @param string $fileName
- * @return bool
- */
- public function is_readable($fileName)
- {
- return is_readable($fileName);
- }
-
- /**
- * Wrapper around global function basename()
- * @see basename()
- *
- * @param string $path
- * @param string|void $suffix
- * @return string
- */
- public function basename($path, $suffix = null)
- {
- return basename($path, $suffix);
- }
-
- /**
- * Wrapper around global function header()
- * @see header()
- *
- * @param string $string
- * @return void
- */
- public function header($string)
- {
- header($string);
- }
-
- /**
- * Wrapper around global function ob_end_clean()
- * @see ob_end_clean()
- *
- * @return void
- */
- public function ob_end_clean()
- {
- if (ob_get_length() > 0) {
- ob_end_clean();
- }
- }
-
- /**
- * Wrapper around global function iconv()
- * @see iconv()
- *
- * @param string $string The string to be converted
- * @param string $sourceEncoding The encoding of the source string
- * @param string $targetEncoding The encoding the source string should be converted to
- * @return string|bool the converted string or FALSE on failure.
- */
- public function iconv($string, $sourceEncoding, $targetEncoding)
- {
- return iconv($sourceEncoding, $targetEncoding, $string);
- }
-
- /**
- * Wrapper around global function mb_convert_encoding()
- * @see mb_convert_encoding()
- *
- * @param string $string The string to be converted
- * @param string $sourceEncoding The encoding of the source string
- * @param string $targetEncoding The encoding the source string should be converted to
- * @return string|bool the converted string or FALSE on failure.
- */
- public function mb_convert_encoding($string, $sourceEncoding, $targetEncoding)
- {
- return mb_convert_encoding($string, $targetEncoding, $sourceEncoding);
- }
-
- /**
- * Wrapper around global function stream_get_wrappers()
- * @see stream_get_wrappers()
- *
- * @return array
- */
- public function stream_get_wrappers()
- {
- return stream_get_wrappers();
- }
-
- /**
- * Wrapper around global function function_exists()
- * @see function_exists()
- *
- * @param string $functionName
- * @return bool
- */
- public function function_exists($functionName)
- {
- return function_exists($functionName);
- }
-}
diff --git a/src/Spout/Common/Helper/StringHelper.php b/src/Spout/Common/Helper/StringHelper.php
deleted file mode 100644
index 273104e..0000000
--- a/src/Spout/Common/Helper/StringHelper.php
+++ /dev/null
@@ -1,71 +0,0 @@
-hasMbstringSupport = extension_loaded('mbstring');
- }
-
- /**
- * Returns the length of the given string.
- * It uses the multi-bytes function is available.
- * @see strlen
- * @see mb_strlen
- *
- * @param string $string
- * @return int
- */
- public function getStringLength($string)
- {
- return $this->hasMbstringSupport ? mb_strlen($string) : strlen($string);
- }
-
- /**
- * Returns the position of the first occurrence of the given character/substring within the given string.
- * It uses the multi-bytes function is available.
- * @see strpos
- * @see mb_strpos
- *
- * @param string $char Needle
- * @param string $string Haystack
- * @return int Char/substring's first occurrence position within the string if found (starts at 0) or -1 if not found
- */
- public function getCharFirstOccurrencePosition($char, $string)
- {
- $position = $this->hasMbstringSupport ? mb_strpos($string, $char) : strpos($string, $char);
- return ($position !== false) ? $position : -1;
- }
-
- /**
- * Returns the position of the last occurrence of the given character/substring within the given string.
- * It uses the multi-bytes function is available.
- * @see strrpos
- * @see mb_strrpos
- *
- * @param string $char Needle
- * @param string $string Haystack
- * @return int Char/substring's last occurrence position within the string if found (starts at 0) or -1 if not found
- */
- public function getCharLastOccurrencePosition($char, $string)
- {
- $position = $this->hasMbstringSupport ? mb_strrpos($string, $char) : strrpos($string, $char);
- return ($position !== false) ? $position : -1;
- }
-}
diff --git a/src/Spout/Common/Singleton.php b/src/Spout/Common/Singleton.php
deleted file mode 100644
index 015ede8..0000000
--- a/src/Spout/Common/Singleton.php
+++ /dev/null
@@ -1,41 +0,0 @@
-init();
- }
-
- /**
- * Initializes the singleton
- * @return void
- */
- protected function init() {}
-
- final private function __wakeup() {}
- final private function __clone() {}
-}
diff --git a/src/Spout/Common/Type.php b/src/Spout/Common/Type.php
deleted file mode 100644
index 5e9b75e..0000000
--- a/src/Spout/Common/Type.php
+++ /dev/null
@@ -1,16 +0,0 @@
-globalFunctionsHelper = $globalFunctionsHelper;
- return $this;
- }
-
- /**
- * Sets whether date/time values should be returned as PHP objects or be formatted as strings.
- *
- * @api
- * @param bool $shouldFormatDates
- * @return AbstractReader
- */
- public function setShouldFormatDates($shouldFormatDates)
- {
- $this->getOptions()->setShouldFormatDates($shouldFormatDates);
- return $this;
- }
-
- /**
- * Sets whether empty rows should be returned or skipped.
- *
- * @api
- * @param bool $shouldPreserveEmptyRows
- * @return AbstractReader
- */
- public function setShouldPreserveEmptyRows($shouldPreserveEmptyRows)
- {
- $this->getOptions()->setShouldPreserveEmptyRows($shouldPreserveEmptyRows);
- return $this;
- }
-
- /**
- * Prepares the reader to read the given file. It also makes sure
- * that the file exists and is readable.
- *
- * @api
- * @param string $filePath Path of the file to be read
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If the file at the given path does not exist, is not readable or is corrupted
- */
- public function open($filePath)
- {
- if ($this->isStreamWrapper($filePath) && (!$this->doesSupportStreamWrapper() || !$this->isSupportedStreamWrapper($filePath))) {
- throw new IOException("Could not open $filePath for reading! Stream wrapper used is not supported for this type of file.");
- }
-
- if (!$this->isPhpStream($filePath)) {
- // we skip the checks if the provided file path points to a PHP stream
- if (!$this->globalFunctionsHelper->file_exists($filePath)) {
- throw new IOException("Could not open $filePath for reading! File does not exist.");
- } else if (!$this->globalFunctionsHelper->is_readable($filePath)) {
- throw new IOException("Could not open $filePath for reading! File is not readable.");
- }
- }
-
- try {
- $fileRealPath = $this->getFileRealPath($filePath);
- $this->openReader($fileRealPath);
- $this->isStreamOpened = true;
- } catch (\Exception $exception) {
- throw new IOException("Could not open $filePath for reading! ({$exception->getMessage()})");
- }
- }
-
- /**
- * Returns the real path of the given path.
- * If the given path is a valid stream wrapper, returns the path unchanged.
- *
- * @param string $filePath
- * @return string
- */
- protected function getFileRealPath($filePath)
- {
- if ($this->isSupportedStreamWrapper($filePath)) {
- return $filePath;
- }
-
- // Need to use realpath to fix "Can't open file" on some Windows setup
- return realpath($filePath);
- }
-
- /**
- * Returns the scheme of the custom stream wrapper, if the path indicates a stream wrapper is used.
- * For example, php://temp => php, s3://path/to/file => s3...
- *
- * @param string $filePath Path of the file to be read
- * @return string|null The stream wrapper scheme or NULL if not a stream wrapper
- */
- protected function getStreamWrapperScheme($filePath)
- {
- $streamScheme = null;
- if (preg_match('/^(\w+):\/\//', $filePath, $matches)) {
- $streamScheme = $matches[1];
- }
- return $streamScheme;
- }
-
- /**
- * Checks if the given path is an unsupported stream wrapper
- * (like local path, php://temp, mystream://foo/bar...).
- *
- * @param string $filePath Path of the file to be read
- * @return bool Whether the given path is an unsupported stream wrapper
- */
- protected function isStreamWrapper($filePath)
- {
- return ($this->getStreamWrapperScheme($filePath) !== null);
- }
-
- /**
- * Checks if the given path is an supported stream wrapper
- * (like php://temp, mystream://foo/bar...).
- * If the given path is a local path, returns true.
- *
- * @param string $filePath Path of the file to be read
- * @return bool Whether the given path is an supported stream wrapper
- */
- protected function isSupportedStreamWrapper($filePath)
- {
- $streamScheme = $this->getStreamWrapperScheme($filePath);
- return ($streamScheme !== null) ?
- in_array($streamScheme, $this->globalFunctionsHelper->stream_get_wrappers()) :
- true;
- }
-
- /**
- * Checks if a path is a PHP stream (like php://output, php://memory, ...)
- *
- * @param string $filePath Path of the file to be read
- * @return bool Whether the given path maps to a PHP stream
- */
- protected function isPhpStream($filePath)
- {
- $streamScheme = $this->getStreamWrapperScheme($filePath);
- return ($streamScheme === 'php');
- }
-
- /**
- * Returns an iterator to iterate over sheets.
- *
- * @api
- * @return \Iterator To iterate over sheets
- * @throws \Box\Spout\Reader\Exception\ReaderNotOpenedException If called before opening the reader
- */
- public function getSheetIterator()
- {
- if (!$this->isStreamOpened) {
- throw new ReaderNotOpenedException('Reader should be opened first.');
- }
-
- return $this->getConcreteSheetIterator();
- }
-
- /**
- * Closes the reader, preventing any additional reading
- *
- * @api
- * @return void
- */
- public function close()
- {
- if ($this->isStreamOpened) {
- $this->closeReader();
-
- $sheetIterator = $this->getConcreteSheetIterator();
- if ($sheetIterator) {
- $sheetIterator->end();
- }
-
- $this->isStreamOpened = false;
- }
- }
-}
diff --git a/src/Spout/Reader/CSV/Reader.php b/src/Spout/Reader/CSV/Reader.php
deleted file mode 100644
index 648a12d..0000000
--- a/src/Spout/Reader/CSV/Reader.php
+++ /dev/null
@@ -1,149 +0,0 @@
-options)) {
- $this->options = new ReaderOptions();
- }
- return $this->options;
- }
-
- /**
- * Sets the field delimiter for the CSV.
- * Needs to be called before opening the reader.
- *
- * @param string $fieldDelimiter Character that delimits fields
- * @return Reader
- */
- public function setFieldDelimiter($fieldDelimiter)
- {
- $this->getOptions()->setFieldDelimiter($fieldDelimiter);
- return $this;
- }
-
- /**
- * Sets the field enclosure for the CSV.
- * Needs to be called before opening the reader.
- *
- * @param string $fieldEnclosure Character that enclose fields
- * @return Reader
- */
- public function setFieldEnclosure($fieldEnclosure)
- {
- $this->getOptions()->setFieldEnclosure($fieldEnclosure);
- return $this;
- }
-
- /**
- * Sets the encoding of the CSV file to be read.
- * Needs to be called before opening the reader.
- *
- * @param string $encoding Encoding of the CSV file to be read
- * @return Reader
- */
- public function setEncoding($encoding)
- {
- $this->getOptions()->setEncoding($encoding);
- return $this;
- }
-
- /**
- * Sets the EOL for the CSV.
- * Needs to be called before opening the reader.
- *
- * @param string $endOfLineCharacter used to properly get lines from the CSV file.
- * @return Reader
- */
- public function setEndOfLineCharacter($endOfLineCharacter)
- {
- $this->getOptions()->setEndOfLineCharacter($endOfLineCharacter);
- return $this;
- }
-
- /**
- * Returns whether stream wrappers are supported
- *
- * @return bool
- */
- protected function doesSupportStreamWrapper()
- {
- return true;
- }
-
- /**
- * Opens the file at the given path to make it ready to be read.
- * If setEncoding() was not called, it assumes that the file is encoded in UTF-8.
- *
- * @param string $filePath Path of the CSV file to be read
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException
- */
- protected function openReader($filePath)
- {
- $this->originalAutoDetectLineEndings = ini_get('auto_detect_line_endings');
- ini_set('auto_detect_line_endings', '1');
-
- $this->filePointer = $this->globalFunctionsHelper->fopen($filePath, 'r');
- if (!$this->filePointer) {
- throw new IOException("Could not open file $filePath for reading.");
- }
-
- $this->sheetIterator = new SheetIterator(
- $this->filePointer,
- $this->getOptions(),
- $this->globalFunctionsHelper
- );
- }
-
- /**
- * Returns an iterator to iterate over sheets.
- *
- * @return SheetIterator To iterate over sheets
- */
- protected function getConcreteSheetIterator()
- {
- return $this->sheetIterator;
- }
-
-
- /**
- * Closes the reader. To be used after reading the file.
- *
- * @return void
- */
- protected function closeReader()
- {
- if ($this->filePointer) {
- $this->globalFunctionsHelper->fclose($this->filePointer);
- }
-
- ini_set('auto_detect_line_endings', $this->originalAutoDetectLineEndings);
- }
-}
diff --git a/src/Spout/Reader/CSV/ReaderOptions.php b/src/Spout/Reader/CSV/ReaderOptions.php
deleted file mode 100644
index 9a1adb8..0000000
--- a/src/Spout/Reader/CSV/ReaderOptions.php
+++ /dev/null
@@ -1,110 +0,0 @@
-fieldDelimiter;
- }
-
- /**
- * Sets the field delimiter for the CSV.
- * Needs to be called before opening the reader.
- *
- * @param string $fieldDelimiter Character that delimits fields
- * @return ReaderOptions
- */
- public function setFieldDelimiter($fieldDelimiter)
- {
- $this->fieldDelimiter = $fieldDelimiter;
- return $this;
- }
-
- /**
- * @return string
- */
- public function getFieldEnclosure()
- {
- return $this->fieldEnclosure;
- }
-
- /**
- * Sets the field enclosure for the CSV.
- * Needs to be called before opening the reader.
- *
- * @param string $fieldEnclosure Character that enclose fields
- * @return ReaderOptions
- */
- public function setFieldEnclosure($fieldEnclosure)
- {
- $this->fieldEnclosure = $fieldEnclosure;
- return $this;
- }
-
- /**
- * @return string
- */
- public function getEncoding()
- {
- return $this->encoding;
- }
-
- /**
- * Sets the encoding of the CSV file to be read.
- * Needs to be called before opening the reader.
- *
- * @param string $encoding Encoding of the CSV file to be read
- * @return ReaderOptions
- */
- public function setEncoding($encoding)
- {
- $this->encoding = $encoding;
- return $this;
- }
-
- /**
- * @return string EOL for the CSV
- */
- public function getEndOfLineCharacter()
- {
- return $this->endOfLineCharacter;
- }
-
- /**
- * Sets the EOL for the CSV.
- * Needs to be called before opening the reader.
- *
- * @param string $endOfLineCharacter used to properly get lines from the CSV file.
- * @return ReaderOptions
- */
- public function setEndOfLineCharacter($endOfLineCharacter)
- {
- $this->endOfLineCharacter = $endOfLineCharacter;
- return $this;
- }
-}
diff --git a/src/Spout/Reader/CSV/RowIterator.php b/src/Spout/Reader/CSV/RowIterator.php
deleted file mode 100644
index a2a6672..0000000
--- a/src/Spout/Reader/CSV/RowIterator.php
+++ /dev/null
@@ -1,260 +0,0 @@
-filePointer = $filePointer;
- $this->fieldDelimiter = $options->getFieldDelimiter();
- $this->fieldEnclosure = $options->getFieldEnclosure();
- $this->encoding = $options->getEncoding();
- $this->inputEOLDelimiter = $options->getEndOfLineCharacter();
- $this->shouldPreserveEmptyRows = $options->shouldPreserveEmptyRows();
- $this->globalFunctionsHelper = $globalFunctionsHelper;
-
- $this->encodingHelper = new EncodingHelper($globalFunctionsHelper);
- }
-
- /**
- * Rewind the Iterator to the first element
- * @link http://php.net/manual/en/iterator.rewind.php
- *
- * @return void
- */
- public function rewind()
- {
- $this->rewindAndSkipBom();
-
- $this->numReadRows = 0;
- $this->rowDataBuffer = null;
-
- $this->next();
- }
-
- /**
- * This rewinds and skips the BOM if inserted at the beginning of the file
- * by moving the file pointer after it, so that it is not read.
- *
- * @return void
- */
- protected function rewindAndSkipBom()
- {
- $byteOffsetToSkipBom = $this->encodingHelper->getBytesOffsetToSkipBOM($this->filePointer, $this->encoding);
-
- // sets the cursor after the BOM (0 means no BOM, so rewind it)
- $this->globalFunctionsHelper->fseek($this->filePointer, $byteOffsetToSkipBom);
- }
-
- /**
- * Checks if current position is valid
- * @link http://php.net/manual/en/iterator.valid.php
- *
- * @return bool
- */
- public function valid()
- {
- return ($this->filePointer && !$this->hasReachedEndOfFile);
- }
-
- /**
- * Move forward to next element. Reads data for the next unprocessed row.
- * @link http://php.net/manual/en/iterator.next.php
- *
- * @return void
- * @throws \Box\Spout\Common\Exception\EncodingConversionException If unable to convert data to UTF-8
- */
- public function next()
- {
- $this->hasReachedEndOfFile = $this->globalFunctionsHelper->feof($this->filePointer);
-
- if (!$this->hasReachedEndOfFile) {
- $this->readDataForNextRow();
- }
- }
-
- /**
- * @return void
- * @throws \Box\Spout\Common\Exception\EncodingConversionException If unable to convert data to UTF-8
- */
- protected function readDataForNextRow()
- {
- do {
- $rowData = $this->getNextUTF8EncodedRow();
- } while ($this->shouldReadNextRow($rowData));
-
- if ($rowData !== false) {
- // str_replace will replace NULL values by empty strings
- $this->rowDataBuffer = str_replace(null, null, $rowData);
- $this->numReadRows++;
- } else {
- // If we reach this point, it means end of file was reached.
- // This happens when the last lines are empty lines.
- $this->hasReachedEndOfFile = true;
- }
- }
-
- /**
- * @param array|bool $currentRowData
- * @return bool Whether the data for the current row can be returned or if we need to keep reading
- */
- protected function shouldReadNextRow($currentRowData)
- {
- $hasSuccessfullyFetchedRowData = ($currentRowData !== false);
- $hasNowReachedEndOfFile = $this->globalFunctionsHelper->feof($this->filePointer);
- $isEmptyLine = $this->isEmptyLine($currentRowData);
-
- return (
- (!$hasSuccessfullyFetchedRowData && !$hasNowReachedEndOfFile) ||
- (!$this->shouldPreserveEmptyRows && $isEmptyLine)
- );
- }
-
- /**
- * Returns the next row, converted if necessary to UTF-8.
- * As fgetcsv() does not manage correctly encoding for non UTF-8 data,
- * we remove manually whitespace with ltrim or rtrim (depending on the order of the bytes)
- *
- * @return array|false The row for the current file pointer, encoded in UTF-8 or FALSE if nothing to read
- * @throws \Box\Spout\Common\Exception\EncodingConversionException If unable to convert data to UTF-8
- */
- protected function getNextUTF8EncodedRow()
- {
- $encodedRowData = $this->globalFunctionsHelper->fgetcsv($this->filePointer, self::MAX_READ_BYTES_PER_LINE, $this->fieldDelimiter, $this->fieldEnclosure);
- if ($encodedRowData === false) {
- return false;
- }
-
- foreach ($encodedRowData as $cellIndex => $cellValue) {
- switch($this->encoding) {
- case EncodingHelper::ENCODING_UTF16_LE:
- case EncodingHelper::ENCODING_UTF32_LE:
- // remove whitespace from the beginning of a string as fgetcsv() add extra whitespace when it try to explode non UTF-8 data
- $cellValue = ltrim($cellValue);
- break;
-
- case EncodingHelper::ENCODING_UTF16_BE:
- case EncodingHelper::ENCODING_UTF32_BE:
- // remove whitespace from the end of a string as fgetcsv() add extra whitespace when it try to explode non UTF-8 data
- $cellValue = rtrim($cellValue);
- break;
- }
-
- $encodedRowData[$cellIndex] = $this->encodingHelper->attemptConversionToUTF8($cellValue, $this->encoding);
- }
-
- return $encodedRowData;
- }
-
- /**
- * Returns the end of line delimiter, encoded using the same encoding as the CSV.
- * The return value is cached.
- *
- * @return string
- */
- protected function getEncodedEOLDelimiter()
- {
- if (!isset($this->encodedEOLDelimiter)) {
- $this->encodedEOLDelimiter = $this->encodingHelper->attemptConversionFromUTF8($this->inputEOLDelimiter, $this->encoding);
- }
-
- return $this->encodedEOLDelimiter;
- }
-
- /**
- * @param array|bool $lineData Array containing the cells value for the line
- * @return bool Whether the given line is empty
- */
- protected function isEmptyLine($lineData)
- {
- return (is_array($lineData) && count($lineData) === 1 && $lineData[0] === null);
- }
-
- /**
- * Return the current element from the buffer
- * @link http://php.net/manual/en/iterator.current.php
- *
- * @return array|null
- */
- public function current()
- {
- return $this->rowDataBuffer;
- }
-
- /**
- * Return the key of the current element
- * @link http://php.net/manual/en/iterator.key.php
- *
- * @return int
- */
- public function key()
- {
- return $this->numReadRows;
- }
-
- /**
- * Cleans up what was created to iterate over the object.
- *
- * @return void
- */
- public function end()
- {
- // do nothing
- }
-}
diff --git a/src/Spout/Reader/CSV/Sheet.php b/src/Spout/Reader/CSV/Sheet.php
deleted file mode 100644
index 9a688db..0000000
--- a/src/Spout/Reader/CSV/Sheet.php
+++ /dev/null
@@ -1,62 +0,0 @@
-rowIterator = new RowIterator($filePointer, $options, $globalFunctionsHelper);
- }
-
- /**
- * @api
- * @return \Box\Spout\Reader\CSV\RowIterator
- */
- public function getRowIterator()
- {
- return $this->rowIterator;
- }
-
- /**
- * @api
- * @return int Index of the sheet
- */
- public function getIndex()
- {
- return 0;
- }
-
- /**
- * @api
- * @return string Name of the sheet - empty string since CSV does not support that
- */
- public function getName()
- {
- return '';
- }
-
- /**
- * @api
- * @return bool Always TRUE as there is only one sheet
- */
- public function isActive()
- {
- return true;
- }
-}
diff --git a/src/Spout/Reader/CSV/SheetIterator.php b/src/Spout/Reader/CSV/SheetIterator.php
deleted file mode 100644
index 58a9480..0000000
--- a/src/Spout/Reader/CSV/SheetIterator.php
+++ /dev/null
@@ -1,95 +0,0 @@
-sheet = new Sheet($filePointer, $options, $globalFunctionsHelper);
- }
-
- /**
- * Rewind the Iterator to the first element
- * @link http://php.net/manual/en/iterator.rewind.php
- *
- * @return void
- */
- public function rewind()
- {
- $this->hasReadUniqueSheet = false;
- }
-
- /**
- * Checks if current position is valid
- * @link http://php.net/manual/en/iterator.valid.php
- *
- * @return bool
- */
- public function valid()
- {
- return (!$this->hasReadUniqueSheet);
- }
-
- /**
- * Move forward to next element
- * @link http://php.net/manual/en/iterator.next.php
- *
- * @return void
- */
- public function next()
- {
- $this->hasReadUniqueSheet = true;
- }
-
- /**
- * Return the current element
- * @link http://php.net/manual/en/iterator.current.php
- *
- * @return \Box\Spout\Reader\CSV\Sheet
- */
- public function current()
- {
- return $this->sheet;
- }
-
- /**
- * Return the key of the current element
- * @link http://php.net/manual/en/iterator.key.php
- *
- * @return int
- */
- public function key()
- {
- return 1;
- }
-
- /**
- * Cleans up what was created to iterate over the object.
- *
- * @return void
- */
- public function end()
- {
- // do nothing
- }
-}
diff --git a/src/Spout/Reader/Common/ReaderOptions.php b/src/Spout/Reader/Common/ReaderOptions.php
deleted file mode 100644
index 4ab7a07..0000000
--- a/src/Spout/Reader/Common/ReaderOptions.php
+++ /dev/null
@@ -1,58 +0,0 @@
-shouldFormatDates;
- }
-
- /**
- * Sets whether date/time values should be returned as PHP objects or be formatted as strings.
- *
- * @param bool $shouldFormatDates
- * @return ReaderOptions
- */
- public function setShouldFormatDates($shouldFormatDates)
- {
- $this->shouldFormatDates = $shouldFormatDates;
- return $this;
- }
-
- /**
- * @return bool Whether empty rows should be returned or skipped.
- */
- public function shouldPreserveEmptyRows()
- {
- return $this->shouldPreserveEmptyRows;
- }
-
- /**
- * Sets whether empty rows should be returned or skipped.
- *
- * @param bool $shouldPreserveEmptyRows
- * @return ReaderOptions
- */
- public function setShouldPreserveEmptyRows($shouldPreserveEmptyRows)
- {
- $this->shouldPreserveEmptyRows = $shouldPreserveEmptyRows;
- return $this;
- }
-}
diff --git a/src/Spout/Reader/Common/XMLProcessor.php b/src/Spout/Reader/Common/XMLProcessor.php
deleted file mode 100644
index d8a1da8..0000000
--- a/src/Spout/Reader/Common/XMLProcessor.php
+++ /dev/null
@@ -1,152 +0,0 @@
-xmlReader = $xmlReader;
- }
-
- /**
- * @param string $nodeName A callback may be triggered when a node with this name is read
- * @param int $nodeType Type of the node [NODE_TYPE_START || NODE_TYPE_END]
- * @param callable $callback Callback to execute when the read node has the given name and type
- * @return XMLProcessor
- */
- public function registerCallback($nodeName, $nodeType, $callback)
- {
- $callbackKey = $this->getCallbackKey($nodeName, $nodeType);
- $this->callbacks[$callbackKey] = $this->getInvokableCallbackData($callback);
-
- return $this;
- }
-
- /**
- * @param string $nodeName Name of the node
- * @param int $nodeType Type of the node [NODE_TYPE_START || NODE_TYPE_END]
- * @return string Key used to store the associated callback
- */
- private function getCallbackKey($nodeName, $nodeType)
- {
- return "$nodeName$nodeType";
- }
-
- /**
- * Because the callback can be a "protected" function, we don't want to use call_user_func() directly
- * but instead invoke the callback using Reflection. This allows the invocation of "protected" functions.
- * Since some functions can be called a lot, we pre-process the callback to only return the elements that
- * will be needed to invoke the callback later.
- *
- * @param callable $callback Array reference to a callback: [OBJECT, METHOD_NAME]
- * @return array Associative array containing the elements needed to invoke the callback using Reflection
- */
- private function getInvokableCallbackData($callback)
- {
- $callbackObject = $callback[0];
- $callbackMethodName = $callback[1];
- $reflectionMethod = new \ReflectionMethod(get_class($callbackObject), $callbackMethodName);
- $reflectionMethod->setAccessible(true);
-
- return [
- self::CALLBACK_REFLECTION_METHOD => $reflectionMethod,
- self::CALLBACK_REFLECTION_OBJECT => $callbackObject,
- ];
- }
-
- /**
- * Resumes the reading of the XML file where it was left off.
- * Stops whenever a callback indicates that reading should stop or at the end of the file.
- *
- * @return void
- * @throws \Box\Spout\Reader\Exception\XMLProcessingException
- */
- public function readUntilStopped()
- {
- while ($this->xmlReader->read()) {
- $nodeType = $this->xmlReader->nodeType;
- $nodeNamePossiblyWithPrefix = $this->xmlReader->name;
- $nodeNameWithoutPrefix = $this->xmlReader->localName;
-
- $callbackData = $this->getRegisteredCallbackData($nodeNamePossiblyWithPrefix, $nodeNameWithoutPrefix, $nodeType);
-
- if ($callbackData !== null) {
- $callbackResponse = $this->invokeCallback($callbackData, [$this->xmlReader]);
-
- if ($callbackResponse === self::PROCESSING_STOP) {
- // stop reading
- break;
- }
- }
- }
- }
-
- /**
- * @param string $nodeNamePossiblyWithPrefix Name of the node, possibly prefixed
- * @param string $nodeNameWithoutPrefix Name of the same node, un-prefixed
- * @param int $nodeType Type of the node [NODE_TYPE_START || NODE_TYPE_END]
- * @return array|null Callback data to be used for execution when a node of the given name/type is read or NULL if none found
- */
- private function getRegisteredCallbackData($nodeNamePossiblyWithPrefix, $nodeNameWithoutPrefix, $nodeType)
- {
- // With prefixed nodes, we should match if (by order of preference):
- // 1. the callback was registered with the prefixed node name (e.g. "x:worksheet")
- // 2. the callback was registered with the un-prefixed node name (e.g. "worksheet")
- $callbackKeyForPossiblyPrefixedName = $this->getCallbackKey($nodeNamePossiblyWithPrefix, $nodeType);
- $callbackKeyForUnPrefixedName = $this->getCallbackKey($nodeNameWithoutPrefix, $nodeType);
- $hasPrefix = ($nodeNamePossiblyWithPrefix !== $nodeNameWithoutPrefix);
-
- $callbackKeyToUse = $callbackKeyForUnPrefixedName;
- if ($hasPrefix && isset($this->callbacks[$callbackKeyForPossiblyPrefixedName])) {
- $callbackKeyToUse = $callbackKeyForPossiblyPrefixedName;
- }
-
- // Using isset here because it is way faster than array_key_exists...
- return isset($this->callbacks[$callbackKeyToUse]) ? $this->callbacks[$callbackKeyToUse] : null;
- }
-
- /**
- * @param array $callbackData Associative array containing data to invoke the callback using Reflection
- * @param array $args Arguments to pass to the callback
- * @return int Callback response
- */
- private function invokeCallback($callbackData, $args)
- {
- $reflectionMethod = $callbackData[self::CALLBACK_REFLECTION_METHOD];
- $callbackObject = $callbackData[self::CALLBACK_REFLECTION_OBJECT];
-
- return $reflectionMethod->invokeArgs($callbackObject, $args);
- }
-}
diff --git a/src/Spout/Reader/Exception/IteratorNotRewindableException.php b/src/Spout/Reader/Exception/IteratorNotRewindableException.php
deleted file mode 100644
index a030c12..0000000
--- a/src/Spout/Reader/Exception/IteratorNotRewindableException.php
+++ /dev/null
@@ -1,13 +0,0 @@
-shouldFormatDates = $shouldFormatDates;
-
- /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
- $this->escaper = \Box\Spout\Common\Escaper\ODS::getInstance();
- }
-
- /**
- * Returns the (unescaped) correctly marshalled, cell value associated to the given XML node.
- * @see http://docs.oasis-open.org/office/v1.2/os/OpenDocument-v1.2-os-part1.html#refTable13
- *
- * @param \DOMNode $node
- * @return string|int|float|bool|\DateTime|\DateInterval|null The value associated with the cell, empty string if cell's type is void/undefined, null on error
- */
- public function extractAndFormatNodeValue($node)
- {
- $cellType = $node->getAttribute(self::XML_ATTRIBUTE_TYPE);
-
- switch ($cellType) {
- case self::CELL_TYPE_STRING:
- return $this->formatStringCellValue($node);
- case self::CELL_TYPE_FLOAT:
- return $this->formatFloatCellValue($node);
- case self::CELL_TYPE_BOOLEAN:
- return $this->formatBooleanCellValue($node);
- case self::CELL_TYPE_DATE:
- return $this->formatDateCellValue($node);
- case self::CELL_TYPE_TIME:
- return $this->formatTimeCellValue($node);
- case self::CELL_TYPE_CURRENCY:
- return $this->formatCurrencyCellValue($node);
- case self::CELL_TYPE_PERCENTAGE:
- return $this->formatPercentageCellValue($node);
- case self::CELL_TYPE_VOID:
- default:
- return '';
- }
- }
-
- /**
- * Returns the cell String value.
- *
- * @param \DOMNode $node
- * @return string The value associated with the cell
- */
- protected function formatStringCellValue($node)
- {
- $pNodeValues = [];
- $pNodes = $node->getElementsByTagName(self::XML_NODE_P);
-
- foreach ($pNodes as $pNode) {
- $currentPValue = '';
-
- foreach ($pNode->childNodes as $childNode) {
- if ($childNode instanceof \DOMText) {
- $currentPValue .= $childNode->nodeValue;
- } else if ($childNode->nodeName === self::XML_NODE_S) {
- $spaceAttribute = $childNode->getAttribute(self::XML_ATTRIBUTE_C);
- $numSpaces = (!empty($spaceAttribute)) ? intval($spaceAttribute) : 1;
- $currentPValue .= str_repeat(' ', $numSpaces);
- } else if ($childNode->nodeName === self::XML_NODE_A || $childNode->nodeName === self::XML_NODE_SPAN) {
- $currentPValue .= $childNode->nodeValue;
- }
- }
-
- $pNodeValues[] = $currentPValue;
- }
-
- $escapedCellValue = implode("\n", $pNodeValues);
- $cellValue = $this->escaper->unescape($escapedCellValue);
- return $cellValue;
- }
-
- /**
- * Returns the cell Numeric value from the given node.
- *
- * @param \DOMNode $node
- * @return int|float The value associated with the cell
- */
- protected function formatFloatCellValue($node)
- {
- $nodeValue = $node->getAttribute(self::XML_ATTRIBUTE_VALUE);
- $nodeIntValue = intval($nodeValue);
- // The "==" is intentionally not a "===" because only the value matters, not the type
- $cellValue = ($nodeIntValue == $nodeValue) ? $nodeIntValue : floatval($nodeValue);
- return $cellValue;
- }
-
- /**
- * Returns the cell Boolean value from the given node.
- *
- * @param \DOMNode $node
- * @return bool The value associated with the cell
- */
- protected function formatBooleanCellValue($node)
- {
- $nodeValue = $node->getAttribute(self::XML_ATTRIBUTE_BOOLEAN_VALUE);
- // !! is similar to boolval()
- $cellValue = !!$nodeValue;
- return $cellValue;
- }
-
- /**
- * Returns the cell Date value from the given node.
- *
- * @param \DOMNode $node
- * @return \DateTime|string|null The value associated with the cell or NULL if invalid date value
- */
- protected function formatDateCellValue($node)
- {
- // The XML node looks like this:
- //
- // 05/19/16 04:39 PM
- //
-
- if ($this->shouldFormatDates) {
- // The date is already formatted in the "p" tag
- $nodeWithValueAlreadyFormatted = $node->getElementsByTagName(self::XML_NODE_P)->item(0);
- return $nodeWithValueAlreadyFormatted->nodeValue;
- } else {
- // otherwise, get it from the "date-value" attribute
- try {
- $nodeValue = $node->getAttribute(self::XML_ATTRIBUTE_DATE_VALUE);
- return new \DateTime($nodeValue);
- } catch (\Exception $e) {
- return null;
- }
- }
- }
-
- /**
- * Returns the cell Time value from the given node.
- *
- * @param \DOMNode $node
- * @return \DateInterval|string|null The value associated with the cell or NULL if invalid time value
- */
- protected function formatTimeCellValue($node)
- {
- // The XML node looks like this:
- //
- // 01:24:00 PM
- //
-
- if ($this->shouldFormatDates) {
- // The date is already formatted in the "p" tag
- $nodeWithValueAlreadyFormatted = $node->getElementsByTagName(self::XML_NODE_P)->item(0);
- return $nodeWithValueAlreadyFormatted->nodeValue;
- } else {
- // otherwise, get it from the "time-value" attribute
- try {
- $nodeValue = $node->getAttribute(self::XML_ATTRIBUTE_TIME_VALUE);
- return new \DateInterval($nodeValue);
- } catch (\Exception $e) {
- return null;
- }
- }
- }
-
- /**
- * Returns the cell Currency value from the given node.
- *
- * @param \DOMNode $node
- * @return string The value associated with the cell (e.g. "100 USD" or "9.99 EUR")
- */
- protected function formatCurrencyCellValue($node)
- {
- $value = $node->getAttribute(self::XML_ATTRIBUTE_VALUE);
- $currency = $node->getAttribute(self::XML_ATTRIBUTE_CURRENCY);
-
- return "$value $currency";
- }
-
- /**
- * Returns the cell Percentage value from the given node.
- *
- * @param \DOMNode $node
- * @return int|float The value associated with the cell
- */
- protected function formatPercentageCellValue($node)
- {
- // percentages are formatted like floats
- return $this->formatFloatCellValue($node);
- }
-}
diff --git a/src/Spout/Reader/ODS/Helper/SettingsHelper.php b/src/Spout/Reader/ODS/Helper/SettingsHelper.php
deleted file mode 100644
index a5388ef..0000000
--- a/src/Spout/Reader/ODS/Helper/SettingsHelper.php
+++ /dev/null
@@ -1,51 +0,0 @@
-openFileInZip($filePath, self::SETTINGS_XML_FILE_PATH) === false) {
- return null;
- }
-
- $activeSheetName = null;
-
- try {
- while ($xmlReader->readUntilNodeFound(self::XML_NODE_CONFIG_ITEM)) {
- if ($xmlReader->getAttribute(self::XML_ATTRIBUTE_CONFIG_NAME) === self::XML_ATTRIBUTE_VALUE_ACTIVE_TABLE) {
- $activeSheetName = $xmlReader->readString();
- break;
- }
- }
- } catch (XMLProcessingException $exception) {
- // do nothing
- }
-
- $xmlReader->close();
-
- return $activeSheetName;
- }
-}
diff --git a/src/Spout/Reader/ODS/Reader.php b/src/Spout/Reader/ODS/Reader.php
deleted file mode 100644
index dbdc47b..0000000
--- a/src/Spout/Reader/ODS/Reader.php
+++ /dev/null
@@ -1,85 +0,0 @@
-options)) {
- $this->options = new ReaderOptions();
- }
- return $this->options;
- }
-
- /**
- * Returns whether stream wrappers are supported
- *
- * @return bool
- */
- protected function doesSupportStreamWrapper()
- {
- return false;
- }
-
- /**
- * Opens the file at the given file path to make it ready to be read.
- *
- * @param string $filePath Path of the file to be read
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If the file at the given path or its content cannot be read
- * @throws \Box\Spout\Reader\Exception\NoSheetsFoundException If there are no sheets in the file
- */
- protected function openReader($filePath)
- {
- $this->zip = new \ZipArchive();
-
- if ($this->zip->open($filePath) === true) {
- $this->sheetIterator = new SheetIterator($filePath, $this->getOptions());
- } else {
- throw new IOException("Could not open $filePath for reading.");
- }
- }
-
- /**
- * Returns an iterator to iterate over sheets.
- *
- * @return SheetIterator To iterate over sheets
- */
- protected function getConcreteSheetIterator()
- {
- return $this->sheetIterator;
- }
-
- /**
- * Closes the reader. To be used after reading the file.
- *
- * @return void
- */
- protected function closeReader()
- {
- if ($this->zip) {
- $this->zip->close();
- }
- }
-}
diff --git a/src/Spout/Reader/ODS/ReaderOptions.php b/src/Spout/Reader/ODS/ReaderOptions.php
deleted file mode 100644
index 2d29640..0000000
--- a/src/Spout/Reader/ODS/ReaderOptions.php
+++ /dev/null
@@ -1,14 +0,0 @@
-" element
- * @param \Box\Spout\Reader\ODS\ReaderOptions $options Reader's current options
- */
- public function __construct($xmlReader, $options)
- {
- $this->xmlReader = $xmlReader;
- $this->shouldPreserveEmptyRows = $options->shouldPreserveEmptyRows();
- $this->cellValueFormatter = new CellValueFormatter($options->shouldFormatDates());
-
- // Register all callbacks to process different nodes when reading the XML file
- $this->xmlProcessor = new XMLProcessor($this->xmlReader);
- $this->xmlProcessor->registerCallback(self::XML_NODE_ROW, XMLProcessor::NODE_TYPE_START, [$this, 'processRowStartingNode']);
- $this->xmlProcessor->registerCallback(self::XML_NODE_CELL, XMLProcessor::NODE_TYPE_START, [$this, 'processCellStartingNode']);
- $this->xmlProcessor->registerCallback(self::XML_NODE_ROW, XMLProcessor::NODE_TYPE_END, [$this, 'processRowEndingNode']);
- $this->xmlProcessor->registerCallback(self::XML_NODE_TABLE, XMLProcessor::NODE_TYPE_END, [$this, 'processTableEndingNode']);
- }
-
- /**
- * Rewind the Iterator to the first element.
- * NOTE: It can only be done once, as it is not possible to read an XML file backwards.
- * @link http://php.net/manual/en/iterator.rewind.php
- *
- * @return void
- * @throws \Box\Spout\Reader\Exception\IteratorNotRewindableException If the iterator is rewound more than once
- */
- public function rewind()
- {
- // Because sheet and row data is located in the file, we can't rewind both the
- // sheet iterator and the row iterator, as XML file cannot be read backwards.
- // Therefore, rewinding the row iterator has been disabled.
- if ($this->hasAlreadyBeenRewound) {
- throw new IteratorNotRewindableException();
- }
-
- $this->hasAlreadyBeenRewound = true;
- $this->lastRowIndexProcessed = 0;
- $this->nextRowIndexToBeProcessed = 1;
- $this->rowDataBuffer = null;
- $this->hasReachedEndOfFile = false;
-
- $this->next();
- }
-
- /**
- * Checks if current position is valid
- * @link http://php.net/manual/en/iterator.valid.php
- *
- * @return bool
- */
- public function valid()
- {
- return (!$this->hasReachedEndOfFile);
- }
-
- /**
- * Move forward to next element. Empty rows will be skipped.
- * @link http://php.net/manual/en/iterator.next.php
- *
- * @return void
- * @throws \Box\Spout\Reader\Exception\SharedStringNotFoundException If a shared string was not found
- * @throws \Box\Spout\Common\Exception\IOException If unable to read the sheet data XML
- */
- public function next()
- {
- if ($this->doesNeedDataForNextRowToBeProcessed()) {
- $this->readDataForNextRow();
- }
-
- $this->lastRowIndexProcessed++;
- }
-
- /**
- * Returns whether we need data for the next row to be processed.
- * We DO need to read data if:
- * - we have not read any rows yet
- * OR
- * - the next row to be processed immediately follows the last read row
- *
- * @return bool Whether we need data for the next row to be processed.
- */
- protected function doesNeedDataForNextRowToBeProcessed()
- {
- $hasReadAtLeastOneRow = ($this->lastRowIndexProcessed !== 0);
-
- return (
- !$hasReadAtLeastOneRow ||
- $this->lastRowIndexProcessed === $this->nextRowIndexToBeProcessed - 1
- );
- }
-
- /**
- * @return void
- * @throws \Box\Spout\Reader\Exception\SharedStringNotFoundException If a shared string was not found
- * @throws \Box\Spout\Common\Exception\IOException If unable to read the sheet data XML
- */
- protected function readDataForNextRow()
- {
- $this->currentlyProcessedRowData = [];
-
- try {
- $this->xmlProcessor->readUntilStopped();
- } catch (XMLProcessingException $exception) {
- throw new IOException("The sheet's data cannot be read. [{$exception->getMessage()}]");
- }
-
- $this->rowDataBuffer = $this->currentlyProcessedRowData;
- }
-
- /**
- * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XMLReader object, positioned on a "" starting node
- * @return int A return code that indicates what action should the processor take next
- */
- protected function processRowStartingNode($xmlReader)
- {
- // Reset data from current row
- $this->hasAlreadyReadOneCellInCurrentRow = false;
- $this->lastProcessedCellValue = null;
- $this->numColumnsRepeated = 1;
- $this->numRowsRepeated = $this->getNumRowsRepeatedForCurrentNode($xmlReader);
-
- return XMLProcessor::PROCESSING_CONTINUE;
- }
-
- /**
- * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XMLReader object, positioned on a "" starting node
- * @return int A return code that indicates what action should the processor take next
- */
- protected function processCellStartingNode($xmlReader)
- {
- $currentNumColumnsRepeated = $this->getNumColumnsRepeatedForCurrentNode($xmlReader);
-
- // NOTE: expand() will automatically decode all XML entities of the child nodes
- $node = $xmlReader->expand();
- $currentCellValue = $this->getCellValue($node);
-
- // process cell N only after having read cell N+1 (see below why)
- if ($this->hasAlreadyReadOneCellInCurrentRow) {
- for ($i = 0; $i < $this->numColumnsRepeated; $i++) {
- $this->currentlyProcessedRowData[] = $this->lastProcessedCellValue;
- }
- }
-
- $this->hasAlreadyReadOneCellInCurrentRow = true;
- $this->lastProcessedCellValue = $currentCellValue;
- $this->numColumnsRepeated = $currentNumColumnsRepeated;
-
- return XMLProcessor::PROCESSING_CONTINUE;
- }
-
- /**
- * @return int A return code that indicates what action should the processor take next
- */
- protected function processRowEndingNode()
- {
- $isEmptyRow = $this->isEmptyRow($this->currentlyProcessedRowData, $this->lastProcessedCellValue);
-
- // if the fetched row is empty and we don't want to preserve it...
- if (!$this->shouldPreserveEmptyRows && $isEmptyRow) {
- // ... skip it
- return XMLProcessor::PROCESSING_CONTINUE;
- }
-
- // if the row is empty, we don't want to return more than one cell
- $actualNumColumnsRepeated = (!$isEmptyRow) ? $this->numColumnsRepeated : 1;
-
- // Only add the value if the last read cell is not a trailing empty cell repeater in Excel.
- // The current count of read columns is determined by counting the values in "$this->currentlyProcessedRowData".
- // This is to avoid creating a lot of empty cells, as Excel adds a last empty ""
- // with a number-columns-repeated value equals to the number of (supported columns - used columns).
- // In Excel, the number of supported columns is 16384, but we don't want to returns rows with
- // always 16384 cells.
- if ((count($this->currentlyProcessedRowData) + $actualNumColumnsRepeated) !== self::MAX_COLUMNS_EXCEL) {
- for ($i = 0; $i < $actualNumColumnsRepeated; $i++) {
- $this->currentlyProcessedRowData[] = $this->lastProcessedCellValue;
- }
- }
-
- // If we are processing row N and the row is repeated M times,
- // then the next row to be processed will be row (N+M).
- $this->nextRowIndexToBeProcessed += $this->numRowsRepeated;
-
- // at this point, we have all the data we need for the row
- // so that we can populate the buffer
- return XMLProcessor::PROCESSING_STOP;
- }
-
- /**
- * @return int A return code that indicates what action should the processor take next
- */
- protected function processTableEndingNode()
- {
- // The closing "" marks the end of the file
- $this->hasReachedEndOfFile = true;
-
- return XMLProcessor::PROCESSING_STOP;
- }
-
- /**
- * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XMLReader object, positioned on a "" starting node
- * @return int The value of "table:number-rows-repeated" attribute of the current node, or 1 if attribute missing
- */
- protected function getNumRowsRepeatedForCurrentNode($xmlReader)
- {
- $numRowsRepeated = $xmlReader->getAttribute(self::XML_ATTRIBUTE_NUM_ROWS_REPEATED);
- return ($numRowsRepeated !== null) ? intval($numRowsRepeated) : 1;
- }
-
- /**
- * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XMLReader object, positioned on a "" starting node
- * @return int The value of "table:number-columns-repeated" attribute of the current node, or 1 if attribute missing
- */
- protected function getNumColumnsRepeatedForCurrentNode($xmlReader)
- {
- $numColumnsRepeated = $xmlReader->getAttribute(self::XML_ATTRIBUTE_NUM_COLUMNS_REPEATED);
- return ($numColumnsRepeated !== null) ? intval($numColumnsRepeated) : 1;
- }
-
- /**
- * Returns the (unescaped) correctly marshalled, cell value associated to the given XML node.
- *
- * @param \DOMNode $node
- * @return string|int|float|bool|\DateTime|\DateInterval|null The value associated with the cell, empty string if cell's type is void/undefined, null on error
- */
- protected function getCellValue($node)
- {
- return $this->cellValueFormatter->extractAndFormatNodeValue($node);
- }
-
- /**
- * After finishing processing each cell, a row is considered empty if it contains
- * no cells or if the value of the last read cell is an empty string.
- * After finishing processing each cell, the last read cell is not part of the
- * row data yet (as we still need to apply the "num-columns-repeated" attribute).
- *
- * @param array $rowData
- * @param string|int|float|bool|\DateTime|\DateInterval|null The value of the last read cell
- * @return bool Whether the row is empty
- */
- protected function isEmptyRow($rowData, $lastReadCellValue)
- {
- return (
- count($rowData) === 0 &&
- (!isset($lastReadCellValue) || trim($lastReadCellValue) === '')
- );
- }
-
- /**
- * Return the current element, from the buffer.
- * @link http://php.net/manual/en/iterator.current.php
- *
- * @return array|null
- */
- public function current()
- {
- return $this->rowDataBuffer;
- }
-
- /**
- * Return the key of the current element
- * @link http://php.net/manual/en/iterator.key.php
- *
- * @return int
- */
- public function key()
- {
- return $this->lastRowIndexProcessed;
- }
-
-
- /**
- * Cleans up what was created to iterate over the object.
- *
- * @return void
- */
- public function end()
- {
- $this->xmlReader->close();
- }
-}
diff --git a/src/Spout/Reader/ODS/Sheet.php b/src/Spout/Reader/ODS/Sheet.php
deleted file mode 100644
index 794ad3a..0000000
--- a/src/Spout/Reader/ODS/Sheet.php
+++ /dev/null
@@ -1,81 +0,0 @@
-" element
- * @param int $sheetIndex Index of the sheet, based on order in the workbook (zero-based)
- * @param string $sheetName Name of the sheet
- * @param bool $isSheetActive Whether the sheet was defined as active
- * @param \Box\Spout\Reader\ODS\ReaderOptions $options Reader's current options
- */
- public function __construct($xmlReader, $sheetIndex, $sheetName, $isSheetActive, $options)
- {
- $this->rowIterator = new RowIterator($xmlReader, $options);
- $this->index = $sheetIndex;
- $this->name = $sheetName;
- $this->isActive = $isSheetActive;
- }
-
- /**
- * @api
- * @return \Box\Spout\Reader\ODS\RowIterator
- */
- public function getRowIterator()
- {
- return $this->rowIterator;
- }
-
- /**
- * @api
- * @return int Index of the sheet, based on order in the workbook (zero-based)
- */
- public function getIndex()
- {
- return $this->index;
- }
-
- /**
- * @api
- * @return string Name of the sheet
- */
- public function getName()
- {
- return $this->name;
- }
-
- /**
- * @api
- * @return bool Whether the sheet was defined as active
- */
- public function isActive()
- {
- return $this->isActive;
- }
-}
diff --git a/src/Spout/Reader/ODS/SheetIterator.php b/src/Spout/Reader/ODS/SheetIterator.php
deleted file mode 100644
index 995c136..0000000
--- a/src/Spout/Reader/ODS/SheetIterator.php
+++ /dev/null
@@ -1,168 +0,0 @@
-filePath = $filePath;
- $this->options = $options;
- $this->xmlReader = new XMLReader();
-
- /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
- $this->escaper = \Box\Spout\Common\Escaper\ODS::getInstance();
-
- $settingsHelper = new SettingsHelper();
- $this->activeSheetName = $settingsHelper->getActiveSheetName($filePath);
- }
-
- /**
- * Rewind the Iterator to the first element
- * @link http://php.net/manual/en/iterator.rewind.php
- *
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If unable to open the XML file containing sheets' data
- */
- public function rewind()
- {
- $this->xmlReader->close();
-
- if ($this->xmlReader->openFileInZip($this->filePath, self::CONTENT_XML_FILE_PATH) === false) {
- $contentXmlFilePath = $this->filePath . '#' . self::CONTENT_XML_FILE_PATH;
- throw new IOException("Could not open \"{$contentXmlFilePath}\".");
- }
-
- try {
- $this->hasFoundSheet = $this->xmlReader->readUntilNodeFound(self::XML_NODE_TABLE);
- } catch (XMLProcessingException $exception) {
- throw new IOException("The content.xml file is invalid and cannot be read. [{$exception->getMessage()}]");
- }
-
- $this->currentSheetIndex = 0;
- }
-
- /**
- * Checks if current position is valid
- * @link http://php.net/manual/en/iterator.valid.php
- *
- * @return bool
- */
- public function valid()
- {
- return $this->hasFoundSheet;
- }
-
- /**
- * Move forward to next element
- * @link http://php.net/manual/en/iterator.next.php
- *
- * @return void
- */
- public function next()
- {
- $this->hasFoundSheet = $this->xmlReader->readUntilNodeFound(self::XML_NODE_TABLE);
-
- if ($this->hasFoundSheet) {
- $this->currentSheetIndex++;
- }
- }
-
- /**
- * Return the current element
- * @link http://php.net/manual/en/iterator.current.php
- *
- * @return \Box\Spout\Reader\ODS\Sheet
- */
- public function current()
- {
- $escapedSheetName = $this->xmlReader->getAttribute(self::XML_ATTRIBUTE_TABLE_NAME);
- $sheetName = $this->escaper->unescape($escapedSheetName);
- $isActiveSheet = $this->isActiveSheet($sheetName, $this->currentSheetIndex, $this->activeSheetName);
-
- return new Sheet($this->xmlReader, $this->currentSheetIndex, $sheetName, $isActiveSheet, $this->options);
- }
-
- /**
- * Returns whether the current sheet was defined as the active one
- *
- * @param string $sheetName Name of the current sheet
- * @param int $sheetIndex Index of the current sheet
- * @param string|null Name of the sheet that was defined as active or NULL if none defined
- * @return bool Whether the current sheet was defined as the active one
- */
- private function isActiveSheet($sheetName, $sheetIndex, $activeSheetName)
- {
- // The given sheet is active if its name matches the defined active sheet's name
- // or if no information about the active sheet was found, it defaults to the first sheet.
- return (
- ($activeSheetName === null && $sheetIndex === 0) ||
- ($activeSheetName === $sheetName)
- );
- }
-
- /**
- * Return the key of the current element
- * @link http://php.net/manual/en/iterator.key.php
- *
- * @return int
- */
- public function key()
- {
- return $this->currentSheetIndex + 1;
- }
-
- /**
- * Cleans up what was created to iterate over the object.
- *
- * @return void
- */
- public function end()
- {
- $this->xmlReader->close();
- }
-}
diff --git a/src/Spout/Reader/ReaderFactory.php b/src/Spout/Reader/ReaderFactory.php
deleted file mode 100644
index 93a52cb..0000000
--- a/src/Spout/Reader/ReaderFactory.php
+++ /dev/null
@@ -1,48 +0,0 @@
-setGlobalFunctionsHelper(new GlobalFunctionsHelper());
-
- return $reader;
- }
-}
diff --git a/src/Spout/Reader/ReaderInterface.php b/src/Spout/Reader/ReaderInterface.php
deleted file mode 100644
index 8ecde30..0000000
--- a/src/Spout/Reader/ReaderInterface.php
+++ /dev/null
@@ -1,36 +0,0 @@
-initialUseInternalErrorsValue = libxml_use_internal_errors(true);
- }
-
- /**
- * Throws an XMLProcessingException if an error occured.
- * It also always resets the "libxml_use_internal_errors" setting back to its initial value.
- *
- * @return void
- * @throws \Box\Spout\Reader\Exception\XMLProcessingException
- */
- protected function resetXMLInternalErrorsSettingAndThrowIfXMLErrorOccured()
- {
- if ($this->hasXMLErrorOccured()) {
- $this->resetXMLInternalErrorsSetting();
- throw new XMLProcessingException($this->getLastXMLErrorMessage());
- }
-
- $this->resetXMLInternalErrorsSetting();
- }
-
- /**
- * Returns whether the a XML error has occured since the last time errors were cleared.
- *
- * @return bool TRUE if an error occured, FALSE otherwise
- */
- private function hasXMLErrorOccured()
- {
- return (libxml_get_last_error() !== false);
- }
-
- /**
- * Returns the error message for the last XML error that occured.
- * @see libxml_get_last_error
- *
- * @return String|null Last XML error message or null if no error
- */
- private function getLastXMLErrorMessage()
- {
- $errorMessage = null;
- $error = libxml_get_last_error();
-
- if ($error !== false) {
- $errorMessage = trim($error->message);
- }
-
- return $errorMessage;
- }
-
- /**
- * @return void
- */
- protected function resetXMLInternalErrorsSetting()
- {
- libxml_use_internal_errors($this->initialUseInternalErrorsValue);
- }
-
-}
diff --git a/src/Spout/Reader/Wrapper/XMLReader.php b/src/Spout/Reader/Wrapper/XMLReader.php
deleted file mode 100644
index 2e20327..0000000
--- a/src/Spout/Reader/Wrapper/XMLReader.php
+++ /dev/null
@@ -1,167 +0,0 @@
-getRealPathURIForFileInZip($zipFilePath, $fileInsideZipPath);
-
- // We need to check first that the file we are trying to read really exist because:
- // - PHP emits a warning when trying to open a file that does not exist.
- // - HHVM does not check if file exists within zip file (@link https://github.com/facebook/hhvm/issues/5779)
- if ($this->fileExistsWithinZip($realPathURI)) {
- $wasOpenSuccessful = $this->open($realPathURI, null, LIBXML_NONET);
- }
-
- return $wasOpenSuccessful;
- }
-
- /**
- * Returns the real path for the given path components.
- * This is useful to avoid issues on some Windows setup.
- *
- * @param string $zipFilePath Path to the ZIP file
- * @param string $fileInsideZipPath Relative or absolute path of the file inside the zip
- * @return string The real path URI
- */
- public function getRealPathURIForFileInZip($zipFilePath, $fileInsideZipPath)
- {
- return (self::ZIP_WRAPPER . realpath($zipFilePath) . '#' . $fileInsideZipPath);
- }
-
- /**
- * Returns whether the file at the given location exists
- *
- * @param string $zipStreamURI URI of a zip stream, e.g. "zip://file.zip#path/inside.xml"
- * @return bool TRUE if the file exists, FALSE otherwise
- */
- protected function fileExistsWithinZip($zipStreamURI)
- {
- $doesFileExists = false;
-
- $pattern = '/zip:\/\/([^#]+)#(.*)/';
- if (preg_match($pattern, $zipStreamURI, $matches)) {
- $zipFilePath = $matches[1];
- $innerFilePath = $matches[2];
-
- $zip = new \ZipArchive();
- if ($zip->open($zipFilePath) === true) {
- $doesFileExists = ($zip->locateName($innerFilePath) !== false);
- $zip->close();
- }
- }
-
- return $doesFileExists;
- }
-
- /**
- * Move to next node in document
- * @see \XMLReader::read
- *
- * @return bool TRUE on success or FALSE on failure
- * @throws \Box\Spout\Reader\Exception\XMLProcessingException If an error/warning occurred
- */
- public function read()
- {
- $this->useXMLInternalErrors();
-
- $wasReadSuccessful = parent::read();
-
- $this->resetXMLInternalErrorsSettingAndThrowIfXMLErrorOccured();
-
- return $wasReadSuccessful;
- }
-
- /**
- * Read until the element with the given name is found, or the end of the file.
- *
- * @param string $nodeName Name of the node to find
- * @return bool TRUE on success or FALSE on failure
- * @throws \Box\Spout\Reader\Exception\XMLProcessingException If an error/warning occurred
- */
- public function readUntilNodeFound($nodeName)
- {
- do {
- $wasReadSuccessful = $this->read();
- $isNotPositionedOnStartingNode = !$this->isPositionedOnStartingNode($nodeName);
- } while ($wasReadSuccessful && $isNotPositionedOnStartingNode);
-
- return $wasReadSuccessful;
- }
-
- /**
- * Move cursor to next node skipping all subtrees
- * @see \XMLReader::next
- *
- * @param string|void $localName The name of the next node to move to
- * @return bool TRUE on success or FALSE on failure
- * @throws \Box\Spout\Reader\Exception\XMLProcessingException If an error/warning occurred
- */
- public function next($localName = null)
- {
- $this->useXMLInternalErrors();
-
- $wasNextSuccessful = parent::next($localName);
-
- $this->resetXMLInternalErrorsSettingAndThrowIfXMLErrorOccured();
-
- return $wasNextSuccessful;
- }
-
- /**
- * @param string $nodeName
- * @return bool Whether the XML Reader is currently positioned on the starting node with given name
- */
- public function isPositionedOnStartingNode($nodeName)
- {
- return $this->isPositionedOnNode($nodeName, XMLReader::ELEMENT);
- }
-
- /**
- * @param string $nodeName
- * @return bool Whether the XML Reader is currently positioned on the ending node with given name
- */
- public function isPositionedOnEndingNode($nodeName)
- {
- return $this->isPositionedOnNode($nodeName, XMLReader::END_ELEMENT);
- }
-
- /**
- * @param string $nodeName
- * @param int $nodeType
- * @return bool Whether the XML Reader is currently positioned on the node with given name and type
- */
- private function isPositionedOnNode($nodeName, $nodeType)
- {
- // In some cases, the node has a prefix (for instance, "" can also be "").
- // So if the given node name does not have a prefix, we need to look at the unprefixed name ("localName").
- // @see https://github.com/box/spout/issues/233
- $hasPrefix = (strpos($nodeName, ':') !== false);
- $currentNodeName = ($hasPrefix) ? $this->name : $this->localName;
-
- return ($this->nodeType === $nodeType && $currentNodeName === $nodeName);
- }
-}
diff --git a/src/Spout/Reader/XLSX/Helper/CellHelper.php b/src/Spout/Reader/XLSX/Helper/CellHelper.php
deleted file mode 100644
index 6077839..0000000
--- a/src/Spout/Reader/XLSX/Helper/CellHelper.php
+++ /dev/null
@@ -1,106 +0,0 @@
- 0, 'B' => 1, 'C' => 2, 'D' => 3, 'E' => 4, 'F' => 5, 'G' => 6,
- 'H' => 7, 'I' => 8, 'J' => 9, 'K' => 10, 'L' => 11, 'M' => 12, 'N' => 13,
- 'O' => 14, 'P' => 15, 'Q' => 16, 'R' => 17, 'S' => 18, 'T' => 19, 'U' => 20,
- 'V' => 21, 'W' => 22, 'X' => 23, 'Y' => 24, 'Z' => 25,
- ];
-
- /**
- * Fills the missing indexes of an array with a given value.
- * For instance, $dataArray = []; $a[1] = 1; $a[3] = 3;
- * Calling fillMissingArrayIndexes($dataArray, 'FILL') will return this array: ['FILL', 1, 'FILL', 3]
- *
- * @param array $dataArray The array to fill
- * @param string|void $fillValue optional
- * @return array
- */
- public static function fillMissingArrayIndexes($dataArray, $fillValue = '')
- {
- if (empty($dataArray)) {
- return [];
- }
- $existingIndexes = array_keys($dataArray);
-
- $newIndexes = array_fill_keys(range(0, max($existingIndexes)), $fillValue);
- $dataArray += $newIndexes;
-
- ksort($dataArray);
-
- return $dataArray;
- }
-
- /**
- * Returns the base 10 column index associated to the cell index (base 26).
- * Excel uses A to Z letters for column indexing, where A is the 1st column,
- * Z is the 26th and AA is the 27th.
- * The mapping is zero based, so that A1 maps to 0, B2 maps to 1, Z13 to 25 and AA4 to 26.
- *
- * @param string $cellIndex The Excel cell index ('A1', 'BC13', ...)
- * @return int
- * @throws \Box\Spout\Common\Exception\InvalidArgumentException When the given cell index is invalid
- */
- public static function getColumnIndexFromCellIndex($cellIndex)
- {
- if (!self::isValidCellIndex($cellIndex)) {
- throw new InvalidArgumentException('Cannot get column index from an invalid cell index.');
- }
-
- $columnIndex = 0;
-
- // Remove row information
- $columnLetters = preg_replace('/\d/', '', $cellIndex);
-
- // strlen() is super slow too... Using isset() is way faster and not too unreadable,
- // since we checked before that there are between 1 and 3 letters.
- $columnLength = isset($columnLetters[1]) ? (isset($columnLetters[2]) ? 3 : 2) : 1;
-
- // Looping over the different letters of the column is slower than this method.
- // Also, not using the pow() function because it's slooooow...
- switch ($columnLength) {
- case 1:
- $columnIndex = (self::$columnLetterToIndexMapping[$columnLetters]);
- break;
- case 2:
- $firstLetterIndex = (self::$columnLetterToIndexMapping[$columnLetters[0]] + 1) * 26;
- $secondLetterIndex = self::$columnLetterToIndexMapping[$columnLetters[1]];
- $columnIndex = $firstLetterIndex + $secondLetterIndex;
- break;
- case 3:
- $firstLetterIndex = (self::$columnLetterToIndexMapping[$columnLetters[0]] + 1) * 676;
- $secondLetterIndex = (self::$columnLetterToIndexMapping[$columnLetters[1]] + 1) * 26;
- $thirdLetterIndex = self::$columnLetterToIndexMapping[$columnLetters[2]];
- $columnIndex = $firstLetterIndex + $secondLetterIndex + $thirdLetterIndex;
- break;
- }
-
- return $columnIndex;
- }
-
- /**
- * Returns whether a cell index is valid, in an Excel world.
- * To be valid, the cell index should start with capital letters and be followed by numbers.
- * There can only be 3 letters, as there can only be 16,384 rows, which is equivalent to 'XFE'.
- *
- * @param string $cellIndex The Excel cell index ('A1', 'BC13', ...)
- * @return bool
- */
- protected static function isValidCellIndex($cellIndex)
- {
- return (preg_match('/^[A-Z]{1,3}\d+$/', $cellIndex) === 1);
- }
-}
diff --git a/src/Spout/Reader/XLSX/Helper/CellValueFormatter.php b/src/Spout/Reader/XLSX/Helper/CellValueFormatter.php
deleted file mode 100644
index b4c6256..0000000
--- a/src/Spout/Reader/XLSX/Helper/CellValueFormatter.php
+++ /dev/null
@@ -1,300 +0,0 @@
-sharedStringsHelper = $sharedStringsHelper;
- $this->styleHelper = $styleHelper;
- $this->shouldFormatDates = $shouldFormatDates;
-
- /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
- $this->escaper = \Box\Spout\Common\Escaper\XLSX::getInstance();
- }
-
- /**
- * Returns the (unescaped) correctly marshalled, cell value associated to the given XML node.
- *
- * @param \DOMNode $node
- * @return string|int|float|bool|\DateTime|null The value associated with the cell (null when the cell has an error)
- */
- public function extractAndFormatNodeValue($node)
- {
- // Default cell type is "n"
- $cellType = $node->getAttribute(self::XML_ATTRIBUTE_TYPE) ?: self::CELL_TYPE_NUMERIC;
- $cellStyleId = intval($node->getAttribute(self::XML_ATTRIBUTE_STYLE_ID));
- $vNodeValue = $this->getVNodeValue($node);
-
- if (($vNodeValue === '') && ($cellType !== self::CELL_TYPE_INLINE_STRING)) {
- return $vNodeValue;
- }
-
- switch ($cellType) {
- case self::CELL_TYPE_INLINE_STRING:
- return $this->formatInlineStringCellValue($node);
- case self::CELL_TYPE_SHARED_STRING:
- return $this->formatSharedStringCellValue($vNodeValue);
- case self::CELL_TYPE_STR:
- return $this->formatStrCellValue($vNodeValue);
- case self::CELL_TYPE_BOOLEAN:
- return $this->formatBooleanCellValue($vNodeValue);
- case self::CELL_TYPE_NUMERIC:
- return $this->formatNumericCellValue($vNodeValue, $cellStyleId);
- case self::CELL_TYPE_DATE:
- return $this->formatDateCellValue($vNodeValue);
- default:
- return null;
- }
- }
-
- /**
- * Returns the cell's string value from a node's nested value node
- *
- * @param \DOMNode $node
- * @return string The value associated with the cell
- */
- protected function getVNodeValue($node)
- {
- // for cell types having a "v" tag containing the value.
- // if not, the returned value should be empty string.
- $vNode = $node->getElementsByTagName(self::XML_NODE_VALUE)->item(0);
- return ($vNode !== null) ? $vNode->nodeValue : '';
- }
-
- /**
- * Returns the cell String value where string is inline.
- *
- * @param \DOMNode $node
- * @return string The value associated with the cell (null when the cell has an error)
- */
- protected function formatInlineStringCellValue($node)
- {
- // inline strings are formatted this way:
- // [INLINE_STRING]
- $tNode = $node->getElementsByTagName(self::XML_NODE_INLINE_STRING_VALUE)->item(0);
- $cellValue = $this->escaper->unescape($tNode->nodeValue);
- return $cellValue;
- }
-
- /**
- * Returns the cell String value from shared-strings file using nodeValue index.
- *
- * @param string $nodeValue
- * @return string The value associated with the cell (null when the cell has an error)
- */
- protected function formatSharedStringCellValue($nodeValue)
- {
- // shared strings are formatted this way:
- // [SHARED_STRING_INDEX]
- $sharedStringIndex = intval($nodeValue);
- $escapedCellValue = $this->sharedStringsHelper->getStringAtIndex($sharedStringIndex);
- $cellValue = $this->escaper->unescape($escapedCellValue);
- return $cellValue;
- }
-
- /**
- * Returns the cell String value, where string is stored in value node.
- *
- * @param string $nodeValue
- * @return string The value associated with the cell (null when the cell has an error)
- */
- protected function formatStrCellValue($nodeValue)
- {
- $escapedCellValue = trim($nodeValue);
- $cellValue = $this->escaper->unescape($escapedCellValue);
- return $cellValue;
- }
-
- /**
- * Returns the cell Numeric value from string of nodeValue.
- * The value can also represent a timestamp and a DateTime will be returned.
- *
- * @param string $nodeValue
- * @param int $cellStyleId 0 being the default style
- * @return int|float|\DateTime|null The value associated with the cell
- */
- protected function formatNumericCellValue($nodeValue, $cellStyleId)
- {
- // Numeric values can represent numbers as well as timestamps.
- // We need to look at the style of the cell to determine whether it is one or the other.
- $shouldFormatAsDate = $this->styleHelper->shouldFormatNumericValueAsDate($cellStyleId);
-
- if ($shouldFormatAsDate) {
- return $this->formatExcelTimestampValue(floatval($nodeValue), $cellStyleId);
- } else {
- $nodeIntValue = intval($nodeValue);
- return ($nodeIntValue == $nodeValue) ? $nodeIntValue : floatval($nodeValue);
- }
- }
-
- /**
- * Returns a cell's PHP Date value, associated to the given timestamp.
- * NOTE: The timestamp is a float representing the number of days since January 1st, 1900.
- * NOTE: The timestamp can also represent a time, if it is a value between 0 and 1.
- *
- * @param float $nodeValue
- * @param int $cellStyleId 0 being the default style
- * @return \DateTime|null The value associated with the cell or NULL if invalid date value
- */
- protected function formatExcelTimestampValue($nodeValue, $cellStyleId)
- {
- // Fix for the erroneous leap year in Excel
- if (ceil($nodeValue) > self::ERRONEOUS_EXCEL_LEAP_YEAR_DAY) {
- --$nodeValue;
- }
-
- if ($nodeValue >= 1) {
- // Values greater than 1 represent "dates". The value 1.0 representing the "base" date: 1900-01-01.
- return $this->formatExcelTimestampValueAsDateValue($nodeValue, $cellStyleId);
- } else if ($nodeValue >= 0) {
- // Values between 0 and 1 represent "times".
- return $this->formatExcelTimestampValueAsTimeValue($nodeValue, $cellStyleId);
- } else {
- // invalid date
- return null;
- }
- }
-
- /**
- * Returns a cell's PHP DateTime value, associated to the given timestamp.
- * Only the time value matters. The date part is set to Jan 1st, 1900 (base Excel date).
- *
- * @param float $nodeValue
- * @param int $cellStyleId 0 being the default style
- * @return \DateTime|string The value associated with the cell
- */
- protected function formatExcelTimestampValueAsTimeValue($nodeValue, $cellStyleId)
- {
- $time = round($nodeValue * self::NUM_SECONDS_IN_ONE_DAY);
- $hours = floor($time / self::NUM_SECONDS_IN_ONE_HOUR);
- $minutes = floor($time / self::NUM_SECONDS_IN_ONE_MINUTE) - ($hours * self::NUM_SECONDS_IN_ONE_MINUTE);
- $seconds = $time - ($hours * self::NUM_SECONDS_IN_ONE_HOUR) - ($minutes * self::NUM_SECONDS_IN_ONE_MINUTE);
-
- // using the base Excel date (Jan 1st, 1900) - not relevant here
- $dateObj = new \DateTime('1900-01-01');
- $dateObj->setTime($hours, $minutes, $seconds);
-
- if ($this->shouldFormatDates) {
- $styleNumberFormatCode = $this->styleHelper->getNumberFormatCode($cellStyleId);
- $phpDateFormat = DateFormatHelper::toPHPDateFormat($styleNumberFormatCode);
- return $dateObj->format($phpDateFormat);
- } else {
- return $dateObj;
- }
- }
-
- /**
- * Returns a cell's PHP Date value, associated to the given timestamp.
- * NOTE: The timestamp is a float representing the number of days since January 1st, 1900.
- *
- * @param float $nodeValue
- * @param int $cellStyleId 0 being the default style
- * @return \DateTime|string|null The value associated with the cell or NULL if invalid date value
- */
- protected function formatExcelTimestampValueAsDateValue($nodeValue, $cellStyleId)
- {
- // Do not use any unix timestamps for calculation to prevent
- // issues with numbers exceeding 2^31.
- $secondsRemainder = fmod($nodeValue, 1) * self::NUM_SECONDS_IN_ONE_DAY;
- $secondsRemainder = round($secondsRemainder, 0);
-
- try {
- $dateObj = \DateTime::createFromFormat('|Y-m-d', '1899-12-31');
- $dateObj->modify('+' . intval($nodeValue) . 'days');
- $dateObj->modify('+' . $secondsRemainder . 'seconds');
-
- if ($this->shouldFormatDates) {
- $styleNumberFormatCode = $this->styleHelper->getNumberFormatCode($cellStyleId);
- $phpDateFormat = DateFormatHelper::toPHPDateFormat($styleNumberFormatCode);
- return $dateObj->format($phpDateFormat);
- } else {
- return $dateObj;
- }
- } catch (\Exception $e) {
- return null;
- }
- }
-
- /**
- * Returns the cell Boolean value from a specific node's Value.
- *
- * @param string $nodeValue
- * @return bool The value associated with the cell
- */
- protected function formatBooleanCellValue($nodeValue)
- {
- // !! is similar to boolval()
- $cellValue = !!$nodeValue;
- return $cellValue;
- }
-
- /**
- * Returns a cell's PHP Date value, associated to the given stored nodeValue.
- * @see ECMA-376 Part 1 - §18.17.4
- *
- * @param string $nodeValue ISO 8601 Date string
- * @return \DateTime|string|null The value associated with the cell or NULL if invalid date value
- */
- protected function formatDateCellValue($nodeValue)
- {
- // Mitigate thrown Exception on invalid date-time format (http://php.net/manual/en/datetime.construct.php)
- try {
- return ($this->shouldFormatDates) ? $nodeValue : new \DateTime($nodeValue);
- } catch (\Exception $e) {
- return null;
- }
- }
-}
diff --git a/src/Spout/Reader/XLSX/Helper/DateFormatHelper.php b/src/Spout/Reader/XLSX/Helper/DateFormatHelper.php
deleted file mode 100644
index 9dba4c6..0000000
--- a/src/Spout/Reader/XLSX/Helper/DateFormatHelper.php
+++ /dev/null
@@ -1,124 +0,0 @@
- [
- // Time
- 'am/pm' => 'A', // Uppercase Ante meridiem and Post meridiem
- ':mm' => ':i', // Minutes with leading zeros - if preceded by a ":" (otherwise month)
- 'mm:' => 'i:', // Minutes with leading zeros - if followed by a ":" (otherwise month)
- 'ss' => 's', // Seconds, with leading zeros
- '.s' => '', // Ignore (fractional seconds format does not exist in PHP)
-
- // Date
- 'e' => 'Y', // Full numeric representation of a year, 4 digits
- 'yyyy' => 'Y', // Full numeric representation of a year, 4 digits
- 'yy' => 'y', // Two digit representation of a year
- 'mmmmm' => 'M', // Short textual representation of a month, three letters ("mmmmm" should only contain the 1st letter...)
- 'mmmm' => 'F', // Full textual representation of a month
- 'mmm' => 'M', // Short textual representation of a month, three letters
- 'mm' => 'm', // Numeric representation of a month, with leading zeros
- 'm' => 'n', // Numeric representation of a month, without leading zeros
- 'dddd' => 'l', // Full textual representation of the day of the week
- 'ddd' => 'D', // Textual representation of a day, three letters
- 'dd' => 'd', // Day of the month, 2 digits with leading zeros
- 'd' => 'j', // Day of the month without leading zeros
- ],
- self::KEY_HOUR_12 => [
- 'hh' => 'h', // 12-hour format of an hour without leading zeros
- 'h' => 'g', // 12-hour format of an hour without leading zeros
- ],
- self::KEY_HOUR_24 => [
- 'hh' => 'H', // 24-hour hours with leading zero
- 'h' => 'G', // 24-hour format of an hour without leading zeros
- ],
- ];
-
- /**
- * Converts the given Excel date format to a format understandable by the PHP date function.
- *
- * @param string $excelDateFormat Excel date format
- * @return string PHP date format (as defined here: http://php.net/manual/en/function.date.php)
- */
- public static function toPHPDateFormat($excelDateFormat)
- {
- // Remove brackets potentially present at the beginning of the format string
- // and text portion of the format at the end of it (starting with ";")
- // See §18.8.31 of ECMA-376 for more detail.
- $dateFormat = preg_replace('/^(?:\[\$[^\]]+?\])?([^;]*).*/', '$1', $excelDateFormat);
-
- // Double quotes are used to escape characters that must not be interpreted.
- // For instance, ["Day " dd] should result in "Day 13" and we should not try to interpret "D", "a", "y"
- // By exploding the format string using double quote as a delimiter, we can get all parts
- // that must be transformed (even indexes) and all parts that must not be (odd indexes).
- $dateFormatParts = explode('"', $dateFormat);
-
- foreach ($dateFormatParts as $partIndex => $dateFormatPart) {
- // do not look at odd indexes
- if ($partIndex % 2 === 1) {
- continue;
- }
-
- // Make sure all characters are lowercase, as the mapping table is using lowercase characters
- $transformedPart = strtolower($dateFormatPart);
-
- // Remove escapes related to non-format characters
- $transformedPart = str_replace('\\', '', $transformedPart);
-
- // Apply general transformation first...
- $transformedPart = strtr($transformedPart, self::$excelDateFormatToPHPDateFormatMapping[self::KEY_GENERAL]);
-
- // ... then apply hour transformation, for 12-hour or 24-hour format
- if (self::has12HourFormatMarker($dateFormatPart)) {
- $transformedPart = strtr($transformedPart, self::$excelDateFormatToPHPDateFormatMapping[self::KEY_HOUR_12]);
- } else {
- $transformedPart = strtr($transformedPart, self::$excelDateFormatToPHPDateFormatMapping[self::KEY_HOUR_24]);
- }
-
- // overwrite the parts array with the new transformed part
- $dateFormatParts[$partIndex] = $transformedPart;
- }
-
- // Merge all transformed parts back together
- $phpDateFormat = implode('"', $dateFormatParts);
-
- // Finally, to have the date format compatible with the DateTime::format() function, we need to escape
- // all characters that are inside double quotes (and double quotes must be removed).
- // For instance, ["Day " dd] should become [\D\a\y\ dd]
- $phpDateFormat = preg_replace_callback('/"(.+?)"/', function($matches) {
- $stringToEscape = $matches[1];
- $letters = preg_split('//u', $stringToEscape, -1, PREG_SPLIT_NO_EMPTY);
- return '\\' . implode('\\', $letters);
- }, $phpDateFormat);
-
- return $phpDateFormat;
- }
-
- /**
- * @param string $excelDateFormat Date format as defined by Excel
- * @return bool Whether the given date format has the 12-hour format marker
- */
- private static function has12HourFormatMarker($excelDateFormat)
- {
- return (stripos($excelDateFormat, 'am/pm') !== false);
- }
-}
diff --git a/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyFactory.php b/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyFactory.php
deleted file mode 100644
index 36e0bfe..0000000
--- a/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyFactory.php
+++ /dev/null
@@ -1,159 +0,0 @@
- 20 * 600 ≈ 12KB
- */
- const AMOUNT_MEMORY_NEEDED_PER_STRING_IN_KB = 12;
-
- /**
- * To avoid running out of memory when extracting a huge number of shared strings, they can be saved to temporary files
- * instead of in memory. Then, when accessing a string, the corresponding file contents will be loaded in memory
- * and the string will be quickly retrieved.
- * The performance bottleneck is not when creating these temporary files, but rather when loading their content.
- * Because the contents of the last loaded file stays in memory until another file needs to be loaded, it works
- * best when the indexes of the shared strings are sorted in the sheet data.
- * 10,000 was chosen because it creates small files that are fast to be loaded in memory.
- */
- const MAX_NUM_STRINGS_PER_TEMP_FILE = 10000;
-
- /** @var CachingStrategyFactory|null Singleton instance */
- protected static $instance = null;
-
- /**
- * Private constructor for singleton
- */
- private function __construct()
- {
- }
-
- /**
- * Returns the singleton instance of the factory
- *
- * @return CachingStrategyFactory
- */
- public static function getInstance()
- {
- if (self::$instance === null) {
- self::$instance = new CachingStrategyFactory();
- }
-
- return self::$instance;
- }
-
- /**
- * Returns the best caching strategy, given the number of unique shared strings
- * and the amount of memory available.
- *
- * @param int|null $sharedStringsUniqueCount Number of unique shared strings (NULL if unknown)
- * @param string|void $tempFolder Temporary folder where the temporary files to store shared strings will be stored
- * @return CachingStrategyInterface The best caching strategy
- */
- public function getBestCachingStrategy($sharedStringsUniqueCount, $tempFolder = null)
- {
- if ($this->isInMemoryStrategyUsageSafe($sharedStringsUniqueCount)) {
- return new InMemoryStrategy($sharedStringsUniqueCount);
- } else {
- return new FileBasedStrategy($tempFolder, self::MAX_NUM_STRINGS_PER_TEMP_FILE);
- }
- }
-
- /**
- * Returns whether it is safe to use in-memory caching, given the number of unique shared strings
- * and the amount of memory available.
- *
- * @param int|null $sharedStringsUniqueCount Number of unique shared strings (NULL if unknown)
- * @return bool
- */
- protected function isInMemoryStrategyUsageSafe($sharedStringsUniqueCount)
- {
- // if the number of shared strings in unknown, do not use "in memory" strategy
- if ($sharedStringsUniqueCount === null) {
- return false;
- }
-
- $memoryAvailable = $this->getMemoryLimitInKB();
-
- if ($memoryAvailable === -1) {
- // if cannot get memory limit or if memory limit set as unlimited, don't trust and play safe
- return ($sharedStringsUniqueCount < self::MAX_NUM_STRINGS_PER_TEMP_FILE);
- } else {
- $memoryNeeded = $sharedStringsUniqueCount * self::AMOUNT_MEMORY_NEEDED_PER_STRING_IN_KB;
- return ($memoryAvailable > $memoryNeeded);
- }
- }
-
- /**
- * Returns the PHP "memory_limit" in Kilobytes
- *
- * @return float
- */
- protected function getMemoryLimitInKB()
- {
- $memoryLimitFormatted = $this->getMemoryLimitFromIni();
- $memoryLimitFormatted = strtolower(trim($memoryLimitFormatted));
-
- // No memory limit
- if ($memoryLimitFormatted === '-1') {
- return -1;
- }
-
- if (preg_match('/(\d+)([bkmgt])b?/', $memoryLimitFormatted, $matches)) {
- $amount = intval($matches[1]);
- $unit = $matches[2];
-
- switch ($unit) {
- case 'b': return ($amount / 1024);
- case 'k': return $amount;
- case 'm': return ($amount * 1024);
- case 'g': return ($amount * 1024 * 1024);
- case 't': return ($amount * 1024 * 1024 * 1024);
- }
- }
-
- return -1;
- }
-
- /**
- * Returns the formatted "memory_limit" value
- *
- * @return string
- */
- protected function getMemoryLimitFromIni()
- {
- return ini_get('memory_limit');
- }
-}
diff --git a/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyInterface.php b/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyInterface.php
deleted file mode 100644
index 631222a..0000000
--- a/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyInterface.php
+++ /dev/null
@@ -1,44 +0,0 @@
-fileSystemHelper = new FileSystemHelper($rootTempFolder);
- $this->tempFolder = $this->fileSystemHelper->createFolder($rootTempFolder, uniqid('sharedstrings'));
-
- $this->maxNumStringsPerTempFile = $maxNumStringsPerTempFile;
-
- $this->globalFunctionsHelper = new GlobalFunctionsHelper();
- $this->tempFilePointer = null;
- }
-
- /**
- * Adds the given string to the cache.
- *
- * @param string $sharedString The string to be added to the cache
- * @param int $sharedStringIndex Index of the shared string in the sharedStrings.xml file
- * @return void
- */
- public function addStringForIndex($sharedString, $sharedStringIndex)
- {
- $tempFilePath = $this->getSharedStringTempFilePath($sharedStringIndex);
-
- if (!$this->globalFunctionsHelper->file_exists($tempFilePath)) {
- if ($this->tempFilePointer) {
- $this->globalFunctionsHelper->fclose($this->tempFilePointer);
- }
- $this->tempFilePointer = $this->globalFunctionsHelper->fopen($tempFilePath, 'w');
- }
-
- // The shared string retrieval logic expects each cell data to be on one line only
- // Encoding the line feed character allows to preserve this assumption
- $lineFeedEncodedSharedString = $this->escapeLineFeed($sharedString);
-
- $this->globalFunctionsHelper->fwrite($this->tempFilePointer, $lineFeedEncodedSharedString . PHP_EOL);
- }
-
- /**
- * Returns the path for the temp file that should contain the string for the given index
- *
- * @param int $sharedStringIndex Index of the shared string in the sharedStrings.xml file
- * @return string The temp file path for the given index
- */
- protected function getSharedStringTempFilePath($sharedStringIndex)
- {
- $numTempFile = intval($sharedStringIndex / $this->maxNumStringsPerTempFile);
- return $this->tempFolder . '/sharedstrings' . $numTempFile;
- }
-
- /**
- * Closes the cache after the last shared string was added.
- * This prevents any additional string from being added to the cache.
- *
- * @return void
- */
- public function closeCache()
- {
- // close pointer to the last temp file that was written
- if ($this->tempFilePointer) {
- $this->globalFunctionsHelper->fclose($this->tempFilePointer);
- }
- }
-
-
- /**
- * Returns the string located at the given index from the cache.
- *
- * @param int $sharedStringIndex Index of the shared string in the sharedStrings.xml file
- * @return string The shared string at the given index
- * @throws \Box\Spout\Reader\Exception\SharedStringNotFoundException If no shared string found for the given index
- */
- public function getStringAtIndex($sharedStringIndex)
- {
- $tempFilePath = $this->getSharedStringTempFilePath($sharedStringIndex);
- $indexInFile = $sharedStringIndex % $this->maxNumStringsPerTempFile;
-
- if (!$this->globalFunctionsHelper->file_exists($tempFilePath)) {
- throw new SharedStringNotFoundException("Shared string temp file not found: $tempFilePath ; for index: $sharedStringIndex");
- }
-
- if ($this->inMemoryTempFilePath !== $tempFilePath) {
- // free memory
- unset($this->inMemoryTempFileContents);
-
- $this->inMemoryTempFileContents = explode(PHP_EOL, $this->globalFunctionsHelper->file_get_contents($tempFilePath));
- $this->inMemoryTempFilePath = $tempFilePath;
- }
-
- $sharedString = null;
-
- // Using isset here because it is way faster than array_key_exists...
- if (isset($this->inMemoryTempFileContents[$indexInFile])) {
- $escapedSharedString = $this->inMemoryTempFileContents[$indexInFile];
- $sharedString = $this->unescapeLineFeed($escapedSharedString);
- }
-
- if ($sharedString === null) {
- throw new SharedStringNotFoundException("Shared string not found for index: $sharedStringIndex");
- }
-
- return rtrim($sharedString, PHP_EOL);
- }
-
- /**
- * Escapes the line feed characters (\n)
- *
- * @param string $unescapedString
- * @return string
- */
- private function escapeLineFeed($unescapedString)
- {
- return str_replace("\n", self::ESCAPED_LINE_FEED_CHARACTER, $unescapedString);
- }
-
- /**
- * Unescapes the line feed characters (\n)
- *
- * @param string $escapedString
- * @return string
- */
- private function unescapeLineFeed($escapedString)
- {
- return str_replace(self::ESCAPED_LINE_FEED_CHARACTER, "\n", $escapedString);
- }
-
- /**
- * Destroys the cache, freeing memory and removing any created artifacts
- *
- * @return void
- */
- public function clearCache()
- {
- if ($this->tempFolder) {
- $this->fileSystemHelper->deleteFolderRecursively($this->tempFolder);
- }
- }
-}
diff --git a/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/InMemoryStrategy.php b/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/InMemoryStrategy.php
deleted file mode 100644
index c6a5321..0000000
--- a/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/InMemoryStrategy.php
+++ /dev/null
@@ -1,83 +0,0 @@
-inMemoryCache = new \SplFixedArray($sharedStringsUniqueCount);
- $this->isCacheClosed = false;
- }
-
- /**
- * Adds the given string to the cache.
- *
- * @param string $sharedString The string to be added to the cache
- * @param int $sharedStringIndex Index of the shared string in the sharedStrings.xml file
- * @return void
- */
- public function addStringForIndex($sharedString, $sharedStringIndex)
- {
- if (!$this->isCacheClosed) {
- $this->inMemoryCache->offsetSet($sharedStringIndex, $sharedString);
- }
- }
-
- /**
- * Closes the cache after the last shared string was added.
- * This prevents any additional string from being added to the cache.
- *
- * @return void
- */
- public function closeCache()
- {
- $this->isCacheClosed = true;
- }
-
- /**
- * Returns the string located at the given index from the cache.
- *
- * @param int $sharedStringIndex Index of the shared string in the sharedStrings.xml file
- * @return string The shared string at the given index
- * @throws \Box\Spout\Reader\Exception\SharedStringNotFoundException If no shared string found for the given index
- */
- public function getStringAtIndex($sharedStringIndex)
- {
- try {
- return $this->inMemoryCache->offsetGet($sharedStringIndex);
- } catch (\RuntimeException $e) {
- throw new SharedStringNotFoundException("Shared string not found for index: $sharedStringIndex");
- }
- }
-
- /**
- * Destroys the cache, freeing memory and removing any created artifacts
- *
- * @return void
- */
- public function clearCache()
- {
- unset($this->inMemoryCache);
- $this->isCacheClosed = false;
- }
-}
diff --git a/src/Spout/Reader/XLSX/Helper/SharedStringsHelper.php b/src/Spout/Reader/XLSX/Helper/SharedStringsHelper.php
deleted file mode 100644
index 0e88839..0000000
--- a/src/Spout/Reader/XLSX/Helper/SharedStringsHelper.php
+++ /dev/null
@@ -1,245 +0,0 @@
-filePath = $filePath;
- $this->tempFolder = $tempFolder;
- }
-
- /**
- * Returns whether the XLSX file contains a shared strings XML file
- *
- * @return bool
- */
- public function hasSharedStrings()
- {
- $hasSharedStrings = false;
- $zip = new \ZipArchive();
-
- if ($zip->open($this->filePath) === true) {
- $hasSharedStrings = ($zip->locateName(self::SHARED_STRINGS_XML_FILE_PATH) !== false);
- $zip->close();
- }
-
- return $hasSharedStrings;
- }
-
- /**
- * Builds an in-memory array containing all the shared strings of the sheet.
- * All the strings are stored in a XML file, located at 'xl/sharedStrings.xml'.
- * It is then accessed by the sheet data, via the string index in the built table.
- *
- * More documentation available here: http://msdn.microsoft.com/en-us/library/office/gg278314.aspx
- *
- * The XML file can be really big with sheets containing a lot of data. That is why
- * we need to use a XML reader that provides streaming like the XMLReader library.
- * Please note that SimpleXML does not provide such a functionality but since it is faster
- * and more handy to parse few XML nodes, it is used in combination with XMLReader for that purpose.
- *
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If sharedStrings.xml can't be read
- */
- public function extractSharedStrings()
- {
- $xmlReader = new XMLReader();
- $sharedStringIndex = 0;
-
- $sharedStringsFilePath = $this->getSharedStringsFilePath();
- if ($xmlReader->open($sharedStringsFilePath) === false) {
- throw new IOException('Could not open "' . self::SHARED_STRINGS_XML_FILE_PATH . '".');
- }
-
- try {
- $sharedStringsUniqueCount = $this->getSharedStringsUniqueCount($xmlReader);
- $this->cachingStrategy = $this->getBestSharedStringsCachingStrategy($sharedStringsUniqueCount);
-
- $xmlReader->readUntilNodeFound(self::XML_NODE_SI);
-
- while ($xmlReader->name === self::XML_NODE_SI) {
- $this->processSharedStringsItem($xmlReader, $sharedStringIndex);
- $sharedStringIndex++;
-
- // jump to the next '' tag
- $xmlReader->next(self::XML_NODE_SI);
- }
-
- $this->cachingStrategy->closeCache();
-
- } catch (XMLProcessingException $exception) {
- throw new IOException("The sharedStrings.xml file is invalid and cannot be read. [{$exception->getMessage()}]");
- }
-
- $xmlReader->close();
- }
-
- /**
- * @return string The path to the shared strings XML file
- */
- protected function getSharedStringsFilePath()
- {
- return 'zip://' . $this->filePath . '#' . self::SHARED_STRINGS_XML_FILE_PATH;
- }
-
- /**
- * Returns the shared strings unique count, as specified in tag.
- *
- * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XMLReader instance
- * @return int|null Number of unique shared strings in the sharedStrings.xml file
- * @throws \Box\Spout\Common\Exception\IOException If sharedStrings.xml is invalid and can't be read
- */
- protected function getSharedStringsUniqueCount($xmlReader)
- {
- $xmlReader->next(self::XML_NODE_SST);
-
- // Iterate over the "sst" elements to get the actual "sst ELEMENT" (skips any DOCTYPE)
- while ($xmlReader->name === self::XML_NODE_SST && $xmlReader->nodeType !== XMLReader::ELEMENT) {
- $xmlReader->read();
- }
-
- $uniqueCount = $xmlReader->getAttribute(self::XML_ATTRIBUTE_UNIQUE_COUNT);
-
- // some software do not add the "uniqueCount" attribute but only use the "count" one
- // @see https://github.com/box/spout/issues/254
- if ($uniqueCount === null) {
- $uniqueCount = $xmlReader->getAttribute(self::XML_ATTRIBUTE_COUNT);
- }
-
- return ($uniqueCount !== null) ? intval($uniqueCount) : null;
- }
-
- /**
- * Returns the best shared strings caching strategy.
- *
- * @param int|null $sharedStringsUniqueCount Number of unique shared strings (NULL if unknown)
- * @return CachingStrategyInterface
- */
- protected function getBestSharedStringsCachingStrategy($sharedStringsUniqueCount)
- {
- return CachingStrategyFactory::getInstance()
- ->getBestCachingStrategy($sharedStringsUniqueCount, $this->tempFolder);
- }
-
- /**
- * Processes the shared strings item XML node which the given XML reader is positioned on.
- *
- * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XML Reader positioned on a "" node
- * @param int $sharedStringIndex Index of the processed shared strings item
- * @return void
- */
- protected function processSharedStringsItem($xmlReader, $sharedStringIndex)
- {
- $sharedStringValue = '';
-
- // NOTE: expand() will automatically decode all XML entities of the child nodes
- $siNode = $xmlReader->expand();
- $textNodes = $siNode->getElementsByTagName(self::XML_NODE_T);
-
- foreach ($textNodes as $textNode) {
- if ($this->shouldExtractTextNodeValue($textNode)) {
- $textNodeValue = $textNode->nodeValue;
- $shouldPreserveWhitespace = $this->shouldPreserveWhitespace($textNode);
-
- $sharedStringValue .= ($shouldPreserveWhitespace) ? $textNodeValue : trim($textNodeValue);
- }
- }
-
- $this->cachingStrategy->addStringForIndex($sharedStringValue, $sharedStringIndex);
- }
-
- /**
- * Not all text nodes' values must be extracted.
- * Some text nodes are part of a node describing the pronunciation for instance.
- * We'll only consider the nodes whose parents are "" or "".
- *
- * @param \DOMElement $textNode Text node to check
- * @return bool Whether the given text node's value must be extracted
- */
- protected function shouldExtractTextNodeValue($textNode)
- {
- $parentTagName = $textNode->parentNode->localName;
- return ($parentTagName === self::XML_NODE_SI || $parentTagName === self::XML_NODE_R);
- }
-
- /**
- * If the text node has the attribute 'xml:space="preserve"', then preserve whitespace.
- *
- * @param \DOMElement $textNode The text node element () whose whitespace may be preserved
- * @return bool Whether whitespace should be preserved
- */
- protected function shouldPreserveWhitespace($textNode)
- {
- $spaceValue = $textNode->getAttribute(self::XML_ATTRIBUTE_XML_SPACE);
- return ($spaceValue === self::XML_ATTRIBUTE_VALUE_PRESERVE);
- }
-
- /**
- * Returns the shared string at the given index, using the previously chosen caching strategy.
- *
- * @param int $sharedStringIndex Index of the shared string in the sharedStrings.xml file
- * @return string The shared string at the given index
- * @throws \Box\Spout\Reader\Exception\SharedStringNotFoundException If no shared string found for the given index
- */
- public function getStringAtIndex($sharedStringIndex)
- {
- return $this->cachingStrategy->getStringAtIndex($sharedStringIndex);
- }
-
- /**
- * Destroys the cache, freeing memory and removing any created artifacts
- *
- * @return void
- */
- public function cleanup()
- {
- if ($this->cachingStrategy) {
- $this->cachingStrategy->clearCache();
- }
- }
-}
diff --git a/src/Spout/Reader/XLSX/Helper/SheetHelper.php b/src/Spout/Reader/XLSX/Helper/SheetHelper.php
deleted file mode 100644
index b74ba01..0000000
--- a/src/Spout/Reader/XLSX/Helper/SheetHelper.php
+++ /dev/null
@@ -1,156 +0,0 @@
-filePath = $filePath;
- $this->options = $options;
- $this->sharedStringsHelper = $sharedStringsHelper;
- $this->globalFunctionsHelper = $globalFunctionsHelper;
- }
-
- /**
- * Returns the sheets metadata of the file located at the previously given file path.
- * The paths to the sheets' data are read from the [Content_Types].xml file.
- *
- * @return Sheet[] Sheets within the XLSX file
- */
- public function getSheets()
- {
- $sheets = [];
- $sheetIndex = 0;
- $activeSheetIndex = 0; // By default, the first sheet is active
-
- $xmlReader = new XMLReader();
- if ($xmlReader->openFileInZip($this->filePath, self::WORKBOOK_XML_FILE_PATH)) {
- while ($xmlReader->read()) {
- if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_WORKBOOK_VIEW)) {
- // The "workbookView" node is located before "sheet" nodes, ensuring that
- // the active sheet is known before parsing sheets data.
- $activeSheetIndex = (int) $xmlReader->getAttribute(self::XML_ATTRIBUTE_ACTIVE_TAB);
- } else if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_SHEET)) {
- $isSheetActive = ($sheetIndex === $activeSheetIndex);
- $sheets[] = $this->getSheetFromSheetXMLNode($xmlReader, $sheetIndex, $isSheetActive);
- $sheetIndex++;
- } else if ($xmlReader->isPositionedOnEndingNode(self::XML_NODE_SHEETS)) {
- // stop reading once all sheets have been read
- break;
- }
- }
-
- $xmlReader->close();
- }
-
- return $sheets;
- }
-
- /**
- * Returns an instance of a sheet, given the XML node describing the sheet - from "workbook.xml".
- * We can find the XML file path describing the sheet inside "workbook.xml.res", by mapping with the sheet ID
- * ("r:id" in "workbook.xml", "Id" in "workbook.xml.res").
- *
- * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReaderOnSheetNode XML Reader instance, pointing on the node describing the sheet, as defined in "workbook.xml"
- * @param int $sheetIndexZeroBased Index of the sheet, based on order of appearance in the workbook (zero-based)
- * @param bool $isSheetActive Whether this sheet was defined as active
- * @return \Box\Spout\Reader\XLSX\Sheet Sheet instance
- */
- protected function getSheetFromSheetXMLNode($xmlReaderOnSheetNode, $sheetIndexZeroBased, $isSheetActive)
- {
- $sheetId = $xmlReaderOnSheetNode->getAttribute(self::XML_ATTRIBUTE_R_ID);
- $escapedSheetName = $xmlReaderOnSheetNode->getAttribute(self::XML_ATTRIBUTE_NAME);
-
- /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
- $escaper = \Box\Spout\Common\Escaper\XLSX::getInstance();
- $sheetName = $escaper->unescape($escapedSheetName);
-
- $sheetDataXMLFilePath = $this->getSheetDataXMLFilePathForSheetId($sheetId);
-
- return new Sheet(
- $this->filePath, $sheetDataXMLFilePath,
- $sheetIndexZeroBased, $sheetName, $isSheetActive,
- $this->options, $this->sharedStringsHelper
- );
- }
-
- /**
- * @param string $sheetId The sheet ID, as defined in "workbook.xml"
- * @return string The XML file path describing the sheet inside "workbook.xml.res", for the given sheet ID
- */
- protected function getSheetDataXMLFilePathForSheetId($sheetId)
- {
- $sheetDataXMLFilePath = '';
-
- // find the file path of the sheet, by looking at the "workbook.xml.res" file
- $xmlReader = new XMLReader();
- if ($xmlReader->openFileInZip($this->filePath, self::WORKBOOK_XML_RELS_FILE_PATH)) {
- while ($xmlReader->read()) {
- if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_RELATIONSHIP)) {
- $relationshipSheetId = $xmlReader->getAttribute(self::XML_ATTRIBUTE_ID);
-
- if ($relationshipSheetId === $sheetId) {
- // In workbook.xml.rels, it is only "worksheets/sheet1.xml"
- // In [Content_Types].xml, the path is "/xl/worksheets/sheet1.xml"
- $sheetDataXMLFilePath = $xmlReader->getAttribute(self::XML_ATTRIBUTE_TARGET);
-
- // sometimes, the sheet data file path already contains "/xl/"...
- if (strpos($sheetDataXMLFilePath, '/xl/') !== 0) {
- $sheetDataXMLFilePath = '/xl/' . $sheetDataXMLFilePath;
- break;
- }
- }
- }
- }
-
- $xmlReader->close();
- }
-
- return $sheetDataXMLFilePath;
- }
-}
diff --git a/src/Spout/Reader/XLSX/Helper/StyleHelper.php b/src/Spout/Reader/XLSX/Helper/StyleHelper.php
deleted file mode 100644
index 000adab..0000000
--- a/src/Spout/Reader/XLSX/Helper/StyleHelper.php
+++ /dev/null
@@ -1,330 +0,0 @@
- 'm/d/yyyy', // @NOTE: ECMA spec is 'mm-dd-yy'
- 15 => 'd-mmm-yy',
- 16 => 'd-mmm',
- 17 => 'mmm-yy',
- 18 => 'h:mm AM/PM',
- 19 => 'h:mm:ss AM/PM',
- 20 => 'h:mm',
- 21 => 'h:mm:ss',
- 22 => 'm/d/yyyy h:mm', // @NOTE: ECMA spec is 'm/d/yy h:mm',
- 45 => 'mm:ss',
- 46 => '[h]:mm:ss',
- 47 => 'mm:ss.0', // @NOTE: ECMA spec is 'mmss.0',
- ];
-
- /** @var string Path of the XLSX file being read */
- protected $filePath;
-
- /** @var array Array containing the IDs of built-in number formats indicating a date */
- protected $builtinNumFmtIdIndicatingDates;
-
- /** @var array Array containing a mapping NUM_FMT_ID => FORMAT_CODE */
- protected $customNumberFormats;
-
- /** @var array Array containing a mapping STYLE_ID => [STYLE_ATTRIBUTES] */
- protected $stylesAttributes;
-
- /** @var array Cache containing a mapping NUM_FMT_ID => IS_DATE_FORMAT. Used to avoid lots of recalculations */
- protected $numFmtIdToIsDateFormatCache = [];
-
- /**
- * @param string $filePath Path of the XLSX file being read
- */
- public function __construct($filePath)
- {
- $this->filePath = $filePath;
- $this->builtinNumFmtIdIndicatingDates = array_keys(self::$builtinNumFmtIdToNumFormatMapping);
- }
-
- /**
- * Returns whether the style with the given ID should consider
- * numeric values as timestamps and format the cell as a date.
- *
- * @param int $styleId Zero-based style ID
- * @return bool Whether the cell with the given cell should display a date instead of a numeric value
- */
- public function shouldFormatNumericValueAsDate($styleId)
- {
- $stylesAttributes = $this->getStylesAttributes();
-
- // Default style (0) does not format numeric values as timestamps. Only custom styles do.
- // Also if the style ID does not exist in the styles.xml file, format as numeric value.
- // Using isset here because it is way faster than array_key_exists...
- if ($styleId === self::DEFAULT_STYLE_ID || !isset($stylesAttributes[$styleId])) {
- return false;
- }
-
- $styleAttributes = $stylesAttributes[$styleId];
-
- return $this->doesStyleIndicateDate($styleAttributes);
- }
-
- /**
- * Reads the styles.xml file and extract the relevant information from the file.
- *
- * @return void
- */
- protected function extractRelevantInfo()
- {
- $this->customNumberFormats = [];
- $this->stylesAttributes = [];
-
- $xmlReader = new XMLReader();
-
- if ($xmlReader->openFileInZip($this->filePath, self::STYLES_XML_FILE_PATH)) {
- while ($xmlReader->read()) {
- if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_NUM_FMTS)) {
- $this->extractNumberFormats($xmlReader);
-
- } else if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_CELL_XFS)) {
- $this->extractStyleAttributes($xmlReader);
- }
- }
-
- $xmlReader->close();
- }
- }
-
- /**
- * Extracts number formats from the "numFmt" nodes.
- * For simplicity, the styles attributes are kept in memory. This is possible thanks
- * to the reuse of formats. So 1 million cells should not use 1 million formats.
- *
- * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XML Reader positioned on the "numFmts" node
- * @return void
- */
- protected function extractNumberFormats($xmlReader)
- {
- while ($xmlReader->read()) {
- if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_NUM_FMT)) {
- $numFmtId = intval($xmlReader->getAttribute(self::XML_ATTRIBUTE_NUM_FMT_ID));
- $formatCode = $xmlReader->getAttribute(self::XML_ATTRIBUTE_FORMAT_CODE);
- $this->customNumberFormats[$numFmtId] = $formatCode;
- } else if ($xmlReader->isPositionedOnEndingNode(self::XML_NODE_NUM_FMTS)) {
- // Once done reading "numFmts" node's children
- break;
- }
- }
- }
-
- /**
- * Extracts style attributes from the "xf" nodes, inside the "cellXfs" section.
- * For simplicity, the styles attributes are kept in memory. This is possible thanks
- * to the reuse of styles. So 1 million cells should not use 1 million styles.
- *
- * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XML Reader positioned on the "cellXfs" node
- * @return void
- */
- protected function extractStyleAttributes($xmlReader)
- {
- while ($xmlReader->read()) {
- if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_XF)) {
- $numFmtId = $xmlReader->getAttribute(self::XML_ATTRIBUTE_NUM_FMT_ID);
- $normalizedNumFmtId = ($numFmtId !== null) ? intval($numFmtId) : null;
-
- $applyNumberFormat = $xmlReader->getAttribute(self::XML_ATTRIBUTE_APPLY_NUMBER_FORMAT);
- $normalizedApplyNumberFormat = ($applyNumberFormat !== null) ? !!$applyNumberFormat : null;
-
- $this->stylesAttributes[] = [
- self::XML_ATTRIBUTE_NUM_FMT_ID => $normalizedNumFmtId,
- self::XML_ATTRIBUTE_APPLY_NUMBER_FORMAT => $normalizedApplyNumberFormat,
- ];
- } else if ($xmlReader->isPositionedOnEndingNode(self::XML_NODE_CELL_XFS)) {
- // Once done reading "cellXfs" node's children
- break;
- }
- }
- }
-
- /**
- * @return array The custom number formats
- */
- protected function getCustomNumberFormats()
- {
- if (!isset($this->customNumberFormats)) {
- $this->extractRelevantInfo();
- }
-
- return $this->customNumberFormats;
- }
-
- /**
- * @return array The styles attributes
- */
- protected function getStylesAttributes()
- {
- if (!isset($this->stylesAttributes)) {
- $this->extractRelevantInfo();
- }
-
- return $this->stylesAttributes;
- }
-
- /**
- * @param array $styleAttributes Array containing the style attributes (2 keys: "applyNumberFormat" and "numFmtId")
- * @return bool Whether the style with the given attributes indicates that the number is a date
- */
- protected function doesStyleIndicateDate($styleAttributes)
- {
- $applyNumberFormat = $styleAttributes[self::XML_ATTRIBUTE_APPLY_NUMBER_FORMAT];
- $numFmtId = $styleAttributes[self::XML_ATTRIBUTE_NUM_FMT_ID];
-
- // A style may apply a date format if it has:
- // - "applyNumberFormat" attribute not set to "false"
- // - "numFmtId" attribute set
- // This is a preliminary check, as having "numFmtId" set just means the style should apply a specific number format,
- // but this is not necessarily a date.
- if ($applyNumberFormat === false || $numFmtId === null) {
- return false;
- }
-
- return $this->doesNumFmtIdIndicateDate($numFmtId);
- }
-
- /**
- * Returns whether the number format ID indicates that the number is a date.
- * The result is cached to avoid recomputing the same thing over and over, as
- * "numFmtId" attributes can be shared between multiple styles.
- *
- * @param int $numFmtId
- * @return bool Whether the number format ID indicates that the number is a date
- */
- protected function doesNumFmtIdIndicateDate($numFmtId)
- {
- if (!isset($this->numFmtIdToIsDateFormatCache[$numFmtId])) {
- $formatCode = $this->getFormatCodeForNumFmtId($numFmtId);
-
- $this->numFmtIdToIsDateFormatCache[$numFmtId] = (
- $this->isNumFmtIdBuiltInDateFormat($numFmtId) ||
- $this->isFormatCodeCustomDateFormat($formatCode)
- );
- }
-
- return $this->numFmtIdToIsDateFormatCache[$numFmtId];
- }
-
- /**
- * @param int $numFmtId
- * @return string|null The custom number format or NULL if none defined for the given numFmtId
- */
- protected function getFormatCodeForNumFmtId($numFmtId)
- {
- $customNumberFormats = $this->getCustomNumberFormats();
-
- // Using isset here because it is way faster than array_key_exists...
- return (isset($customNumberFormats[$numFmtId])) ? $customNumberFormats[$numFmtId] : null;
- }
-
- /**
- * @param int $numFmtId
- * @return bool Whether the number format ID indicates that the number is a date
- */
- protected function isNumFmtIdBuiltInDateFormat($numFmtId)
- {
- return in_array($numFmtId, $this->builtinNumFmtIdIndicatingDates);
- }
-
- /**
- * @param string|null $formatCode
- * @return bool Whether the given format code indicates that the number is a date
- */
- protected function isFormatCodeCustomDateFormat($formatCode)
- {
- // if no associated format code or if using the default "General" format
- if ($formatCode === null || strcasecmp($formatCode, self::NUMBER_FORMAT_GENERAL) === 0) {
- return false;
- }
-
- return $this->isFormatCodeMatchingDateFormatPattern($formatCode);
- }
-
- /**
- * @param string $formatCode
- * @return bool Whether the given format code matches a date format pattern
- */
- protected function isFormatCodeMatchingDateFormatPattern($formatCode)
- {
- // Remove extra formatting (what's between [ ], the brackets should not be preceded by a "\")
- $pattern = '((?getStylesAttributes();
- $styleAttributes = $stylesAttributes[$styleId];
- $numFmtId = $styleAttributes[self::XML_ATTRIBUTE_NUM_FMT_ID];
-
- if ($this->isNumFmtIdBuiltInDateFormat($numFmtId)) {
- $numberFormatCode = self::$builtinNumFmtIdToNumFormatMapping[$numFmtId];
- } else {
- $customNumberFormats = $this->getCustomNumberFormats();
- $numberFormatCode = $customNumberFormats[$numFmtId];
- }
-
- return $numberFormatCode;
- }
-}
diff --git a/src/Spout/Reader/XLSX/Reader.php b/src/Spout/Reader/XLSX/Reader.php
deleted file mode 100644
index 76e8e32..0000000
--- a/src/Spout/Reader/XLSX/Reader.php
+++ /dev/null
@@ -1,113 +0,0 @@
-options)) {
- $this->options = new ReaderOptions();
- }
- return $this->options;
- }
-
- /**
- * @param string $tempFolder Temporary folder where the temporary files will be created
- * @return Reader
- */
- public function setTempFolder($tempFolder)
- {
- $this->getOptions()->setTempFolder($tempFolder);
- return $this;
- }
-
- /**
- * Returns whether stream wrappers are supported
- *
- * @return bool
- */
- protected function doesSupportStreamWrapper()
- {
- return false;
- }
-
- /**
- * Opens the file at the given file path to make it ready to be read.
- * It also parses the sharedStrings.xml file to get all the shared strings available in memory
- * and fetches all the available sheets.
- *
- * @param string $filePath Path of the file to be read
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If the file at the given path or its content cannot be read
- * @throws \Box\Spout\Reader\Exception\NoSheetsFoundException If there are no sheets in the file
- */
- protected function openReader($filePath)
- {
- $this->zip = new \ZipArchive();
-
- if ($this->zip->open($filePath) === true) {
- $this->sharedStringsHelper = new SharedStringsHelper($filePath, $this->getOptions()->getTempFolder());
-
- if ($this->sharedStringsHelper->hasSharedStrings()) {
- // Extracts all the strings from the sheets for easy access in the future
- $this->sharedStringsHelper->extractSharedStrings();
- }
-
- $this->sheetIterator = new SheetIterator($filePath, $this->getOptions(), $this->sharedStringsHelper, $this->globalFunctionsHelper);
- } else {
- throw new IOException("Could not open $filePath for reading.");
- }
- }
-
- /**
- * Returns an iterator to iterate over sheets.
- *
- * @return SheetIterator To iterate over sheets
- */
- protected function getConcreteSheetIterator()
- {
- return $this->sheetIterator;
- }
-
- /**
- * Closes the reader. To be used after reading the file.
- *
- * @return void
- */
- protected function closeReader()
- {
- if ($this->zip) {
- $this->zip->close();
- }
-
- if ($this->sharedStringsHelper) {
- $this->sharedStringsHelper->cleanup();
- }
- }
-}
diff --git a/src/Spout/Reader/XLSX/ReaderOptions.php b/src/Spout/Reader/XLSX/ReaderOptions.php
deleted file mode 100644
index 5f78c5d..0000000
--- a/src/Spout/Reader/XLSX/ReaderOptions.php
+++ /dev/null
@@ -1,33 +0,0 @@
-tempFolder;
- }
-
- /**
- * @param string|null $tempFolder Temporary folder where the temporary files will be created
- * @return ReaderOptions
- */
- public function setTempFolder($tempFolder)
- {
- $this->tempFolder = $tempFolder;
- return $this;
- }
-}
diff --git a/src/Spout/Reader/XLSX/RowIterator.php b/src/Spout/Reader/XLSX/RowIterator.php
deleted file mode 100644
index 2440593..0000000
--- a/src/Spout/Reader/XLSX/RowIterator.php
+++ /dev/null
@@ -1,406 +0,0 @@
-filePath = $filePath;
- $this->sheetDataXMLFilePath = $this->normalizeSheetDataXMLFilePath($sheetDataXMLFilePath);
-
- $this->xmlReader = new XMLReader();
-
- $this->styleHelper = new StyleHelper($filePath);
- $this->cellValueFormatter = new CellValueFormatter($sharedStringsHelper, $this->styleHelper, $options->shouldFormatDates());
-
- $this->shouldPreserveEmptyRows = $options->shouldPreserveEmptyRows();
-
- // Register all callbacks to process different nodes when reading the XML file
- $this->xmlProcessor = new XMLProcessor($this->xmlReader);
- $this->xmlProcessor->registerCallback(self::XML_NODE_DIMENSION, XMLProcessor::NODE_TYPE_START, [$this, 'processDimensionStartingNode']);
- $this->xmlProcessor->registerCallback(self::XML_NODE_ROW, XMLProcessor::NODE_TYPE_START, [$this, 'processRowStartingNode']);
- $this->xmlProcessor->registerCallback(self::XML_NODE_CELL, XMLProcessor::NODE_TYPE_START, [$this, 'processCellStartingNode']);
- $this->xmlProcessor->registerCallback(self::XML_NODE_ROW, XMLProcessor::NODE_TYPE_END, [$this, 'processRowEndingNode']);
- $this->xmlProcessor->registerCallback(self::XML_NODE_WORKSHEET, XMLProcessor::NODE_TYPE_END, [$this, 'processWorksheetEndingNode']);
- }
-
- /**
- * @param string $sheetDataXMLFilePath Path of the sheet data XML file as in [Content_Types].xml
- * @return string Path of the XML file containing the sheet data,
- * without the leading slash.
- */
- protected function normalizeSheetDataXMLFilePath($sheetDataXMLFilePath)
- {
- return ltrim($sheetDataXMLFilePath, '/');
- }
-
- /**
- * Rewind the Iterator to the first element.
- * Initializes the XMLReader object that reads the associated sheet data.
- * The XMLReader is configured to be safe from billion laughs attack.
- * @link http://php.net/manual/en/iterator.rewind.php
- *
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If the sheet data XML cannot be read
- */
- public function rewind()
- {
- $this->xmlReader->close();
-
- $sheetDataFilePath = 'zip://' . $this->filePath . '#' . $this->sheetDataXMLFilePath;
- if ($this->xmlReader->open($sheetDataFilePath) === false) {
- throw new IOException("Could not open \"{$this->sheetDataXMLFilePath}\".");
- }
-
- $this->numReadRows = 0;
- $this->lastRowIndexProcessed = 0;
- $this->nextRowIndexToBeProcessed = 0;
- $this->rowDataBuffer = null;
- $this->hasReachedEndOfFile = false;
- $this->numColumns = 0;
-
- $this->next();
- }
-
- /**
- * Checks if current position is valid
- * @link http://php.net/manual/en/iterator.valid.php
- *
- * @return bool
- */
- public function valid()
- {
- return (!$this->hasReachedEndOfFile);
- }
-
- /**
- * Move forward to next element. Reads data describing the next unprocessed row.
- * @link http://php.net/manual/en/iterator.next.php
- *
- * @return void
- * @throws \Box\Spout\Reader\Exception\SharedStringNotFoundException If a shared string was not found
- * @throws \Box\Spout\Common\Exception\IOException If unable to read the sheet data XML
- */
- public function next()
- {
- $this->nextRowIndexToBeProcessed++;
-
- if ($this->doesNeedDataForNextRowToBeProcessed()) {
- $this->readDataForNextRow();
- }
- }
-
- /**
- * Returns whether we need data for the next row to be processed.
- * We don't need to read data if:
- * we have already read at least one row
- * AND
- * we need to preserve empty rows
- * AND
- * the last row that was read is not the row that need to be processed
- * (i.e. if we need to return empty rows)
- *
- * @return bool Whether we need data for the next row to be processed.
- */
- protected function doesNeedDataForNextRowToBeProcessed()
- {
- $hasReadAtLeastOneRow = ($this->lastRowIndexProcessed !== 0);
-
- return (
- !$hasReadAtLeastOneRow ||
- !$this->shouldPreserveEmptyRows ||
- $this->lastRowIndexProcessed < $this->nextRowIndexToBeProcessed
- );
- }
-
- /**
- * @return void
- * @throws \Box\Spout\Reader\Exception\SharedStringNotFoundException If a shared string was not found
- * @throws \Box\Spout\Common\Exception\IOException If unable to read the sheet data XML
- */
- protected function readDataForNextRow()
- {
- $this->currentlyProcessedRowData = [];
-
- try {
- $this->xmlProcessor->readUntilStopped();
- } catch (XMLProcessingException $exception) {
- throw new IOException("The {$this->sheetDataXMLFilePath} file cannot be read. [{$exception->getMessage()}]");
- }
-
- $this->rowDataBuffer = $this->currentlyProcessedRowData;
- }
-
- /**
- * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XMLReader object, positioned on a "" starting node
- * @return int A return code that indicates what action should the processor take next
- */
- protected function processDimensionStartingNode($xmlReader)
- {
- // Read dimensions of the sheet
- $dimensionRef = $xmlReader->getAttribute(self::XML_ATTRIBUTE_REF); // returns 'A1:M13' for instance (or 'A1' for empty sheet)
- if (preg_match('/[A-Z]+\d+:([A-Z]+\d+)/', $dimensionRef, $matches)) {
- $this->numColumns = CellHelper::getColumnIndexFromCellIndex($matches[1]) + 1;
- }
-
- return XMLProcessor::PROCESSING_CONTINUE;
- }
-
- /**
- * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XMLReader object, positioned on a "" starting node
- * @return int A return code that indicates what action should the processor take next
- */
- protected function processRowStartingNode($xmlReader)
- {
- // Reset index of the last processed column
- $this->lastColumnIndexProcessed = -1;
-
- // Mark the last processed row as the one currently being read
- $this->lastRowIndexProcessed = $this->getRowIndex($xmlReader);
-
- // Read spans info if present
- $numberOfColumnsForRow = $this->numColumns;
- $spans = $xmlReader->getAttribute(self::XML_ATTRIBUTE_SPANS); // returns '1:5' for instance
- if ($spans) {
- list(, $numberOfColumnsForRow) = explode(':', $spans);
- $numberOfColumnsForRow = intval($numberOfColumnsForRow);
- }
-
- $this->currentlyProcessedRowData = ($numberOfColumnsForRow !== 0) ? array_fill(0, $numberOfColumnsForRow, '') : [];
-
- return XMLProcessor::PROCESSING_CONTINUE;
- }
-
- /**
- * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XMLReader object, positioned on a "" starting node
- * @return int A return code that indicates what action should the processor take next
- */
- protected function processCellStartingNode($xmlReader)
- {
- $currentColumnIndex = $this->getColumnIndex($xmlReader);
-
- // NOTE: expand() will automatically decode all XML entities of the child nodes
- $node = $xmlReader->expand();
- $this->currentlyProcessedRowData[$currentColumnIndex] = $this->getCellValue($node);
- $this->lastColumnIndexProcessed = $currentColumnIndex;
-
- return XMLProcessor::PROCESSING_CONTINUE;
- }
-
- /**
- * @return int A return code that indicates what action should the processor take next
- */
- protected function processRowEndingNode()
- {
- // if the fetched row is empty and we don't want to preserve it..,
- if (!$this->shouldPreserveEmptyRows && $this->isEmptyRow($this->currentlyProcessedRowData)) {
- // ... skip it
- return XMLProcessor::PROCESSING_CONTINUE;
- }
-
- $this->numReadRows++;
-
- // If needed, we fill the empty cells
- if ($this->numColumns === 0) {
- $this->currentlyProcessedRowData = CellHelper::fillMissingArrayIndexes($this->currentlyProcessedRowData);
- }
-
- // at this point, we have all the data we need for the row
- // so that we can populate the buffer
- return XMLProcessor::PROCESSING_STOP;
- }
-
- /**
- * @return int A return code that indicates what action should the processor take next
- */
- protected function processWorksheetEndingNode()
- {
- // The closing "" marks the end of the file
- $this->hasReachedEndOfFile = true;
-
- return XMLProcessor::PROCESSING_STOP;
- }
-
- /**
- * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XMLReader object, positioned on a "" node
- * @return int Row index
- * @throws \Box\Spout\Common\Exception\InvalidArgumentException When the given cell index is invalid
- */
- protected function getRowIndex($xmlReader)
- {
- // Get "r" attribute if present (from something like
- $currentRowIndex = $xmlReader->getAttribute(self::XML_ATTRIBUTE_ROW_INDEX);
-
- return ($currentRowIndex !== null) ?
- intval($currentRowIndex) :
- $this->lastRowIndexProcessed + 1;
- }
-
- /**
- * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XMLReader object, positioned on a "" node
- * @return int Column index
- * @throws \Box\Spout\Common\Exception\InvalidArgumentException When the given cell index is invalid
- */
- protected function getColumnIndex($xmlReader)
- {
- // Get "r" attribute if present (from something like
- $currentCellIndex = $xmlReader->getAttribute(self::XML_ATTRIBUTE_CELL_INDEX);
-
- return ($currentCellIndex !== null) ?
- CellHelper::getColumnIndexFromCellIndex($currentCellIndex) :
- $this->lastColumnIndexProcessed + 1;
- }
-
- /**
- * Returns the (unescaped) correctly marshalled, cell value associated to the given XML node.
- *
- * @param \DOMNode $node
- * @return string|int|float|bool|\DateTime|null The value associated with the cell (null when the cell has an error)
- */
- protected function getCellValue($node)
- {
- return $this->cellValueFormatter->extractAndFormatNodeValue($node);
- }
-
- /**
- * @param array $rowData
- * @return bool Whether the given row is empty
- */
- protected function isEmptyRow($rowData)
- {
- return (count($rowData) === 1 && $rowData[0] === '');
- }
-
- /**
- * Return the current element, either an empty row or from the buffer.
- * @link http://php.net/manual/en/iterator.current.php
- *
- * @return array|null
- */
- public function current()
- {
- $rowDataForRowToBeProcessed = $this->rowDataBuffer;
-
- if ($this->shouldPreserveEmptyRows) {
- // when we need to preserve empty rows, we will either return
- // an empty row or the last row read. This depends whether the
- // index of last row that was read matches the index of the last
- // row whose value should be returned.
- if ($this->lastRowIndexProcessed !== $this->nextRowIndexToBeProcessed) {
- // return empty row if mismatch between last processed row
- // and the row that needs to be returned
- $rowDataForRowToBeProcessed = [''];
- }
- }
-
- return $rowDataForRowToBeProcessed;
- }
-
- /**
- * Return the key of the current element. Here, the row index.
- * @link http://php.net/manual/en/iterator.key.php
- *
- * @return int
- */
- public function key()
- {
- // TODO: This should return $this->nextRowIndexToBeProcessed
- // but to avoid a breaking change, the return value for
- // this function has been kept as the number of rows read.
- return $this->shouldPreserveEmptyRows ?
- $this->nextRowIndexToBeProcessed :
- $this->numReadRows;
- }
-
-
- /**
- * Cleans up what was created to iterate over the object.
- *
- * @return void
- */
- public function end()
- {
- $this->xmlReader->close();
- }
-}
diff --git a/src/Spout/Reader/XLSX/Sheet.php b/src/Spout/Reader/XLSX/Sheet.php
deleted file mode 100644
index 9baaef2..0000000
--- a/src/Spout/Reader/XLSX/Sheet.php
+++ /dev/null
@@ -1,79 +0,0 @@
-rowIterator = new RowIterator($filePath, $sheetDataXMLFilePath, $options, $sharedStringsHelper);
- $this->index = $sheetIndex;
- $this->name = $sheetName;
- $this->isActive = $isSheetActive;
- }
-
- /**
- * @api
- * @return \Box\Spout\Reader\XLSX\RowIterator
- */
- public function getRowIterator()
- {
- return $this->rowIterator;
- }
-
- /**
- * @api
- * @return int Index of the sheet, based on order in the workbook (zero-based)
- */
- public function getIndex()
- {
- return $this->index;
- }
-
- /**
- * @api
- * @return string Name of the sheet
- */
- public function getName()
- {
- return $this->name;
- }
-
- /**
- * @api
- * @return bool Whether the sheet was defined as active
- */
- public function isActive()
- {
- return $this->isActive;
- }
-}
diff --git a/src/Spout/Reader/XLSX/SheetIterator.php b/src/Spout/Reader/XLSX/SheetIterator.php
deleted file mode 100644
index 7ba07d3..0000000
--- a/src/Spout/Reader/XLSX/SheetIterator.php
+++ /dev/null
@@ -1,114 +0,0 @@
-sheets = $sheetHelper->getSheets();
-
- if (count($this->sheets) === 0) {
- throw new NoSheetsFoundException('The file must contain at least one sheet.');
- }
- }
-
- /**
- * Rewind the Iterator to the first element
- * @link http://php.net/manual/en/iterator.rewind.php
- *
- * @return void
- */
- public function rewind()
- {
- $this->currentSheetIndex = 0;
- }
-
- /**
- * Checks if current position is valid
- * @link http://php.net/manual/en/iterator.valid.php
- *
- * @return bool
- */
- public function valid()
- {
- return ($this->currentSheetIndex < count($this->sheets));
- }
-
- /**
- * Move forward to next element
- * @link http://php.net/manual/en/iterator.next.php
- *
- * @return void
- */
- public function next()
- {
- // Using isset here because it is way faster than array_key_exists...
- if (isset($this->sheets[$this->currentSheetIndex])) {
- $currentSheet = $this->sheets[$this->currentSheetIndex];
- $currentSheet->getRowIterator()->end();
-
- $this->currentSheetIndex++;
- }
- }
-
- /**
- * Return the current element
- * @link http://php.net/manual/en/iterator.current.php
- *
- * @return \Box\Spout\Reader\XLSX\Sheet
- */
- public function current()
- {
- return $this->sheets[$this->currentSheetIndex];
- }
-
- /**
- * Return the key of the current element
- * @link http://php.net/manual/en/iterator.key.php
- *
- * @return int
- */
- public function key()
- {
- return $this->currentSheetIndex + 1;
- }
-
- /**
- * Cleans up what was created to iterate over the object.
- *
- * @return void
- */
- public function end()
- {
- // make sure we are not leaking memory in case the iteration stopped before the end
- foreach ($this->sheets as $sheet) {
- $sheet->getRowIterator()->end();
- }
- }
-}
diff --git a/src/Spout/Writer/AbstractMultiSheetsWriter.php b/src/Spout/Writer/AbstractMultiSheetsWriter.php
deleted file mode 100644
index d119660..0000000
--- a/src/Spout/Writer/AbstractMultiSheetsWriter.php
+++ /dev/null
@@ -1,119 +0,0 @@
-throwIfWriterAlreadyOpened('Writer must be configured before opening it.');
-
- $this->shouldCreateNewSheetsAutomatically = $shouldCreateNewSheetsAutomatically;
- return $this;
- }
-
- /**
- * Returns all the workbook's sheets
- *
- * @api
- * @return Common\Sheet[] All the workbook's sheets
- * @throws \Box\Spout\Writer\Exception\WriterNotOpenedException If the writer has not been opened yet
- */
- public function getSheets()
- {
- $this->throwIfBookIsNotAvailable();
-
- $externalSheets = [];
- $worksheets = $this->getWorkbook()->getWorksheets();
-
- /** @var Common\Internal\WorksheetInterface $worksheet */
- foreach ($worksheets as $worksheet) {
- $externalSheets[] = $worksheet->getExternalSheet();
- }
-
- return $externalSheets;
- }
-
- /**
- * Creates a new sheet and make it the current sheet. The data will now be written to this sheet.
- *
- * @api
- * @return Common\Sheet The created sheet
- * @throws \Box\Spout\Writer\Exception\WriterNotOpenedException If the writer has not been opened yet
- */
- public function addNewSheetAndMakeItCurrent()
- {
- $this->throwIfBookIsNotAvailable();
- $worksheet = $this->getWorkbook()->addNewSheetAndMakeItCurrent();
-
- return $worksheet->getExternalSheet();
- }
-
- /**
- * Returns the current sheet
- *
- * @api
- * @return Common\Sheet The current sheet
- * @throws \Box\Spout\Writer\Exception\WriterNotOpenedException If the writer has not been opened yet
- */
- public function getCurrentSheet()
- {
- $this->throwIfBookIsNotAvailable();
- return $this->getWorkbook()->getCurrentWorksheet()->getExternalSheet();
- }
-
- /**
- * Sets the given sheet as the current one. New data will be written to this sheet.
- * The writing will resume where it stopped (i.e. data won't be truncated).
- *
- * @api
- * @param Common\Sheet $sheet The sheet to set as current
- * @return void
- * @throws \Box\Spout\Writer\Exception\WriterNotOpenedException If the writer has not been opened yet
- * @throws \Box\Spout\Writer\Exception\SheetNotFoundException If the given sheet does not exist in the workbook
- */
- public function setCurrentSheet($sheet)
- {
- $this->throwIfBookIsNotAvailable();
- $this->getWorkbook()->setCurrentSheet($sheet);
- }
-
- /**
- * Checks if the book has been created. Throws an exception if not created yet.
- *
- * @return void
- * @throws \Box\Spout\Writer\Exception\WriterNotOpenedException If the book is not created yet
- */
- protected function throwIfBookIsNotAvailable()
- {
- if (!$this->getWorkbook()) {
- throw new WriterNotOpenedException('The writer must be opened before performing this action.');
- }
- }
-}
-
diff --git a/src/Spout/Writer/AbstractWriter.php b/src/Spout/Writer/AbstractWriter.php
deleted file mode 100644
index 83e190f..0000000
--- a/src/Spout/Writer/AbstractWriter.php
+++ /dev/null
@@ -1,384 +0,0 @@
-defaultRowStyle = $this->getDefaultRowStyle();
- $this->resetRowStyleToDefault();
- }
-
- /**
- * Sets the default styles for all rows added with "addRow".
- * Overriding the default style instead of using "addRowWithStyle" improves performance by 20%.
- * @see https://github.com/box/spout/issues/272
- *
- * @param Style\Style $defaultStyle
- * @return AbstractWriter
- */
- public function setDefaultRowStyle($defaultStyle)
- {
- $this->defaultRowStyle = $defaultStyle;
- $this->resetRowStyleToDefault();
- return $this;
- }
-
- /**
- * @param \Box\Spout\Common\Helper\GlobalFunctionsHelper $globalFunctionsHelper
- * @return AbstractWriter
- */
- public function setGlobalFunctionsHelper($globalFunctionsHelper)
- {
- $this->globalFunctionsHelper = $globalFunctionsHelper;
- return $this;
- }
-
- /**
- * Inits the writer and opens it to accept data.
- * By using this method, the data will be written to a file.
- *
- * @api
- * @param string $outputFilePath Path of the output file that will contain the data
- * @return AbstractWriter
- * @throws \Box\Spout\Common\Exception\IOException If the writer cannot be opened or if the given path is not writable
- */
- public function openToFile($outputFilePath)
- {
- $this->outputFilePath = $outputFilePath;
-
- $this->filePointer = $this->globalFunctionsHelper->fopen($this->outputFilePath, 'wb+');
- $this->throwIfFilePointerIsNotAvailable();
-
- $this->openWriter();
- $this->isWriterOpened = true;
-
- return $this;
- }
-
- /**
- * Inits the writer and opens it to accept data.
- * By using this method, the data will be outputted directly to the browser.
- *
- * @codeCoverageIgnore
- *
- * @api
- * @param string $outputFileName Name of the output file that will contain the data. If a path is passed in, only the file name will be kept
- * @return AbstractWriter
- * @throws \Box\Spout\Common\Exception\IOException If the writer cannot be opened
- */
- public function openToBrowser($outputFileName)
- {
- $this->outputFilePath = $this->globalFunctionsHelper->basename($outputFileName);
-
- $this->filePointer = $this->globalFunctionsHelper->fopen('php://output', 'w');
- $this->throwIfFilePointerIsNotAvailable();
-
- // Clear any previous output (otherwise the generated file will be corrupted)
- // @see https://github.com/box/spout/issues/241
- $this->globalFunctionsHelper->ob_end_clean();
-
- // Set headers
- $this->globalFunctionsHelper->header('Content-Type: ' . static::$headerContentType);
- $this->globalFunctionsHelper->header('Content-Disposition: attachment; filename="' . $this->outputFilePath . '"');
-
- /*
- * When forcing the download of a file over SSL,IE8 and lower browsers fail
- * if the Cache-Control and Pragma headers are not set.
- *
- * @see http://support.microsoft.com/KB/323308
- * @see https://github.com/liuggio/ExcelBundle/issues/45
- */
- $this->globalFunctionsHelper->header('Cache-Control: max-age=0');
- $this->globalFunctionsHelper->header('Pragma: public');
-
- $this->openWriter();
- $this->isWriterOpened = true;
-
- return $this;
- }
-
- /**
- * Checks if the pointer to the file/stream to write to is available.
- * Will throw an exception if not available.
- *
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If the pointer is not available
- */
- protected function throwIfFilePointerIsNotAvailable()
- {
- if (!$this->filePointer) {
- throw new IOException('File pointer has not be opened');
- }
- }
-
- /**
- * Checks if the writer has already been opened, since some actions must be done before it gets opened.
- * Throws an exception if already opened.
- *
- * @param string $message Error message
- * @return void
- * @throws \Box\Spout\Writer\Exception\WriterAlreadyOpenedException If the writer was already opened and must not be.
- */
- protected function throwIfWriterAlreadyOpened($message)
- {
- if ($this->isWriterOpened) {
- throw new WriterAlreadyOpenedException($message);
- }
- }
-
- /**
- * Write given data to the output. New data will be appended to end of stream.
- *
- * @param array $dataRow Array containing data to be streamed.
- * If empty, no data is added (i.e. not even as a blank row)
- * Example: $dataRow = ['data1', 1234, null, '', 'data5', false];
- * @api
- * @return AbstractWriter
- * @throws \Box\Spout\Writer\Exception\WriterNotOpenedException If this function is called before opening the writer
- * @throws \Box\Spout\Common\Exception\IOException If unable to write data
- * @throws \Box\Spout\Common\Exception\SpoutException If anything else goes wrong while writing data
- */
- public function addRow(array $dataRow)
- {
- if ($this->isWriterOpened) {
- // empty $dataRow should not add an empty line
- if (!empty($dataRow)) {
- try {
- $this->addRowToWriter($dataRow, $this->rowStyle);
- } catch (SpoutException $e) {
- // if an exception occurs while writing data,
- // close the writer and remove all files created so far.
- $this->closeAndAttemptToCleanupAllFiles();
-
- // re-throw the exception to alert developers of the error
- throw $e;
- }
- }
- } else {
- throw new WriterNotOpenedException('The writer needs to be opened before adding row.');
- }
-
- return $this;
- }
-
- /**
- * Write given data to the output and apply the given style.
- * @see addRow
- *
- * @api
- * @param array $dataRow Array of array containing data to be streamed.
- * @param Style\Style $style Style to be applied to the row.
- * @return AbstractWriter
- * @throws \Box\Spout\Common\Exception\InvalidArgumentException If the input param is not valid
- * @throws \Box\Spout\Writer\Exception\WriterNotOpenedException If this function is called before opening the writer
- * @throws \Box\Spout\Common\Exception\IOException If unable to write data
- */
- public function addRowWithStyle(array $dataRow, $style)
- {
- if (!$style instanceof Style\Style) {
- throw new InvalidArgumentException('The "$style" argument must be a Style instance and cannot be NULL.');
- }
-
- $this->setRowStyle($style);
- $this->addRow($dataRow);
- $this->resetRowStyleToDefault();
-
- return $this;
- }
-
- /**
- * Write given data to the output. New data will be appended to end of stream.
- *
- * @api
- * @param array $dataRows Array of array containing data to be streamed.
- * If a row is empty, it won't be added (i.e. not even as a blank row)
- * Example: $dataRows = [
- * ['data11', 12, , '', 'data13'],
- * ['data21', 'data22', null, false],
- * ];
- * @return AbstractWriter
- * @throws \Box\Spout\Common\Exception\InvalidArgumentException If the input param is not valid
- * @throws \Box\Spout\Writer\Exception\WriterNotOpenedException If this function is called before opening the writer
- * @throws \Box\Spout\Common\Exception\IOException If unable to write data
- */
- public function addRows(array $dataRows)
- {
- if (!empty($dataRows)) {
- $firstRow = reset($dataRows);
- if (!is_array($firstRow)) {
- throw new InvalidArgumentException('The input should be an array of arrays');
- }
-
- foreach ($dataRows as $dataRow) {
- $this->addRow($dataRow);
- }
- }
-
- return $this;
- }
-
- /**
- * Write given data to the output and apply the given style.
- * @see addRows
- *
- * @api
- * @param array $dataRows Array of array containing data to be streamed.
- * @param Style\Style $style Style to be applied to the rows.
- * @return AbstractWriter
- * @throws \Box\Spout\Common\Exception\InvalidArgumentException If the input param is not valid
- * @throws \Box\Spout\Writer\Exception\WriterNotOpenedException If this function is called before opening the writer
- * @throws \Box\Spout\Common\Exception\IOException If unable to write data
- */
- public function addRowsWithStyle(array $dataRows, $style)
- {
- if (!$style instanceof Style\Style) {
- throw new InvalidArgumentException('The "$style" argument must be a Style instance and cannot be NULL.');
- }
-
- $this->setRowStyle($style);
- $this->addRows($dataRows);
- $this->resetRowStyleToDefault();
-
- return $this;
- }
-
- /**
- * Returns the default style to be applied to rows.
- * Can be overriden by children to have a custom style.
- *
- * @return Style\Style
- */
- protected function getDefaultRowStyle()
- {
- return (new StyleBuilder())->build();
- }
-
- /**
- * Sets the style to be applied to the next written rows
- * until it is changed or reset.
- *
- * @param Style\Style $style
- * @return void
- */
- private function setRowStyle($style)
- {
- // Merge given style with the default one to inherit custom properties
- $this->rowStyle = $style->mergeWith($this->defaultRowStyle);
- }
-
- /**
- * Resets the style to be applied to the next written rows.
- *
- * @return void
- */
- private function resetRowStyleToDefault()
- {
- $this->rowStyle = $this->defaultRowStyle;
- }
-
- /**
- * Closes the writer. This will close the streamer as well, preventing new data
- * to be written to the file.
- *
- * @api
- * @return void
- */
- public function close()
- {
- if (!$this->isWriterOpened) {
- return;
- }
-
- $this->closeWriter();
-
- if (is_resource($this->filePointer)) {
- $this->globalFunctionsHelper->fclose($this->filePointer);
- }
-
- $this->isWriterOpened = false;
- }
-
- /**
- * Closes the writer and attempts to cleanup all files that were
- * created during the writing process (temp files & final file).
- *
- * @return void
- */
- private function closeAndAttemptToCleanupAllFiles()
- {
- // close the writer, which should remove all temp files
- $this->close();
-
- // remove output file if it was created
- if ($this->globalFunctionsHelper->file_exists($this->outputFilePath)) {
- $outputFolderPath = dirname($this->outputFilePath);
- $fileSystemHelper = new FileSystemHelper($outputFolderPath);
- $fileSystemHelper->deleteFile($this->outputFilePath);
- }
- }
-}
diff --git a/src/Spout/Writer/CSV/Writer.php b/src/Spout/Writer/CSV/Writer.php
deleted file mode 100644
index f7f1fda..0000000
--- a/src/Spout/Writer/CSV/Writer.php
+++ /dev/null
@@ -1,118 +0,0 @@
-fieldDelimiter = $fieldDelimiter;
- return $this;
- }
-
- /**
- * Sets the field enclosure for the CSV
- *
- * @api
- * @param string $fieldEnclosure Character that enclose fields
- * @return Writer
- */
- public function setFieldEnclosure($fieldEnclosure)
- {
- $this->fieldEnclosure = $fieldEnclosure;
- return $this;
- }
-
- /**
- * Set if a BOM has to be added to the file
- *
- * @param bool $shouldAddBOM
- * @return Writer
- */
- public function setShouldAddBOM($shouldAddBOM)
- {
- $this->shouldAddBOM = (bool) $shouldAddBOM;
- return $this;
- }
-
- /**
- * Opens the CSV streamer and makes it ready to accept data.
- *
- * @return void
- */
- protected function openWriter()
- {
- if ($this->shouldAddBOM) {
- // Adds UTF-8 BOM for Unicode compatibility
- $this->globalFunctionsHelper->fputs($this->filePointer, EncodingHelper::BOM_UTF8);
- }
- }
-
- /**
- * Adds data to the currently opened writer.
- *
- * @param array $dataRow Array containing data to be written.
- * Example $dataRow = ['data1', 1234, null, '', 'data5'];
- * @param \Box\Spout\Writer\Style\Style $style Ignored here since CSV does not support styling.
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If unable to write data
- */
- protected function addRowToWriter(array $dataRow, $style)
- {
- $wasWriteSuccessful = $this->globalFunctionsHelper->fputcsv($this->filePointer, $dataRow, $this->fieldDelimiter, $this->fieldEnclosure);
- if ($wasWriteSuccessful === false) {
- throw new IOException('Unable to write data');
- }
-
- $this->lastWrittenRowIndex++;
- if ($this->lastWrittenRowIndex % self::FLUSH_THRESHOLD === 0) {
- $this->globalFunctionsHelper->fflush($this->filePointer);
- }
- }
-
- /**
- * Closes the CSV streamer, preventing any additional writing.
- * If set, sets the headers and redirects output to the browser.
- *
- * @return void
- */
- protected function closeWriter()
- {
- $this->lastWrittenRowIndex = 0;
- }
-}
diff --git a/src/Spout/Writer/Common/Helper/AbstractStyleHelper.php b/src/Spout/Writer/Common/Helper/AbstractStyleHelper.php
deleted file mode 100644
index fa5e267..0000000
--- a/src/Spout/Writer/Common/Helper/AbstractStyleHelper.php
+++ /dev/null
@@ -1,138 +0,0 @@
- [STYLE_ID] mapping table, keeping track of the registered styles */
- protected $serializedStyleToStyleIdMappingTable = [];
-
- /** @var array [STYLE_ID] => [STYLE] mapping table, keeping track of the registered styles */
- protected $styleIdToStyleMappingTable = [];
-
- /**
- * @param \Box\Spout\Writer\Style\Style $defaultStyle
- */
- public function __construct($defaultStyle)
- {
- // This ensures that the default style is the first one to be registered
- $this->registerStyle($defaultStyle);
- }
-
- /**
- * Registers the given style as a used style.
- * Duplicate styles won't be registered more than once.
- *
- * @param \Box\Spout\Writer\Style\Style $style The style to be registered
- * @return \Box\Spout\Writer\Style\Style The registered style, updated with an internal ID.
- */
- public function registerStyle($style)
- {
- $serializedStyle = $style->serialize();
-
- if (!$this->hasStyleAlreadyBeenRegistered($style)) {
- $nextStyleId = count($this->serializedStyleToStyleIdMappingTable);
- $style->setId($nextStyleId);
-
- $this->serializedStyleToStyleIdMappingTable[$serializedStyle] = $nextStyleId;
- $this->styleIdToStyleMappingTable[$nextStyleId] = $style;
- }
-
- return $this->getStyleFromSerializedStyle($serializedStyle);
- }
-
- /**
- * Returns whether the given style has already been registered.
- *
- * @param \Box\Spout\Writer\Style\Style $style
- * @return bool
- */
- protected function hasStyleAlreadyBeenRegistered($style)
- {
- $serializedStyle = $style->serialize();
-
- // Using isset here because it is way faster than array_key_exists...
- return isset($this->serializedStyleToStyleIdMappingTable[$serializedStyle]);
- }
-
- /**
- * Returns the registered style associated to the given serialization.
- *
- * @param string $serializedStyle The serialized style from which the actual style should be fetched from
- * @return \Box\Spout\Writer\Style\Style
- */
- protected function getStyleFromSerializedStyle($serializedStyle)
- {
- $styleId = $this->serializedStyleToStyleIdMappingTable[$serializedStyle];
- return $this->styleIdToStyleMappingTable[$styleId];
- }
-
- /**
- * @return \Box\Spout\Writer\Style\Style[] List of registered styles
- */
- protected function getRegisteredStyles()
- {
- return array_values($this->styleIdToStyleMappingTable);
- }
-
- /**
- * Returns the default style
- *
- * @return \Box\Spout\Writer\Style\Style Default style
- */
- protected function getDefaultStyle()
- {
- // By construction, the default style has ID 0
- return $this->styleIdToStyleMappingTable[0];
- }
-
- /**
- * Apply additional styles if the given row needs it.
- * Typically, set "wrap text" if a cell contains a new line.
- *
- * @param \Box\Spout\Writer\Style\Style $style The original style
- * @param array $dataRow The row the style will be applied to
- * @return \Box\Spout\Writer\Style\Style The updated style
- */
- public function applyExtraStylesIfNeeded($style, $dataRow)
- {
- $updatedStyle = $this->applyWrapTextIfCellContainsNewLine($style, $dataRow);
- return $updatedStyle;
- }
-
- /**
- * Set the "wrap text" option if a cell of the given row contains a new line.
- *
- * @NOTE: There is a bug on the Mac version of Excel (2011 and below) where new lines
- * are ignored even when the "wrap text" option is set. This only occurs with
- * inline strings (shared strings do work fine).
- * A workaround would be to encode "\n" as "_x000D_" but it does not work
- * on the Windows version of Excel...
- *
- * @param \Box\Spout\Writer\Style\Style $style The original style
- * @param array $dataRow The row the style will be applied to
- * @return \Box\Spout\Writer\Style\Style The eventually updated style
- */
- protected function applyWrapTextIfCellContainsNewLine($style, $dataRow)
- {
- // if the "wrap text" option is already set, no-op
- if ($style->hasSetWrapText()) {
- return $style;
- }
-
- foreach ($dataRow as $cell) {
- if (is_string($cell) && strpos($cell, "\n") !== false) {
- $style->setShouldWrapText();
- break;
- }
- }
-
- return $style;
- }
-}
diff --git a/src/Spout/Writer/Common/Helper/CellHelper.php b/src/Spout/Writer/Common/Helper/CellHelper.php
deleted file mode 100644
index 50ead93..0000000
--- a/src/Spout/Writer/Common/Helper/CellHelper.php
+++ /dev/null
@@ -1,91 +0,0 @@
- cell index */
- private static $columnIndexToCellIndexCache = [];
-
- /**
- * Returns the cell index (base 26) associated to the base 10 column index.
- * Excel uses A to Z letters for column indexing, where A is the 1st column,
- * Z is the 26th and AA is the 27th.
- * The mapping is zero based, so that 0 maps to A, B maps to 1, Z to 25 and AA to 26.
- *
- * @param int $columnIndex The Excel column index (0, 42, ...)
- * @return string The associated cell index ('A', 'BC', ...)
- */
- public static function getCellIndexFromColumnIndex($columnIndex)
- {
- $originalColumnIndex = $columnIndex;
-
- // Using isset here because it is way faster than array_key_exists...
- if (!isset(self::$columnIndexToCellIndexCache[$originalColumnIndex])) {
- $cellIndex = '';
- $capitalAAsciiValue = ord('A');
-
- do {
- $modulus = $columnIndex % 26;
- $cellIndex = chr($capitalAAsciiValue + $modulus) . $cellIndex;
-
- // substracting 1 because it's zero-based
- $columnIndex = intval($columnIndex / 26) - 1;
-
- } while ($columnIndex >= 0);
-
- self::$columnIndexToCellIndexCache[$originalColumnIndex] = $cellIndex;
- }
-
- return self::$columnIndexToCellIndexCache[$originalColumnIndex];
- }
-
- /**
- * @param $value
- * @return bool Whether the given value is considered "empty"
- */
- public static function isEmpty($value)
- {
- return ($value === null || $value === '');
- }
-
- /**
- * @param $value
- * @return bool Whether the given value is a non empty string
- */
- public static function isNonEmptyString($value)
- {
- return (gettype($value) === 'string' && $value !== '');
- }
-
- /**
- * Returns whether the given value is numeric.
- * A numeric value is from type "integer" or "double" ("float" is not returned by gettype).
- *
- * @param $value
- * @return bool Whether the given value is numeric
- */
- public static function isNumeric($value)
- {
- $valueType = gettype($value);
- return ($valueType === 'integer' || $valueType === 'double');
- }
-
- /**
- * Returns whether the given value is boolean.
- * "true"/"false" and 0/1 are not booleans.
- *
- * @param $value
- * @return bool Whether the given value is boolean
- */
- public static function isBoolean($value)
- {
- return gettype($value) === 'boolean';
- }
-}
diff --git a/src/Spout/Writer/Common/Helper/ZipHelper.php b/src/Spout/Writer/Common/Helper/ZipHelper.php
deleted file mode 100644
index 1670d17..0000000
--- a/src/Spout/Writer/Common/Helper/ZipHelper.php
+++ /dev/null
@@ -1,217 +0,0 @@
-tmpFolderPath = $tmpFolderPath;
- }
-
- /**
- * Returns the already created ZipArchive instance or
- * creates one if none exists.
- *
- * @return \ZipArchive
- */
- protected function createOrGetZip()
- {
- if (!isset($this->zip)) {
- $this->zip = new \ZipArchive();
- $zipFilePath = $this->getZipFilePath();
-
- $this->zip->open($zipFilePath, \ZipArchive::CREATE|\ZipArchive::OVERWRITE);
- }
-
- return $this->zip;
- }
-
- /**
- * @return string Path where the zip file of the given folder will be created
- */
- public function getZipFilePath()
- {
- return $this->tmpFolderPath . self::ZIP_EXTENSION;
- }
-
- /**
- * Adds the given file, located under the given root folder to the archive.
- * The file will be compressed.
- *
- * Example of use:
- * addFileToArchive('/tmp/xlsx/foo', 'bar/baz.xml');
- * => will add the file located at '/tmp/xlsx/foo/bar/baz.xml' in the archive, but only as 'bar/baz.xml'
- *
- * @param string $rootFolderPath Path of the root folder that will be ignored in the archive tree.
- * @param string $localFilePath Path of the file to be added, under the root folder
- * @param string|void $existingFileMode Controls what to do when trying to add an existing file
- * @return void
- */
- public function addFileToArchive($rootFolderPath, $localFilePath, $existingFileMode = self::EXISTING_FILES_OVERWRITE)
- {
- $this->addFileToArchiveWithCompressionMethod(
- $rootFolderPath,
- $localFilePath,
- $existingFileMode,
- \ZipArchive::CM_DEFAULT
- );
- }
-
- /**
- * Adds the given file, located under the given root folder to the archive.
- * The file will NOT be compressed.
- *
- * Example of use:
- * addUncompressedFileToArchive('/tmp/xlsx/foo', 'bar/baz.xml');
- * => will add the file located at '/tmp/xlsx/foo/bar/baz.xml' in the archive, but only as 'bar/baz.xml'
- *
- * @param string $rootFolderPath Path of the root folder that will be ignored in the archive tree.
- * @param string $localFilePath Path of the file to be added, under the root folder
- * @param string|void $existingFileMode Controls what to do when trying to add an existing file
- * @return void
- */
- public function addUncompressedFileToArchive($rootFolderPath, $localFilePath, $existingFileMode = self::EXISTING_FILES_OVERWRITE)
- {
- $this->addFileToArchiveWithCompressionMethod(
- $rootFolderPath,
- $localFilePath,
- $existingFileMode,
- \ZipArchive::CM_STORE
- );
- }
-
- /**
- * Adds the given file, located under the given root folder to the archive.
- * The file will NOT be compressed.
- *
- * Example of use:
- * addUncompressedFileToArchive('/tmp/xlsx/foo', 'bar/baz.xml');
- * => will add the file located at '/tmp/xlsx/foo/bar/baz.xml' in the archive, but only as 'bar/baz.xml'
- *
- * @param string $rootFolderPath Path of the root folder that will be ignored in the archive tree.
- * @param string $localFilePath Path of the file to be added, under the root folder
- * @param string $existingFileMode Controls what to do when trying to add an existing file
- * @param int $compressionMethod The compression method
- * @return void
- */
- protected function addFileToArchiveWithCompressionMethod($rootFolderPath, $localFilePath, $existingFileMode, $compressionMethod)
- {
- $zip = $this->createOrGetZip();
-
- if (!$this->shouldSkipFile($zip, $localFilePath, $existingFileMode)) {
- $normalizedFullFilePath = $this->getNormalizedRealPath($rootFolderPath . '/' . $localFilePath);
- $zip->addFile($normalizedFullFilePath, $localFilePath);
-
- if (self::canChooseCompressionMethod()) {
- $zip->setCompressionName($localFilePath, $compressionMethod);
- }
- }
- }
-
- /**
- * @return bool Whether it is possible to choose the desired compression method to be used
- */
- public static function canChooseCompressionMethod()
- {
- // setCompressionName() is a PHP7+ method...
- return (method_exists(new \ZipArchive(), 'setCompressionName'));
- }
-
- /**
- * @param string $folderPath Path to the folder to be zipped
- * @param string|void $existingFileMode Controls what to do when trying to add an existing file
- * @return void
- */
- public function addFolderToArchive($folderPath, $existingFileMode = self::EXISTING_FILES_OVERWRITE)
- {
- $zip = $this->createOrGetZip();
-
- $folderRealPath = $this->getNormalizedRealPath($folderPath) . '/';
- $itemIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($folderPath, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST);
-
- foreach ($itemIterator as $itemInfo) {
- $itemRealPath = $this->getNormalizedRealPath($itemInfo->getPathname());
- $itemLocalPath = str_replace($folderRealPath, '', $itemRealPath);
-
- if ($itemInfo->isFile() && !$this->shouldSkipFile($zip, $itemLocalPath, $existingFileMode)) {
- $zip->addFile($itemRealPath, $itemLocalPath);
- }
- }
- }
-
- /**
- * @param \ZipArchive $zip
- * @param string $itemLocalPath
- * @param string $existingFileMode
- * @return bool Whether the file should be added to the archive or skipped
- */
- protected function shouldSkipFile($zip, $itemLocalPath, $existingFileMode)
- {
- // Skip files if:
- // - EXISTING_FILES_SKIP mode chosen
- // - File already exists in the archive
- return ($existingFileMode === self::EXISTING_FILES_SKIP && $zip->locateName($itemLocalPath) !== false);
- }
-
- /**
- * Returns canonicalized absolute pathname, containing only forward slashes.
- *
- * @param string $path Path to normalize
- * @return string Normalized and canonicalized path
- */
- protected function getNormalizedRealPath($path)
- {
- $realPath = realpath($path);
- return str_replace(DIRECTORY_SEPARATOR, '/', $realPath);
- }
-
- /**
- * Closes the archive and copies it into the given stream
- *
- * @param resource $streamPointer Pointer to the stream to copy the zip
- * @return void
- */
- public function closeArchiveAndCopyToStream($streamPointer)
- {
- $zip = $this->createOrGetZip();
- $zip->close();
- unset($this->zip);
-
- $this->copyZipToStream($streamPointer);
- }
-
- /**
- * Streams the contents of the zip file into the given stream
- *
- * @param resource $pointer Pointer to the stream to copy the zip
- * @return void
- */
- protected function copyZipToStream($pointer)
- {
- $zipFilePointer = fopen($this->getZipFilePath(), 'r');
- stream_copy_to_stream($zipFilePointer, $pointer);
- fclose($zipFilePointer);
- }
-}
diff --git a/src/Spout/Writer/Common/Internal/AbstractWorkbook.php b/src/Spout/Writer/Common/Internal/AbstractWorkbook.php
deleted file mode 100644
index e852e1a..0000000
--- a/src/Spout/Writer/Common/Internal/AbstractWorkbook.php
+++ /dev/null
@@ -1,192 +0,0 @@
-shouldCreateNewSheetsAutomatically = $shouldCreateNewSheetsAutomatically;
- $this->internalId = uniqid();
- }
-
- /**
- * @return \Box\Spout\Writer\Common\Helper\AbstractStyleHelper The specific style helper
- */
- abstract protected function getStyleHelper();
-
- /**
- * @return int Maximum number of rows/columns a sheet can contain
- */
- abstract protected function getMaxRowsPerWorksheet();
-
- /**
- * Creates a new sheet in the workbook. The current sheet remains unchanged.
- *
- * @return WorksheetInterface The created sheet
- * @throws \Box\Spout\Common\Exception\IOException If unable to open the sheet for writing
- */
- abstract public function addNewSheet();
-
- /**
- * Creates a new sheet in the workbook and make it the current sheet.
- * The writing will resume where it stopped (i.e. data won't be truncated).
- *
- * @return WorksheetInterface The created sheet
- * @throws \Box\Spout\Common\Exception\IOException If unable to open the sheet for writing
- */
- public function addNewSheetAndMakeItCurrent()
- {
- $worksheet = $this->addNewSheet();
- $this->setCurrentWorksheet($worksheet);
-
- return $worksheet;
- }
-
- /**
- * @return WorksheetInterface[] All the workbook's sheets
- */
- public function getWorksheets()
- {
- return $this->worksheets;
- }
-
- /**
- * Returns the current sheet
- *
- * @return WorksheetInterface The current sheet
- */
- public function getCurrentWorksheet()
- {
- return $this->currentWorksheet;
- }
-
- /**
- * Sets the given sheet as the current one. New data will be written to this sheet.
- * The writing will resume where it stopped (i.e. data won't be truncated).
- *
- * @param \Box\Spout\Writer\Common\Sheet $sheet The "external" sheet to set as current
- * @return void
- * @throws \Box\Spout\Writer\Exception\SheetNotFoundException If the given sheet does not exist in the workbook
- */
- public function setCurrentSheet($sheet)
- {
- $worksheet = $this->getWorksheetFromExternalSheet($sheet);
- if ($worksheet !== null) {
- $this->currentWorksheet = $worksheet;
- } else {
- throw new SheetNotFoundException('The given sheet does not exist in the workbook.');
- }
- }
-
- /**
- * @param WorksheetInterface $worksheet
- * @return void
- */
- protected function setCurrentWorksheet($worksheet)
- {
- $this->currentWorksheet = $worksheet;
- }
-
- /**
- * Returns the worksheet associated to the given external sheet.
- *
- * @param \Box\Spout\Writer\Common\Sheet $sheet
- * @return WorksheetInterface|null The worksheet associated to the given external sheet or null if not found.
- */
- protected function getWorksheetFromExternalSheet($sheet)
- {
- $worksheetFound = null;
-
- foreach ($this->worksheets as $worksheet) {
- if ($worksheet->getExternalSheet() === $sheet) {
- $worksheetFound = $worksheet;
- break;
- }
- }
-
- return $worksheetFound;
- }
-
- /**
- * Adds data to the current sheet.
- * If shouldCreateNewSheetsAutomatically option is set to true, it will handle pagination
- * with the creation of new worksheets if one worksheet has reached its maximum capicity.
- *
- * @param array $dataRow Array containing data to be written. Cannot be empty.
- * Example $dataRow = ['data1', 1234, null, '', 'data5'];
- * @param \Box\Spout\Writer\Style\Style $style Style to be applied to the row.
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If trying to create a new sheet and unable to open the sheet for writing
- * @throws \Box\Spout\Writer\Exception\WriterException If unable to write data
- */
- public function addRowToCurrentWorksheet($dataRow, $style)
- {
- $currentWorksheet = $this->getCurrentWorksheet();
- $hasReachedMaxRows = $this->hasCurrentWorkseetReachedMaxRows();
- $styleHelper = $this->getStyleHelper();
-
- // if we reached the maximum number of rows for the current sheet...
- if ($hasReachedMaxRows) {
- // ... continue writing in a new sheet if option set
- if ($this->shouldCreateNewSheetsAutomatically) {
- $currentWorksheet = $this->addNewSheetAndMakeItCurrent();
-
- $updatedStyle = $styleHelper->applyExtraStylesIfNeeded($style, $dataRow);
- $registeredStyle = $styleHelper->registerStyle($updatedStyle);
- $currentWorksheet->addRow($dataRow, $registeredStyle);
- } else {
- // otherwise, do nothing as the data won't be read anyways
- }
- } else {
- $updatedStyle = $styleHelper->applyExtraStylesIfNeeded($style, $dataRow);
- $registeredStyle = $styleHelper->registerStyle($updatedStyle);
- $currentWorksheet->addRow($dataRow, $registeredStyle);
- }
- }
-
- /**
- * @return bool Whether the current worksheet has reached the maximum number of rows per sheet.
- */
- protected function hasCurrentWorkseetReachedMaxRows()
- {
- $currentWorksheet = $this->getCurrentWorksheet();
- return ($currentWorksheet->getLastWrittenRowIndex() >= $this->getMaxRowsPerWorksheet());
- }
-
- /**
- * Closes the workbook and all its associated sheets.
- * All the necessary files are written to disk and zipped together to create the ODS file.
- * All the temporary files are then deleted.
- *
- * @param resource $finalFilePointer Pointer to the ODS that will be created
- * @return void
- */
- abstract public function close($finalFilePointer);
-}
diff --git a/src/Spout/Writer/Common/Internal/WorkbookInterface.php b/src/Spout/Writer/Common/Internal/WorkbookInterface.php
deleted file mode 100644
index fda0793..0000000
--- a/src/Spout/Writer/Common/Internal/WorkbookInterface.php
+++ /dev/null
@@ -1,74 +0,0 @@
- [[SHEET_INDEX] => [SHEET_NAME]] keeping track of sheets' name to enforce uniqueness per workbook */
- protected static $SHEETS_NAME_USED = [];
-
- /** @var int Index of the sheet, based on order in the workbook (zero-based) */
- protected $index;
-
- /** @var string ID of the sheet's associated workbook. Used to restrict sheet name uniqueness enforcement to a single workbook */
- protected $associatedWorkbookId;
-
- /** @var string Name of the sheet */
- protected $name;
-
- /** @var \Box\Spout\Common\Helper\StringHelper */
- protected $stringHelper;
-
- /**
- * @param int $sheetIndex Index of the sheet, based on order in the workbook (zero-based)
- * @param string $associatedWorkbookId ID of the sheet's associated workbook
- */
- public function __construct($sheetIndex, $associatedWorkbookId)
- {
- $this->index = $sheetIndex;
- $this->associatedWorkbookId = $associatedWorkbookId;
- if (!isset(self::$SHEETS_NAME_USED[$associatedWorkbookId])) {
- self::$SHEETS_NAME_USED[$associatedWorkbookId] = [];
- }
-
- $this->stringHelper = new StringHelper();
- $this->setName(self::DEFAULT_SHEET_NAME_PREFIX . ($sheetIndex + 1));
- }
-
- /**
- * @api
- * @return int Index of the sheet, based on order in the workbook (zero-based)
- */
- public function getIndex()
- {
- return $this->index;
- }
-
- /**
- * @api
- * @return string Name of the sheet
- */
- public function getName()
- {
- return $this->name;
- }
-
- /**
- * Sets the name of the sheet. Note that Excel has some restrictions on the name:
- * - it should not be blank
- * - it should not exceed 31 characters
- * - it should not contain these characters: \ / ? * : [ or ]
- * - it should be unique
- *
- * @api
- * @param string $name Name of the sheet
- * @return Sheet
- * @throws \Box\Spout\Writer\Exception\InvalidSheetNameException If the sheet's name is invalid.
- */
- public function setName($name)
- {
- $this->throwIfNameIsInvalid($name);
-
- $this->name = $name;
- self::$SHEETS_NAME_USED[$this->associatedWorkbookId][$this->index] = $name;
-
- return $this;
- }
-
- /**
- * Throws an exception if the given sheet's name is not valid.
- * @see Sheet::setName for validity rules.
- *
- * @param string $name
- * @return void
- * @throws \Box\Spout\Writer\Exception\InvalidSheetNameException If the sheet's name is invalid.
- */
- protected function throwIfNameIsInvalid($name)
- {
- if (!is_string($name)) {
- $actualType = gettype($name);
- $errorMessage = "The sheet's name is invalid. It must be a string ($actualType given).";
- throw new InvalidSheetNameException($errorMessage);
- }
-
- $failedRequirements = [];
- $nameLength = $this->stringHelper->getStringLength($name);
-
- if (!$this->isNameUnique($name)) {
- $failedRequirements[] = 'It should be unique';
- } else {
- if ($nameLength === 0) {
- $failedRequirements[] = 'It should not be blank';
- } else {
- if ($nameLength > self::MAX_LENGTH_SHEET_NAME) {
- $failedRequirements[] = 'It should not exceed 31 characters';
- }
-
- if ($this->doesContainInvalidCharacters($name)) {
- $failedRequirements[] = 'It should not contain these characters: \\ / ? * : [ or ]';
- }
-
- if ($this->doesStartOrEndWithSingleQuote($name)) {
- $failedRequirements[] = 'It should not start or end with a single quote';
- }
- }
- }
-
- if (count($failedRequirements) !== 0) {
- $errorMessage = "The sheet's name (\"$name\") is invalid. It did not respect these rules:\n - ";
- $errorMessage .= implode("\n - ", $failedRequirements);
- throw new InvalidSheetNameException($errorMessage);
- }
- }
-
- /**
- * Returns whether the given name contains at least one invalid character.
- * @see Sheet::$INVALID_CHARACTERS_IN_SHEET_NAME for the full list.
- *
- * @param string $name
- * @return bool TRUE if the name contains invalid characters, FALSE otherwise.
- */
- protected function doesContainInvalidCharacters($name)
- {
- return (str_replace(self::$INVALID_CHARACTERS_IN_SHEET_NAME, '', $name) !== $name);
- }
-
- /**
- * Returns whether the given name starts or ends with a single quote
- *
- * @param string $name
- * @return bool TRUE if the name starts or ends with a single quote, FALSE otherwise.
- */
- protected function doesStartOrEndWithSingleQuote($name)
- {
- $startsWithSingleQuote = ($this->stringHelper->getCharFirstOccurrencePosition('\'', $name) === 0);
- $endsWithSingleQuote = ($this->stringHelper->getCharLastOccurrencePosition('\'', $name) === ($this->stringHelper->getStringLength($name) - 1));
-
- return ($startsWithSingleQuote || $endsWithSingleQuote);
- }
-
- /**
- * Returns whether the given name is unique.
- *
- * @param string $name
- * @return bool TRUE if the name is unique, FALSE otherwise.
- */
- protected function isNameUnique($name)
- {
- foreach (self::$SHEETS_NAME_USED[$this->associatedWorkbookId] as $sheetIndex => $sheetName) {
- if ($sheetIndex !== $this->index && $sheetName === $name) {
- return false;
- }
- }
-
- return true;
- }
-}
diff --git a/src/Spout/Writer/Exception/Border/InvalidNameException.php b/src/Spout/Writer/Exception/Border/InvalidNameException.php
deleted file mode 100644
index 13ac06c..0000000
--- a/src/Spout/Writer/Exception/Border/InvalidNameException.php
+++ /dev/null
@@ -1,16 +0,0 @@
-
- */
-class BorderHelper
-{
- /**
- * Width mappings
- *
- * @var array
- */
- protected static $widthMap = [
- Border::WIDTH_THIN => '0.75pt',
- Border::WIDTH_MEDIUM => '1.75pt',
- Border::WIDTH_THICK => '2.5pt',
- ];
-
- /**
- * Style mapping
- *
- * @var array
- */
- protected static $styleMap = [
- Border::STYLE_SOLID => 'solid',
- Border::STYLE_DASHED => 'dashed',
- Border::STYLE_DOTTED => 'dotted',
- Border::STYLE_DOUBLE => 'double',
- ];
-
- /**
- * @param BorderPart $borderPart
- * @return string
- */
- public static function serializeBorderPart(BorderPart $borderPart)
- {
- $definition = 'fo:border-%s="%s"';
-
- if ($borderPart->getStyle() === Border::STYLE_NONE) {
- $borderPartDefinition = sprintf($definition, $borderPart->getName(), 'none');
- } else {
- $attributes = [
- self::$widthMap[$borderPart->getWidth()],
- self::$styleMap[$borderPart->getStyle()],
- '#' . $borderPart->getColor(),
- ];
- $borderPartDefinition = sprintf($definition, $borderPart->getName(), implode(' ', $attributes));
- }
-
- return $borderPartDefinition;
- }
-}
diff --git a/src/Spout/Writer/ODS/Helper/FileSystemHelper.php b/src/Spout/Writer/ODS/Helper/FileSystemHelper.php
deleted file mode 100644
index 34ace0a..0000000
--- a/src/Spout/Writer/ODS/Helper/FileSystemHelper.php
+++ /dev/null
@@ -1,279 +0,0 @@
-rootFolder;
- }
-
- /**
- * @return string
- */
- public function getSheetsContentTempFolder()
- {
- return $this->sheetsContentTempFolder;
- }
-
- /**
- * Creates all the folders needed to create a ODS file, as well as the files that won't change.
- *
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If unable to create at least one of the base folders
- */
- public function createBaseFilesAndFolders()
- {
- $this
- ->createRootFolder()
- ->createMetaInfoFolderAndFile()
- ->createSheetsContentTempFolder()
- ->createMetaFile()
- ->createMimetypeFile();
- }
-
- /**
- * Creates the folder that will be used as root
- *
- * @return FileSystemHelper
- * @throws \Box\Spout\Common\Exception\IOException If unable to create the folder
- */
- protected function createRootFolder()
- {
- $this->rootFolder = $this->createFolder($this->baseFolderRealPath, uniqid('ods'));
- return $this;
- }
-
- /**
- * Creates the "META-INF" folder under the root folder as well as the "manifest.xml" file in it
- *
- * @return FileSystemHelper
- * @throws \Box\Spout\Common\Exception\IOException If unable to create the folder or the "manifest.xml" file
- */
- protected function createMetaInfoFolderAndFile()
- {
- $this->metaInfFolder = $this->createFolder($this->rootFolder, self::META_INF_FOLDER_NAME);
-
- $this->createManifestFile();
-
- return $this;
- }
-
- /**
- * Creates the "manifest.xml" file under the "META-INF" folder (under root)
- *
- * @return FileSystemHelper
- * @throws \Box\Spout\Common\Exception\IOException If unable to create the file
- */
- protected function createManifestFile()
- {
- $manifestXmlFileContents = <<
-
-
-
-
-
-
-EOD;
-
- $this->createFileWithContents($this->metaInfFolder, self::MANIFEST_XML_FILE_NAME, $manifestXmlFileContents);
-
- return $this;
- }
-
- /**
- * Creates the temp folder where specific sheets content will be written to.
- * This folder is not part of the final ODS file and is only used to be able to jump between sheets.
- *
- * @return FileSystemHelper
- * @throws \Box\Spout\Common\Exception\IOException If unable to create the folder
- */
- protected function createSheetsContentTempFolder()
- {
- $this->sheetsContentTempFolder = $this->createFolder($this->rootFolder, self::SHEETS_CONTENT_TEMP_FOLDER_NAME);
- return $this;
- }
-
- /**
- * Creates the "meta.xml" file under the root folder
- *
- * @return FileSystemHelper
- * @throws \Box\Spout\Common\Exception\IOException If unable to create the file
- */
- protected function createMetaFile()
- {
- $appName = self::APP_NAME;
- $createdDate = (new \DateTime())->format(\DateTime::W3C);
-
- $metaXmlFileContents = <<
-
-
- $appName
- $createdDate
- $createdDate
-
-
-EOD;
-
- $this->createFileWithContents($this->rootFolder, self::META_XML_FILE_NAME, $metaXmlFileContents);
-
- return $this;
- }
-
- /**
- * Creates the "mimetype" file under the root folder
- *
- * @return FileSystemHelper
- * @throws \Box\Spout\Common\Exception\IOException If unable to create the file
- */
- protected function createMimetypeFile()
- {
- $this->createFileWithContents($this->rootFolder, self::MIMETYPE_FILE_NAME, self::MIMETYPE);
- return $this;
- }
-
- /**
- * Creates the "content.xml" file under the root folder
- *
- * @param Worksheet[] $worksheets
- * @param StyleHelper $styleHelper
- * @return FileSystemHelper
- */
- public function createContentFile($worksheets, $styleHelper)
- {
- $contentXmlFileContents = <<
-
-EOD;
-
- $contentXmlFileContents .= $styleHelper->getContentXmlFontFaceSectionContent();
- $contentXmlFileContents .= $styleHelper->getContentXmlAutomaticStylesSectionContent(count($worksheets));
-
- $contentXmlFileContents .= '';
-
- $this->createFileWithContents($this->rootFolder, self::CONTENT_XML_FILE_NAME, $contentXmlFileContents);
-
- // Append sheets content to "content.xml"
- $contentXmlFilePath = $this->rootFolder . '/' . self::CONTENT_XML_FILE_NAME;
- $contentXmlHandle = fopen($contentXmlFilePath, 'a');
-
- foreach ($worksheets as $worksheet) {
- // write the "" node, with the final sheet's name
- fwrite($contentXmlHandle, $worksheet->getTableElementStartAsString());
-
- $worksheetFilePath = $worksheet->getWorksheetFilePath();
- $this->copyFileContentsToTarget($worksheetFilePath, $contentXmlHandle);
-
- fwrite($contentXmlHandle, '');
- }
-
- $contentXmlFileContents = '';
-
- fwrite($contentXmlHandle, $contentXmlFileContents);
- fclose($contentXmlHandle);
-
- return $this;
- }
-
- /**
- * Streams the content of the file at the given path into the target resource.
- * Depending on which mode the target resource was created with, it will truncate then copy
- * or append the content to the target file.
- *
- * @param string $sourceFilePath Path of the file whose content will be copied
- * @param resource $targetResource Target resource that will receive the content
- * @return void
- */
- protected function copyFileContentsToTarget($sourceFilePath, $targetResource)
- {
- $sourceHandle = fopen($sourceFilePath, 'r');
- stream_copy_to_stream($sourceHandle, $targetResource);
- fclose($sourceHandle);
- }
-
- /**
- * Deletes the temporary folder where sheets content was stored.
- *
- * @return FileSystemHelper
- */
- public function deleteWorksheetTempFolder()
- {
- $this->deleteFolderRecursively($this->sheetsContentTempFolder);
- return $this;
- }
-
-
- /**
- * Creates the "styles.xml" file under the root folder
- *
- * @param StyleHelper $styleHelper
- * @param int $numWorksheets Number of created worksheets
- * @return FileSystemHelper
- */
- public function createStylesFile($styleHelper, $numWorksheets)
- {
- $stylesXmlFileContents = $styleHelper->getStylesXMLFileContent($numWorksheets);
- $this->createFileWithContents($this->rootFolder, self::STYLES_XML_FILE_NAME, $stylesXmlFileContents);
-
- return $this;
- }
-
- /**
- * Zips the root folder and streams the contents of the zip into the given stream
- *
- * @param resource $streamPointer Pointer to the stream to copy the zip
- * @return void
- */
- public function zipRootFolderAndCopyToStream($streamPointer)
- {
- $zipHelper = new ZipHelper($this->rootFolder);
-
- // In order to have the file's mime type detected properly, files need to be added
- // to the zip file in a particular order.
- // @see http://www.jejik.com/articles/2010/03/how_to_correctly_create_odf_documents_using_zip/
- $zipHelper->addUncompressedFileToArchive($this->rootFolder, self::MIMETYPE_FILE_NAME);
-
- $zipHelper->addFolderToArchive($this->rootFolder, ZipHelper::EXISTING_FILES_SKIP);
- $zipHelper->closeArchiveAndCopyToStream($streamPointer);
-
- // once the zip is copied, remove it
- $this->deleteFile($zipHelper->getZipFilePath());
- }
-}
diff --git a/src/Spout/Writer/ODS/Helper/StyleHelper.php b/src/Spout/Writer/ODS/Helper/StyleHelper.php
deleted file mode 100644
index f5ad3bc..0000000
--- a/src/Spout/Writer/ODS/Helper/StyleHelper.php
+++ /dev/null
@@ -1,356 +0,0 @@
- [] Map whose keys contain all the fonts used */
- protected $usedFontsSet = [];
-
- /**
- * Registers the given style as a used style.
- * Duplicate styles won't be registered more than once.
- *
- * @param \Box\Spout\Writer\Style\Style $style The style to be registered
- * @return \Box\Spout\Writer\Style\Style The registered style, updated with an internal ID.
- */
- public function registerStyle($style)
- {
- $this->usedFontsSet[$style->getFontName()] = true;
- return parent::registerStyle($style);
- }
-
- /**
- * @return string[] List of used fonts name
- */
- protected function getUsedFonts()
- {
- return array_keys($this->usedFontsSet);
- }
-
- /**
- * Returns the content of the "styles.xml" file, given a list of styles.
- *
- * @param int $numWorksheets Number of worksheets created
- * @return string
- */
- public function getStylesXMLFileContent($numWorksheets)
- {
- $content = <<
-
-EOD;
-
- $content .= $this->getFontFaceSectionContent();
- $content .= $this->getStylesSectionContent();
- $content .= $this->getAutomaticStylesSectionContent($numWorksheets);
- $content .= $this->getMasterStylesSectionContent($numWorksheets);
-
- $content .= <<
-EOD;
-
- return $content;
- }
-
- /**
- * Returns the content of the "" section, inside "styles.xml" file.
- *
- * @return string
- */
- protected function getFontFaceSectionContent()
- {
- $content = '';
- foreach ($this->getUsedFonts() as $fontName) {
- $content .= '';
- }
- $content .= '';
-
- return $content;
- }
-
- /**
- * Returns the content of the "" section, inside "styles.xml" file.
- *
- * @return string
- */
- protected function getStylesSectionContent()
- {
- $defaultStyle = $this->getDefaultStyle();
-
- return <<
-
-
-
-
-
-
-
-
-EOD;
- }
-
- /**
- * Returns the content of the "" section, inside "styles.xml" file.
- *
- * @param int $numWorksheets Number of worksheets created
- * @return string
- */
- protected function getAutomaticStylesSectionContent($numWorksheets)
- {
- $content = '';
-
- for ($i = 1; $i <= $numWorksheets; $i++) {
- $content .= <<
-
-
-
-
-EOD;
- }
-
- $content .= '';
-
- return $content;
- }
-
- /**
- * Returns the content of the "" section, inside "styles.xml" file.
- *
- * @param int $numWorksheets Number of worksheets created
- * @return string
- */
- protected function getMasterStylesSectionContent($numWorksheets)
- {
- $content = '';
-
- for ($i = 1; $i <= $numWorksheets; $i++) {
- $content .= <<
-
-
-
-
-
-EOD;
- }
-
- $content .= '';
-
- return $content;
- }
-
-
- /**
- * Returns the contents of the "" section, inside "content.xml" file.
- *
- * @return string
- */
- public function getContentXmlFontFaceSectionContent()
- {
- $content = '';
- foreach ($this->getUsedFonts() as $fontName) {
- $content .= '';
- }
- $content .= '';
-
- return $content;
- }
-
- /**
- * Returns the contents of the "" section, inside "content.xml" file.
- *
- * @param int $numWorksheets Number of worksheets created
- * @return string
- */
- public function getContentXmlAutomaticStylesSectionContent($numWorksheets)
- {
- $content = '';
-
- foreach ($this->getRegisteredStyles() as $style) {
- $content .= $this->getStyleSectionContent($style);
- }
-
- $content .= <<
-
-
-
-
-
-EOD;
-
- for ($i = 1; $i <= $numWorksheets; $i++) {
- $content .= <<
-
-
-EOD;
- }
-
- $content .= '';
-
- return $content;
- }
-
- /**
- * Returns the contents of the "" section, inside "" section
- *
- * @param \Box\Spout\Writer\Style\Style $style
- * @return string
- */
- protected function getStyleSectionContent($style)
- {
- $styleIndex = $style->getId() + 1; // 1-based
-
- $content = '';
-
- $content .= $this->getTextPropertiesSectionContent($style);
- $content .= $this->getTableCellPropertiesSectionContent($style);
-
- $content .= '';
-
- return $content;
- }
-
- /**
- * Returns the contents of the "" section, inside "" section
- *
- * @param \Box\Spout\Writer\Style\Style $style
- * @return string
- */
- private function getTextPropertiesSectionContent($style)
- {
- $content = '';
-
- if ($style->shouldApplyFont()) {
- $content .= $this->getFontSectionContent($style);
- }
-
- return $content;
- }
-
- /**
- * Returns the contents of the "" section, inside "" section
- *
- * @param \Box\Spout\Writer\Style\Style $style
- * @return string
- */
- private function getFontSectionContent($style)
- {
- $defaultStyle = $this->getDefaultStyle();
-
- $content = 'getFontColor();
- if ($fontColor !== $defaultStyle->getFontColor()) {
- $content .= ' fo:color="#' . $fontColor . '"';
- }
-
- $fontName = $style->getFontName();
- if ($fontName !== $defaultStyle->getFontName()) {
- $content .= ' style:font-name="' . $fontName . '" style:font-name-asian="' . $fontName . '" style:font-name-complex="' . $fontName . '"';
- }
-
- $fontSize = $style->getFontSize();
- if ($fontSize !== $defaultStyle->getFontSize()) {
- $content .= ' fo:font-size="' . $fontSize . 'pt" style:font-size-asian="' . $fontSize . 'pt" style:font-size-complex="' . $fontSize . 'pt"';
- }
-
- if ($style->isFontBold()) {
- $content .= ' fo:font-weight="bold" style:font-weight-asian="bold" style:font-weight-complex="bold"';
- }
- if ($style->isFontItalic()) {
- $content .= ' fo:font-style="italic" style:font-style-asian="italic" style:font-style-complex="italic"';
- }
- if ($style->isFontUnderline()) {
- $content .= ' style:text-underline-style="solid" style:text-underline-type="single"';
- }
- if ($style->isFontStrikethrough()) {
- $content .= ' style:text-line-through-style="solid"';
- }
-
- $content .= '/>';
-
- return $content;
- }
-
- /**
- * Returns the contents of the "" section, inside "" section
- *
- * @param \Box\Spout\Writer\Style\Style $style
- * @return string
- */
- private function getTableCellPropertiesSectionContent($style)
- {
- $content = '';
-
- if ($style->shouldWrapText()) {
- $content .= $this->getWrapTextXMLContent();
- }
-
- if ($style->shouldApplyBorder()) {
- $content .= $this->getBorderXMLContent($style);
- }
-
- if ($style->shouldApplyBackgroundColor()) {
- $content .= $this->getBackgroundColorXMLContent($style);
- }
-
- return $content;
- }
-
- /**
- * Returns the contents of the wrap text definition for the "" section
- *
- * @return string
- */
- private function getWrapTextXMLContent()
- {
- return '';
- }
-
- /**
- * Returns the contents of the borders definition for the "" section
- *
- * @param \Box\Spout\Writer\Style\Style $style
- * @return string
- */
- private function getBorderXMLContent($style)
- {
- $borderProperty = '';
-
- $borders = array_map(function (BorderPart $borderPart) {
- return BorderHelper::serializeBorderPart($borderPart);
- }, $style->getBorder()->getParts());
-
- return sprintf($borderProperty, implode(' ', $borders));
- }
-
- /**
- * Returns the contents of the background color definition for the "" section
- *
- * @param \Box\Spout\Writer\Style\Style $style
- * @return string
- */
- private function getBackgroundColorXMLContent($style)
- {
- return sprintf(
- '',
- $style->getBackgroundColor()
- );
- }
-}
diff --git a/src/Spout/Writer/ODS/Internal/Workbook.php b/src/Spout/Writer/ODS/Internal/Workbook.php
deleted file mode 100644
index fc64ada..0000000
--- a/src/Spout/Writer/ODS/Internal/Workbook.php
+++ /dev/null
@@ -1,119 +0,0 @@
-fileSystemHelper = new FileSystemHelper($tempFolder);
- $this->fileSystemHelper->createBaseFilesAndFolders();
-
- $this->styleHelper = new StyleHelper($defaultRowStyle);
- }
-
- /**
- * @return \Box\Spout\Writer\ODS\Helper\StyleHelper Helper to apply styles to ODS files
- */
- protected function getStyleHelper()
- {
- return $this->styleHelper;
- }
-
- /**
- * @return int Maximum number of rows/columns a sheet can contain
- */
- protected function getMaxRowsPerWorksheet()
- {
- return self::$maxRowsPerWorksheet;
- }
-
- /**
- * Creates a new sheet in the workbook. The current sheet remains unchanged.
- *
- * @return Worksheet The created sheet
- * @throws \Box\Spout\Common\Exception\IOException If unable to open the sheet for writing
- */
- public function addNewSheet()
- {
- $newSheetIndex = count($this->worksheets);
- $sheet = new Sheet($newSheetIndex, $this->internalId);
-
- $sheetsContentTempFolder = $this->fileSystemHelper->getSheetsContentTempFolder();
- $worksheet = new Worksheet($sheet, $sheetsContentTempFolder);
- $this->worksheets[] = $worksheet;
-
- return $worksheet;
- }
-
- /**
- * Closes the workbook and all its associated sheets.
- * All the necessary files are written to disk and zipped together to create the ODS file.
- * All the temporary files are then deleted.
- *
- * @param resource $finalFilePointer Pointer to the ODS that will be created
- * @return void
- */
- public function close($finalFilePointer)
- {
- /** @var Worksheet[] $worksheets */
- $worksheets = $this->worksheets;
- $numWorksheets = count($worksheets);
-
- foreach ($worksheets as $worksheet) {
- $worksheet->close();
- }
-
- // Finish creating all the necessary files before zipping everything together
- $this->fileSystemHelper
- ->createContentFile($worksheets, $this->styleHelper)
- ->deleteWorksheetTempFolder()
- ->createStylesFile($this->styleHelper, $numWorksheets)
- ->zipRootFolderAndCopyToStream($finalFilePointer);
-
- $this->cleanupTempFolder();
- }
-
- /**
- * Deletes the root folder created in the temp folder and all its contents.
- *
- * @return void
- */
- protected function cleanupTempFolder()
- {
- $xlsxRootFolder = $this->fileSystemHelper->getRootFolder();
- $this->fileSystemHelper->deleteFolderRecursively($xlsxRootFolder);
- }
-}
diff --git a/src/Spout/Writer/ODS/Internal/Worksheet.php b/src/Spout/Writer/ODS/Internal/Worksheet.php
deleted file mode 100644
index 0920b6d..0000000
--- a/src/Spout/Writer/ODS/Internal/Worksheet.php
+++ /dev/null
@@ -1,233 +0,0 @@
-externalSheet = $externalSheet;
- /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
- $this->stringsEscaper = \Box\Spout\Common\Escaper\ODS::getInstance();
- $this->worksheetFilePath = $worksheetFilesFolder . '/sheet' . $externalSheet->getIndex() . '.xml';
-
- $this->stringHelper = new StringHelper();
-
- $this->startSheet();
- }
-
- /**
- * Prepares the worksheet to accept data
- * The XML file does not contain the "" node as it contains the sheet's name
- * which may change during the execution of the program. It will be added at the end.
- *
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
- */
- protected function startSheet()
- {
- $this->sheetFilePointer = fopen($this->worksheetFilePath, 'w');
- $this->throwIfSheetFilePointerIsNotAvailable();
- }
-
- /**
- * Checks if the book has been created. Throws an exception if not created yet.
- *
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
- */
- protected function throwIfSheetFilePointerIsNotAvailable()
- {
- if (!$this->sheetFilePointer) {
- throw new IOException('Unable to open sheet for writing.');
- }
- }
-
- /**
- * @return string Path to the temporary sheet content XML file
- */
- public function getWorksheetFilePath()
- {
- return $this->worksheetFilePath;
- }
-
- /**
- * Returns the table XML root node as string.
- *
- * @return string node as string
- */
- public function getTableElementStartAsString()
- {
- $escapedSheetName = $this->stringsEscaper->escape($this->externalSheet->getName());
- $tableStyleName = 'ta' . ($this->externalSheet->getIndex() + 1);
-
- $tableElement = '';
- $tableElement .= '';
-
- return $tableElement;
- }
-
- /**
- * @return \Box\Spout\Writer\Common\Sheet The "external" sheet
- */
- public function getExternalSheet()
- {
- return $this->externalSheet;
- }
-
- /**
- * @return int The index of the last written row
- */
- public function getLastWrittenRowIndex()
- {
- return $this->lastWrittenRowIndex;
- }
-
- /**
- * Adds data to the worksheet.
- *
- * @param array $dataRow Array containing data to be written. Cannot be empty.
- * Example $dataRow = ['data1', 1234, null, '', 'data5'];
- * @param \Box\Spout\Writer\Style\Style $style Style to be applied to the row. NULL means use default style.
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If the data cannot be written
- * @throws \Box\Spout\Common\Exception\InvalidArgumentException If a cell value's type is not supported
- */
- public function addRow($dataRow, $style)
- {
- // $dataRow can be an associative array. We need to transform
- // it into a regular array, as we'll use the numeric indexes.
- $dataRowWithNumericIndexes = array_values($dataRow);
-
- $styleIndex = ($style->getId() + 1); // 1-based
- $cellsCount = count($dataRow);
- $this->maxNumColumns = max($this->maxNumColumns, $cellsCount);
-
- $data = '';
-
- $currentCellIndex = 0;
- $nextCellIndex = 1;
-
- for ($i = 0; $i < $cellsCount; $i++) {
- $currentCellValue = $dataRowWithNumericIndexes[$currentCellIndex];
-
- // Using isset here because it is way faster than array_key_exists...
- if (!isset($dataRowWithNumericIndexes[$nextCellIndex]) ||
- $currentCellValue !== $dataRowWithNumericIndexes[$nextCellIndex]) {
-
- $numTimesValueRepeated = ($nextCellIndex - $currentCellIndex);
- $data .= $this->getCellXML($currentCellValue, $styleIndex, $numTimesValueRepeated);
-
- $currentCellIndex = $nextCellIndex;
- }
-
- $nextCellIndex++;
- }
-
- $data .= '';
-
- $wasWriteSuccessful = fwrite($this->sheetFilePointer, $data);
- if ($wasWriteSuccessful === false) {
- throw new IOException("Unable to write data in {$this->worksheetFilePath}");
- }
-
- // only update the count if the write worked
- $this->lastWrittenRowIndex++;
- }
-
- /**
- * Returns the cell XML content, given its value.
- *
- * @param mixed $cellValue The value to be written
- * @param int $styleIndex Index of the used style
- * @param int $numTimesValueRepeated Number of times the value is consecutively repeated
- * @return string The cell XML content
- * @throws \Box\Spout\Common\Exception\InvalidArgumentException If a cell value's type is not supported
- */
- protected function getCellXML($cellValue, $styleIndex, $numTimesValueRepeated)
- {
- $data = 'stringsEscaper->escape($cellValueLine) . '';
- }
-
- $data .= '';
- } else if (CellHelper::isBoolean($cellValue)) {
- $data .= ' office:value-type="boolean" calcext:value-type="boolean" office:boolean-value="' . $cellValue . '">';
- $data .= '' . $cellValue . '';
- $data .= '';
- } else if (CellHelper::isNumeric($cellValue)) {
- $data .= ' office:value-type="float" calcext:value-type="float" office:value="' . $cellValue . '">';
- $data .= '' . $cellValue . '';
- $data .= '';
- } else if (empty($cellValue)) {
- $data .= '/>';
- } else {
- throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cellValue));
- }
-
- return $data;
- }
-
- /**
- * Closes the worksheet
- *
- * @return void
- */
- public function close()
- {
- if (!is_resource($this->sheetFilePointer)) {
- return;
- }
-
- fclose($this->sheetFilePointer);
- }
-}
diff --git a/src/Spout/Writer/ODS/Writer.php b/src/Spout/Writer/ODS/Writer.php
deleted file mode 100644
index 6571d00..0000000
--- a/src/Spout/Writer/ODS/Writer.php
+++ /dev/null
@@ -1,93 +0,0 @@
-throwIfWriterAlreadyOpened('Writer must be configured before opening it.');
-
- $this->tempFolder = $tempFolder;
- return $this;
- }
-
- /**
- * Configures the write and sets the current sheet pointer to a new sheet.
- *
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If unable to open the file for writing
- */
- protected function openWriter()
- {
- $tempFolder = ($this->tempFolder) ? : sys_get_temp_dir();
- $this->book = new Workbook($tempFolder, $this->shouldCreateNewSheetsAutomatically, $this->defaultRowStyle);
- $this->book->addNewSheetAndMakeItCurrent();
- }
-
- /**
- * @return Internal\Workbook The workbook representing the file to be written
- */
- protected function getWorkbook()
- {
- return $this->book;
- }
-
- /**
- * Adds data to the currently opened writer.
- * If shouldCreateNewSheetsAutomatically option is set to true, it will handle pagination
- * with the creation of new worksheets if one worksheet has reached its maximum capicity.
- *
- * @param array $dataRow Array containing data to be written.
- * Example $dataRow = ['data1', 1234, null, '', 'data5'];
- * @param \Box\Spout\Writer\Style\Style $style Style to be applied to the row.
- * @return void
- * @throws \Box\Spout\Writer\Exception\WriterNotOpenedException If the book is not created yet
- * @throws \Box\Spout\Common\Exception\IOException If unable to write data
- */
- protected function addRowToWriter(array $dataRow, $style)
- {
- $this->throwIfBookIsNotAvailable();
- $this->book->addRowToCurrentWorksheet($dataRow, $style);
- }
-
- /**
- * Closes the writer, preventing any additional writing.
- *
- * @return void
- */
- protected function closeWriter()
- {
- if ($this->book) {
- $this->book->close($this->filePointer);
- }
- }
-}
diff --git a/src/Spout/Writer/Style/Border.php b/src/Spout/Writer/Style/Border.php
deleted file mode 100644
index 75f6a49..0000000
--- a/src/Spout/Writer/Style/Border.php
+++ /dev/null
@@ -1,85 +0,0 @@
-setParts($borderParts);
- }
-
- /**
- * @param $name The name of the border part
- * @return null|BorderPart
- */
- public function getPart($name)
- {
- return $this->hasPart($name) ? $this->parts[$name] : null;
- }
-
- /**
- * @param $name The name of the border part
- * @return bool
- */
- public function hasPart($name)
- {
- return isset($this->parts[$name]);
- }
-
- /**
- * @return array
- */
- public function getParts()
- {
- return $this->parts;
- }
-
- /**
- * Set BorderParts
- * @param array $parts
- */
- public function setParts($parts)
- {
- unset($this->parts);
- foreach ($parts as $part) {
- $this->addPart($part);
- }
- }
-
- /**
- * @param BorderPart $borderPart
- * @return self
- */
- public function addPart(BorderPart $borderPart)
- {
- $this->parts[$borderPart->getName()] = $borderPart;
- return $this;
- }
-}
diff --git a/src/Spout/Writer/Style/BorderBuilder.php b/src/Spout/Writer/Style/BorderBuilder.php
deleted file mode 100644
index c0b8aea..0000000
--- a/src/Spout/Writer/Style/BorderBuilder.php
+++ /dev/null
@@ -1,75 +0,0 @@
-border = new Border();
- }
-
- /**
- * @param string|void $color Border A RGB color code
- * @param string|void $width Border width @see BorderPart::allowedWidths
- * @param string|void $style Border style @see BorderPart::allowedStyles
- * @return BorderBuilder
- */
- public function setBorderTop($color = Color::BLACK, $width = Border::WIDTH_MEDIUM, $style = Border::STYLE_SOLID)
- {
- $this->border->addPart(new BorderPart(Border::TOP, $color, $width, $style));
- return $this;
- }
-
- /**
- * @param string|void $color Border A RGB color code
- * @param string|void $width Border width @see BorderPart::allowedWidths
- * @param string|void $style Border style @see BorderPart::allowedStyles
- * @return BorderBuilder
- */
- public function setBorderRight($color = Color::BLACK, $width = Border::WIDTH_MEDIUM, $style = Border::STYLE_SOLID)
- {
- $this->border->addPart(new BorderPart(Border::RIGHT, $color, $width, $style));
- return $this;
- }
-
- /**
- * @param string|void $color Border A RGB color code
- * @param string|void $width Border width @see BorderPart::allowedWidths
- * @param string|void $style Border style @see BorderPart::allowedStyles
- * @return BorderBuilder
- */
- public function setBorderBottom($color = Color::BLACK, $width = Border::WIDTH_MEDIUM, $style = Border::STYLE_SOLID)
- {
- $this->border->addPart(new BorderPart(Border::BOTTOM, $color, $width, $style));
- return $this;
- }
-
- /**
- * @param string|void $color Border A RGB color code
- * @param string|void $width Border width @see BorderPart::allowedWidths
- * @param string|void $style Border style @see BorderPart::allowedStyles
- * @return BorderBuilder
- */
- public function setBorderLeft($color = Color::BLACK, $width = Border::WIDTH_MEDIUM, $style = Border::STYLE_SOLID)
- {
- $this->border->addPart(new BorderPart(Border::LEFT, $color, $width, $style));
- return $this;
- }
-
- /**
- * @return Border
- */
- public function build()
- {
- return $this->border;
- }
-}
diff --git a/src/Spout/Writer/Style/BorderPart.php b/src/Spout/Writer/Style/BorderPart.php
deleted file mode 100644
index 9ade797..0000000
--- a/src/Spout/Writer/Style/BorderPart.php
+++ /dev/null
@@ -1,184 +0,0 @@
-setName($name);
- $this->setColor($color);
- $this->setWidth($width);
- $this->setStyle($style);
- }
-
- /**
- * @return string
- */
- public function getName()
- {
- return $this->name;
- }
-
- /**
- * @param string $name The name of the border part @see BorderPart::$allowedNames
- * @throws InvalidNameException
- * @return void
- */
- public function setName($name)
- {
- if (!in_array($name, self::$allowedNames)) {
- throw new InvalidNameException($name);
- }
- $this->name = $name;
- }
-
- /**
- * @return string
- */
- public function getStyle()
- {
- return $this->style;
- }
-
- /**
- * @param string $style The style of the border part @see BorderPart::$allowedStyles
- * @throws InvalidStyleException
- * @return void
- */
- public function setStyle($style)
- {
- if (!in_array($style, self::$allowedStyles)) {
- throw new InvalidStyleException($style);
- }
- $this->style = $style;
- }
-
- /**
- * @return string
- */
- public function getColor()
- {
- return $this->color;
- }
-
- /**
- * @param string $color The color of the border part @see Color::rgb()
- * @return void
- */
- public function setColor($color)
- {
- $this->color = $color;
- }
-
- /**
- * @return string
- */
- public function getWidth()
- {
- return $this->width;
- }
-
- /**
- * @param string $width The width of the border part @see BorderPart::$allowedWidths
- * @throws InvalidWidthException
- * @return void
- */
- public function setWidth($width)
- {
- if (!in_array($width, self::$allowedWidths)) {
- throw new InvalidWidthException($width);
- }
- $this->width = $width;
- }
-
- /**
- * @return array
- */
- public static function getAllowedStyles()
- {
- return self::$allowedStyles;
- }
-
- /**
- * @return array
- */
- public static function getAllowedNames()
- {
- return self::$allowedNames;
- }
-
- /**
- * @return array
- */
- public static function getAllowedWidths()
- {
- return self::$allowedWidths;
- }
-}
diff --git a/src/Spout/Writer/Style/Color.php b/src/Spout/Writer/Style/Color.php
deleted file mode 100644
index 3c86eb7..0000000
--- a/src/Spout/Writer/Style/Color.php
+++ /dev/null
@@ -1,87 +0,0 @@
- 255) {
- throw new InvalidColorException("The RGB components must be between 0 and 255. Received: $colorComponent");
- }
- }
-
- /**
- * Converts the color component to its corresponding hexadecimal value
- *
- * @param int $colorComponent Color component, 0 - 255
- * @return string Corresponding hexadecimal value, with a leading 0 if needed. E.g "0f", "2d"
- */
- protected static function convertColorComponentToHex($colorComponent)
- {
- return str_pad(dechex($colorComponent), 2, '0', STR_PAD_LEFT);
- }
-
- /**
- * Returns the ARGB color of the given RGB color,
- * assuming that alpha value is always 1.
- *
- * @param string $rgbColor RGB color like "FF08B2"
- * @return string ARGB color
- */
- public static function toARGB($rgbColor)
- {
- return 'FF' . $rgbColor;
- }
-}
diff --git a/src/Spout/Writer/Style/Style.php b/src/Spout/Writer/Style/Style.php
deleted file mode 100644
index b408ad3..0000000
--- a/src/Spout/Writer/Style/Style.php
+++ /dev/null
@@ -1,426 +0,0 @@
-id;
- }
-
- /**
- * @param int $id
- * @return Style
- */
- public function setId($id)
- {
- $this->id = $id;
- return $this;
- }
-
- /**
- * @return Border
- */
- public function getBorder()
- {
- return $this->border;
- }
-
- /**
- * @param Border $border
- * @return Style
- */
- public function setBorder(Border $border)
- {
- $this->shouldApplyBorder = true;
- $this->border = $border;
- return $this;
- }
-
- /**
- * @return bool
- */
- public function shouldApplyBorder()
- {
- return $this->shouldApplyBorder;
- }
-
- /**
- * @return bool
- */
- public function isFontBold()
- {
- return $this->fontBold;
- }
-
- /**
- * @return Style
- */
- public function setFontBold()
- {
- $this->fontBold = true;
- $this->hasSetFontBold = true;
- $this->shouldApplyFont = true;
- return $this;
- }
-
- /**
- * @return bool
- */
- public function isFontItalic()
- {
- return $this->fontItalic;
- }
-
- /**
- * @return Style
- */
- public function setFontItalic()
- {
- $this->fontItalic = true;
- $this->hasSetFontItalic = true;
- $this->shouldApplyFont = true;
- return $this;
- }
-
- /**
- * @return bool
- */
- public function isFontUnderline()
- {
- return $this->fontUnderline;
- }
-
- /**
- * @return Style
- */
- public function setFontUnderline()
- {
- $this->fontUnderline = true;
- $this->hasSetFontUnderline = true;
- $this->shouldApplyFont = true;
- return $this;
- }
-
- /**
- * @return bool
- */
- public function isFontStrikethrough()
- {
- return $this->fontStrikethrough;
- }
-
- /**
- * @return Style
- */
- public function setFontStrikethrough()
- {
- $this->fontStrikethrough = true;
- $this->hasSetFontStrikethrough = true;
- $this->shouldApplyFont = true;
- return $this;
- }
-
- /**
- * @return int
- */
- public function getFontSize()
- {
- return $this->fontSize;
- }
-
- /**
- * @param int $fontSize Font size, in pixels
- * @return Style
- */
- public function setFontSize($fontSize)
- {
- $this->fontSize = $fontSize;
- $this->hasSetFontSize = true;
- $this->shouldApplyFont = true;
- return $this;
- }
-
- /**
- * @return string
- */
- public function getFontColor()
- {
- return $this->fontColor;
- }
-
- /**
- * Sets the font color.
- *
- * @param string $fontColor ARGB color (@see Color)
- * @return Style
- */
- public function setFontColor($fontColor)
- {
- $this->fontColor = $fontColor;
- $this->hasSetFontColor = true;
- $this->shouldApplyFont = true;
- return $this;
- }
-
- /**
- * @return string
- */
- public function getFontName()
- {
- return $this->fontName;
- }
-
- /**
- * @param string $fontName Name of the font to use
- * @return Style
- */
- public function setFontName($fontName)
- {
- $this->fontName = $fontName;
- $this->hasSetFontName = true;
- $this->shouldApplyFont = true;
- return $this;
- }
-
- /**
- * @return bool
- */
- public function shouldWrapText()
- {
- return $this->shouldWrapText;
- }
-
- /**
- * @param bool|void $shouldWrap Should the text be wrapped
- * @return Style
- */
- public function setShouldWrapText($shouldWrap = true)
- {
- $this->shouldWrapText = $shouldWrap;
- $this->hasSetWrapText = true;
- return $this;
- }
-
- /**
- * @return bool
- */
- public function hasSetWrapText()
- {
- return $this->hasSetWrapText;
- }
-
- /**
- * @return bool Whether specific font properties should be applied
- */
- public function shouldApplyFont()
- {
- return $this->shouldApplyFont;
- }
-
- /**
- * Sets the background color
- * @param string $color ARGB color (@see Color)
- * @return Style
- */
- public function setBackgroundColor($color)
- {
- $this->hasSetBackgroundColor = true;
- $this->backgroundColor = $color;
- return $this;
- }
-
- /**
- * @return string
- */
- public function getBackgroundColor()
- {
- return $this->backgroundColor;
- }
-
- /**
- *
- * @return bool Whether the background color should be applied
- */
- public function shouldApplyBackgroundColor()
- {
- return $this->hasSetBackgroundColor;
- }
-
- /**
- * Serializes the style for future comparison with other styles.
- * The ID is excluded from the comparison, as we only care about
- * actual style properties.
- *
- * @return string The serialized style
- */
- public function serialize()
- {
- // In order to be able to properly compare style, set static ID value
- $currentId = $this->id;
- $this->setId(0);
-
- $serializedStyle = serialize($this);
-
- $this->setId($currentId);
-
- return $serializedStyle;
- }
-
- /**
- * Merges the current style with the given style, using the given style as a base. This means that:
- * - if current style and base style both have property A set, use current style property's value
- * - if current style has property A set but base style does not, use current style property's value
- * - if base style has property A set but current style does not, use base style property's value
- *
- * @NOTE: This function returns a new style.
- *
- * @param Style $baseStyle
- * @return Style New style corresponding to the merge of the 2 styles
- */
- public function mergeWith($baseStyle)
- {
- $mergedStyle = clone $this;
-
- $this->mergeFontStyles($mergedStyle, $baseStyle);
- $this->mergeOtherFontProperties($mergedStyle, $baseStyle);
- $this->mergeCellProperties($mergedStyle, $baseStyle);
-
- return $mergedStyle;
- }
-
- /**
- * @param Style $styleToUpdate (passed as reference)
- * @param Style $baseStyle
- * @return void
- */
- private function mergeFontStyles($styleToUpdate, $baseStyle)
- {
- if (!$this->hasSetFontBold && $baseStyle->isFontBold()) {
- $styleToUpdate->setFontBold();
- }
- if (!$this->hasSetFontItalic && $baseStyle->isFontItalic()) {
- $styleToUpdate->setFontItalic();
- }
- if (!$this->hasSetFontUnderline && $baseStyle->isFontUnderline()) {
- $styleToUpdate->setFontUnderline();
- }
- if (!$this->hasSetFontStrikethrough && $baseStyle->isFontStrikethrough()) {
- $styleToUpdate->setFontStrikethrough();
- }
- }
-
- /**
- * @param Style $styleToUpdate Style to update (passed as reference)
- * @param Style $baseStyle
- * @return void
- */
- private function mergeOtherFontProperties($styleToUpdate, $baseStyle)
- {
- if (!$this->hasSetFontSize && $baseStyle->getFontSize() !== self::DEFAULT_FONT_SIZE) {
- $styleToUpdate->setFontSize($baseStyle->getFontSize());
- }
- if (!$this->hasSetFontColor && $baseStyle->getFontColor() !== self::DEFAULT_FONT_COLOR) {
- $styleToUpdate->setFontColor($baseStyle->getFontColor());
- }
- if (!$this->hasSetFontName && $baseStyle->getFontName() !== self::DEFAULT_FONT_NAME) {
- $styleToUpdate->setFontName($baseStyle->getFontName());
- }
- }
-
- /**
- * @param Style $styleToUpdate Style to update (passed as reference)
- * @param Style $baseStyle
- * @return void
- */
- private function mergeCellProperties($styleToUpdate, $baseStyle)
- {
- if (!$this->hasSetWrapText && $baseStyle->shouldWrapText()) {
- $styleToUpdate->setShouldWrapText();
- }
- if (!$this->getBorder() && $baseStyle->shouldApplyBorder()) {
- $styleToUpdate->setBorder($baseStyle->getBorder());
- }
- if (!$this->hasSetBackgroundColor && $baseStyle->shouldApplyBackgroundColor()) {
- $styleToUpdate->setBackgroundColor($baseStyle->getBackgroundColor());
- }
- }
-}
diff --git a/src/Spout/Writer/Style/StyleBuilder.php b/src/Spout/Writer/Style/StyleBuilder.php
deleted file mode 100644
index 2676cbe..0000000
--- a/src/Spout/Writer/Style/StyleBuilder.php
+++ /dev/null
@@ -1,159 +0,0 @@
-style = new Style();
- }
-
- /**
- * Makes the font bold.
- *
- * @api
- * @return StyleBuilder
- */
- public function setFontBold()
- {
- $this->style->setFontBold();
- return $this;
- }
-
- /**
- * Makes the font italic.
- *
- * @api
- * @return StyleBuilder
- */
- public function setFontItalic()
- {
- $this->style->setFontItalic();
- return $this;
- }
-
- /**
- * Makes the font underlined.
- *
- * @api
- * @return StyleBuilder
- */
- public function setFontUnderline()
- {
- $this->style->setFontUnderline();
- return $this;
- }
-
- /**
- * Makes the font struck through.
- *
- * @api
- * @return StyleBuilder
- */
- public function setFontStrikethrough()
- {
- $this->style->setFontStrikethrough();
- return $this;
- }
-
- /**
- * Sets the font size.
- *
- * @api
- * @param int $fontSize Font size, in pixels
- * @return StyleBuilder
- */
- public function setFontSize($fontSize)
- {
- $this->style->setFontSize($fontSize);
- return $this;
- }
-
- /**
- * Sets the font color.
- *
- * @api
- * @param string $fontColor ARGB color (@see Color)
- * @return StyleBuilder
- */
- public function setFontColor($fontColor)
- {
- $this->style->setFontColor($fontColor);
- return $this;
- }
-
- /**
- * Sets the font name.
- *
- * @api
- * @param string $fontName Name of the font to use
- * @return StyleBuilder
- */
- public function setFontName($fontName)
- {
- $this->style->setFontName($fontName);
- return $this;
- }
-
- /**
- * Makes the text wrap in the cell if requested
- *
- * @api
- * @param bool $shouldWrap Should the text be wrapped
- * @return StyleBuilder
- */
- public function setShouldWrapText($shouldWrap = true)
- {
- $this->style->setShouldWrapText($shouldWrap);
- return $this;
- }
-
- /**
- * Set a border
- *
- * @param Border $border
- * @return $this
- */
- public function setBorder(Border $border)
- {
- $this->style->setBorder($border);
- return $this;
- }
-
- /**
- * Sets a background color
- *
- * @api
- * @param string $color ARGB color (@see Color)
- * @return StyleBuilder
- */
- public function setBackgroundColor($color)
- {
- $this->style->setBackgroundColor($color);
- return $this;
- }
-
- /**
- * Returns the configured style. The style is cached and can be reused.
- *
- * @api
- * @return Style
- */
- public function build()
- {
- return $this->style;
- }
-}
diff --git a/src/Spout/Writer/WriterFactory.php b/src/Spout/Writer/WriterFactory.php
deleted file mode 100644
index 7588940..0000000
--- a/src/Spout/Writer/WriterFactory.php
+++ /dev/null
@@ -1,48 +0,0 @@
-setGlobalFunctionsHelper(new GlobalFunctionsHelper());
-
- return $writer;
- }
-}
diff --git a/src/Spout/Writer/WriterInterface.php b/src/Spout/Writer/WriterInterface.php
deleted file mode 100644
index e2d9f8d..0000000
--- a/src/Spout/Writer/WriterInterface.php
+++ /dev/null
@@ -1,91 +0,0 @@
- [
- Border::WIDTH_THIN => 'thin',
- Border::WIDTH_MEDIUM => 'medium',
- Border::WIDTH_THICK => 'thick'
- ],
- Border::STYLE_DOTTED => [
- Border::WIDTH_THIN => 'dotted',
- Border::WIDTH_MEDIUM => 'dotted',
- Border::WIDTH_THICK => 'dotted',
- ],
- Border::STYLE_DASHED => [
- Border::WIDTH_THIN => 'dashed',
- Border::WIDTH_MEDIUM => 'mediumDashed',
- Border::WIDTH_THICK => 'mediumDashed',
- ],
- Border::STYLE_DOUBLE => [
- Border::WIDTH_THIN => 'double',
- Border::WIDTH_MEDIUM => 'double',
- Border::WIDTH_THICK => 'double',
- ],
- Border::STYLE_NONE => [
- Border::WIDTH_THIN => 'none',
- Border::WIDTH_MEDIUM => 'none',
- Border::WIDTH_THICK => 'none',
- ],
- ];
-
- /**
- * @param BorderPart $borderPart
- * @return string
- */
- public static function serializeBorderPart(BorderPart $borderPart)
- {
- $borderStyle = self::getBorderStyle($borderPart);
-
- $colorEl = $borderPart->getColor() ? sprintf('', $borderPart->getColor()) : '';
- $partEl = sprintf(
- '<%s style="%s">%s%s>',
- $borderPart->getName(),
- $borderStyle,
- $colorEl,
- $borderPart->getName()
- );
-
- return $partEl . PHP_EOL;
- }
-
- /**
- * Get the style definition from the style map
- *
- * @param BorderPart $borderPart
- * @return string
- */
- protected static function getBorderStyle(BorderPart $borderPart)
- {
- return self::$xlsxStyleMap[$borderPart->getStyle()][$borderPart->getWidth()];
- }
-}
diff --git a/src/Spout/Writer/XLSX/Helper/FileSystemHelper.php b/src/Spout/Writer/XLSX/Helper/FileSystemHelper.php
deleted file mode 100644
index 86515f3..0000000
--- a/src/Spout/Writer/XLSX/Helper/FileSystemHelper.php
+++ /dev/null
@@ -1,371 +0,0 @@
-rootFolder;
- }
-
- /**
- * @return string
- */
- public function getXlFolder()
- {
- return $this->xlFolder;
- }
-
- /**
- * @return string
- */
- public function getXlWorksheetsFolder()
- {
- return $this->xlWorksheetsFolder;
- }
-
- /**
- * Creates all the folders needed to create a XLSX file, as well as the files that won't change.
- *
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If unable to create at least one of the base folders
- */
- public function createBaseFilesAndFolders()
- {
- $this
- ->createRootFolder()
- ->createRelsFolderAndFile()
- ->createDocPropsFolderAndFiles()
- ->createXlFolderAndSubFolders();
- }
-
- /**
- * Creates the folder that will be used as root
- *
- * @return FileSystemHelper
- * @throws \Box\Spout\Common\Exception\IOException If unable to create the folder
- */
- protected function createRootFolder()
- {
- $this->rootFolder = $this->createFolder($this->baseFolderRealPath, uniqid('xlsx', true));
- return $this;
- }
-
- /**
- * Creates the "_rels" folder under the root folder as well as the ".rels" file in it
- *
- * @return FileSystemHelper
- * @throws \Box\Spout\Common\Exception\IOException If unable to create the folder or the ".rels" file
- */
- protected function createRelsFolderAndFile()
- {
- $this->relsFolder = $this->createFolder($this->rootFolder, self::RELS_FOLDER_NAME);
-
- $this->createRelsFile();
-
- return $this;
- }
-
- /**
- * Creates the ".rels" file under the "_rels" folder (under root)
- *
- * @return FileSystemHelper
- * @throws \Box\Spout\Common\Exception\IOException If unable to create the file
- */
- protected function createRelsFile()
- {
- $relsFileContents = <<
-
-
-
-
-
-EOD;
-
- $this->createFileWithContents($this->relsFolder, self::RELS_FILE_NAME, $relsFileContents);
-
- return $this;
- }
-
- /**
- * Creates the "docProps" folder under the root folder as well as the "app.xml" and "core.xml" files in it
- *
- * @return FileSystemHelper
- * @throws \Box\Spout\Common\Exception\IOException If unable to create the folder or one of the files
- */
- protected function createDocPropsFolderAndFiles()
- {
- $this->docPropsFolder = $this->createFolder($this->rootFolder, self::DOC_PROPS_FOLDER_NAME);
-
- $this->createAppXmlFile();
- $this->createCoreXmlFile();
-
- return $this;
- }
-
- /**
- * Creates the "app.xml" file under the "docProps" folder
- *
- * @return FileSystemHelper
- * @throws \Box\Spout\Common\Exception\IOException If unable to create the file
- */
- protected function createAppXmlFile()
- {
- $appName = self::APP_NAME;
- $appXmlFileContents = <<
-
- $appName
- 0
-
-EOD;
-
- $this->createFileWithContents($this->docPropsFolder, self::APP_XML_FILE_NAME, $appXmlFileContents);
-
- return $this;
- }
-
- /**
- * Creates the "core.xml" file under the "docProps" folder
- *
- * @return FileSystemHelper
- * @throws \Box\Spout\Common\Exception\IOException If unable to create the file
- */
- protected function createCoreXmlFile()
- {
- $createdDate = (new \DateTime())->format(\DateTime::W3C);
- $coreXmlFileContents = <<
-
- $createdDate
- $createdDate
- 0
-
-EOD;
-
- $this->createFileWithContents($this->docPropsFolder, self::CORE_XML_FILE_NAME, $coreXmlFileContents);
-
- return $this;
- }
-
- /**
- * Creates the "xl" folder under the root folder as well as its subfolders
- *
- * @return FileSystemHelper
- * @throws \Box\Spout\Common\Exception\IOException If unable to create at least one of the folders
- */
- protected function createXlFolderAndSubFolders()
- {
- $this->xlFolder = $this->createFolder($this->rootFolder, self::XL_FOLDER_NAME);
- $this->createXlRelsFolder();
- $this->createXlWorksheetsFolder();
-
- return $this;
- }
-
- /**
- * Creates the "_rels" folder under the "xl" folder
- *
- * @return FileSystemHelper
- * @throws \Box\Spout\Common\Exception\IOException If unable to create the folder
- */
- protected function createXlRelsFolder()
- {
- $this->xlRelsFolder = $this->createFolder($this->xlFolder, self::RELS_FOLDER_NAME);
- return $this;
- }
-
- /**
- * Creates the "worksheets" folder under the "xl" folder
- *
- * @return FileSystemHelper
- * @throws \Box\Spout\Common\Exception\IOException If unable to create the folder
- */
- protected function createXlWorksheetsFolder()
- {
- $this->xlWorksheetsFolder = $this->createFolder($this->xlFolder, self::WORKSHEETS_FOLDER_NAME);
- return $this;
- }
-
- /**
- * Creates the "[Content_Types].xml" file under the root folder
- *
- * @param Worksheet[] $worksheets
- * @return FileSystemHelper
- */
- public function createContentTypesFile($worksheets)
- {
- $contentTypesXmlFileContents = <<
-
-
-
-
-EOD;
-
- /** @var Worksheet $worksheet */
- foreach ($worksheets as $worksheet) {
- $contentTypesXmlFileContents .= '';
- }
-
- $contentTypesXmlFileContents .= <<
-
-
-
-
-EOD;
-
- $this->createFileWithContents($this->rootFolder, self::CONTENT_TYPES_XML_FILE_NAME, $contentTypesXmlFileContents);
-
- return $this;
- }
-
- /**
- * Creates the "workbook.xml" file under the "xl" folder
- *
- * @param Worksheet[] $worksheets
- * @return FileSystemHelper
- */
- public function createWorkbookFile($worksheets)
- {
- $workbookXmlFileContents = <<
-
-
-EOD;
-
- /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
- $escaper = \Box\Spout\Common\Escaper\XLSX::getInstance();
-
- /** @var Worksheet $worksheet */
- foreach ($worksheets as $worksheet) {
- $worksheetName = $worksheet->getExternalSheet()->getName();
- $worksheetId = $worksheet->getId();
- $workbookXmlFileContents .= '';
- }
-
- $workbookXmlFileContents .= <<
-
-EOD;
-
- $this->createFileWithContents($this->xlFolder, self::WORKBOOK_XML_FILE_NAME, $workbookXmlFileContents);
-
- return $this;
- }
-
- /**
- * Creates the "workbook.xml.res" file under the "xl/_res" folder
- *
- * @param Worksheet[] $worksheets
- * @return FileSystemHelper
- */
- public function createWorkbookRelsFile($worksheets)
- {
- $workbookRelsXmlFileContents = <<
-
-
-
-EOD;
-
- /** @var Worksheet $worksheet */
- foreach ($worksheets as $worksheet) {
- $worksheetId = $worksheet->getId();
- $workbookRelsXmlFileContents .= '';
- }
-
- $workbookRelsXmlFileContents .= '';
-
- $this->createFileWithContents($this->xlRelsFolder, self::WORKBOOK_RELS_XML_FILE_NAME, $workbookRelsXmlFileContents);
-
- return $this;
- }
-
- /**
- * Creates the "styles.xml" file under the "xl" folder
- *
- * @param StyleHelper $styleHelper
- * @return FileSystemHelper
- */
- public function createStylesFile($styleHelper)
- {
- $stylesXmlFileContents = $styleHelper->getStylesXMLFileContent();
- $this->createFileWithContents($this->xlFolder, self::STYLES_XML_FILE_NAME, $stylesXmlFileContents);
-
- return $this;
- }
-
- /**
- * Zips the root folder and streams the contents of the zip into the given stream
- *
- * @param resource $streamPointer Pointer to the stream to copy the zip
- * @return void
- */
- public function zipRootFolderAndCopyToStream($streamPointer)
- {
- $zipHelper = new ZipHelper($this->rootFolder);
-
- // In order to have the file's mime type detected properly, files need to be added
- // to the zip file in a particular order.
- // "[Content_Types].xml" then at least 2 files located in "xl" folder should be zipped first.
- $zipHelper->addFileToArchive($this->rootFolder, self::CONTENT_TYPES_XML_FILE_NAME);
- $zipHelper->addFileToArchive($this->rootFolder, self::XL_FOLDER_NAME . '/' . self::WORKBOOK_XML_FILE_NAME);
- $zipHelper->addFileToArchive($this->rootFolder, self::XL_FOLDER_NAME . '/' . self::STYLES_XML_FILE_NAME);
-
- $zipHelper->addFolderToArchive($this->rootFolder, ZipHelper::EXISTING_FILES_SKIP);
- $zipHelper->closeArchiveAndCopyToStream($streamPointer);
-
- // once the zip is copied, remove it
- $this->deleteFile($zipHelper->getZipFilePath());
- }
-}
diff --git a/src/Spout/Writer/XLSX/Helper/SharedStringsHelper.php b/src/Spout/Writer/XLSX/Helper/SharedStringsHelper.php
deleted file mode 100644
index 292b663..0000000
--- a/src/Spout/Writer/XLSX/Helper/SharedStringsHelper.php
+++ /dev/null
@@ -1,107 +0,0 @@
-
-sharedStringsFilePointer = fopen($sharedStringsFilePath, 'w');
-
- $this->throwIfSharedStringsFilePointerIsNotAvailable();
-
- // the headers is split into different parts so that we can fseek and put in the correct count and uniqueCount later
- $header = self::SHARED_STRINGS_XML_FILE_FIRST_PART_HEADER . ' ' . self::DEFAULT_STRINGS_COUNT_PART . '>';
- fwrite($this->sharedStringsFilePointer, $header);
-
- /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
- $this->stringsEscaper = \Box\Spout\Common\Escaper\XLSX::getInstance();
- }
-
- /**
- * Checks if the book has been created. Throws an exception if not created yet.
- *
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
- */
- protected function throwIfSharedStringsFilePointerIsNotAvailable()
- {
- if (!$this->sharedStringsFilePointer) {
- throw new IOException('Unable to open shared strings file for writing.');
- }
- }
-
- /**
- * Writes the given string into the sharedStrings.xml file.
- * Starting and ending whitespaces are preserved.
- *
- * @param string $string
- * @return int ID of the written shared string
- */
- public function writeString($string)
- {
- fwrite($this->sharedStringsFilePointer, '' . $this->stringsEscaper->escape($string) . '');
- $this->numSharedStrings++;
-
- // Shared string ID is zero-based
- return ($this->numSharedStrings - 1);
- }
-
- /**
- * Finishes writing the data in the sharedStrings.xml file and closes the file.
- *
- * @return void
- */
- public function close()
- {
- if (!is_resource($this->sharedStringsFilePointer)) {
- return;
- }
-
- fwrite($this->sharedStringsFilePointer, '');
-
- // Replace the default strings count with the actual number of shared strings in the file header
- $firstPartHeaderLength = strlen(self::SHARED_STRINGS_XML_FILE_FIRST_PART_HEADER);
- $defaultStringsCountPartLength = strlen(self::DEFAULT_STRINGS_COUNT_PART);
-
- // Adding 1 to take into account the space between the last xml attribute and "count"
- fseek($this->sharedStringsFilePointer, $firstPartHeaderLength + 1);
- fwrite($this->sharedStringsFilePointer, sprintf("%-{$defaultStringsCountPartLength}s", 'count="' . $this->numSharedStrings . '" uniqueCount="' . $this->numSharedStrings . '"'));
-
- fclose($this->sharedStringsFilePointer);
- }
-}
diff --git a/src/Spout/Writer/XLSX/Helper/StyleHelper.php b/src/Spout/Writer/XLSX/Helper/StyleHelper.php
deleted file mode 100644
index 4a13c95..0000000
--- a/src/Spout/Writer/XLSX/Helper/StyleHelper.php
+++ /dev/null
@@ -1,344 +0,0 @@
- [FILL_ID] maps a style to a fill declaration
- */
- protected $styleIdToFillMappingTable = [];
-
- /**
- * Excel preserves two default fills with index 0 and 1
- * Since Excel is the dominant vendor - we play along here
- *
- * @var int The fill index counter for custom fills.
- */
- protected $fillIndex = 2;
-
- /**
- * @var array
- */
- protected $registeredBorders = [];
-
- /**
- * @var array [STYLE_ID] => [BORDER_ID] maps a style to a border declaration
- */
- protected $styleIdToBorderMappingTable = [];
-
- /**
- * XLSX specific operations on the registered styles
- *
- * @param \Box\Spout\Writer\Style\Style $style
- * @return \Box\Spout\Writer\Style\Style
- */
- public function registerStyle($style)
- {
- $registeredStyle = parent::registerStyle($style);
- $this->registerFill($registeredStyle);
- $this->registerBorder($registeredStyle);
- return $registeredStyle;
- }
-
- /**
- * Register a fill definition
- *
- * @param \Box\Spout\Writer\Style\Style $style
- */
- protected function registerFill($style)
- {
- $styleId = $style->getId();
-
- // Currently - only solid backgrounds are supported
- // so $backgroundColor is a scalar value (RGB Color)
- $backgroundColor = $style->getBackgroundColor();
-
- if ($backgroundColor) {
- $isBackgroundColorRegistered = isset($this->registeredFills[$backgroundColor]);
-
- // We need to track the already registered background definitions
- if ($isBackgroundColorRegistered) {
- $registeredStyleId = $this->registeredFills[$backgroundColor];
- $registeredFillId = $this->styleIdToFillMappingTable[$registeredStyleId];
- $this->styleIdToFillMappingTable[$styleId] = $registeredFillId;
- } else {
- $this->registeredFills[$backgroundColor] = $styleId;
- $this->styleIdToFillMappingTable[$styleId] = $this->fillIndex++;
- }
-
- } else {
- // The fillId maps a style to a fill declaration
- // When there is no background color definition - we default to 0
- $this->styleIdToFillMappingTable[$styleId] = 0;
- }
- }
-
- /**
- * Register a border definition
- *
- * @param \Box\Spout\Writer\Style\Style $style
- */
- protected function registerBorder($style)
- {
- $styleId = $style->getId();
-
- if ($style->shouldApplyBorder()) {
- $border = $style->getBorder();
- $serializedBorder = serialize($border);
-
- $isBorderAlreadyRegistered = isset($this->registeredBorders[$serializedBorder]);
-
- if ($isBorderAlreadyRegistered) {
- $registeredStyleId = $this->registeredBorders[$serializedBorder];
- $registeredBorderId = $this->styleIdToBorderMappingTable[$registeredStyleId];
- $this->styleIdToBorderMappingTable[$styleId] = $registeredBorderId;
- } else {
- $this->registeredBorders[$serializedBorder] = $styleId;
- $this->styleIdToBorderMappingTable[$styleId] = count($this->registeredBorders);
- }
-
- } else {
- // If no border should be applied - the mapping is the default border: 0
- $this->styleIdToBorderMappingTable[$styleId] = 0;
- }
- }
-
-
- /**
- * For empty cells, we can specify a style or not. If no style are specified,
- * then the software default will be applied. But sometimes, it may be useful
- * to override this default style, for instance if the cell should have a
- * background color different than the default one or some borders
- * (fonts property don't really matter here).
- *
- * @param int $styleId
- * @return bool Whether the cell should define a custom style
- */
- public function shouldApplyStyleOnEmptyCell($styleId)
- {
- $hasStyleCustomFill = (isset($this->styleIdToFillMappingTable[$styleId]) && $this->styleIdToFillMappingTable[$styleId] !== 0);
- $hasStyleCustomBorders = (isset($this->styleIdToBorderMappingTable[$styleId]) && $this->styleIdToBorderMappingTable[$styleId] !== 0);
-
- return ($hasStyleCustomFill || $hasStyleCustomBorders);
- }
-
-
- /**
- * Returns the content of the "styles.xml" file, given a list of styles.
- *
- * @return string
- */
- public function getStylesXMLFileContent()
- {
- $content = <<
-
-EOD;
-
- $content .= $this->getFontsSectionContent();
- $content .= $this->getFillsSectionContent();
- $content .= $this->getBordersSectionContent();
- $content .= $this->getCellStyleXfsSectionContent();
- $content .= $this->getCellXfsSectionContent();
- $content .= $this->getCellStylesSectionContent();
-
- $content .= <<
-EOD;
-
- return $content;
- }
-
- /**
- * Returns the content of the "" section.
- *
- * @return string
- */
- protected function getFontsSectionContent()
- {
- $content = '';
-
- /** @var \Box\Spout\Writer\Style\Style $style */
- foreach ($this->getRegisteredStyles() as $style) {
- $content .= '';
-
- $content .= '';
- $content .= '';
- $content .= '';
-
- if ($style->isFontBold()) {
- $content .= '';
- }
- if ($style->isFontItalic()) {
- $content .= '';
- }
- if ($style->isFontUnderline()) {
- $content .= '';
- }
- if ($style->isFontStrikethrough()) {
- $content .= '';
- }
-
- $content .= '';
- }
-
- $content .= '';
-
- return $content;
- }
-
- /**
- * Returns the content of the "" section.
- *
- * @return string
- */
- protected function getFillsSectionContent()
- {
- // Excel reserves two default fills
- $fillsCount = count($this->registeredFills) + 2;
- $content = sprintf('', $fillsCount);
-
- $content .= '';
- $content .= '';
-
- // The other fills are actually registered by setting a background color
- foreach ($this->registeredFills as $styleId) {
- /** @var Style $style */
- $style = $this->styleIdToStyleMappingTable[$styleId];
-
- $backgroundColor = $style->getBackgroundColor();
- $content .= sprintf(
- '',
- $backgroundColor
- );
- }
-
- $content .= '';
-
- return $content;
- }
-
- /**
- * Returns the content of the "" section.
- *
- * @return string
- */
- protected function getBordersSectionContent()
- {
-
- // There is one default border with index 0
- $borderCount = count($this->registeredBorders) + 1;
-
- $content = '';
-
- // Default border starting at index 0
- $content .= '';
-
- foreach ($this->registeredBorders as $styleId) {
- /** @var \Box\Spout\Writer\Style\Style $style */
- $style = $this->styleIdToStyleMappingTable[$styleId];
- $border = $style->getBorder();
- $content .= '';
-
- // @link https://github.com/box/spout/issues/271
- $sortOrder = ['left', 'right', 'top', 'bottom'];
-
- foreach ($sortOrder as $partName) {
- if ($border->hasPart($partName)) {
- /** @var $part \Box\Spout\Writer\Style\BorderPart */
- $part = $border->getPart($partName);
- $content .= BorderHelper::serializeBorderPart($part);
- }
-
- }
-
- $content .= '';
- }
-
- $content .= '';
-
- return $content;
- }
-
- /**
- * Returns the content of the "" section.
- *
- * @return string
- */
- protected function getCellStyleXfsSectionContent()
- {
- return <<
-
-
-EOD;
- }
-
- /**
- * Returns the content of the "" section.
- *
- * @return string
- */
- protected function getCellXfsSectionContent()
- {
- $registeredStyles = $this->getRegisteredStyles();
-
- $content = '';
-
- foreach ($registeredStyles as $style) {
- $styleId = $style->getId();
- $fillId = $this->styleIdToFillMappingTable[$styleId];
- $borderId = $this->styleIdToBorderMappingTable[$styleId];
-
- $content .= 'shouldApplyFont()) {
- $content .= ' applyFont="1"';
- }
-
- $content .= sprintf(' applyBorder="%d"', $style->shouldApplyBorder() ? 1 : 0);
-
- if ($style->shouldWrapText()) {
- $content .= ' applyAlignment="1">';
- $content .= '';
- $content .= '';
- } else {
- $content .= '/>';
- }
- }
-
- $content .= '';
-
- return $content;
- }
-
- /**
- * Returns the content of the "" section.
- *
- * @return string
- */
- protected function getCellStylesSectionContent()
- {
- return <<
-
-
-EOD;
- }
-}
diff --git a/src/Spout/Writer/XLSX/Internal/Workbook.php b/src/Spout/Writer/XLSX/Internal/Workbook.php
deleted file mode 100644
index bcdce7f..0000000
--- a/src/Spout/Writer/XLSX/Internal/Workbook.php
+++ /dev/null
@@ -1,135 +0,0 @@
-shouldUseInlineStrings = $shouldUseInlineStrings;
-
- $this->fileSystemHelper = new FileSystemHelper($tempFolder);
- $this->fileSystemHelper->createBaseFilesAndFolders();
-
- $this->styleHelper = new StyleHelper($defaultRowStyle);
-
- // This helper will be shared by all sheets
- $xlFolder = $this->fileSystemHelper->getXlFolder();
- $this->sharedStringsHelper = new SharedStringsHelper($xlFolder);
- }
-
- /**
- * @return \Box\Spout\Writer\XLSX\Helper\StyleHelper Helper to apply styles to XLSX files
- */
- protected function getStyleHelper()
- {
- return $this->styleHelper;
- }
-
- /**
- * @return int Maximum number of rows/columns a sheet can contain
- */
- protected function getMaxRowsPerWorksheet()
- {
- return self::$maxRowsPerWorksheet;
- }
-
- /**
- * Creates a new sheet in the workbook. The current sheet remains unchanged.
- *
- * @return Worksheet The created sheet
- * @throws \Box\Spout\Common\Exception\IOException If unable to open the sheet for writing
- */
- public function addNewSheet()
- {
- $newSheetIndex = count($this->worksheets);
- $sheet = new Sheet($newSheetIndex, $this->internalId);
-
- $worksheetFilesFolder = $this->fileSystemHelper->getXlWorksheetsFolder();
- $worksheet = new Worksheet($sheet, $worksheetFilesFolder, $this->sharedStringsHelper, $this->styleHelper, $this->shouldUseInlineStrings);
- $this->worksheets[] = $worksheet;
-
- return $worksheet;
- }
-
- /**
- * Closes the workbook and all its associated sheets.
- * All the necessary files are written to disk and zipped together to create the XLSX file.
- * All the temporary files are then deleted.
- *
- * @param resource $finalFilePointer Pointer to the XLSX that will be created
- * @return void
- */
- public function close($finalFilePointer)
- {
- /** @var Worksheet[] $worksheets */
- $worksheets = $this->worksheets;
-
- foreach ($worksheets as $worksheet) {
- $worksheet->close();
- }
-
- $this->sharedStringsHelper->close();
-
- // Finish creating all the necessary files before zipping everything together
- $this->fileSystemHelper
- ->createContentTypesFile($worksheets)
- ->createWorkbookFile($worksheets)
- ->createWorkbookRelsFile($worksheets)
- ->createStylesFile($this->styleHelper)
- ->zipRootFolderAndCopyToStream($finalFilePointer);
-
- $this->cleanupTempFolder();
- }
-
- /**
- * Deletes the root folder created in the temp folder and all its contents.
- *
- * @return void
- */
- protected function cleanupTempFolder()
- {
- $xlsxRootFolder = $this->fileSystemHelper->getRootFolder();
- $this->fileSystemHelper->deleteFolderRecursively($xlsxRootFolder);
- }
-}
diff --git a/src/Spout/Writer/XLSX/Internal/Worksheet.php b/src/Spout/Writer/XLSX/Internal/Worksheet.php
deleted file mode 100644
index b5a3dc7..0000000
--- a/src/Spout/Writer/XLSX/Internal/Worksheet.php
+++ /dev/null
@@ -1,275 +0,0 @@
-
-
-EOD;
-
- /** @var \Box\Spout\Writer\Common\Sheet The "external" sheet */
- protected $externalSheet;
-
- /** @var string Path to the XML file that will contain the sheet data */
- protected $worksheetFilePath;
-
- /** @var \Box\Spout\Writer\XLSX\Helper\SharedStringsHelper Helper to write shared strings */
- protected $sharedStringsHelper;
-
- /** @var \Box\Spout\Writer\XLSX\Helper\StyleHelper Helper to work with styles */
- protected $styleHelper;
-
- /** @var bool Whether inline or shared strings should be used */
- protected $shouldUseInlineStrings;
-
- /** @var \Box\Spout\Common\Escaper\XLSX Strings escaper */
- protected $stringsEscaper;
-
- /** @var \Box\Spout\Common\Helper\StringHelper String helper */
- protected $stringHelper;
-
- /** @var Resource Pointer to the sheet data file (e.g. xl/worksheets/sheet1.xml) */
- protected $sheetFilePointer;
-
- /** @var int Index of the last written row */
- protected $lastWrittenRowIndex = 0;
-
- /**
- * @param \Box\Spout\Writer\Common\Sheet $externalSheet The associated "external" sheet
- * @param string $worksheetFilesFolder Temporary folder where the files to create the XLSX will be stored
- * @param \Box\Spout\Writer\XLSX\Helper\SharedStringsHelper $sharedStringsHelper Helper for shared strings
- * @param \Box\Spout\Writer\XLSX\Helper\StyleHelper Helper to work with styles
- * @param bool $shouldUseInlineStrings Whether inline or shared strings should be used
- * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
- */
- public function __construct($externalSheet, $worksheetFilesFolder, $sharedStringsHelper, $styleHelper, $shouldUseInlineStrings)
- {
- $this->externalSheet = $externalSheet;
- $this->sharedStringsHelper = $sharedStringsHelper;
- $this->styleHelper = $styleHelper;
- $this->shouldUseInlineStrings = $shouldUseInlineStrings;
-
- /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
- $this->stringsEscaper = \Box\Spout\Common\Escaper\XLSX::getInstance();
- $this->stringHelper = new StringHelper();
-
- $this->worksheetFilePath = $worksheetFilesFolder . '/' . strtolower($this->externalSheet->getName()) . '.xml';
- $this->startSheet();
- }
-
- /**
- * Prepares the worksheet to accept data
- *
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
- */
- protected function startSheet()
- {
- $this->sheetFilePointer = fopen($this->worksheetFilePath, 'w');
- $this->throwIfSheetFilePointerIsNotAvailable();
-
- fwrite($this->sheetFilePointer, self::SHEET_XML_FILE_HEADER);
- fwrite($this->sheetFilePointer, '');
- }
-
- /**
- * Checks if the book has been created. Throws an exception if not created yet.
- *
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
- */
- protected function throwIfSheetFilePointerIsNotAvailable()
- {
- if (!$this->sheetFilePointer) {
- throw new IOException('Unable to open sheet for writing.');
- }
- }
-
- /**
- * @return \Box\Spout\Writer\Common\Sheet The "external" sheet
- */
- public function getExternalSheet()
- {
- return $this->externalSheet;
- }
-
- /**
- * @return int The index of the last written row
- */
- public function getLastWrittenRowIndex()
- {
- return $this->lastWrittenRowIndex;
- }
-
- /**
- * @return int The ID of the worksheet
- */
- public function getId()
- {
- // sheet index is zero-based, while ID is 1-based
- return $this->externalSheet->getIndex() + 1;
- }
-
- /**
- * Adds data to the worksheet.
- *
- * @param array $dataRow Array containing data to be written. Cannot be empty.
- * Example $dataRow = ['data1', 1234, null, '', 'data5'];
- * @param \Box\Spout\Writer\Style\Style $style Style to be applied to the row. NULL means use default style.
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If the data cannot be written
- * @throws \Box\Spout\Common\Exception\InvalidArgumentException If a cell value's type is not supported
- */
- public function addRow($dataRow, $style)
- {
- if (!$this->isEmptyRow($dataRow)) {
- $this->addNonEmptyRow($dataRow, $style);
- }
-
- $this->lastWrittenRowIndex++;
- }
-
- /**
- * Returns whether the given row is empty
- *
- * @param array $dataRow Array containing data to be written. Cannot be empty.
- * Example $dataRow = ['data1', 1234, null, '', 'data5'];
- * @return bool Whether the given row is empty
- */
- private function isEmptyRow($dataRow)
- {
- $numCells = count($dataRow);
- // using "reset()" instead of "$dataRow[0]" because $dataRow can be an associative array
- return ($numCells === 1 && CellHelper::isEmpty(reset($dataRow)));
- }
-
- /**
- * Adds non empty row to the worksheet.
- *
- * @param array $dataRow Array containing data to be written. Cannot be empty.
- * Example $dataRow = ['data1', 1234, null, '', 'data5'];
- * @param \Box\Spout\Writer\Style\Style $style Style to be applied to the row. NULL means use default style.
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If the data cannot be written
- * @throws \Box\Spout\Common\Exception\InvalidArgumentException If a cell value's type is not supported
- */
- private function addNonEmptyRow($dataRow, $style)
- {
- $cellNumber = 0;
- $rowIndex = $this->lastWrittenRowIndex + 1;
- $numCells = count($dataRow);
-
- $rowXML = '';
-
- foreach($dataRow as $cellValue) {
- $rowXML .= $this->getCellXML($rowIndex, $cellNumber, $cellValue, $style->getId());
- $cellNumber++;
- }
-
- $rowXML .= ' ';
-
- $wasWriteSuccessful = fwrite($this->sheetFilePointer, $rowXML);
- if ($wasWriteSuccessful === false) {
- throw new IOException("Unable to write data in {$this->worksheetFilePath}");
- }
- }
-
- /**
- * Build and return xml for a single cell.
- *
- * @param int $rowIndex
- * @param int $cellNumber
- * @param mixed $cellValue
- * @param int $styleId
- * @return string
- * @throws InvalidArgumentException If the given value cannot be processed
- */
- private function getCellXML($rowIndex, $cellNumber, $cellValue, $styleId)
- {
- $columnIndex = CellHelper::getCellIndexFromColumnIndex($cellNumber);
- $cellXML = 'getCellXMLFragmentForNonEmptyString($cellValue);
- } else if (CellHelper::isBoolean($cellValue)) {
- $cellXML .= ' t="b">' . intval($cellValue) . '';
- } else if (CellHelper::isNumeric($cellValue)) {
- $cellXML .= '>' . $cellValue . '';
- } else if (empty($cellValue)) {
- if ($this->styleHelper->shouldApplyStyleOnEmptyCell($styleId)) {
- $cellXML .= '/>';
- } else {
- // don't write empty cells that do no need styling
- // NOTE: not appending to $cellXML is the right behavior!!
- $cellXML = '';
- }
- } else {
- throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cellValue));
- }
-
- return $cellXML;
- }
-
- /**
- * Returns the XML fragment for a cell containing a non empty string
- *
- * @param string $cellValue The cell value
- * @return string The XML fragment representing the cell
- * @throws InvalidArgumentException If the string exceeds the maximum number of characters allowed per cell
- */
- private function getCellXMLFragmentForNonEmptyString($cellValue)
- {
- if ($this->stringHelper->getStringLength($cellValue) > self::MAX_CHARACTERS_PER_CELL) {
- throw new InvalidArgumentException('Trying to add a value that exceeds the maximum number of characters allowed in a cell (32,767)');
- }
-
- if ($this->shouldUseInlineStrings) {
- $cellXMLFragment = ' t="inlineStr">' . $this->stringsEscaper->escape($cellValue) . '';
- } else {
- $sharedStringId = $this->sharedStringsHelper->writeString($cellValue);
- $cellXMLFragment = ' t="s">' . $sharedStringId . '';
- }
-
- return $cellXMLFragment;
- }
-
- /**
- * Closes the worksheet
- *
- * @return void
- */
- public function close()
- {
- if (!is_resource($this->sheetFilePointer)) {
- return;
- }
-
- fwrite($this->sheetFilePointer, '');
- fwrite($this->sheetFilePointer, '');
- fclose($this->sheetFilePointer);
- }
-}
diff --git a/src/Spout/Writer/XLSX/Writer.php b/src/Spout/Writer/XLSX/Writer.php
deleted file mode 100644
index 965955a..0000000
--- a/src/Spout/Writer/XLSX/Writer.php
+++ /dev/null
@@ -1,132 +0,0 @@
-throwIfWriterAlreadyOpened('Writer must be configured before opening it.');
-
- $this->tempFolder = $tempFolder;
- return $this;
- }
-
- /**
- * Use inline string to be more memory efficient. If set to false, it will use shared strings.
- * This must be set before opening the writer.
- *
- * @api
- * @param bool $shouldUseInlineStrings Whether inline or shared strings should be used
- * @return Writer
- * @throws \Box\Spout\Writer\Exception\WriterAlreadyOpenedException If the writer was already opened
- */
- public function setShouldUseInlineStrings($shouldUseInlineStrings)
- {
- $this->throwIfWriterAlreadyOpened('Writer must be configured before opening it.');
-
- $this->shouldUseInlineStrings = $shouldUseInlineStrings;
- return $this;
- }
-
- /**
- * Configures the write and sets the current sheet pointer to a new sheet.
- *
- * @return void
- * @throws \Box\Spout\Common\Exception\IOException If unable to open the file for writing
- */
- protected function openWriter()
- {
- if (!$this->book) {
- $tempFolder = ($this->tempFolder) ? : sys_get_temp_dir();
- $this->book = new Workbook($tempFolder, $this->shouldUseInlineStrings, $this->shouldCreateNewSheetsAutomatically, $this->defaultRowStyle);
- $this->book->addNewSheetAndMakeItCurrent();
- }
- }
-
- /**
- * @return Internal\Workbook The workbook representing the file to be written
- */
- protected function getWorkbook()
- {
- return $this->book;
- }
-
- /**
- * Adds data to the currently opened writer.
- * If shouldCreateNewSheetsAutomatically option is set to true, it will handle pagination
- * with the creation of new worksheets if one worksheet has reached its maximum capicity.
- *
- * @param array $dataRow Array containing data to be written.
- * Example $dataRow = ['data1', 1234, null, '', 'data5'];
- * @param \Box\Spout\Writer\Style\Style $style Style to be applied to the row.
- * @return void
- * @throws \Box\Spout\Writer\Exception\WriterNotOpenedException If the book is not created yet
- * @throws \Box\Spout\Common\Exception\IOException If unable to write data
- */
- protected function addRowToWriter(array $dataRow, $style)
- {
- $this->throwIfBookIsNotAvailable();
- $this->book->addRowToCurrentWorksheet($dataRow, $style);
- }
-
- /**
- * Returns the default style to be applied to rows.
- *
- * @return \Box\Spout\Writer\Style\Style
- */
- protected function getDefaultRowStyle()
- {
- return (new StyleBuilder())
- ->setFontSize(self::DEFAULT_FONT_SIZE)
- ->setFontName(self::DEFAULT_FONT_NAME)
- ->build();
- }
-
- /**
- * Closes the writer, preventing any additional writing.
- *
- * @return void
- */
- protected function closeWriter()
- {
- if ($this->book) {
- $this->book->close($this->filePointer);
- }
- }
-}
diff --git a/tests/Spout/Common/Escaper/ODSTest.php b/tests/Spout/Common/Escaper/ODSTest.php
deleted file mode 100644
index 77b4913..0000000
--- a/tests/Spout/Common/Escaper/ODSTest.php
+++ /dev/null
@@ -1,42 +0,0 @@
-escape($stringToEscape);
-
- $this->assertEquals($expectedEscapedString, $escapedString, 'Incorrect escaped string');
- }
-}
diff --git a/tests/Spout/Common/Escaper/XLSXTest.php b/tests/Spout/Common/Escaper/XLSXTest.php
deleted file mode 100644
index 0f2098f..0000000
--- a/tests/Spout/Common/Escaper/XLSXTest.php
+++ /dev/null
@@ -1,83 +0,0 @@
-escape($stringToEscape);
-
- $this->assertEquals($expectedEscapedString, $escapedString, 'Incorrect escaped string');
- }
-
- /**
- * @return array
- */
- public function dataProviderForTestUnescape()
- {
- return [
- ['test', 'test'],
- ['adam's "car"', 'adam's "car"'],
- ["\n", "\n"],
- ["\r", "\r"],
- ["\t", "\t"],
- ['_x0000_', chr(0)],
- ['_x0004_', chr(4)],
- ['_x005F_x0000_', '_x0000_'],
- ['_x0015_', chr(21)],
- ['control _x0015_ character', 'control '.chr(21).' character'],
- ['control's _x0015_ "character"', 'control's '.chr(21).' "character"'],
- ];
- }
-
- /**
- * @dataProvider dataProviderForTestUnescape
- *
- * @param string $stringToUnescape
- * @param string $expectedUnescapedString
- * @return void
- */
- public function testUnescape($stringToUnescape, $expectedUnescapedString)
- {
- /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
- $escaper = \Box\Spout\Common\Escaper\XLSX::getInstance();
- $unescapedString = $escaper->unescape($stringToUnescape);
-
- $this->assertEquals($expectedUnescapedString, $unescapedString, 'Incorrect escaped string');
- }
-}
diff --git a/tests/Spout/Common/Helper/EncodingHelperTest.php b/tests/Spout/Common/Helper/EncodingHelperTest.php
deleted file mode 100644
index d142d4e..0000000
--- a/tests/Spout/Common/Helper/EncodingHelperTest.php
+++ /dev/null
@@ -1,223 +0,0 @@
-getResourcePath($fileName);
- $filePointer = fopen($resourcePath, 'r');
-
- $encodingHelper = new EncodingHelper(new GlobalFunctionsHelper());
- $bytesOffset = $encodingHelper->getBytesOffsetToSkipBOM($filePointer, $encoding);
-
- $this->assertEquals($expectedBytesOffset, $bytesOffset);
- }
-
- /**
- * @return array
- */
- public function dataProviderForIconvOrMbstringUsage()
- {
- return [
- [$shouldUseIconv = true],
- [$shouldNotUseIconv = false],
- ];
- }
-
- /**
- * @dataProvider dataProviderForIconvOrMbstringUsage
- * @expectedException \Box\Spout\Common\Exception\EncodingConversionException
- *
- * @param bool $shouldUseIconv
- * @return void
- */
- public function testAttemptConversionToUTF8ShouldThrowIfConversionFailed($shouldUseIconv)
- {
- $helperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\GlobalFunctionsHelper')
- ->setMethods(['iconv', 'mb_convert_encoding'])
- ->getMock();
- $helperStub->method('iconv')->willReturn(false);
- $helperStub->method('mb_convert_encoding')->willReturn(false);
-
- /** @var EncodingHelper $encodingHelperStub */
- $encodingHelperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\EncodingHelper')
- ->setConstructorArgs([$helperStub])
- ->setMethods(['canUseIconv', 'canUseMbString'])
- ->getMock();
- $encodingHelperStub->method('canUseIconv')->willReturn($shouldUseIconv);
- $encodingHelperStub->method('canUseMbString')->willReturn(true);
-
- $encodingHelperStub->attemptConversionToUTF8('input', EncodingHelper::ENCODING_UTF16_LE);
- }
-
- /**
- * @expectedException \Box\Spout\Common\Exception\EncodingConversionException
- *
- * @return void
- */
- public function testAttemptConversionToUTF8ShouldThrowIfConversionNotSupported()
- {
- /** @var EncodingHelper $encodingHelperStub */
- $encodingHelperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\EncodingHelper')
- ->disableOriginalConstructor()
- ->setMethods(['canUseIconv', 'canUseMbString'])
- ->getMock();
- $encodingHelperStub->method('canUseIconv')->willReturn(false);
- $encodingHelperStub->method('canUseMbString')->willReturn(false);
-
- $encodingHelperStub->attemptConversionToUTF8('input', EncodingHelper::ENCODING_UTF16_LE);
- }
-
- /**
- * @dataProvider dataProviderForIconvOrMbstringUsage
- *
- * @param bool $shouldUseIconv
- * @return void
- */
- public function testAttemptConversionToUTF8ShouldReturnReencodedString($shouldUseIconv)
- {
- /** @var EncodingHelper $encodingHelperStub */
- $encodingHelperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\EncodingHelper')
- ->setConstructorArgs([new GlobalFunctionsHelper()])
- ->setMethods(['canUseIconv', 'canUseMbString'])
- ->getMock();
- $encodingHelperStub->method('canUseIconv')->willReturn($shouldUseIconv);
- $encodingHelperStub->method('canUseMbString')->willReturn(true);
-
- $encodedString = iconv(EncodingHelper::ENCODING_UTF8, EncodingHelper::ENCODING_UTF16_LE, 'input');
- $decodedString = $encodingHelperStub->attemptConversionToUTF8($encodedString, EncodingHelper::ENCODING_UTF16_LE);
-
- $this->assertEquals('input', $decodedString);
- }
-
- /**
- * @return void
- */
- public function testAttemptConversionToUTF8ShouldBeNoopWhenTargetIsUTF8()
- {
- /** @var EncodingHelper $encodingHelperStub */
- $encodingHelperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\EncodingHelper')
- ->disableOriginalConstructor()
- ->setMethods(['canUseIconv'])
- ->getMock();
- $encodingHelperStub->expects($this->never())->method('canUseIconv');
-
- $decodedString = $encodingHelperStub->attemptConversionToUTF8('input', EncodingHelper::ENCODING_UTF8);
- $this->assertEquals('input', $decodedString);
- }
-
- /**
- * @dataProvider dataProviderForIconvOrMbstringUsage
- * @expectedException \Box\Spout\Common\Exception\EncodingConversionException
- *
- * @param bool $shouldUseIconv
- * @return void
- */
- public function testAttemptConversionFromUTF8ShouldThrowIfConversionFailed($shouldUseIconv)
- {
- $helperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\GlobalFunctionsHelper')
- ->setMethods(['iconv', 'mb_convert_encoding'])
- ->getMock();
- $helperStub->method('iconv')->willReturn(false);
- $helperStub->method('mb_convert_encoding')->willReturn(false);
-
- /** @var EncodingHelper $encodingHelperStub */
- $encodingHelperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\EncodingHelper')
- ->setConstructorArgs([$helperStub])
- ->setMethods(['canUseIconv', 'canUseMbString'])
- ->getMock();
- $encodingHelperStub->method('canUseIconv')->willReturn($shouldUseIconv);
- $encodingHelperStub->method('canUseMbString')->willReturn(true);
-
- $encodingHelperStub->attemptConversionFromUTF8('input', EncodingHelper::ENCODING_UTF16_LE);
- }
-
- /**
- * @expectedException \Box\Spout\Common\Exception\EncodingConversionException
- *
- * @return void
- */
- public function testAttemptConversionFromUTF8ShouldThrowIfConversionNotSupported()
- {
- /** @var EncodingHelper $encodingHelperStub */
- $encodingHelperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\EncodingHelper')
- ->disableOriginalConstructor()
- ->setMethods(['canUseIconv', 'canUseMbString'])
- ->getMock();
- $encodingHelperStub->method('canUseIconv')->willReturn(false);
- $encodingHelperStub->method('canUseMbString')->willReturn(false);
-
- $encodingHelperStub->attemptConversionFromUTF8('input', EncodingHelper::ENCODING_UTF16_LE);
- }
-
- /**
- * @dataProvider dataProviderForIconvOrMbstringUsage
- *
- * @param bool $shouldUseIconv
- * @return void
- */
- public function testAttemptConversionFromUTF8ShouldReturnReencodedString($shouldUseIconv)
- {
- /** @var EncodingHelper $encodingHelperStub */
- $encodingHelperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\EncodingHelper')
- ->setConstructorArgs([new GlobalFunctionsHelper()])
- ->setMethods(['canUseIconv', 'canUseMbString'])
- ->getMock();
- $encodingHelperStub->method('canUseIconv')->willReturn($shouldUseIconv);
- $encodingHelperStub->method('canUseMbString')->willReturn(true);
-
- $encodedString = $encodingHelperStub->attemptConversionFromUTF8('input', EncodingHelper::ENCODING_UTF16_LE);
- $encodedStringWithIconv = iconv(EncodingHelper::ENCODING_UTF8, EncodingHelper::ENCODING_UTF16_LE, 'input');
-
- $this->assertEquals($encodedStringWithIconv, $encodedString);
- }
-
- /**
- * @return void
- */
- public function testAttemptConversionFromUTF8ShouldBeNoopWhenTargetIsUTF8()
- {
- /** @var EncodingHelper $encodingHelperStub */
- $encodingHelperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\EncodingHelper')
- ->disableOriginalConstructor()
- ->setMethods(['canUseIconv'])
- ->getMock();
- $encodingHelperStub->expects($this->never())->method('canUseIconv');
-
- $encodedString = $encodingHelperStub->attemptConversionFromUTF8('input', EncodingHelper::ENCODING_UTF8);
- $this->assertEquals('input', $encodedString);
- }
-}
diff --git a/tests/Spout/Common/Helper/FileSystemHelperTest.php b/tests/Spout/Common/Helper/FileSystemHelperTest.php
deleted file mode 100644
index a73e7f2..0000000
--- a/tests/Spout/Common/Helper/FileSystemHelperTest.php
+++ /dev/null
@@ -1,59 +0,0 @@
-fileSystemHelper = new FileSystemHelper($baseFolder);
- }
-
- /**
- * @expectedException \Box\Spout\Common\Exception\IOException
- * @return void
- */
- public function testCreateFolderShouldThrowExceptionIfOutsideOfBaseFolder()
- {
- $this->fileSystemHelper->createFolder('/tmp/folder_outside_base_folder', 'folder_name');
- }
-
- /**
- * @expectedException \Box\Spout\Common\Exception\IOException
- * @return void
- */
- public function testCreateFileWithContentsShouldThrowExceptionIfOutsideOfBaseFolder()
- {
- $this->fileSystemHelper->createFileWithContents('/tmp/folder_outside_base_folder', 'file_name', 'contents');
- }
-
- /**
- * @expectedException \Box\Spout\Common\Exception\IOException
- * @return void
- */
- public function testDeleteFileShouldThrowExceptionIfOutsideOfBaseFolder()
- {
- $this->fileSystemHelper->deleteFile('/tmp/folder_outside_base_folder/file_name');
- }
-
- /**
- * @expectedException \Box\Spout\Common\Exception\IOException
- * @return void
- */
- public function testDeleteFolderRecursivelyShouldThrowExceptionIfOutsideOfBaseFolder()
- {
- $this->fileSystemHelper->deleteFolderRecursively('/tmp/folder_outside_base_folder');
- }
-}
diff --git a/tests/Spout/Reader/CSV/ReaderTest.php b/tests/Spout/Reader/CSV/ReaderTest.php
deleted file mode 100644
index 429ffa6..0000000
--- a/tests/Spout/Reader/CSV/ReaderTest.php
+++ /dev/null
@@ -1,518 +0,0 @@
-open('/path/to/fake/file.csv');
- }
-
- /**
- * @expectedException \Box\Spout\Reader\Exception\ReaderNotOpenedException
- *
- * @return void
- */
- public function testOpenShouldThrowExceptionIfTryingToReadBeforeOpeningReader()
- {
- ReaderFactory::create(Type::CSV)->getSheetIterator();
- }
-
- /**
- * @expectedException \Box\Spout\Common\Exception\IOException
- *
- * @return void
- */
- public function testOpenShouldThrowExceptionIfFileNotReadable()
- {
- $helperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\GlobalFunctionsHelper')
- ->setMethods(['is_readable'])
- ->getMock();
- $helperStub->method('is_readable')->willReturn(false);
-
- $resourcePath = $this->getResourcePath('csv_standard.csv');
-
- $reader = ReaderFactory::create(Type::CSV);
- $reader->setGlobalFunctionsHelper($helperStub);
- $reader->open($resourcePath);
- }
-
- /**
- * @expectedException \Box\Spout\Common\Exception\IOException
- *
- * @return void
- */
- public function testOpenShouldThrowExceptionIfCannotOpenFile()
- {
- $helperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\GlobalFunctionsHelper')
- ->setMethods(['fopen'])
- ->getMock();
- $helperStub->method('fopen')->willReturn(false);
-
- $resourcePath = $this->getResourcePath('csv_standard.csv');
-
- $reader = ReaderFactory::create(Type::CSV);
- $reader->setGlobalFunctionsHelper($helperStub);
- $reader->open($resourcePath);
- }
-
-
- /**
- * @return void
- */
- public function testReadStandardCSV()
- {
- $allRows = $this->getAllRowsForFile('csv_standard.csv');
-
- $expectedRows = [
- ['csv--11', 'csv--12', 'csv--13'],
- ['csv--21', 'csv--22', 'csv--23'],
- ['csv--31', 'csv--32', 'csv--33'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldNotStopAtCommaIfEnclosed()
- {
- $allRows = $this->getAllRowsForFile('csv_with_comma_enclosed.csv');
- $this->assertEquals('This is, a comma', $allRows[0][0]);
- }
-
- /**
- * @return void
- */
- public function testReadShouldKeepEmptyCells()
- {
- $allRows = $this->getAllRowsForFile('csv_with_empty_cells.csv');
-
- $expectedRows = [
- ['csv--11', 'csv--12', 'csv--13'],
- ['csv--21', '', 'csv--23'],
- ['csv--31', 'csv--32', ''],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSkipEmptyLinesIfShouldPreserveEmptyRowsNotSet()
- {
- $allRows = $this->getAllRowsForFile('csv_with_multiple_empty_lines.csv');
-
- $expectedRows = [
- // skipped row here
- ['csv--21', 'csv--22', 'csv--23'],
- // skipped row here
- ['csv--41', 'csv--42', 'csv--43'],
- // skipped row here
- // last row empty
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldReturnEmptyLinesIfShouldPreserveEmptyRowsSet()
- {
- $allRows = $this->getAllRowsForFile(
- 'csv_with_multiple_empty_lines.csv',
- ',', '"', "\n", EncodingHelper::ENCODING_UTF8,
- $shouldPreserveEmptyRows = true
- );
-
- $expectedRows = [
- [''],
- ['csv--21', 'csv--22', 'csv--23'],
- [''],
- ['csv--41', 'csv--42', 'csv--43'],
- [''],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return array
- */
- public function dataProviderForTestReadShouldReadEmptyFile()
- {
- return [
- ['csv_empty.csv'],
- ['csv_all_lines_empty.csv'],
- ];
- }
-
- /**
- * @dataProvider dataProviderForTestReadShouldReadEmptyFile
- *
- * @param string $fileName
- * @return void
- */
- public function testReadShouldReadEmptyFile($fileName)
- {
- $allRows = $this->getAllRowsForFile($fileName);
- $this->assertEquals([], $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldHaveTheRightNumberOfCells()
- {
- $allRows = $this->getAllRowsForFile('csv_with_different_cells_number.csv');
-
- $expectedRows = [
- ['csv--11', 'csv--12', 'csv--13'],
- ['csv--21', 'csv--22'],
- ['csv--31'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSupportCustomFieldDelimiter()
- {
- $allRows = $this->getAllRowsForFile('csv_delimited_with_pipes.csv', '|');
-
- $expectedRows = [
- ['csv--11', 'csv--12', 'csv--13'],
- ['csv--21', 'csv--22', 'csv--23'],
- ['csv--31', 'csv--32', 'csv--33'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSupportCustomFieldEnclosure()
- {
- $allRows = $this->getAllRowsForFile('csv_text_enclosed_with_pound.csv', ',', '#');
- $this->assertEquals('This is, a comma', $allRows[0][0]);
- }
-
- /**
- * @return void
- */
- public function testReadCustomEOLs()
- {
- $allRows = $this->getAllRowsForFile('csv_with_CR_EOL.csv', ',', '"', "\r");
-
- $expectedRows = [
- ['csv--11', 'csv--12', 'csv--13'],
- ['csv--21', 'csv--22', 'csv--23'],
- ['csv--31', 'csv--32', 'csv--33'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldNotTruncateLineBreak()
- {
- $allRows = $this->getAllRowsForFile('csv_with_line_breaks.csv', ',');
- $this->assertEquals("This is,\na comma", $allRows[0][0]);
- }
-
- /**
- * @return array
- */
- public function dataProviderForTestReadShouldSkipBom()
- {
- return [
- ['csv_with_utf8_bom.csv', EncodingHelper::ENCODING_UTF8],
- ['csv_with_utf16le_bom.csv', EncodingHelper::ENCODING_UTF16_LE],
- ['csv_with_utf16be_bom.csv', EncodingHelper::ENCODING_UTF16_BE],
- ['csv_with_utf32le_bom.csv', EncodingHelper::ENCODING_UTF32_LE],
- ['csv_with_utf32be_bom.csv', EncodingHelper::ENCODING_UTF32_BE],
- ];
- }
-
- /**
- * @dataProvider dataProviderForTestReadShouldSkipBom
- *
- * @param string $fileName
- * @param string $fileEncoding
- * @return void
- */
- public function testReadShouldSkipBom($fileName, $fileEncoding)
- {
- $allRows = $this->getAllRowsForFile($fileName, ',', '"', "\n", $fileEncoding);
-
- $expectedRows = [
- ['csv--11', 'csv--12', 'csv--13'],
- ['csv--21', 'csv--22', 'csv--23'],
- ['csv--31', 'csv--32', 'csv--33'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return array
- */
- public function dataProviderForTestReadShouldSupportNonUTF8FilesWithoutBOMs()
- {
- $shouldUseIconv = true;
- $shouldNotUseIconv = false;
-
- return [
- ['csv_with_encoding_utf16le_no_bom.csv', EncodingHelper::ENCODING_UTF16_LE, $shouldUseIconv],
- ['csv_with_encoding_utf16le_no_bom.csv', EncodingHelper::ENCODING_UTF16_LE, $shouldNotUseIconv],
- ['csv_with_encoding_cp1252.csv', 'CP1252', $shouldUseIconv],
- ['csv_with_encoding_cp1252.csv', 'CP1252', $shouldNotUseIconv],
- ];
- }
-
- /**
- * @dataProvider dataProviderForTestReadShouldSupportNonUTF8FilesWithoutBOMs
- *
- * @param string $fileName
- * @param string $fileEncoding
- * @param bool $shouldUseIconv
- * @return void
- */
- public function testReadShouldSupportNonUTF8FilesWithoutBOMs($fileName, $fileEncoding, $shouldUseIconv)
- {
- $allRows = [];
- $resourcePath = $this->getResourcePath($fileName);
-
- /** @var \Box\Spout\Common\Helper\GlobalFunctionsHelper|\PHPUnit_Framework_MockObject_MockObject $helperStub */
- $helperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\GlobalFunctionsHelper')
- ->setMethods(['function_exists'])
- ->getMock();
-
- $returnValueMap = [
- ['iconv', $shouldUseIconv],
- ['mb_convert_encoding', true],
- ];
- $helperStub->method('function_exists')->will($this->returnValueMap($returnValueMap));
-
- /** @var \Box\Spout\Reader\CSV\Reader $reader */
- $reader = ReaderFactory::create(Type::CSV);
- $reader
- ->setGlobalFunctionsHelper($helperStub)
- ->setEncoding($fileEncoding)
- ->open($resourcePath);
-
- foreach ($reader->getSheetIterator() as $sheet) {
- foreach ($sheet->getRowIterator() as $row) {
- $allRows[] = $row;
- }
- }
-
- $reader->close();
-
- $expectedRows = [
- ['csv--11', 'csv--12', 'csv--13'],
- ['csv--21', 'csv--22', 'csv--23'],
- ['csv--31', 'csv--32', 'csv--33'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadMultipleTimesShouldRewindReader()
- {
- $allRows = [];
- $resourcePath = $this->getResourcePath('csv_standard.csv');
-
- $reader = ReaderFactory::create(Type::CSV);
- $reader->open($resourcePath);
-
- foreach ($reader->getSheetIterator() as $sheet) {
- // do nothing
- }
-
- foreach ($reader->getSheetIterator() as $sheet) {
- foreach ($sheet->getRowIterator() as $row) {
- $allRows[] = $row;
- break;
- }
-
- foreach ($sheet->getRowIterator() as $row) {
- $allRows[] = $row;
- break;
- }
- }
-
- foreach ($reader->getSheetIterator() as $sheet) {
- foreach ($sheet->getRowIterator() as $row) {
- $allRows[] = $row;
- break;
- }
- }
-
- $reader->close();
-
- $expectedRows = [
- ['csv--11', 'csv--12', 'csv--13'],
- ['csv--11', 'csv--12', 'csv--13'],
- ['csv--11', 'csv--12', 'csv--13'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * https://github.com/box/spout/issues/184
- * @return void
- */
- public function testReadShouldInludeRowsWithZerosOnly()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_zeros_in_row.csv');
-
- $expectedRows = [
- ['A', 'B', 'C'],
- ['1', '2', '3'],
- ['0', '0', '0']
- ];
- $this->assertEquals($expectedRows, $allRows, 'There should be only 3 rows, because zeros (0) are valid values');
- }
-
- /**
- * https://github.com/box/spout/issues/184
- * @return void
- */
- public function testReadShouldCreateOutputEmptyCellPreserved()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_empty_cells.csv');
-
- $expectedRows = [
- ['A', 'B', 'C'],
- ['0', '', ''],
- ['1', '1', '']
- ];
- $this->assertEquals($expectedRows, $allRows, 'There should be 3 rows, with equal length');
- }
-
- /**
- * https://github.com/box/spout/issues/195
- * @return void
- */
- public function testReaderShouldNotTrimCellValues()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_untrimmed_strings.csv');
-
- $expectedRows = [
- ['A'],
- [' A '],
- ["\n\tA\n\t"],
- ];
-
- $this->assertEquals($expectedRows, $allRows, 'Cell values should not be trimmed');
- }
-
- /**
- * @param string $fileName
- * @param string|void $fieldDelimiter
- * @param string|void $fieldEnclosure
- * @param string|void $endOfLineCharacter
- * @param string|void $encoding
- * @param bool|void $shouldPreserveEmptyRows
- * @return array All the read rows the given file
- */
- private function getAllRowsForFile(
- $fileName,
- $fieldDelimiter = ',',
- $fieldEnclosure = '"',
- $endOfLineCharacter = "\n",
- $encoding = EncodingHelper::ENCODING_UTF8,
- $shouldPreserveEmptyRows = false)
- {
- $allRows = [];
- $resourcePath = $this->getResourcePath($fileName);
-
- /** @var \Box\Spout\Reader\CSV\Reader $reader */
- $reader = ReaderFactory::create(Type::CSV);
- $reader
- ->setFieldDelimiter($fieldDelimiter)
- ->setFieldEnclosure($fieldEnclosure)
- ->setEndOfLineCharacter($endOfLineCharacter)
- ->setEncoding($encoding)
- ->setShouldPreserveEmptyRows($shouldPreserveEmptyRows)
- ->open($resourcePath);
-
- foreach ($reader->getSheetIterator() as $sheetIndex => $sheet) {
- foreach ($sheet->getRowIterator() as $rowIndex => $row) {
- $allRows[] = $row;
- }
- }
-
- $reader->close();
-
- return $allRows;
- }
-
- /**
- * @return void
- */
- public function testReadCustomStreamWrapper()
- {
- $allRows = [];
- $resourcePath = 'spout://csv_standard';
-
- // register stream wrapper
- stream_wrapper_register('spout', SpoutTestStream::CLASS_NAME);
-
- /** @var \Box\Spout\Reader\CSV\Reader $reader */
- $reader = ReaderFactory::create(Type::CSV);
- $reader->open($resourcePath);
-
- foreach ($reader->getSheetIterator() as $sheet) {
- foreach ($sheet->getRowIterator() as $row) {
- $allRows[] = $row;
- }
- }
-
- $reader->close();
-
- $expectedRows = [
- ['csv--11', 'csv--12', 'csv--13'],
- ['csv--21', 'csv--22', 'csv--23'],
- ['csv--31', 'csv--32', 'csv--33'],
- ];
- $this->assertEquals($expectedRows, $allRows);
-
- // cleanup
- stream_wrapper_unregister('spout');
- }
-
- /**
- * @expectedException \Box\Spout\Common\Exception\IOException
- *
- * @return void
- */
- public function testReadWithUnsupportedCustomStreamWrapper()
- {
- /** @var \Box\Spout\Reader\CSV\Reader $reader */
- $reader = ReaderFactory::create(Type::CSV);
- $reader->open('unsupported://foobar');
- }
-
-}
diff --git a/tests/Spout/Reader/CSV/SheetTest.php b/tests/Spout/Reader/CSV/SheetTest.php
deleted file mode 100644
index ae18c2f..0000000
--- a/tests/Spout/Reader/CSV/SheetTest.php
+++ /dev/null
@@ -1,46 +0,0 @@
-openFileAndReturnSheet('csv_standard.csv');
-
- $this->assertEquals('', $sheet->getName());
- $this->assertEquals(0, $sheet->getIndex());
- $this->assertTrue($sheet->isActive());
- }
-
- /**
- * @param string $fileName
- * @return Sheet
- */
- private function openFileAndReturnSheet($fileName)
- {
- $resourcePath = $this->getResourcePath($fileName);
- $reader = ReaderFactory::create(Type::CSV);
- $reader->open($resourcePath);
-
- $sheet = $reader->getSheetIterator()->current();
-
- $reader->close();
-
- return $sheet;
- }
-}
diff --git a/tests/Spout/Reader/CSV/SpoutTestStream.php b/tests/Spout/Reader/CSV/SpoutTestStream.php
deleted file mode 100644
index fdaeb18..0000000
--- a/tests/Spout/Reader/CSV/SpoutTestStream.php
+++ /dev/null
@@ -1,120 +0,0 @@
-getFilePathFromStreamPath($path);
- return stat($filePath);
- }
-
- /**
- * @param string $streamPath
- * @return string
- */
- private function getFilePathFromStreamPath($streamPath)
- {
- $fileName = parse_url($streamPath, PHP_URL_HOST);
- return self::PATH_TO_CSV_RESOURCES . $fileName . self::CSV_EXTENSION;
- }
-
- /**
- * @param string $path
- * @param string $mode
- * @param int $options
- * @param string $opened_path
- * @return bool
- */
- public function stream_open($path, $mode, $options, &$opened_path)
- {
- $this->position = 0;
-
- // the path is like "spout://csv_name" so the actual file name correspond the name of the host.
- $filePath = $this->getFilePathFromStreamPath($path);
- $this->fileHandle = fopen($filePath, $mode);
-
- return true;
- }
-
- /**
- * @param int $numBytes
- * @return string
- */
- public function stream_read($numBytes)
- {
- $this->position += $numBytes;
- return fread($this->fileHandle, $numBytes);
- }
-
- /**
- * @return int
- */
- public function stream_tell()
- {
- return $this->position;
- }
-
- /**
- * @param int $offset
- * @param int|void $whence
- * @return bool
- */
- public function stream_seek($offset, $whence = SEEK_SET)
- {
- $result = fseek($this->fileHandle, $offset, $whence);
- if ($result === -1) {
- return false;
- }
-
- if ($whence === SEEK_SET) {
- $this->position = $offset;
- } else if ($whence === SEEK_CUR) {
- $this->position += $offset;
- } else {
- // not implemented
- }
-
- return true;
- }
-
- /**
- * @return bool
- */
- public function stream_close()
- {
- return fclose($this->fileHandle);
- }
-
- /**
- * @return bool
- */
- public function stream_eof()
- {
- return feof($this->fileHandle);
- }
-}
diff --git a/tests/Spout/Reader/ODS/ReaderTest.php b/tests/Spout/Reader/ODS/ReaderTest.php
deleted file mode 100644
index f36348f..0000000
--- a/tests/Spout/Reader/ODS/ReaderTest.php
+++ /dev/null
@@ -1,549 +0,0 @@
-getAllRowsForFile($filePath);
- }
-
- /**
- * @return array
- */
- public function dataProviderForTestReadForAllWorksheets()
- {
- return [
- ['one_sheet_with_strings.ods', 2, 3],
- ['two_sheets_with_strings.ods', 4, 3],
- ];
- }
-
- /**
- * @dataProvider dataProviderForTestReadForAllWorksheets
- *
- * @param string $resourceName
- * @param int $expectedNumOfRows
- * @param int $expectedNumOfCellsPerRow
- * @return void
- */
- public function testReadForAllWorksheets($resourceName, $expectedNumOfRows, $expectedNumOfCellsPerRow)
- {
- $allRows = $this->getAllRowsForFile($resourceName);
-
- $this->assertEquals($expectedNumOfRows, count($allRows), "There should be $expectedNumOfRows rows");
- foreach ($allRows as $row) {
- $this->assertEquals($expectedNumOfCellsPerRow, count($row), "There should be $expectedNumOfCellsPerRow cells for every row");
- }
- }
-
- /**
- * @return void
- */
- public function testReadShouldSupportRowWithOnlyOneCell()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_only_one_cell.ods');
- $this->assertEquals([['foo']], $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSupportNumberRowsRepeated()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_number_rows_repeated.ods');
- $expectedRows = [
- ['foo', 10.43],
- ['foo', 10.43],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSupportNumberColumnsRepeated()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_number_columns_repeated.ods');
- $expectedRows = [
- [
- 'foo', 'foo', 'foo',
- '', '',
- true, true,
- 10.43, 10.43, 10.43, 10.43,
- ],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return array
- */
- public function dataProviderForTestReadWithFilesGeneratedByExternalSoftwares()
- {
- return [
- ['file_generated_by_libre_office.ods', true],
- ['file_generated_by_excel_2010_windows.ods', false],
- ['file_generated_by_excel_office_online.ods', false],
- ];
- }
-
- /**
- * @dataProvider dataProviderForTestReadWithFilesGeneratedByExternalSoftwares
- * The files contain styles, different value types, gaps between cells,
- * repeated values, empty row, different number of cells per row.
- *
- * @param bool $skipLastEmptyValues
- * @param string $fileName
- * @return void
- */
- public function testReadWithFilesGeneratedByExternalSoftwares($fileName, $skipLastEmptyValues)
- {
- $allRows = $this->getAllRowsForFile($fileName);
-
- $expectedRows = [
- ['header1','header2','header3','header4'],
- ['val11','val12','val13','val14'],
- ['val21','','val23','val23'],
- ['', 10.43, 29.11],
- ];
-
- // In the description of the last cell, Excel specifies that the empty value needs to be repeated
- // a lot of times (16384 - number of cells used in the row). To avoid creating 16384 cells all the time,
- // this cell is skipped alltogether.
- if ($skipLastEmptyValues) {
- $expectedRows[3][] = '';
- }
-
- $this->assertEquals($expectedRows, $allRows);
- }
-
-
- /**
- * @return void
- */
- public function testReadShouldSupportAllCellTypes()
- {
- $utcTz = new \DateTimeZone('UTC');
- $honoluluTz = new \DateTimeZone('Pacific/Honolulu'); // UTC-10
-
- $allRows = $this->getAllRowsForFile('sheet_with_all_cell_types.ods');
-
- $expectedRows = [
- [
- 'ods--11', 'ods--12',
- true, false,
- 0, 10.43,
- new \DateTime('1987-11-29T00:00:00', $utcTz), new \DateTime('1987-11-29T13:37:00', $utcTz),
- new \DateTime('1987-11-29T13:37:00', $utcTz), new \DateTime('1987-11-29T13:37:00', $honoluluTz),
- new \DateInterval('PT13H37M00S'),
- 0, 0.42,
- '42 USD', '9.99 EUR',
- '',
- ],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSupportFormatDatesAndTimesIfSpecified()
- {
- $shouldFormatDates = true;
- $allRows = $this->getAllRowsForFile('sheet_with_dates_and_times.ods', $shouldFormatDates);
-
- $expectedRows = [
- ['05/19/2016', '5/19/16', '05/19/2016 16:39:00', '05/19/16 04:39 PM', '5/19/2016'],
- ['11:29', '13:23:45', '01:23:45', '01:23:45 AM', '01:23:45 PM'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldReturnEmptyStringOnUndefinedCellType()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_undefined_value_type.ods');
- $this->assertEquals([['ods--11', '', 'ods--13']], $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldReturnNullOnInvalidDateOrTime()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_invalid_date_time.ods');
- $this->assertEquals([[null, null]], $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSupportMultilineStrings()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_multiline_string.ods');
-
- $expectedRows = [["string\non multiple\nlines!"]];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSkipEmptyRowsIfShouldPreserveEmptyRowsNotSet()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_empty_rows.ods');
-
- $this->assertEquals(3, count($allRows), 'There should be only 3 rows, because the empty rows are skipped');
-
- $expectedRows = [
- // skipped row here
- ['ods--21', 'ods--22', 'ods--23'],
- // skipped row here
- // skipped row here
- ['ods--51', 'ods--52', 'ods--53'],
- ['ods--61', 'ods--62', 'ods--63'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldReturnEmptyLinesIfShouldPreserveEmptyRowsSet()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_empty_rows.ods', false, true);
-
- $this->assertEquals(6, count($allRows), 'There should be 6 rows');
-
- $expectedRows = [
- [''],
- ['ods--21', 'ods--22', 'ods--23'],
- [''],
- [''],
- ['ods--51', 'ods--52', 'ods--53'],
- ['ods--61', 'ods--62', 'ods--63'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldPreserveSpacing()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_various_spaces.ods');
-
- $expectedRow = [
- ' 4 spaces before and after ',
- ' 1 space before and after ',
- '2 spaces after ',
- ' 2 spaces before',
- "3 spaces in the middle\nand 2 spaces in the middle",
- ];
- $this->assertEquals([$expectedRow], $allRows);
- }
-
-
- /**
- * @NOTE: The LIBXML_NOENT is used to ACTUALLY substitute entities (and should therefore not be used)
- *
- * @return void
- */
- public function testReadShouldBeProtectedAgainstBillionLaughsAttack()
- {
- $startTime = microtime(true);
- $fileName = 'attack_billion_laughs.ods';
-
- try {
- // using @ to prevent warnings/errors from being displayed
- @$this->getAllRowsForFile($fileName);
- $this->fail('An exception should have been thrown');
- } catch (IOException $exception) {
- $duration = microtime(true) - $startTime;
- $this->assertLessThan(10, $duration, 'Entities should not be expanded and therefore take more than 10 seconds to be parsed.');
-
- $expectedMaxMemoryUsage = 30 * 1024 * 1024; // 30MB
- $this->assertLessThan($expectedMaxMemoryUsage, memory_get_peak_usage(true), 'Entities should not be expanded and therefore consume all the memory.');
- }
- }
-
- /**
- * @NOTE: The LIBXML_NOENT is used to ACTUALLY substitute entities (and should therefore not be used)
- *
- * @return void
- */
- public function testReadShouldBeProtectedAgainstQuadraticBlowupAttack()
- {
- $startTime = microtime(true);
-
- $fileName = 'attack_quadratic_blowup.ods';
- $allRows = $this->getAllRowsForFile($fileName);
-
- $this->assertEquals('', $allRows[0][0], 'Entities should not have been expanded');
-
- $duration = microtime(true) - $startTime;
- $this->assertLessThan(10, $duration, 'Entities should not be expanded and therefore take more than 10 seconds to be parsed.');
-
- $expectedMaxMemoryUsage = 30 * 1024 * 1024; // 30MB
- $this->assertLessThan($expectedMaxMemoryUsage, memory_get_peak_usage(true), 'Entities should not be expanded and therefore consume all the memory.');
- }
-
- /**
- * @return void
- */
- public function testReadShouldBeAbleToProcessEmptySheets()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_no_cells.ods');
- $this->assertEquals([], $allRows, 'Sheet with no cells should be correctly processed.');
- }
-
- /**
- * @return void
- */
- public function testReadShouldSkipFormulas()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_formulas.ods');
-
- $expectedRows = [
- ['val1', 'val2', 'total1', 'total2'],
- [10, 20, 30, 21],
- [11, 21, 32, 41],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @expectedException \Box\Spout\Reader\Exception\IteratorNotRewindableException
- *
- * @return void
- */
- public function testReadShouldThrowIfTryingToRewindRowIterator()
- {
- $resourcePath = $this->getResourcePath('one_sheet_with_strings.ods');
- $reader = ReaderFactory::create(Type::ODS);
- $reader->open($resourcePath);
-
- foreach ($reader->getSheetIterator() as $sheet) {
- // start looping throw the rows
- foreach ($sheet->getRowIterator() as $row) {
- break;
- }
-
- // this will rewind the row iterator
- foreach ($sheet->getRowIterator() as $row) {
- break;
- }
- }
- }
-
- /**
- * @return void
- */
- public function testReadMultipleTimesShouldRewindReader()
- {
- $allRows = [];
- $resourcePath = $this->getResourcePath('two_sheets_with_strings.ods');
-
- $reader = ReaderFactory::create(Type::ODS);
- $reader->open($resourcePath);
-
- foreach ($reader->getSheetIterator() as $sheet) {
- // do nothing
- }
-
- // this loop should only add the first row of each sheet
- foreach ($reader->getSheetIterator() as $sheet) {
- foreach ($sheet->getRowIterator() as $row) {
- $allRows[] = $row;
- break;
- }
- }
-
- // this loop should only add the first row of the first sheet
- foreach ($reader->getSheetIterator() as $sheet) {
- foreach ($sheet->getRowIterator() as $row) {
- $allRows[] = $row;
- break;
- }
-
- // stop reading more sheets
- break;
- }
-
- $reader->close();
-
- $expectedRows = [
- ['ods--sheet1--11', 'ods--sheet1--12', 'ods--sheet1--13'], // 1st row, 1st sheet
- ['ods--sheet2--11', 'ods--sheet2--12', 'ods--sheet2--13'], // 1st row, 2nd sheet
- ['ods--sheet1--11', 'ods--sheet1--12', 'ods--sheet1--13'], // 1st row, 1st sheet
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @expectedException \Box\Spout\Common\Exception\IOException
- *
- * @return void
- */
- public function testReadWithUnsupportedCustomStreamWrapper()
- {
- /** @var \Box\Spout\Reader\ODS\Reader $reader */
- $reader = ReaderFactory::create(Type::ODS);
- $reader->open('unsupported://foobar');
- }
-
- /**
- * @expectedException \Box\Spout\Common\Exception\IOException
- *
- * @return void
- */
- public function testReadWithSupportedCustomStreamWrapper()
- {
- /** @var \Box\Spout\Reader\ODS\Reader $reader */
- $reader = ReaderFactory::create(Type::ODS);
- $reader->open('php://memory');
- }
-
- /**
- * https://github.com/box/spout/issues/184
- * @return void
- */
- public function testReadShouldInludeRowsWithZerosOnly()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_zeros_in_row.ods');
-
- $expectedRows = [
- ['A', 'B', 'C'],
- ['1', '2', '3'],
- ['0', '0', '0']
- ];
- $this->assertEquals($expectedRows, $allRows, 'There should be only 3 rows, because zeros (0) are valid values');
- }
-
- /**
- * https://github.com/box/spout/issues/184
- * @return void
- */
- public function testReadShouldCreateOutputEmptyCellPreserved()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_empty_cells.ods');
-
- $expectedRows = [
- ['A', 'B', 'C'],
- ['0', '', ''],
- ['1', '1', '']
- ];
- $this->assertEquals($expectedRows, $allRows, 'There should be 3 rows, with equal length');
- }
-
- /**
- * https://github.com/box/spout/issues/195
- * @return void
- */
- public function testReaderShouldNotTrimCellValues()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_untrimmed_strings.ods');
-
- $expectedRows = [
- ['A'],
- [' A '],
- ["\n\tA\n\t"],
- ];
-
- $this->assertEquals($expectedRows, $allRows, 'Cell values should not be trimmed');
- }
-
- /**
- * https://github.com/box/spout/issues/218
- * @return void
- */
- public function testReaderShouldReadTextInHyperlinks()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_hyperlinks.ods');
-
- $expectedRows = [
- ['email', 'text'],
- ['1@example.com', 'text'],
- ['2@example.com', 'text and https://github.com/box/spout/issues/218 and text'],
- ];
-
- $this->assertEquals($expectedRows, $allRows, 'Text in hyperlinks should be read');
- }
-
- /**
- * @return void
- */
- public function testReaderShouldReadInlineFontFormattingAsText()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_inline_font_formatting.ods');
-
- $expectedRows = [
- ['I am a yellow bird']
- ];
-
- $this->assertEquals($expectedRows, $allRows, 'Text formatted inline should be read');
- }
-
- /**
- * @param string $fileName
- * @param bool|void $shouldFormatDates
- * @param bool|void $shouldPreserveEmptyRows
- * @return array All the read rows the given file
- */
- private function getAllRowsForFile($fileName, $shouldFormatDates = false, $shouldPreserveEmptyRows = false)
- {
- $allRows = [];
- $resourcePath = $this->getResourcePath($fileName);
-
- /** @var \Box\Spout\Reader\ODS\Reader $reader */
- $reader = ReaderFactory::create(Type::ODS);
- $reader->setShouldFormatDates($shouldFormatDates);
- $reader->setShouldPreserveEmptyRows($shouldPreserveEmptyRows);
- $reader->open($resourcePath);
-
- foreach ($reader->getSheetIterator() as $sheetIndex => $sheet) {
- foreach ($sheet->getRowIterator() as $rowIndex => $row) {
- $allRows[] = $row;
- }
- }
-
- $reader->close();
-
- return $allRows;
- }
-}
diff --git a/tests/Spout/Reader/ODS/SheetTest.php b/tests/Spout/Reader/ODS/SheetTest.php
deleted file mode 100644
index cc3bd03..0000000
--- a/tests/Spout/Reader/ODS/SheetTest.php
+++ /dev/null
@@ -1,66 +0,0 @@
-openFileAndReturnSheets('two_sheets_with_custom_names.ods');
-
- $this->assertEquals('Sheet First', $sheets[0]->getName());
- $this->assertEquals(0, $sheets[0]->getIndex());
- $this->assertFalse($sheets[0]->isActive());
-
- $this->assertEquals('Sheet Last', $sheets[1]->getName());
- $this->assertEquals(1, $sheets[1]->getIndex());
- $this->assertTrue($sheets[1]->isActive());
- }
-
- /**
- * @return void
- */
- public function testReaderShouldDefineFirstSheetAsActiveByDefault()
- {
- // NOTE: This spreadsheet has no information about the active sheet
- $sheets = $this->openFileAndReturnSheets('two_sheets_with_no_settings_xml_file.ods');
-
- $this->assertTrue($sheets[0]->isActive());
- $this->assertFalse($sheets[1]->isActive());
- }
-
- /**
- * @param string $fileName
- * @return Sheet[]
- */
- private function openFileAndReturnSheets($fileName)
- {
- $resourcePath = $this->getResourcePath($fileName);
- $reader = ReaderFactory::create(Type::ODS);
- $reader->open($resourcePath);
-
- $sheets = [];
- foreach ($reader->getSheetIterator() as $sheet) {
- $sheets[] = $sheet;
- }
-
- $reader->close();
-
- return $sheets;
- }
-}
diff --git a/tests/Spout/Reader/ReaderFactoryTest.php b/tests/Spout/Reader/ReaderFactoryTest.php
deleted file mode 100644
index 57a0b55..0000000
--- a/tests/Spout/Reader/ReaderFactoryTest.php
+++ /dev/null
@@ -1,21 +0,0 @@
-getResourcePath('one_sheet_with_inline_strings.xlsx');
-
- $xmlReader = new XMLReader();
-
- // using "@" to prevent errors/warning to be displayed
- $wasOpenSuccessful = @$xmlReader->openFileInZip($resourcePath, 'path/to/fake/file.xml');
-
- $this->assertTrue($wasOpenSuccessful === false);
- }
-
- /**
- * Testing a HHVM bug: https://github.com/facebook/hhvm/issues/5779
- * The associated code in XMLReader::open() can be removed when the issue is fixed (and this test starts failing).
- * @see XMLReader::open()
- *
- * @return void
- */
- public function testHHVMStillDoesNotComplainWhenCallingOpenWithFileInsideZipNotExisting()
- {
- // Test should only be run on HHVM
- if ($this->isRunningHHVM()) {
- $resourcePath = $this->getResourcePath('one_sheet_with_inline_strings.xlsx');
- $nonExistingXMLFilePath = 'zip://' . $resourcePath . '#path/to/fake/file.xml';
-
- libxml_clear_errors();
- $initialUseInternalErrorsSetting = libxml_use_internal_errors(true);
-
- // using the built-in XMLReader
- $xmlReader = new \XMLReader();
- $this->assertTrue($xmlReader->open($nonExistingXMLFilePath) !== false);
- $this->assertTrue(libxml_get_last_error() === false);
-
- libxml_use_internal_errors($initialUseInternalErrorsSetting);
- }
- }
-
- /**
- * @return bool TRUE if running on HHVM, FALSE otherwise
- */
- private function isRunningHHVM()
- {
- return defined('HHVM_VERSION');
- }
-
- /**
- * @expectedException \Box\Spout\Reader\Exception\XMLProcessingException
- *
- * @return void
- */
- public function testReadShouldThrowExceptionOnError()
- {
- $resourcePath = $this->getResourcePath('one_sheet_with_invalid_xml_characters.xlsx');
-
- $xmlReader = new XMLReader();
- if ($xmlReader->openFileInZip($resourcePath, 'xl/worksheets/sheet1.xml') === false) {
- $this->fail();
- }
-
- // using "@" to prevent errors/warning to be displayed
- while (@$xmlReader->read()) {
- // do nothing
- }
- }
-
- /**
- * @expectedException \Box\Spout\Reader\Exception\XMLProcessingException
- *
- * @return void
- */
- public function testNextShouldThrowExceptionOnError()
- {
- // The sharedStrings.xml file in "attack_billion_laughs.xlsx" contains
- // a doctype element that causes read errors
- $resourcePath = $this->getResourcePath('attack_billion_laughs.xlsx');
-
- $xmlReader = new XMLReader();
- if ($xmlReader->openFileInZip($resourcePath, 'xl/sharedStrings.xml') !== false) {
- @$xmlReader->next('sst');
- }
- }
-
- /**
- * @return array
- */
- public function dataProviderForTestFileExistsWithinZip()
- {
- return [
- ['[Content_Types].xml', true],
- ['xl/sharedStrings.xml', true],
- ['xl/worksheets/sheet1.xml', true],
- ['/invalid/file.xml', false],
- ['another/invalid/file.xml', false],
- ];
- }
-
- /**
- * @dataProvider dataProviderForTestFileExistsWithinZip
- *
- * @param string $innerFilePath
- * @param bool $expectedResult
- * @return void
- */
- public function testFileExistsWithinZip($innerFilePath, $expectedResult)
- {
- $resourcePath = $this->getResourcePath('one_sheet_with_inline_strings.xlsx');
- $zipStreamURI = 'zip://' . $resourcePath . '#' . $innerFilePath;
-
- $xmlReader = new XMLReader();
- $isZipStream = \ReflectionHelper::callMethodOnObject($xmlReader, 'fileExistsWithinZip', $zipStreamURI);
-
- $this->assertEquals($expectedResult, $isZipStream);
- }
-
- /**
- * @return array
- */
- public function dataProviderForTestGetRealPathURIForFileInZip()
- {
- $tempFolder = realpath(sys_get_temp_dir());
- $tempFolderName = basename($tempFolder);
- $expectedRealPathURI = 'zip://' . $tempFolder . '/test.xlsx#test.xml';
-
- return [
- [$tempFolder, "$tempFolder/test.xlsx", 'test.xml', $expectedRealPathURI],
- [$tempFolder, "$tempFolder/../$tempFolderName/test.xlsx", 'test.xml', $expectedRealPathURI],
- ];
- }
-
- /**
- * @dataProvider dataProviderForTestGetRealPathURIForFileInZip
- *
- * @param string $tempFolder
- * @param string $zipFilePath
- * @param string $fileInsideZipPath
- * @param string $expectedRealPathURI
- * @return void
- */
- public function testGetRealPathURIForFileInZip($tempFolder, $zipFilePath, $fileInsideZipPath, $expectedRealPathURI)
- {
- touch($tempFolder . '/test.xlsx');
-
- $xmlReader = new XMLReader();
- $realPathURI = \ReflectionHelper::callMethodOnObject($xmlReader, 'getRealPathURIForFileInZip', $zipFilePath, $fileInsideZipPath);
-
- // Normalizing path separators for Windows support
- $normalizedRealPathURI = str_replace('\\', '/', $realPathURI);
- $normalizedExpectedRealPathURI = str_replace('\\', '/', $expectedRealPathURI);
-
- $this->assertEquals($normalizedExpectedRealPathURI, $normalizedRealPathURI);
-
- unlink($tempFolder . '/test.xlsx');
- }
-
- /**
- * @return array
- */
- public function dataProviderForTestIsPositionedOnStartingAndEndingNode()
- {
- return [
- [''], // not prefixed
- [''], // prefixed
- ];
- }
-
- /**
- * @dataProvider dataProviderForTestIsPositionedOnStartingAndEndingNode
- *
- * @param string $testXML
- * @return void
- */
- public function testIsPositionedOnStartingAndEndingNode($testXML)
- {
- $xmlReader = new XMLReader();
- $xmlReader->XML($testXML);
-
- // the first read moves the pointer to ""
- $xmlReader->read();
- $this->assertTrue($xmlReader->isPositionedOnStartingNode('test'));
- $this->assertFalse($xmlReader->isPositionedOnEndingNode('test'));
-
- // the seconds read moves the pointer to ""
- $xmlReader->read();
- $this->assertFalse($xmlReader->isPositionedOnStartingNode('test'));
- $this->assertTrue($xmlReader->isPositionedOnEndingNode('test'));
-
- $xmlReader->close();
- }
-}
diff --git a/tests/Spout/Reader/XLSX/Helper/CellHelperTest.php b/tests/Spout/Reader/XLSX/Helper/CellHelperTest.php
deleted file mode 100644
index a410d9d..0000000
--- a/tests/Spout/Reader/XLSX/Helper/CellHelperTest.php
+++ /dev/null
@@ -1,71 +0,0 @@
- 1, 3 => 3], ['FILL', 1, 'FILL', 3] ]
- ];
- }
-
- /**
- * @dataProvider dataProviderForTestFillMissingArrayIndexes
- * @param array $arrayToFill
- * @param array $expectedFilledArray
- */
- public function testFillMissingArrayIndexes($arrayToFill, array $expectedFilledArray)
- {
- $filledArray = CellHelper::fillMissingArrayIndexes($arrayToFill, 'FILL');
- $this->assertEquals($expectedFilledArray, $filledArray);
- }
-
- /**
- * @return array
- */
- public function dataProviderForTestGetColumnIndexFromCellIndex()
- {
- return [
- ['A1', 0],
- ['Z3', 25],
- ['AA5', 26],
- ['AB24', 27],
- ['BC5', 54],
- ['BCZ99', 1455],
- ];
- }
-
- /**
- * @dataProvider dataProviderForTestGetColumnIndexFromCellIndex
- *
- * @param string $cellIndex
- * @param int $expectedColumnIndex
- * @return void
- */
- public function testGetColumnIndexFromCellIndex($cellIndex, $expectedColumnIndex)
- {
- $this->assertEquals($expectedColumnIndex, CellHelper::getColumnIndexFromCellIndex($cellIndex));
- }
-
- /**
- * @expectedException \Box\Spout\Common\Exception\InvalidArgumentException
- *
- * @return void
- */
- public function testGetColumnIndexFromCellIndexShouldThrowIfInvalidCellIndex()
- {
- CellHelper::getColumnIndexFromCellIndex('InvalidCellIndex');
- }
-}
diff --git a/tests/Spout/Reader/XLSX/Helper/CellValueFormatterTest.php b/tests/Spout/Reader/XLSX/Helper/CellValueFormatterTest.php
deleted file mode 100644
index 96c71a9..0000000
--- a/tests/Spout/Reader/XLSX/Helper/CellValueFormatterTest.php
+++ /dev/null
@@ -1,175 +0,0 @@
-getMockBuilder('DOMNodeList')->disableOriginalConstructor()->getMock();
-
- $nodeListMock
- ->expects($this->atLeastOnce())
- ->method('item')
- ->with(0)
- ->will($this->returnValue((object)['nodeValue' => $nodeValue]));
-
- $nodeMock = $this->getMockBuilder('DOMElement')->disableOriginalConstructor()->getMock();
-
- $nodeMock
- ->expects($this->atLeastOnce())
- ->method('getAttribute')
- ->will($this->returnValueMap([
- [CellValueFormatter::XML_ATTRIBUTE_TYPE, $cellType],
- [CellValueFormatter::XML_ATTRIBUTE_STYLE_ID, 123],
- ]));
-
- $nodeMock
- ->expects($this->atLeastOnce())
- ->method('getElementsByTagName')
- ->with(CellValueFormatter::XML_NODE_VALUE)
- ->will($this->returnValue($nodeListMock));
-
- $styleHelperMock = $this->getMockBuilder('Box\Spout\Reader\XLSX\Helper\StyleHelper')->disableOriginalConstructor()->getMock();
-
- $styleHelperMock
- ->expects($this->once())
- ->method('shouldFormatNumericValueAsDate')
- ->with(123)
- ->will($this->returnValue(true));
-
- $formatter = new CellValueFormatter(null, $styleHelperMock, false);
- $result = $formatter->extractAndFormatNodeValue($nodeMock);
-
- if ($expectedDateAsString === null) {
- $this->assertNull($result);
- } else {
- $this->assertInstanceOf('DateTime', $result);
- $this->assertSame($expectedDateAsString, $result->format('Y-m-d H:i:s'));
- }
- }
-
- /**
- * @return array
- */
- public function dataProviderForTestFormatNumericCellValueWithNumbers()
- {
- // Some test values exceed PHP_INT_MAX on 32-bit PHP. They are
- // therefore converted to as doubles automatically by PHP.
- $expectedBigNumberType = (PHP_INT_SIZE < 8 ? 'double' : 'integer');
-
- return [
- [42, 42, 'integer'],
- [42.5, 42.5, 'double'],
- [-42, -42, 'integer'],
- [-42.5, -42.5, 'double'],
- ['42', 42, 'integer'],
- ['42.5', 42.5, 'double'],
- [865640023012945, 865640023012945, $expectedBigNumberType],
- ['865640023012945', 865640023012945, $expectedBigNumberType],
- [865640023012945.5, 865640023012945.5, 'double'],
- ['865640023012945.5', 865640023012945.5, 'double'],
- [PHP_INT_MAX, PHP_INT_MAX, 'integer'],
- [~PHP_INT_MAX + 1, ~PHP_INT_MAX + 1, 'integer'], // ~PHP_INT_MAX === PHP_INT_MIN, PHP_INT_MIN being PHP7+
- [PHP_INT_MAX + 1, PHP_INT_MAX + 1, 'double'],
- ];
- }
-
- /**
- * @dataProvider dataProviderForTestFormatNumericCellValueWithNumbers
- *
- * @param int|float|string $value
- * @param int|float $expectedFormattedValue
- * @param string $expectedType
- * @return void
- */
- public function testFormatNumericCellValueWithNumbers($value, $expectedFormattedValue, $expectedType)
- {
- $styleHelperMock = $this->getMockBuilder('Box\Spout\Reader\XLSX\Helper\StyleHelper')->disableOriginalConstructor()->getMock();
- $styleHelperMock
- ->expects($this->once())
- ->method('shouldFormatNumericValueAsDate')
- ->will($this->returnValue(false));
-
- $formatter = new CellValueFormatter(null, $styleHelperMock, false);
- $formattedValue = \ReflectionHelper::callMethodOnObject($formatter, 'formatNumericCellValue', $value, 0);
-
- $this->assertEquals($expectedFormattedValue, $formattedValue);
- $this->assertEquals($expectedType, gettype($formattedValue));
- }
-
- /**
- * @return array
- */
- public function dataProviderForTestFormatStringCellValue()
- {
- return [
- ['A', 'A'],
- [' A ', ' A '],
- ["\n\tA\n\t", "\n\tA\n\t"],
- [' ', ' '],
- ];
- }
-
- /**
- * @dataProvider dataProviderForTestFormatStringCellValue
- *
- * @param string $value
- * @param string $expectedFormattedValue
- * @return void
- */
- public function testFormatInlineStringCellValue($value, $expectedFormattedValue)
- {
- $nodeListMock = $this->getMockBuilder('DOMNodeList')->disableOriginalConstructor()->getMock();
- $nodeListMock
- ->expects($this->atLeastOnce())
- ->method('item')
- ->with(0)
- ->will($this->returnValue((object)['nodeValue' => $value]));
-
- $nodeMock = $this->getMockBuilder('DOMElement')->disableOriginalConstructor()->getMock();
- $nodeMock
- ->expects($this->atLeastOnce())
- ->method('getElementsByTagName')
- ->with(CellValueFormatter::XML_NODE_INLINE_STRING_VALUE)
- ->will($this->returnValue($nodeListMock));
-
- $formatter = new CellValueFormatter(null, null, false);
- $formattedValue = \ReflectionHelper::callMethodOnObject($formatter, 'formatInlineStringCellValue', $nodeMock);
-
- $this->assertEquals($expectedFormattedValue, $formattedValue);
- }
-}
diff --git a/tests/Spout/Reader/XLSX/Helper/DateFormatHelperTest.php b/tests/Spout/Reader/XLSX/Helper/DateFormatHelperTest.php
deleted file mode 100644
index cca02a7..0000000
--- a/tests/Spout/Reader/XLSX/Helper/DateFormatHelperTest.php
+++ /dev/null
@@ -1,49 +0,0 @@
-assertEquals($expectedPHPDateFormat, $phpDateFormat);
- }
-}
diff --git a/tests/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyFactoryTest.php b/tests/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyFactoryTest.php
deleted file mode 100644
index e61760a..0000000
--- a/tests/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyFactoryTest.php
+++ /dev/null
@@ -1,100 +0,0 @@
-getMockBuilder('\Box\Spout\Reader\XLSX\Helper\SharedStringsCaching\CachingStrategyFactory')
- ->disableOriginalConstructor()
- ->setMethods(['getMemoryLimitInKB'])
- ->getMock();
-
- $factoryStub->method('getMemoryLimitInKB')->willReturn($memoryLimitInKB);
-
- \ReflectionHelper::setStaticValue('\Box\Spout\Reader\XLSX\Helper\SharedStringsCaching\CachingStrategyFactory', 'instance', $factoryStub);
-
- $strategy = $factoryStub->getBestCachingStrategy($sharedStringsUniqueCount, null);
-
- $fullExpectedStrategyClassName = 'Box\Spout\Reader\XLSX\Helper\SharedStringsCaching\\' . $expectedStrategyClassName;
- $this->assertEquals($fullExpectedStrategyClassName, get_class($strategy));
-
- $strategy->clearCache();
- \ReflectionHelper::reset();
- }
-
- /**
- * @return array
- */
- public function dataProviderForTestGetMemoryLimitInKB()
- {
- return [
- ['-1', -1],
- ['invalid', -1],
- ['1024B', 1],
- ['128K', 128],
- ['256KB', 256],
- ['512M', 512 * 1024],
- ['2MB', 2 * 1024],
- ['1G', 1 * 1024 * 1024],
- ['10GB', 10 * 1024 * 1024],
- ['2T', 2 * 1024 * 1024 * 1024],
- ['5TB', 5 * 1024 * 1024 * 1024],
- ];
- }
-
- /**
- * @dataProvider dataProviderForTestGetMemoryLimitInKB
- *
- * @param string $memoryLimitFormatted
- * @param float $expectedMemoryLimitInKB
- * @return void
- */
- public function testGetMemoryLimitInKB($memoryLimitFormatted, $expectedMemoryLimitInKB)
- {
- /** @var CachingStrategyFactory|\PHPUnit_Framework_MockObject_MockObject $factoryStub */
- $factoryStub = $this
- ->getMockBuilder('\Box\Spout\Reader\XLSX\Helper\SharedStringsCaching\CachingStrategyFactory')
- ->disableOriginalConstructor()
- ->setMethods(['getMemoryLimitFromIni'])
- ->getMock();
-
- $factoryStub->method('getMemoryLimitFromIni')->willReturn($memoryLimitFormatted);
-
- $memoryLimitInKB = \ReflectionHelper::callMethodOnObject($factoryStub, 'getMemoryLimitInKB');
-
- $this->assertEquals($expectedMemoryLimitInKB, $memoryLimitInKB);
- }
-}
diff --git a/tests/Spout/Reader/XLSX/Helper/SharedStringsHelperTest.php b/tests/Spout/Reader/XLSX/Helper/SharedStringsHelperTest.php
deleted file mode 100644
index 17d1b52..0000000
--- a/tests/Spout/Reader/XLSX/Helper/SharedStringsHelperTest.php
+++ /dev/null
@@ -1,144 +0,0 @@
-getResourcePath('one_sheet_with_shared_strings.xlsx');
- $this->sharedStringsHelper = new SharedStringsHelper($resourcePath);
- }
-
- /**
- * @return void
- */
- public function tearDown()
- {
- $this->sharedStringsHelper->cleanup();
- }
-
- /**
- * @expectedException \Box\Spout\Reader\Exception\SharedStringNotFoundException
- * @return void
- */
- public function testGetStringAtIndexShouldThrowExceptionIfStringNotFound()
- {
- $this->sharedStringsHelper->extractSharedStrings();
- $this->sharedStringsHelper->getStringAtIndex(PHP_INT_MAX);
- }
-
- /**
- * @return void
- */
- public function testGetStringAtIndexShouldReturnTheCorrectStringIfFound()
- {
- $this->sharedStringsHelper->extractSharedStrings();
-
- $sharedString = $this->sharedStringsHelper->getStringAtIndex(0);
- $this->assertEquals('s1--A1', $sharedString);
-
- $sharedString = $this->sharedStringsHelper->getStringAtIndex(24);
- $this->assertEquals('s1--E5', $sharedString);
-
- $usedCachingStrategy = \ReflectionHelper::getValueOnObject($this->sharedStringsHelper, 'cachingStrategy');
- $this->assertTrue($usedCachingStrategy instanceof InMemoryStrategy);
- }
-
- /**
- * @return void
- */
- public function testGetStringAtIndexShouldWorkWithMultilineStrings()
- {
- $resourcePath = $this->getResourcePath('one_sheet_with_shared_multiline_strings.xlsx');
- $sharedStringsHelper = new SharedStringsHelper($resourcePath);
-
- $sharedStringsHelper->extractSharedStrings();
-
- $sharedString = $sharedStringsHelper->getStringAtIndex(0);
- $this->assertEquals("s1\nA1", $sharedString);
-
- $sharedString = $sharedStringsHelper->getStringAtIndex(24);
- $this->assertEquals("s1\nE5", $sharedString);
-
- $sharedStringsHelper->cleanup();
- }
-
- /**
- * @return void
- */
- public function testGetStringAtIndexShouldWorkWithStringsContainingTextAndHyperlinkInSameCell()
- {
- $resourcePath = $this->getResourcePath('one_sheet_with_shared_strings_containing_text_and_hyperlink_in_same_cell.xlsx');
- $sharedStringsHelper = new SharedStringsHelper($resourcePath);
-
- $sharedStringsHelper->extractSharedStrings();
-
- $sharedString = $sharedStringsHelper->getStringAtIndex(0);
- $this->assertEquals('go to https://github.com please', $sharedString);
-
- $sharedStringsHelper->cleanup();
- }
-
- /**
- * @return void
- */
- public function testGetStringAtIndexShouldNotDoubleDecodeHTMLEntities()
- {
- $resourcePath = $this->getResourcePath('one_sheet_with_pre_encoded_html_entities.xlsx');
- $sharedStringsHelper = new SharedStringsHelper($resourcePath);
-
- $sharedStringsHelper->extractSharedStrings();
-
- $sharedString = $sharedStringsHelper->getStringAtIndex(0);
- $this->assertEquals('quote: " - ampersand: &', $sharedString);
-
- $sharedStringsHelper->cleanup();
- }
-
- /**
- * @return void
- */
- public function testGetStringAtIndexWithFileBasedStrategy()
- {
- // force the file-based strategy by setting no memory limit
- $originalMemoryLimit = ini_get('memory_limit');
- ini_set('memory_limit', '-1');
-
- $resourcePath = $this->getResourcePath('sheet_with_lots_of_shared_strings.xlsx');
- $sharedStringsHelper = new SharedStringsHelper($resourcePath);
-
- $sharedStringsHelper->extractSharedStrings();
-
- $sharedString = $sharedStringsHelper->getStringAtIndex(0);
- $this->assertEquals('str', $sharedString);
-
- $sharedString = $sharedStringsHelper->getStringAtIndex(CachingStrategyFactory::MAX_NUM_STRINGS_PER_TEMP_FILE + 1);
- $this->assertEquals('str', $sharedString);
-
- $usedCachingStrategy = \ReflectionHelper::getValueOnObject($sharedStringsHelper, 'cachingStrategy');
- $this->assertTrue($usedCachingStrategy instanceof FileBasedStrategy);
-
- $sharedStringsHelper->cleanup();
-
- ini_set('memory_limit', $originalMemoryLimit);
- }
-}
diff --git a/tests/Spout/Reader/XLSX/Helper/StyleHelperTest.php b/tests/Spout/Reader/XLSX/Helper/StyleHelperTest.php
deleted file mode 100644
index c06d94f..0000000
--- a/tests/Spout/Reader/XLSX/Helper/StyleHelperTest.php
+++ /dev/null
@@ -1,179 +0,0 @@
-getMockBuilder('\Box\Spout\Reader\XLSX\Helper\StyleHelper')
- ->setConstructorArgs(['/path/to/file.xlsx'])
- ->setMethods(['getCustomNumberFormats', 'getStylesAttributes'])
- ->getMock();
-
- $styleHelper->method('getStylesAttributes')->willReturn($styleAttributes);
- $styleHelper->method('getCustomNumberFormats')->willReturn($customNumberFormats);
-
- return $styleHelper;
- }
-
- /**
- * @return void
- */
- public function testShouldFormatNumericValueAsDateWithDefaultStyle()
- {
- $styleHelper = $this->getStyleHelperMock();
- $shouldFormatAsDate = $styleHelper->shouldFormatNumericValueAsDate(0);
- $this->assertFalse($shouldFormatAsDate);
- }
-
- /**
- * @return void
- */
- public function testShouldFormatNumericValueAsDateWhenShouldNotApplyNumberFormat()
- {
- $styleHelper = $this->getStyleHelperMock([[], ['applyNumberFormat' => false, 'numFmtId' => 14]]);
- $shouldFormatAsDate = $styleHelper->shouldFormatNumericValueAsDate(1);
- $this->assertFalse($shouldFormatAsDate);
- }
-
- /**
- * @return void
- */
- public function testShouldFormatNumericValueAsDateWithGeneralFormat()
- {
- $styleHelper = $this->getStyleHelperMock([[], ['applyNumberFormat' => true, 'numFmtId' => 0]]);
- $shouldFormatAsDate = $styleHelper->shouldFormatNumericValueAsDate(1);
- $this->assertFalse($shouldFormatAsDate);
- }
-
- /**
- * @return void
- */
- public function testShouldFormatNumericValueAsDateWithNonDateBuiltinFormat()
- {
- $styleHelper = $this->getStyleHelperMock([[], ['applyNumberFormat' => true, 'numFmtId' => 9]]);
- $shouldFormatAsDate = $styleHelper->shouldFormatNumericValueAsDate(1);
- $this->assertFalse($shouldFormatAsDate);
- }
-
- /**
- * @return void
- */
- public function testShouldFormatNumericValueAsDateWithNoNumFmtId()
- {
- $styleHelper = $this->getStyleHelperMock([[], ['applyNumberFormat' => true, 'numFmtId' => null]]);
- $shouldFormatAsDate = $styleHelper->shouldFormatNumericValueAsDate(1);
- $this->assertFalse($shouldFormatAsDate);
- }
-
- /**
- * @return void
- */
- public function testShouldFormatNumericValueAsDateWithBuiltinDateFormats()
- {
- $builtinNumFmtIdsForDate = [14, 15, 16, 17, 18, 19, 20, 21, 22, 45, 46, 47];
-
- foreach ($builtinNumFmtIdsForDate as $builtinNumFmtIdForDate) {
- $styleHelper = $this->getStyleHelperMock([[], ['applyNumberFormat' => true, 'numFmtId' => $builtinNumFmtIdForDate]]);
- $shouldFormatAsDate = $styleHelper->shouldFormatNumericValueAsDate(1);
-
- $this->assertTrue($shouldFormatAsDate);
- }
- }
-
- /**
- * @return void
- */
- public function testShouldFormatNumericValueAsDateWhenApplyNumberFormatNotSetAndUsingBuiltinDateFormat()
- {
- $styleHelper = $this->getStyleHelperMock([[], ['applyNumberFormat' => null, 'numFmtId' => 14]]);
- $shouldFormatAsDate = $styleHelper->shouldFormatNumericValueAsDate(1);
-
- $this->assertTrue($shouldFormatAsDate);
- }
-
- /**
- * @return void
- */
- public function testShouldFormatNumericValueAsDateWhenApplyNumberFormatNotSetAndUsingBuiltinNonDateFormat()
- {
- $styleHelper = $this->getStyleHelperMock([[], ['applyNumberFormat' => null, 'numFmtId' => 9]]);
- $shouldFormatAsDate = $styleHelper->shouldFormatNumericValueAsDate(1);
-
- $this->assertFalse($shouldFormatAsDate);
- }
-
- /**
- * @return void
- */
- public function testShouldFormatNumericValueAsDateWhenCustomNumberFormatNotFound()
- {
- $styleHelper = $this->getStyleHelperMock([[], ['applyNumberFormat' => true, 'numFmtId' => 165]], [166 => []]);
- $shouldFormatAsDate = $styleHelper->shouldFormatNumericValueAsDate(1);
-
- $this->assertFalse($shouldFormatAsDate);
- }
-
- /**
- * @return array
- */
- public function dataProviderForCustomDateFormats()
- {
- return [
- // number format, expectedResult
- ['[$-409]dddd\,\ mmmm\ d\,\ yy', true],
- ['[$-409]d\-mmm\-yy;@', true],
- ['[$-409]d\-mmm\-yyyy;@', true],
- ['mm/dd/yy;@', true],
- ['MM/DD/YY;@', true],
- ['[$-F800]dddd\,\ mmmm\ dd\,\ yyyy', true],
- ['m/d;@', true],
- ['m/d/yy;@', true],
- ['[$-409]d\-mmm;@', true],
- ['[$-409]dd\-mmm\-yy;@', true],
- ['[$-409]mmm\-yy;@', true],
- ['[$-409]mmmm\-yy;@', true],
- ['[$-409]mmmm\ d\,\ yyyy;@', true],
- ['[$-409]m/d/yy\ h:mm\ AM/PM;@', true],
- ['m/d/yy\ h:mm;@', true],
- ['[$-409]mmmmm;@', true],
- ['[$-409]MMmmM;@', true],
- ['[$-409]mmmmm\-yy;@', true],
- ['m/d/yyyy;@', true],
- ['[$-409]m/d/yy\--h:mm;@', true],
- ['General', false],
- ['GENERAL', false],
- ['\ma\yb\e', false],
- ['[Red]foo;', false],
- ];
- }
-
- /**
- * @dataProvider dataProviderForCustomDateFormats
- *
- * @param string $numberFormat
- * @param bool $expectedResult
- * @return void
- */
- public function testShouldFormatNumericValueAsDateWithCustomDateFormats($numberFormat, $expectedResult)
- {
- $numFmtId = 165;
- $styleHelper = $this->getStyleHelperMock([[], ['applyNumberFormat' => true, 'numFmtId' => $numFmtId]], [$numFmtId => $numberFormat]);
- $shouldFormatAsDate = $styleHelper->shouldFormatNumericValueAsDate(1);
-
- $this->assertEquals($expectedResult, $shouldFormatAsDate);
- }
-}
diff --git a/tests/Spout/Reader/XLSX/ReaderTest.php b/tests/Spout/Reader/XLSX/ReaderTest.php
deleted file mode 100644
index b9e032e..0000000
--- a/tests/Spout/Reader/XLSX/ReaderTest.php
+++ /dev/null
@@ -1,649 +0,0 @@
-getAllRowsForFile($filePath);
- }
-
- /**
- * @return array
- */
- public function dataProviderForTestReadForAllWorksheets()
- {
- return [
- ['one_sheet_with_shared_strings.xlsx', 5, 5],
- ['one_sheet_with_inline_strings.xlsx', 5, 5],
- ['two_sheets_with_shared_strings.xlsx', 10, 5],
- ['two_sheets_with_inline_strings.xlsx', 10, 5]
- ];
- }
-
- /**
- * @dataProvider dataProviderForTestReadForAllWorksheets
- *
- * @param string $resourceName
- * @param int $expectedNumOfRows
- * @param int $expectedNumOfCellsPerRow
- * @return void
- */
- public function testReadForAllWorksheets($resourceName, $expectedNumOfRows, $expectedNumOfCellsPerRow)
- {
- $allRows = $this->getAllRowsForFile($resourceName);
-
- $this->assertEquals($expectedNumOfRows, count($allRows), "There should be $expectedNumOfRows rows");
- foreach ($allRows as $row) {
- $this->assertEquals($expectedNumOfCellsPerRow, count($row), "There should be $expectedNumOfCellsPerRow cells for every row");
- }
- }
-
- /**
- * @return void
- */
- public function testReadShouldSupportSheetsDefinitionInRandomOrder()
- {
- $allRows = $this->getAllRowsForFile('two_sheets_with_sheets_definition_in_reverse_order.xlsx');
-
- $expectedRows = [
- ['s1 - A1', 's1 - B1', 's1 - C1', 's1 - D1', 's1 - E1'],
- ['s1 - A2', 's1 - B2', 's1 - C2', 's1 - D2', 's1 - E2'],
- ['s1 - A3', 's1 - B3', 's1 - C3', 's1 - D3', 's1 - E3'],
- ['s1 - A4', 's1 - B4', 's1 - C4', 's1 - D4', 's1 - E4'],
- ['s1 - A5', 's1 - B5', 's1 - C5', 's1 - D5', 's1 - E5'],
- ['s2 - A1', 's2 - B1', 's2 - C1', 's2 - D1', 's2 - E1'],
- ['s2 - A2', 's2 - B2', 's2 - C2', 's2 - D2', 's2 - E2'],
- ['s2 - A3', 's2 - B3', 's2 - C3', 's2 - D3', 's2 - E3'],
- ['s2 - A4', 's2 - B4', 's2 - C4', 's2 - D4', 's2 - E4'],
- ['s2 - A5', 's2 - B5', 's2 - C5', 's2 - D5', 's2 - E5'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSupportPrefixedXMLFiles()
- {
- // The XML files of this spreadsheet are prefixed.
- // For instance, they use "" instead of "", etc.
- $allRows = $this->getAllRowsForFile('sheet_with_prefixed_xml_files.xlsx');
-
- $expectedRows = [
- ['s1 - A1', 's1 - B1', 's1 - C1'],
- ['s1 - A2', 's1 - B2', 's1 - C2'],
- ['s1 - A3', 's1 - B3', 's1 - C3'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSupportSheetWithSharedStringsMissingUniqueCountAttribute()
- {
- $allRows = $this->getAllRowsForFile('one_sheet_with_shared_strings_missing_unique_count.xlsx');
-
- $expectedRows = [
- ['s1--A1', 's1--B1'],
- ['s1--A2', 's1--B2'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSupportSheetWithSharedStringsMissingUniqueCountAndCountAttributes()
- {
- $allRows = $this->getAllRowsForFile('one_sheet_with_shared_strings_missing_unique_count_and_count.xlsx');
-
- $expectedRows = [
- ['s1--A1', 's1--B1'],
- ['s1--A2', 's1--B2'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSupportFilesWithoutSharedStringsFile()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_no_shared_strings_file.xlsx');
-
- $expectedRows = [
- [10, 11],
- [20, 21],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSupportFilesWithoutCellReference()
- {
- // file where the cell definition does not have a "r" attribute
- // as in ...
- $allRows = $this->getAllRowsForFile('sheet_with_missing_cell_reference.xlsx');
-
- $expectedRows = [
- ['s1--A1'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSupportAllCellTypes()
- {
- // make sure dates are always created with the same timezone
- date_default_timezone_set('UTC');
-
- $allRows = $this->getAllRowsForFile('sheet_with_all_cell_types.xlsx');
-
- $expectedRows = [
- [
- 's1--A1', 's1--A2',
- false, true,
- \DateTime::createFromFormat('Y-m-d H:i:s', '2015-06-03 13:21:58'),
- \DateTime::createFromFormat('Y-m-d H:i:s', '2015-06-01 00:00:00'),
- 10, 10.43,
- null,
- 'weird string', // valid 'str' string
- null, // invalid date
- ],
- ['', '', '', '', '', '', '', '', ''],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSupportNumericTimestampFormattedDifferentlyAsDate()
- {
- // make sure dates are always created with the same timezone
- date_default_timezone_set('UTC');
-
- $allRows = $this->getAllRowsForFile('sheet_with_same_numeric_value_date_formatted_differently.xlsx');
-
- $expectedDate = \DateTime::createFromFormat('Y-m-d H:i:s', '2015-01-01 00:00:00');
- $expectedRows = [
- array_fill(0, 10, $expectedDate),
- array_fill(0, 10, $expectedDate),
- array_fill(0, 10, $expectedDate),
- array_merge(array_fill(0, 7, $expectedDate), ['', '', '']),
- ];
-
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSupportDifferentDatesAsNumericTimestamp()
- {
- // make sure dates are always created with the same timezone
- date_default_timezone_set('UTC');
-
- $allRows = $this->getAllRowsForFile('sheet_with_different_numeric_value_dates.xlsx');
-
- $expectedRows = [
- [
- \DateTime::createFromFormat('Y-m-d H:i:s', '2015-09-01 00:00:00'),
- \DateTime::createFromFormat('Y-m-d H:i:s', '2015-09-02 00:00:00'),
- \DateTime::createFromFormat('Y-m-d H:i:s', '2015-09-01 22:23:00'),
- ],
- [
- \DateTime::createFromFormat('Y-m-d H:i:s', '1900-02-28 23:59:59'),
- \DateTime::createFromFormat('Y-m-d H:i:s', '1900-03-01 00:00:00'),
- \DateTime::createFromFormat('Y-m-d H:i:s', '1900-02-28 11:00:00'), // 1900-02-29 should be converted to 1900-02-28
- ]
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSupportDifferentTimesAsNumericTimestamp()
- {
- // make sure dates are always created with the same timezone
- date_default_timezone_set('UTC');
-
- $allRows = $this->getAllRowsForFile('sheet_with_different_numeric_value_times.xlsx');
-
- $expectedRows = [
- [
- \DateTime::createFromFormat('Y-m-d H:i:s', '1900-01-01 00:00:00'),
- \DateTime::createFromFormat('Y-m-d H:i:s', '1900-01-01 11:29:00'),
- \DateTime::createFromFormat('Y-m-d H:i:s', '1900-01-01 23:29:00'),
- \DateTime::createFromFormat('Y-m-d H:i:s', '1900-01-01 01:42:25'),
- \DateTime::createFromFormat('Y-m-d H:i:s', '1900-01-01 13:42:25'),
- ]
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSupportFormatDatesAndTimesIfSpecified()
- {
- $shouldFormatDates = true;
- $allRows = $this->getAllRowsForFile('sheet_with_dates_and_times.xlsx', $shouldFormatDates);
-
- $expectedRows = [
- ['1/13/2016', '01/13/2016', '13-Jan-16', 'Wednesday January 13, 16', 'Today is 1/13/2016'],
- ['4:43:25', '04:43', '4:43', '4:43:25 AM', '4:43:25 PM'],
- ['1976-11-22T08:30:00.000', '1976-11-22T08:30', '1582-10-15', '08:30:00', '08:30'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldApplyCustomDateFormatNumberEvenIfApplyNumberFormatNotSpecified()
- {
- $shouldFormatDates = true;
- $allRows = $this->getAllRowsForFile('sheet_with_custom_date_formats_and_no_apply_number_format.xlsx', $shouldFormatDates);
-
- $expectedRows = [
- // "General", "GENERAL", "MM/DD/YYYY", "MM/dd/YYYY", "H:MM:SS"
- ['42382', '42382', '01/13/2016', '01/13/2016', '4:43:25'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldKeepEmptyCellsAtTheEndIfDimensionsSpecified()
- {
- $allRows = $this->getAllRowsForFile('sheet_without_dimensions_but_spans_and_empty_cells.xlsx');
-
- $this->assertEquals(2, count($allRows), 'There should be 2 rows');
- foreach ($allRows as $row) {
- $this->assertEquals(5, count($row), 'There should be 5 cells for every row, because empty rows should be preserved');
- }
-
- $expectedRows = [
- ['s1--A1', 's1--B1', 's1--C1', 's1--D1', 's1--E1'],
- ['s1--A2', 's1--B2', 's1--C2', '', ''],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldKeepEmptyCellsAtTheEndIfNoDimensionsButSpansSpecified()
- {
- $allRows = $this->getAllRowsForFile('sheet_without_dimensions_and_empty_cells.xlsx');
-
- $this->assertEquals(2, count($allRows), 'There should be 2 rows');
- $this->assertEquals(5, count($allRows[0]), 'There should be 5 cells in the first row');
- $this->assertEquals(3, count($allRows[1]), 'There should be only 3 cells in the second row, because empty rows at the end should be skip');
-
- $expectedRows = [
- ['s1--A1', 's1--B1', 's1--C1', 's1--D1', 's1--E1'],
- ['s1--A2', 's1--B2', 's1--C2'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSkipEmptyCellsAtTheEndIfDimensionsNotSpecified()
- {
- $allRows = $this->getAllRowsForFile('sheet_without_dimensions_and_empty_cells.xlsx');
-
- $this->assertEquals(2, count($allRows), 'There should be 2 rows');
- $this->assertEquals(5, count($allRows[0]), 'There should be 5 cells in the first row');
- $this->assertEquals(3, count($allRows[1]), 'There should be only 3 cells in the second row, because empty rows at the end should be skip');
-
- $expectedRows = [
- ['s1--A1', 's1--B1', 's1--C1', 's1--D1', 's1--E1'],
- ['s1--A2', 's1--B2', 's1--C2'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSkipEmptyRowsIfShouldPreserveEmptyRowsNotSet()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_empty_rows_and_missing_row_index.xlsx');
-
- $this->assertEquals(3, count($allRows), 'There should be only 3 rows, because the empty rows are skipped');
-
- $expectedRows = [
- // skipped row here
- ['s1--A2', 's1--B2', 's1--C2'],
- // skipped row here
- // skipped row here
- ['s1--A5', 's1--B5', 's1--C5'],
- ['s1--A6', 's1--B6', 's1--C6'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldReturnEmptyLinesIfShouldPreserveEmptyRowsSet()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_empty_rows_and_missing_row_index.xlsx', false, true);
-
- $this->assertEquals(6, count($allRows), 'There should be 6 rows');
-
- $expectedRows = [
- [''],
- ['s1--A2', 's1--B2', 's1--C2'],
- [''],
- [''],
- ['s1--A5', 's1--B5', 's1--C5'],
- ['s1--A6', 's1--B6', 's1--C6'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSupportEmptySharedString()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_empty_shared_string.xlsx');
-
- $expectedRows = [
- ['s1--A1', '', 's1--C1'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldPreserveSpaceIfSpecified()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_preserve_space_shared_strings.xlsx');
-
- $expectedRows = [
- [' s1--A1', 's1--B1 ', ' s1--C1 '],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadShouldSkipPronunciationData()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_pronunciation.xlsx');
-
- $expectedRow = ['名前', '一二三四'];
- $this->assertEquals($expectedRow, $allRows[0], 'Pronunciation data should be removed.');
- }
-
- /**
- * @NOTE: The LIBXML_NOENT is used to ACTUALLY substitute entities (and should therefore not be used)
- *
- * @return void
- */
- public function testReadShouldBeProtectedAgainstBillionLaughsAttack()
- {
- $startTime = microtime(true);
-
- try {
- // using @ to prevent warnings/errors from being displayed
- @$this->getAllRowsForFile('attack_billion_laughs.xlsx');
- $this->fail('An exception should have been thrown');
- } catch (IOException $exception) {
- $duration = microtime(true) - $startTime;
- $this->assertLessThan(10, $duration, 'Entities should not be expanded and therefore take more than 10 seconds to be parsed.');
-
- $expectedMaxMemoryUsage = 40 * 1024 * 1024; // 40MB
- $this->assertLessThan($expectedMaxMemoryUsage, memory_get_peak_usage(true), 'Entities should not be expanded and therefore consume all the memory.');
- }
- }
-
- /**
- * @NOTE: The LIBXML_NOENT is used to ACTUALLY substitute entities (and should therefore not be used)
- *
- * @return void
- */
- public function testReadShouldBeProtectedAgainstQuadraticBlowupAttack()
- {
- $startTime = microtime(true);
-
- $this->getAllRowsForFile('attack_quadratic_blowup.xlsx');
-
- $duration = microtime(true) - $startTime;
- $this->assertLessThan(10, $duration, 'Entities should not be expanded and therefore take more than 10 seconds to be parsed.');
-
- $expectedMaxMemoryUsage = 40 * 1024 * 1024; // 40MB
- $this->assertLessThan($expectedMaxMemoryUsage, memory_get_peak_usage(true), 'Entities should not be expanded and therefore consume all the memory.');
- }
-
- /**
- * @return void
- */
- public function testReadShouldBeAbleToProcessEmptySheets()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_no_cells.xlsx');
- $this->assertEquals([], $allRows, 'Sheet with no cells should be correctly processed.');
- }
-
- /**
- * @return void
- */
- public function testReadShouldSkipFormulas()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_formulas.xlsx');
-
- $expectedRows = [
- ['val1', 'val2', 'total1', 'total2'],
- [10, 20, 30, 21],
- [11, 21, 32, 41],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @return void
- */
- public function testReadMultipleTimesShouldRewindReader()
- {
- $allRows = [];
- $resourcePath = $this->getResourcePath('two_sheets_with_inline_strings.xlsx');
-
- $reader = ReaderFactory::create(Type::XLSX);
- $reader->open($resourcePath);
-
- foreach ($reader->getSheetIterator() as $sheet) {
- // do nothing
- }
-
- foreach ($reader->getSheetIterator() as $sheet) {
- // this loop should only add the first row of the first sheet
- foreach ($sheet->getRowIterator() as $row) {
- $allRows[] = $row;
- break;
- }
-
- // this loop should rewind the iterator and restart reading from the 1st row again
- // therefore, it should only add the first row of the first sheet
- foreach ($sheet->getRowIterator() as $row) {
- $allRows[] = $row;
- break;
- }
-
- // not reading any more sheets
- break;
- }
-
- foreach ($reader->getSheetIterator() as $sheet) {
- // this loop should only add the first row of the current sheet
- foreach ($sheet->getRowIterator() as $row) {
- $allRows[] = $row;
- break;
- }
-
- // not breaking, so we keep reading the next sheets
- }
-
- $reader->close();
-
- $expectedRows = [
- ['s1 - A1', 's1 - B1', 's1 - C1', 's1 - D1', 's1 - E1'],
- ['s1 - A1', 's1 - B1', 's1 - C1', 's1 - D1', 's1 - E1'],
- ['s1 - A1', 's1 - B1', 's1 - C1', 's1 - D1', 's1 - E1'],
- ['s2 - A1', 's2 - B1', 's2 - C1', 's2 - D1', 's2 - E1'],
- ];
- $this->assertEquals($expectedRows, $allRows);
- }
-
- /**
- * @expectedException \Box\Spout\Common\Exception\IOException
- *
- * @return void
- */
- public function testReadWithUnsupportedCustomStreamWrapper()
- {
- /** @var \Box\Spout\Reader\XLSX\Reader $reader */
- $reader = ReaderFactory::create(Type::XLSX);
- $reader->open('unsupported://foobar');
- }
-
- /**
- * @expectedException \Box\Spout\Common\Exception\IOException
- *
- * @return void
- */
- public function testReadWithSupportedCustomStreamWrapper()
- {
- /** @var \Box\Spout\Reader\XLSX\Reader $reader */
- $reader = ReaderFactory::create(Type::XLSX);
- $reader->open('php://memory');
- }
-
- /**
- * https://github.com/box/spout/issues/184
- * @return void
- */
- public function testReadShouldInludeRowsWithZerosOnly()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_zeros_in_row.xlsx');
-
- $expectedRows = [
- ['A', 'B', 'C'],
- ['1', '2', '3'],
- ['0', '0', '0']
- ];
- $this->assertEquals($expectedRows, $allRows, 'There should be only 3 rows, because zeros (0) are valid values');
- }
-
- /**
- * https://github.com/box/spout/issues/184
- * @return void
- */
- public function testReadShouldCreateOutputEmptyCellPreserved()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_empty_cells.xlsx');
-
- $expectedRows = [
- ['A', 'B', 'C'],
- ['0', '', ''],
- ['1', '1', '']
- ];
- $this->assertEquals($expectedRows, $allRows, 'There should be 3 rows, with equal length');
- }
-
-
- /**
- * https://github.com/box/spout/issues/195
- * @return void
- */
- public function testReaderShouldNotTrimCellValues()
- {
- $allRows = $this->getAllRowsForFile('sheet_with_untrimmed_inline_strings.xlsx');
-
- $expectedRows = [
- ['A'],
- [' A '],
- ["\n\tA\n\t"],
- ];
-
- $this->assertEquals($expectedRows, $allRows, 'Cell values should not be trimmed');
- }
-
-
- /**
- * @param string $fileName
- * @param bool|void $shouldFormatDates
- * @param bool|void $shouldPreserveEmptyRows
- * @return array All the read rows the given file
- */
- private function getAllRowsForFile($fileName, $shouldFormatDates = false, $shouldPreserveEmptyRows = false)
- {
- $allRows = [];
- $resourcePath = $this->getResourcePath($fileName);
-
- /** @var \Box\Spout\Reader\XLSX\Reader $reader */
- $reader = ReaderFactory::create(Type::XLSX);
- $reader->setShouldFormatDates($shouldFormatDates);
- $reader->setShouldPreserveEmptyRows($shouldPreserveEmptyRows);
- $reader->open($resourcePath);
-
- foreach ($reader->getSheetIterator() as $sheetIndex => $sheet) {
- foreach ($sheet->getRowIterator() as $rowIndex => $row) {
- $allRows[] = $row;
- }
- }
-
- $reader->close();
-
- return $allRows;
- }
-}
diff --git a/tests/Spout/Reader/XLSX/SheetTest.php b/tests/Spout/Reader/XLSX/SheetTest.php
deleted file mode 100644
index b8c332b..0000000
--- a/tests/Spout/Reader/XLSX/SheetTest.php
+++ /dev/null
@@ -1,54 +0,0 @@
-openFileAndReturnSheets('two_sheets_with_custom_names_and_custom_active_tab.xlsx');
-
- $this->assertEquals('CustomName1', $sheets[0]->getName());
- $this->assertEquals(0, $sheets[0]->getIndex());
- $this->assertFalse($sheets[0]->isActive());
-
- $this->assertEquals('CustomName2', $sheets[1]->getName());
- $this->assertEquals(1, $sheets[1]->getIndex());
- $this->assertTrue($sheets[1]->isActive());
- }
-
- /**
- * @param string $fileName
- * @return Sheet[]
- */
- private function openFileAndReturnSheets($fileName)
- {
- $resourcePath = $this->getResourcePath($fileName);
- $reader = ReaderFactory::create(Type::XLSX);
- $reader->open($resourcePath);
-
- $sheets = [];
- foreach ($reader->getSheetIterator() as $sheet) {
- $sheets[] = $sheet;
- }
-
- $reader->close();
-
- return $sheets;
- }
-}
diff --git a/tests/Spout/ReflectionHelper.php b/tests/Spout/ReflectionHelper.php
deleted file mode 100644
index df02de8..0000000
--- a/tests/Spout/ReflectionHelper.php
+++ /dev/null
@@ -1,115 +0,0 @@
- $valueNames) {
- foreach ($valueNames as $valueName => $originalValue) {
- self::setStaticValue($class, $valueName, $originalValue, $saveOriginalValue = false);
- }
- }
- self::$privateVarsToReset = array();
- }
-
- /**
- * Get the value of a static private or public class property.
- * Used to test internals of class without having to make the property public
- *
- * @param string $class
- * @param string $valueName
- * @return mixed|null
- */
- public static function getStaticValue($class, $valueName)
- {
- $reflectionClass = new ReflectionClass($class);
- $reflectionProperty = $reflectionClass->getProperty($valueName);
- $reflectionProperty->setAccessible(true);
- $value = $reflectionProperty->getValue();
-
- // clean up
- $reflectionProperty->setAccessible(false);
-
- return $value;
- }
-
- /**
- * Set the value of a static private or public class property.
- * Used to test internals of class without having to make the property public
- *
- * @param string $class
- * @param string $valueName
- * @param mixed|null $value
- * @param bool|void $saveOriginalValue
- * @return void
- */
- public static function setStaticValue($class, $valueName, $value, $saveOriginalValue = true)
- {
- $reflectionClass = new ReflectionClass($class);
- $reflectionProperty = $reflectionClass->getProperty($valueName);
- $reflectionProperty->setAccessible(true);
-
- // to prevent side-effects in later tests, we need to remember the original value and reset it on tear down
- // @NOTE: we need to check isset in case the original value was null or array()
- if ($saveOriginalValue && (!isset(self::$privateVarsToReset[$class]) || !isset(self::$privateVarsToReset[$class][$name]))) {
- self::$privateVarsToReset[$class][$valueName] = $reflectionProperty->getValue();
- }
- $reflectionProperty->setValue($value);
-
- // clean up
- $reflectionProperty->setAccessible(false);
- }
-
- /**
- * @param object $object
- * @param string $valueName
- *
- * @return mixed|null
- */
- public static function getValueOnObject($object, $valueName)
- {
- $reflectionObject = new ReflectionObject($object);
- $reflectionProperty = $reflectionObject->getProperty($valueName);
- $reflectionProperty->setAccessible(true);
- $value = $reflectionProperty->getValue($object);
-
- // clean up
- $reflectionProperty->setAccessible(false);
-
- return $value;
- }
-
- /**
- * Invoke a the given public or protected method on the given object.
- *
- * @param object $object
- * @param string $methodName
- * @param *mixed|null $params
- *
- * @return mixed|null
- */
- public static function callMethodOnObject($object, $methodName)
- {
- $params = func_get_args();
- array_shift($params); // object
- array_shift($params); // methodName
-
- $className = get_class($object);
- $class = new ReflectionClass($className);
- $method = $class->getMethod($methodName);
- $method->setAccessible(true);
-
- return $method->invokeArgs($object, $params);
- }
-}
diff --git a/tests/Spout/TestUsingResource.php b/tests/Spout/TestUsingResource.php
deleted file mode 100644
index 2b200d9..0000000
--- a/tests/Spout/TestUsingResource.php
+++ /dev/null
@@ -1,141 +0,0 @@
-resourcesPath) . '/' . strtolower($resourceType) . '/' . $resourceName;
-
- return (file_exists($resourcePath) ? $resourcePath : null);
- }
-
- /**
- * @param string $resourceName
- * @return string Path of the generated resource for the given name
- */
- protected function getGeneratedResourcePath($resourceName)
- {
- $resourceType = pathinfo($resourceName, PATHINFO_EXTENSION);
- $generatedResourcePath = realpath($this->generatedResourcesPath) . '/' . strtolower($resourceType) . '/' . $resourceName;
-
- return $generatedResourcePath;
- }
-
- /**
- * @param string $resourceName
- * @return void
- */
- protected function createGeneratedFolderIfNeeded($resourceName)
- {
- $resourceType = pathinfo($resourceName, PATHINFO_EXTENSION);
- $generatedResourcePathForType = $this->generatedResourcesPath . '/' . strtolower($resourceType);
-
- if (!file_exists($generatedResourcePathForType)) {
- mkdir($generatedResourcePathForType, 0777, true);
- }
- }
-
- /**
- * @param string $resourceName
- * @return string Path of the generated unwritable (because parent folder is read only) resource for the given name
- */
- protected function getGeneratedUnwritableResourcePath($resourceName)
- {
- return realpath($this->generatedUnwritableResourcesPath) . '/' . $resourceName;
- }
-
- /**
- * @return void
- */
- protected function createUnwritableFolderIfNeeded()
- {
- // On Windows, chmod() or the mkdir's mode is ignored
- if ($this->isWindows()) {
- $this->markTestSkipped('Skipping because Windows cannot create read-only folders through PHP');
- }
-
- if (!file_exists($this->generatedUnwritableResourcesPath)) {
- // Make sure generated folder exists first
- if (!file_exists($this->generatedResourcesPath)) {
- mkdir($this->generatedResourcesPath, 0777, true);
- }
-
- // 0444 = read only
- mkdir($this->generatedUnwritableResourcesPath, 0444, true);
- }
- }
-
- /**
- * @return string Path of the temp folder
- */
- protected function getTempFolderPath()
- {
- return realpath($this->tempFolderPath);
- }
-
- /**
- * @return void
- */
- protected function recreateTempFolder()
- {
- if (file_exists($this->tempFolderPath)) {
- $this->deleteFolderRecursively($this->tempFolderPath);
- }
-
- mkdir($this->tempFolderPath, 0777, true);
- }
-
- /**
- * @param string $folderPath
- * @return void
- */
- private function deleteFolderRecursively($folderPath)
- {
- $itemIterator = new \RecursiveIteratorIterator(
- new \RecursiveDirectoryIterator($folderPath, \RecursiveDirectoryIterator::SKIP_DOTS),
- \RecursiveIteratorIterator::CHILD_FIRST
- );
-
- foreach ($itemIterator as $item) {
- if ($item->isDir()) {
- rmdir($item->getPathname());
- } else {
- unlink($item->getPathname());
- }
- }
-
- rmdir($folderPath);
- }
-
- /**
- * @return bool Whether the OS on which PHP is installed is Windows
- */
- protected function isWindows()
- {
- return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
- }
-}
diff --git a/tests/Spout/Writer/CSV/WriterTest.php b/tests/Spout/Writer/CSV/WriterTest.php
deleted file mode 100644
index 9558129..0000000
--- a/tests/Spout/Writer/CSV/WriterTest.php
+++ /dev/null
@@ -1,214 +0,0 @@
-createUnwritableFolderIfNeeded();
- $filePath = $this->getGeneratedUnwritableResourcePath($fileName);
-
- $writer = WriterFactory::create(Type::CSV);
- @$writer->openToFile($filePath);
- $writer->addRow(['csv--11', 'csv--12']);
- $writer->close();
- }
-
- /**
- * @expectedException \Box\Spout\Writer\Exception\WriterNotOpenedException
- */
- public function testWriteShouldThrowExceptionIfCallAddRowBeforeOpeningWriter()
- {
- $writer = WriterFactory::create(Type::CSV);
- $writer->addRow(['csv--11', 'csv--12']);
- $writer->close();
- }
-
- /**
- * @expectedException \Box\Spout\Writer\Exception\WriterNotOpenedException
- */
- public function testWriteShouldThrowExceptionIfCallAddRowsBeforeOpeningWriter()
- {
- $writer = WriterFactory::create(Type::CSV);
- $writer->addRows([['csv--11', 'csv--12']]);
- $writer->close();
- }
-
- /**
- * @expectedException \Box\Spout\Common\Exception\InvalidArgumentException
- */
- public function testAddRowsShouldThrowExceptionIfRowsAreNotArrayOfArrays()
- {
- $writer = WriterFactory::create(Type::CSV);
- $writer->addRows(['csv--11', 'csv--12']);
- $writer->close();
- }
-
- /**
- * @return void
- */
- public function testCloseShouldNoopWhenWriterIsNotOpened()
- {
- $fileName = 'test_double_close_calls.csv';
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $writer = WriterFactory::create(Type::CSV);
- $writer->close(); // This call should not cause any error
-
- $writer->openToFile($resourcePath);
- $writer->close();
- $writer->close(); // This call should not cause any error
- }
-
- /**
- * @return void
- */
- public function testWriteShouldAddUtf8Bom()
- {
- $allRows = [
- ['csv--11', 'csv--12'],
- ];
- $writtenContent = $this->writeToCsvFileAndReturnWrittenContent($allRows, 'csv_with_utf8_bom.csv');
-
- $this->assertContains(EncodingHelper::BOM_UTF8, $writtenContent, 'The CSV file should contain a UTF-8 BOM');
- }
-
- /**
- * @return void
- */
- public function testWriteShouldNotAddUtf8Bom()
- {
- $allRows = [
- ['csv--11', 'csv--12'],
- ];
- $writtenContent = $this->writeToCsvFileAndReturnWrittenContent($allRows, 'csv_no_bom.csv', ',', '"', false);
-
- $this->assertNotContains(EncodingHelper::BOM_UTF8, $writtenContent, 'The CSV file should not contain a UTF-8 BOM');
- }
-
- /**
- * @return void
- */
- public function testWriteShouldSupportAssociativeArrays()
- {
- $allRows = [
- ['foo' => 'csv--11', 'bar' => 'csv--12'],
- ];
- $writtenContent = $this->writeToCsvFileAndReturnWrittenContent($allRows, 'csv_from_associative_arrays.csv');
- $writtenContent = $this->trimWrittenContent($writtenContent);
-
- $this->assertEquals('csv--11,csv--12', $writtenContent, 'Values from associative arrays should be written');
- }
-
- /**
- * @return void
- */
- public function testWriteShouldSupportNullValues()
- {
- $allRows = [
- ['csv--11', null, 'csv--13'],
- ];
- $writtenContent = $this->writeToCsvFileAndReturnWrittenContent($allRows, 'csv_with_null_values.csv');
- $writtenContent = $this->trimWrittenContent($writtenContent);
-
- $this->assertEquals('csv--11,,csv--13', $writtenContent, 'The null values should be replaced by empty values');
- }
-
- /**
- * @return void
- */
- public function testWriteShouldSkipEmptyRows()
- {
- $allRows = [
- ['csv--11', 'csv--12'],
- [],
- ['csv--31', 'csv--32'],
- ];
- $writtenContent = $this->writeToCsvFileAndReturnWrittenContent($allRows, 'csv_with_empty_rows.csv');
- $writtenContent = $this->trimWrittenContent($writtenContent);
-
- $this->assertEquals("csv--11,csv--12\ncsv--31,csv--32", $writtenContent, 'Empty rows should be skipped');
- }
-
- /**
- * @return void
- */
- public function testWriteShouldSupportCustomFieldDelimiter()
- {
- $allRows = [
- ['csv--11', 'csv--12', 'csv--13'],
- ['csv--21', 'csv--22', 'csv--23'],
- ];
- $writtenContent = $this->writeToCsvFileAndReturnWrittenContent($allRows, 'csv_with_pipe_delimiters.csv', '|');
- $writtenContent = $this->trimWrittenContent($writtenContent);
-
- $this->assertEquals("csv--11|csv--12|csv--13\ncsv--21|csv--22|csv--23", $writtenContent, 'The fields should be delimited with |');
- }
-
- /**
- * @return void
- */
- public function testWriteShouldSupportCustomFieldEnclosure()
- {
- $allRows = [
- ['This is, a comma', 'csv--12', 'csv--13'],
- ];
- $writtenContent = $this->writeToCsvFileAndReturnWrittenContent($allRows, 'csv_with_pound_enclosures.csv', ',', '#');
- $writtenContent = $this->trimWrittenContent($writtenContent);
-
- $this->assertEquals('#This is, a comma#,csv--12,csv--13', $writtenContent, 'The fields should be enclosed with #');
- }
-
- /**
- * @param array $allRows
- * @param string $fileName
- * @param string $fieldDelimiter
- * @param string $fieldEnclosure
- * @param bool $shouldAddBOM
- * @return null|string
- */
- private function writeToCsvFileAndReturnWrittenContent($allRows, $fileName, $fieldDelimiter = ',', $fieldEnclosure = '"', $shouldAddBOM = true)
- {
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $writer = WriterFactory::create(Type::CSV);
- $writer->setFieldDelimiter($fieldDelimiter);
- $writer->setFieldEnclosure($fieldEnclosure);
- $writer->setShouldAddBOM($shouldAddBOM);
-
- $writer->openToFile($resourcePath);
- $writer->addRows($allRows);
- $writer->close();
-
- return file_get_contents($resourcePath);
- }
-
- /**
- * @param string $writtenContent
- * @return string
- */
- private function trimWrittenContent($writtenContent)
- {
- // remove line feeds and UTF-8 BOM
- return trim($writtenContent, PHP_EOL . EncodingHelper::BOM_UTF8);
- }
-}
diff --git a/tests/Spout/Writer/Common/Helper/CellHelperTest.php b/tests/Spout/Writer/Common/Helper/CellHelperTest.php
deleted file mode 100644
index a07046f..0000000
--- a/tests/Spout/Writer/Common/Helper/CellHelperTest.php
+++ /dev/null
@@ -1,112 +0,0 @@
-assertEquals($expectedCellIndex, CellHelper::getCellIndexFromColumnIndex($columnIndex));
- }
-
- /**
- * @return array
- */
- public function testIsEmpty()
- {
- $this->assertTrue(CellHelper::isEmpty(null));
- $this->assertTrue(CellHelper::isEmpty(""));
-
- $this->assertFalse(CellHelper::isEmpty("string"));
- $this->assertFalse(CellHelper::isEmpty(0));
- $this->assertFalse(CellHelper::isEmpty(1));
- $this->assertFalse(CellHelper::isEmpty(true));
- $this->assertFalse(CellHelper::isEmpty(false));
- $this->assertFalse(CellHelper::isEmpty(["string"]));
- $this->assertFalse(CellHelper::isEmpty(new \stdClass()));
- }
-
- /**
- * @return array
- */
- public function testIsNonEmptyString()
- {
- $this->assertTrue(CellHelper::isNonEmptyString("string"));
-
- $this->assertFalse(CellHelper::isNonEmptyString(""));
- $this->assertFalse(CellHelper::isNonEmptyString(0));
- $this->assertFalse(CellHelper::isNonEmptyString(1));
- $this->assertFalse(CellHelper::isNonEmptyString(true));
- $this->assertFalse(CellHelper::isNonEmptyString(false));
- $this->assertFalse(CellHelper::isNonEmptyString(["string"]));
- $this->assertFalse(CellHelper::isNonEmptyString(new \stdClass()));
- $this->assertFalse(CellHelper::isNonEmptyString(null));
- }
-
- /**
- * @return array
- */
- public function testIsNumeric()
- {
- $this->assertTrue(CellHelper::isNumeric(0));
- $this->assertTrue(CellHelper::isNumeric(10));
- $this->assertTrue(CellHelper::isNumeric(10.1));
- $this->assertTrue(CellHelper::isNumeric(10.10000000000000000000001));
- $this->assertTrue(CellHelper::isNumeric(0x539));
- $this->assertTrue(CellHelper::isNumeric(02471));
- $this->assertTrue(CellHelper::isNumeric(0b10100111001));
- $this->assertTrue(CellHelper::isNumeric(1337e0));
-
- $this->assertFalse(CellHelper::isNumeric("0"));
- $this->assertFalse(CellHelper::isNumeric("42"));
- $this->assertFalse(CellHelper::isNumeric(true));
- $this->assertFalse(CellHelper::isNumeric([2]));
- $this->assertFalse(CellHelper::isNumeric(new \stdClass()));
- $this->assertFalse(CellHelper::isNumeric(null));
- }
-
- /**
- * @return array
- */
- public function testIsBoolean()
- {
- $this->assertTrue(CellHelper::isBoolean(true));
- $this->assertTrue(CellHelper::isBoolean(false));
-
- $this->assertFalse(CellHelper::isBoolean(0));
- $this->assertFalse(CellHelper::isBoolean(1));
- $this->assertFalse(CellHelper::isBoolean("0"));
- $this->assertFalse(CellHelper::isBoolean("1"));
- $this->assertFalse(CellHelper::isBoolean("true"));
- $this->assertFalse(CellHelper::isBoolean("false"));
- $this->assertFalse(CellHelper::isBoolean([true]));
- $this->assertFalse(CellHelper::isBoolean(new \stdClass()));
- $this->assertFalse(CellHelper::isBoolean(null));
- }
-}
diff --git a/tests/Spout/Writer/Common/SheetTest.php b/tests/Spout/Writer/Common/SheetTest.php
deleted file mode 100644
index 032c775..0000000
--- a/tests/Spout/Writer/Common/SheetTest.php
+++ /dev/null
@@ -1,111 +0,0 @@
-assertEquals('Sheet1', $sheets[0]->getName(), 'Invalid name for the first sheet');
- $this->assertEquals('Sheet2', $sheets[1]->getName(), 'Invalid name for the second sheet');
- }
-
- /**
- * @return void
- */
- public function testSetSheetNameShouldCreateSheetWithCustomName()
- {
- $customSheetName = 'CustomName';
- $sheet = new Sheet(0, 'workbookId1');
- $sheet->setName($customSheetName);
-
- $this->assertEquals($customSheetName, $sheet->getName(), "The sheet name should have been changed to '$customSheetName'");
- }
-
- /**
- * @return array
- */
- public function dataProviderForInvalidSheetNames()
- {
- return [
- [null],
- [21],
- [''],
- ['this title exceeds the 31 characters limit'],
- ['Illegal \\'],
- ['Illegal /'],
- ['Illegal ?'],
- ['Illegal *'],
- ['Illegal :'],
- ['Illegal ['],
- ['Illegal ]'],
- ['\'Illegal start'],
- ['Illegal end\''],
- ];
- }
-
- /**
- * @dataProvider dataProviderForInvalidSheetNames
- * @expectedException \Box\Spout\Writer\Exception\InvalidSheetNameException
- *
- * @param string $customSheetName
- * @return void
- */
- public function testSetSheetNameShouldThrowOnInvalidName($customSheetName)
- {
- (new Sheet(0, 'workbookId1'))->setName($customSheetName);
- }
-
- /**
- * @return void
- */
- public function testSetSheetNameShouldNotThrowWhenSettingSameNameAsCurrentOne()
- {
- $customSheetName = 'Sheet name';
- $sheet = new Sheet(0, 'workbookId1');
- $sheet->setName($customSheetName);
- $sheet->setName($customSheetName);
- }
-
- /**
- * @expectedException \Box\Spout\Writer\Exception\InvalidSheetNameException
- * @return void
- */
- public function testSetSheetNameShouldThrowWhenNameIsAlreadyUsed()
- {
- $customSheetName = 'Sheet name';
-
- $sheet = new Sheet(0, 'workbookId1');
- $sheet->setName($customSheetName);
-
- $sheet = new Sheet(1, 'workbookId1');
- $sheet->setName($customSheetName);
- }
-
- /**
- * @return void
- */
- public function testSetSheetNameShouldNotThrowWhenSameNameUsedInDifferentWorkbooks()
- {
- $customSheetName = 'Sheet name';
-
- $sheet = new Sheet(0, 'workbookId1');
- $sheet->setName($customSheetName);
-
- $sheet = new Sheet(0, 'workbookId2');
- $sheet->setName($customSheetName);
-
- $sheet = new Sheet(1, 'workbookId3');
- $sheet->setName($customSheetName);
- }
-}
diff --git a/tests/Spout/Writer/ODS/Helper/StyleHelperTest.php b/tests/Spout/Writer/ODS/Helper/StyleHelperTest.php
deleted file mode 100644
index 763f904..0000000
--- a/tests/Spout/Writer/ODS/Helper/StyleHelperTest.php
+++ /dev/null
@@ -1,89 +0,0 @@
-defaultStyle = (new StyleBuilder())->build();
- }
-
- /**
- * @return void
- */
- public function testRegisterStyleShouldUpdateId()
- {
- $style1 = (new StyleBuilder())->setFontBold()->build();
- $style2 = (new StyleBuilder())->setFontUnderline()->build();
-
- $this->assertEquals(0, $this->defaultStyle->getId(), 'Default style ID should be 0');
- $this->assertNull($style1->getId());
- $this->assertNull($style2->getId());
-
- $styleHelper = new StyleHelper($this->defaultStyle);
- $registeredStyle1 = $styleHelper->registerStyle($style1);
- $registeredStyle2 = $styleHelper->registerStyle($style2);
-
- $this->assertEquals(1, $registeredStyle1->getId());
- $this->assertEquals(2, $registeredStyle2->getId());
- }
-
- /**
- * @return void
- */
- public function testRegisterStyleShouldReuseAlreadyRegisteredStyles()
- {
- $style = (new StyleBuilder())->setFontBold()->build();
-
- $styleHelper = new StyleHelper($this->defaultStyle);
- $registeredStyle1 = $styleHelper->registerStyle($style);
- $registeredStyle2 = $styleHelper->registerStyle($style);
-
- $this->assertEquals(1, $registeredStyle1->getId());
- $this->assertEquals(1, $registeredStyle2->getId());
- }
-
- /**
- * @return void
- */
- public function testApplyExtraStylesIfNeededShouldApplyWrapTextIfCellContainsNewLine()
- {
- $style = clone $this->defaultStyle;
- $styleHelper = new StyleHelper($this->defaultStyle);
-
- $this->assertFalse($style->shouldWrapText());
-
- $updatedStyle = $styleHelper->applyExtraStylesIfNeeded($style, [12, 'single line', "multi\nlines", null]);
-
- $this->assertTrue($updatedStyle->shouldWrapText());
- }
-
- /**
- * @return void
- */
- public function testApplyExtraStylesIfNeededShouldDoNothingIfWrapTextAlreadyApplied()
- {
- $style = (new StyleBuilder())->setShouldWrapText()->build();
- $styleHelper = new StyleHelper($this->defaultStyle);
-
- $this->assertTrue($style->shouldWrapText());
-
- $updatedStyle = $styleHelper->applyExtraStylesIfNeeded($style, ["multi\nlines"]);
-
- $this->assertTrue($updatedStyle->shouldWrapText());
- }
-}
diff --git a/tests/Spout/Writer/ODS/SheetTest.php b/tests/Spout/Writer/ODS/SheetTest.php
deleted file mode 100644
index ee59501..0000000
--- a/tests/Spout/Writer/ODS/SheetTest.php
+++ /dev/null
@@ -1,134 +0,0 @@
-writeDataToMulitpleSheetsAndReturnSheets('test_get_sheet_index.ods');
-
- $this->assertEquals(2, count($sheets), '2 sheets should have been created');
- $this->assertEquals(0, $sheets[0]->getIndex(), 'The first sheet should be index 0');
- $this->assertEquals(1, $sheets[1]->getIndex(), 'The second sheet should be index 1');
- }
-
- /**
- * @return void
- */
- public function testGetSheetName()
- {
- $sheets = $this->writeDataToMulitpleSheetsAndReturnSheets('test_get_sheet_name.ods');
-
- $this->assertEquals(2, count($sheets), '2 sheets should have been created');
- $this->assertEquals('Sheet1', $sheets[0]->getName(), 'Invalid name for the first sheet');
- $this->assertEquals('Sheet2', $sheets[1]->getName(), 'Invalid name for the second sheet');
- }
-
- /**
- * @return void
- */
- public function testSetSheetNameShouldCreateSheetWithCustomName()
- {
- $fileName = 'test_set_name_should_create_sheet_with_custom_name.ods';
- $customSheetName = 'CustomName';
- $this->writeDataAndReturnSheetWithCustomName($fileName, $customSheetName);
-
- $this->assertSheetNameEquals($customSheetName, $fileName, "The sheet name should have been changed to '$customSheetName'");
- }
-
- /**
- * @expectedException \Box\Spout\Writer\Exception\InvalidSheetNameException
- * @return void
- */
- public function testSetSheetNameShouldThrowWhenNameIsAlreadyUsed()
- {
- $fileName = 'test_set_name_with_non_unique_name.ods';
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $writer = WriterFactory::create(Type::ODS);
- $writer->openToFile($resourcePath);
-
- $customSheetName = 'Sheet name';
-
- $sheet = $writer->getCurrentSheet();
- $sheet->setName($customSheetName);
-
- $writer->addNewSheetAndMakeItCurrent();
- $sheet = $writer->getCurrentSheet();
- $sheet->setName($customSheetName);
- }
-
- /**
- * @param string $fileName
- * @param string $sheetName
- * @return Sheet
- */
- private function writeDataAndReturnSheetWithCustomName($fileName, $sheetName)
- {
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $writer = WriterFactory::create(Type::ODS);
- $writer->openToFile($resourcePath);
-
- $sheet = $writer->getCurrentSheet();
- $sheet->setName($sheetName);
-
- $writer->addRow(['ods--11', 'ods--12']);
- $writer->close();
- }
-
- /**
- * @param string $fileName
- * @return Sheet[]
- */
- private function writeDataToMulitpleSheetsAndReturnSheets($fileName)
- {
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- /** @var \Box\Spout\Writer\ODS\Writer $writer */
- $writer = WriterFactory::create(Type::ODS);
- $writer->openToFile($resourcePath);
-
- $writer->addRow(['ods--sheet1--11', 'ods--sheet1--12']);
- $writer->addNewSheetAndMakeItCurrent();
- $writer->addRow(['ods--sheet2--11', 'ods--sheet2--12', 'ods--sheet2--13']);
-
- $writer->close();
-
- return $writer->getSheets();
- }
-
- /**
- * @param string $expectedName
- * @param string $fileName
- * @param string $message
- * @return void
- */
- private function assertSheetNameEquals($expectedName, $fileName, $message = '')
- {
- $resourcePath = $this->getGeneratedResourcePath($fileName);
- $pathToWorkbookFile = $resourcePath . '#content.xml';
- $xmlContents = file_get_contents('zip://' . $pathToWorkbookFile);
-
- $this->assertContains("table:name=\"$expectedName\"", $xmlContents, $message);
- }
-}
diff --git a/tests/Spout/Writer/ODS/WriterTest.php b/tests/Spout/Writer/ODS/WriterTest.php
deleted file mode 100644
index 836e679..0000000
--- a/tests/Spout/Writer/ODS/WriterTest.php
+++ /dev/null
@@ -1,603 +0,0 @@
-createUnwritableFolderIfNeeded();
- $filePath = $this->getGeneratedUnwritableResourcePath($fileName);
-
- $writer = WriterFactory::create(Type::ODS);
- @$writer->openToFile($filePath);
- }
-
- /**
- * @expectedException \Box\Spout\Writer\Exception\WriterNotOpenedException
- */
- public function testAddRowShouldThrowExceptionIfCallAddRowBeforeOpeningWriter()
- {
- $writer = WriterFactory::create(Type::ODS);
- $writer->addRow(['ods--11', 'ods--12']);
- }
-
- /**
- * @expectedException \Box\Spout\Writer\Exception\WriterNotOpenedException
- */
- public function testAddRowShouldThrowExceptionIfCalledBeforeOpeningWriter()
- {
- $writer = WriterFactory::create(Type::ODS);
- $writer->addRows([['ods--11', 'ods--12']]);
- }
-
- /**
- * @expectedException \Box\Spout\Writer\Exception\WriterAlreadyOpenedException
- */
- public function testSetTempFolderShouldThrowExceptionIfCalledAfterOpeningWriter()
- {
- $fileName = 'file_that_wont_be_written.ods';
- $filePath = $this->getGeneratedResourcePath($fileName);
-
- /** @var \Box\Spout\Writer\ODS\Writer $writer */
- $writer = WriterFactory::create(Type::ODS);
- $writer->openToFile($filePath);
-
- $writer->setTempFolder('');
- }
-
- /**
- * @expectedException \Box\Spout\Writer\Exception\WriterAlreadyOpenedException
- */
- public function testSetShouldCreateNewSheetsAutomaticallyShouldThrowExceptionIfCalledAfterOpeningWriter()
- {
- $fileName = 'file_that_wont_be_written.ods';
- $filePath = $this->getGeneratedResourcePath($fileName);
-
- /** @var \Box\Spout\Writer\ODS\Writer $writer */
- $writer = WriterFactory::create(Type::ODS);
- $writer->openToFile($filePath);
-
- $writer->setShouldCreateNewSheetsAutomatically(true);
- }
-
- /**
- * @expectedException \Box\Spout\Common\Exception\InvalidArgumentException
- */
- public function testAddRowShouldThrowExceptionIfUnsupportedDataTypePassedIn()
- {
- $fileName = 'test_add_row_should_throw_exception_if_unsupported_data_type_passed_in.ods';
- $dataRows = [
- [new \stdClass()],
- ];
-
- $this->writeToODSFile($dataRows, $fileName);
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldCleanupAllFilesIfExceptionIsThrown()
- {
- $fileName = 'test_add_row_should_cleanup_all_files_if_exception_thrown.ods';
- $dataRows = [
- ['wrong'],
- [new \stdClass()],
- ];
-
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $this->recreateTempFolder();
- $tempFolderPath = $this->getTempFolderPath();
-
- /** @var \Box\Spout\Writer\ODS\Writer $writer */
- $writer = WriterFactory::create(Type::ODS);
- $writer->setTempFolder($tempFolderPath);
- $writer->openToFile($resourcePath);
-
- try {
- $writer->addRows($dataRows);
- $this->fail('Exception should have been thrown');
- } catch (SpoutException $e) {
- $this->assertFalse(file_exists($fileName), 'Output file should have been deleted');
-
- $numFiles = iterator_count(new \FilesystemIterator($tempFolderPath, \FilesystemIterator::SKIP_DOTS));
- $this->assertEquals(0, $numFiles, 'All temp files should have been deleted');
- }
- }
-
- /**
- * @return void
- */
- public function testAddNewSheetAndMakeItCurrent()
- {
- $fileName = 'test_add_new_sheet_and_make_it_current.ods';
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- /** @var Writer $writer */
- $writer = WriterFactory::create(Type::ODS);
- $writer->openToFile($resourcePath);
- $writer->addNewSheetAndMakeItCurrent();
- $writer->close();
-
- $sheets = $writer->getSheets();
- $this->assertEquals(2, count($sheets), 'There should be 2 sheets');
- $this->assertEquals($sheets[1], $writer->getCurrentSheet(), 'The current sheet should be the second one.');
- }
-
- /**
- * @return void
- */
- public function testSetCurrentSheet()
- {
- $fileName = 'test_set_current_sheet.ods';
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $writer = WriterFactory::create(Type::ODS);
- $writer->openToFile($resourcePath);
-
- $writer->addNewSheetAndMakeItCurrent();
- $writer->addNewSheetAndMakeItCurrent();
-
- $firstSheet = $writer->getSheets()[0];
- $writer->setCurrentSheet($firstSheet);
-
- $writer->close();
-
- $this->assertEquals($firstSheet, $writer->getCurrentSheet(), 'The current sheet should be the first one.');
- }
-
- /**
- * @return void
- */
- public function testCloseShouldNoopWhenWriterIsNotOpened()
- {
- $fileName = 'test_double_close_calls.ods';
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $writer = WriterFactory::create(Type::ODS);
- $writer->close(); // This call should not cause any error
-
- $writer->openToFile($resourcePath);
- $writer->close();
- $writer->close(); // This call should not cause any error
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldWriteGivenDataToSheet()
- {
- $fileName = 'test_add_row_should_write_given_data_to_sheet.ods';
- $dataRows = [
- ['ods--11', 'ods--12'],
- ['ods--21', 'ods--22', 'ods--23'],
- ];
-
- $this->writeToODSFile($dataRows, $fileName);
-
- foreach ($dataRows as $dataRow) {
- foreach ($dataRow as $cellValue) {
- $this->assertValueWasWritten($fileName, $cellValue);
- }
- }
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldWriteGivenDataToTwoSheets()
- {
- $fileName = 'test_add_row_should_write_given_data_to_two_sheets.ods';
- $dataRows = [
- ['ods--11', 'ods--12'],
- ['ods--21', 'ods--22', 'ods--23'],
- ];
-
- $numSheets = 2;
- $this->writeToMultipleSheetsInODSFile($dataRows, $numSheets, $fileName);
-
- for ($i = 1; $i <= $numSheets; $i++) {
- foreach ($dataRows as $dataRow) {
- foreach ($dataRow as $cellValue) {
- $this->assertValueWasWritten($fileName, $cellValue);
- }
- }
- }
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldSupportAssociativeArrays()
- {
- $fileName = 'test_add_row_should_support_associative_arrays.ods';
- $dataRows = [
- ['foo' => 'ods--11', 'bar' => 'ods--12'],
- ];
-
- $this->writeToODSFile($dataRows, $fileName);
-
- foreach ($dataRows as $dataRow) {
- foreach ($dataRow as $cellValue) {
- $this->assertValueWasWritten($fileName, $cellValue);
- }
- }
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldSupportMultipleTypesOfData()
- {
- $fileName = 'test_add_row_should_support_multiple_types_of_data.ods';
- $dataRows = [
- ['ods--11', true, '', 0, 10.2, null],
- ];
-
- $this->writeToODSFile($dataRows, $fileName);
-
- $this->assertValueWasWritten($fileName, 'ods--11');
- $this->assertValueWasWrittenToSheet($fileName, 1, 1); // true is converted to 1
- $this->assertValueWasWrittenToSheet($fileName, 1, 0);
- $this->assertValueWasWrittenToSheet($fileName, 1, 10.2);
- }
-
- /**
- * @return array
- */
- public function dataProviderForTestAddRowShouldUseNumberColumnsRepeatedForRepeatedValues()
- {
- return [
- [['ods--11', 'ods--11', 'ods--11'], 1, 3],
- [['', ''], 1, 2],
- [[true, true, true, true], 1, 4],
- [[1.1, 1.1], 1, 2],
- [['foo', 'bar'], 2, 0],
- ];
- }
- /**
- * @dataProvider dataProviderForTestAddRowShouldUseNumberColumnsRepeatedForRepeatedValues
- *
- * @param array $dataRow
- * @param int $expectedNumTableCells
- * @param int $expectedNumColumnsRepeated
- * @return void
- */
- public function testAddRowShouldUseNumberColumnsRepeatedForRepeatedValues($dataRow, $expectedNumTableCells, $expectedNumColumnsRepeated)
- {
- $fileName = 'test_add_row_should_use_number_columns_repeated.ods';
- $this->writeToODSFile([$dataRow], $fileName);
-
- $sheetXmlNode = $this->getSheetXmlNode($fileName, 1);
- $tableCellNodes = $sheetXmlNode->getElementsByTagName('table-cell');
-
- $this->assertEquals($expectedNumTableCells, $tableCellNodes->length);
-
- if ($expectedNumTableCells === 1) {
- $tableCellNode = $tableCellNodes->item(0);
- $numColumnsRepeated = intval($tableCellNode->getAttribute('table:number-columns-repeated'));
- $this->assertEquals($expectedNumColumnsRepeated, $numColumnsRepeated);
- } else {
- foreach ($tableCellNodes as $tableCellNode) {
- $this->assertFalse($tableCellNode->hasAttribute('table:number-columns-repeated'));
- }
- }
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldWriteGivenDataToTheCorrectSheet()
- {
- $fileName = 'test_add_row_should_write_given_data_to_the_correct_sheet.ods';
- $dataRowsSheet1 = [
- ['ods--sheet1--11', 'ods--sheet1--12'],
- ['ods--sheet1--21', 'ods--sheet1--22', 'ods--sheet1--23'],
- ];
- $dataRowsSheet2 = [
- ['ods--sheet2--11', 'ods--sheet2--12'],
- ['ods--sheet2--21', 'ods--sheet2--22', 'ods--sheet2--23'],
- ];
- $dataRowsSheet1Again = [
- ['ods--sheet1--31', 'ods--sheet1--32'],
- ['ods--sheet1--41', 'ods--sheet1--42', 'ods--sheet1--43'],
- ];
-
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- /** @var \Box\Spout\Writer\ODS\Writer $writer */
- $writer = WriterFactory::create(Type::ODS);
- $writer->openToFile($resourcePath);
-
- $writer->addRows($dataRowsSheet1);
-
- $writer->addNewSheetAndMakeItCurrent();
- $writer->addRows($dataRowsSheet2);
-
- $firstSheet = $writer->getSheets()[0];
- $writer->setCurrentSheet($firstSheet);
-
- $writer->addRows($dataRowsSheet1Again);
-
- $writer->close();
-
- foreach ($dataRowsSheet1 as $dataRow) {
- foreach ($dataRow as $cellValue) {
- $this->assertValueWasWrittenToSheet($fileName, 1, $cellValue, 'Data should have been written in Sheet 1');
- }
- }
- foreach ($dataRowsSheet2 as $dataRow) {
- foreach ($dataRow as $cellValue) {
- $this->assertValueWasWrittenToSheet($fileName, 2, $cellValue, 'Data should have been written in Sheet 2');
- }
- }
- foreach ($dataRowsSheet1Again as $dataRow) {
- foreach ($dataRow as $cellValue) {
- $this->assertValueWasWrittenToSheet($fileName, 1, $cellValue, 'Data should have been written in Sheet 1');
- }
- }
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldAutomaticallyCreateNewSheetsIfMaxRowsReachedAndOptionTurnedOn()
- {
- $fileName = 'test_add_row_should_automatically_create_new_sheets_if_max_rows_reached_and_option_turned_on.ods';
- $dataRows = [
- ['ods--sheet1--11', 'ods--sheet1--12'],
- ['ods--sheet1--21', 'ods--sheet1--22', 'ods--sheet1--23'],
- ['ods--sheet2--11', 'ods--sheet2--12'], // this should be written in a new sheet
- ];
-
- // set the maxRowsPerSheet limit to 2
- \ReflectionHelper::setStaticValue('\Box\Spout\Writer\ODS\Internal\Workbook', 'maxRowsPerWorksheet', 2);
-
- $writer = $this->writeToODSFile($dataRows, $fileName, $shouldCreateSheetsAutomatically = true);
- $this->assertEquals(2, count($writer->getSheets()), '2 sheets should have been created.');
-
- $this->assertValueWasNotWrittenToSheet($fileName, 1, 'ods--sheet2--11');
- $this->assertValueWasWrittenToSheet($fileName, 2, 'ods--sheet2--11');
-
- \ReflectionHelper::reset();
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldNotCreateNewSheetsIfMaxRowsReachedAndOptionTurnedOff()
- {
- $fileName = 'test_add_row_should_not_create_new_sheets_if_max_rows_reached_and_option_turned_off.ods';
- $dataRows = [
- ['ods--sheet1--11', 'ods--sheet1--12'],
- ['ods--sheet1--21', 'ods--sheet1--22', 'ods--sheet1--23'],
- ['ods--sheet1--31', 'ods--sheet1--32'], // this should NOT be written in a new sheet
- ];
-
- // set the maxRowsPerSheet limit to 2
- \ReflectionHelper::setStaticValue('\Box\Spout\Writer\ODS\Internal\Workbook', 'maxRowsPerWorksheet', 2);
-
- $writer = $this->writeToODSFile($dataRows, $fileName, $shouldCreateSheetsAutomatically = false);
- $this->assertEquals(1, count($writer->getSheets()), 'Only 1 sheet should have been created.');
-
- $this->assertValueWasNotWrittenToSheet($fileName, 1, 'ods--sheet1--31');
-
- \ReflectionHelper::reset();
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldEscapeHtmlSpecialCharacters()
- {
- $fileName = 'test_add_row_should_escape_html_special_characters.ods';
- $dataRows = [
- ['I\'m in "great" mood', 'This be escaped & tested'],
- ];
-
- $this->writeToODSFile($dataRows, $fileName);
-
- $this->assertValueWasWritten($fileName, 'I\'m in "great" mood', 'Quotes should not be escaped');
- $this->assertValueWasWritten($fileName, 'This <must> be escaped & tested', '<, > and & should be escaped');
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldKeepNewLines()
- {
- $fileName = 'test_add_row_should_keep_new_lines.ods';
- $dataRow = ["I have\na dream"];
-
- $this->writeToODSFile([$dataRow], $fileName);
-
- $this->assertValueWasWrittenToSheet($fileName, 1, 'I have');
- $this->assertValueWasWrittenToSheet($fileName, 1, 'a dream');
- }
-
- /**
- * @return void
- */
- public function testGeneratedFileShouldHaveTheCorrectMimeType()
- {
- // Only PHP7+ gives the correct mime type since it requires adding
- // uncompressed files to the final archive (which support was added in PHP7)
- if (!ZipHelper::canChooseCompressionMethod()) {
- $this->markTestSkipped(
- 'The PHP version used does not support setting the compression method of archived files,
- resulting in the mime type to be detected incorrectly.'
- );
- }
-
- $fileName = 'test_mime_type.ods';
- $resourcePath = $this->getGeneratedResourcePath($fileName);
- $dataRow = ['foo'];
-
- $this->writeToODSFile([$dataRow], $fileName);
-
- $finfo = new \finfo(FILEINFO_MIME_TYPE);
- $this->assertEquals('application/vnd.oasis.opendocument.spreadsheet', $finfo->file($resourcePath));
- }
-
- /**
- * @param array $allRows
- * @param string $fileName
- * @param bool $shouldCreateSheetsAutomatically
- * @return Writer
- */
- private function writeToODSFile($allRows, $fileName, $shouldCreateSheetsAutomatically = true)
- {
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- /** @var \Box\Spout\Writer\ODS\Writer $writer */
- $writer = WriterFactory::create(Type::ODS);
- $writer->setShouldCreateNewSheetsAutomatically($shouldCreateSheetsAutomatically);
-
- $writer->openToFile($resourcePath);
- $writer->addRows($allRows);
- $writer->close();
-
- return $writer;
- }
-
- /**
- * @param array $allRows
- * @param int $numSheets
- * @param string $fileName
- * @param bool $shouldCreateSheetsAutomatically
- * @return Writer
- */
- private function writeToMultipleSheetsInODSFile($allRows, $numSheets, $fileName, $shouldCreateSheetsAutomatically = true)
- {
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- /** @var \Box\Spout\Writer\ODS\Writer $writer */
- $writer = WriterFactory::create(Type::ODS);
- $writer->setShouldCreateNewSheetsAutomatically($shouldCreateSheetsAutomatically);
-
- $writer->openToFile($resourcePath);
- $writer->addRows($allRows);
-
- for ($i = 1; $i < $numSheets; $i++) {
- $writer->addNewSheetAndMakeItCurrent();
- $writer->addRows($allRows);
- }
-
- $writer->close();
-
- return $writer;
- }
-
- /**
- * @param string $fileName
- * @param string $value
- * @param string $message
- * @return void
- */
- private function assertValueWasWritten($fileName, $value, $message = '')
- {
- $resourcePath = $this->getGeneratedResourcePath($fileName);
- $pathToContentFile = $resourcePath . '#content.xml';
- $xmlContents = file_get_contents('zip://' . $pathToContentFile);
-
- $this->assertContains($value, $xmlContents, $message);
- }
-
- /**
- * @param string $fileName
- * @param int $sheetIndex
- * @param mixed $value
- * @param string $message
- * @return void
- */
- private function assertValueWasWrittenToSheet($fileName, $sheetIndex, $value, $message = '')
- {
- $sheetXmlAsString = $this->getSheetXmlNodeAsString($fileName, $sheetIndex);
- $valueAsXmlString = "$value";
-
- $this->assertContains($valueAsXmlString, $sheetXmlAsString, $message);
- }
-
- /**
- * @param string $fileName
- * @param int $sheetIndex
- * @param mixed $value
- * @param string $message
- * @return void
- */
- private function assertValueWasNotWrittenToSheet($fileName, $sheetIndex, $value, $message = '')
- {
- $sheetXmlAsString = $this->getSheetXmlNodeAsString($fileName, $sheetIndex);
- $valueAsXmlString = "$value";
-
- $this->assertNotContains($valueAsXmlString, $sheetXmlAsString, $message);
- }
-
- /**
- * @param string $fileName
- * @param int $sheetIndex
- * @return \DOMNode
- */
- private function getSheetXmlNode($fileName, $sheetIndex)
- {
- $xmlReader = $this->moveReaderToCorrectTableNode($fileName, $sheetIndex);
- return $xmlReader->expand();
- }
-
- /**
- * @param string $fileName
- * @param int $sheetIndex
- * @return string
- */
- private function getSheetXmlNodeAsString($fileName, $sheetIndex)
- {
- $xmlReader = $this->moveReaderToCorrectTableNode($fileName, $sheetIndex);
- return $xmlReader->readOuterXml();
- }
-
- /**
- * @param string $fileName
- * @param int $sheetIndex
- * @return XMLReader
- */
- private function moveReaderToCorrectTableNode($fileName, $sheetIndex)
- {
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $xmlReader = new XMLReader();
- $xmlReader->openFileInZip($resourcePath, 'content.xml');
- $xmlReader->readUntilNodeFound('table:table');
-
- for ($i = 1; $i < $sheetIndex; $i++) {
- $xmlReader->readUntilNodeFound('table:table');
- }
-
- return $xmlReader;
- }
-}
diff --git a/tests/Spout/Writer/ODS/WriterWithStyleTest.php b/tests/Spout/Writer/ODS/WriterWithStyleTest.php
deleted file mode 100644
index f6af4a1..0000000
--- a/tests/Spout/Writer/ODS/WriterWithStyleTest.php
+++ /dev/null
@@ -1,494 +0,0 @@
-defaultStyle = (new StyleBuilder())->build();
- }
-
- /**
- * @expectedException \Box\Spout\Writer\Exception\WriterNotOpenedException
- */
- public function testAddRowWithStyleShouldThrowExceptionIfCallAddRowBeforeOpeningWriter()
- {
- $writer = WriterFactory::create(Type::ODS);
- $writer->addRowWithStyle(['ods--11', 'ods--12'], $this->defaultStyle);
- }
-
- /**
- * @expectedException \Box\Spout\Writer\Exception\WriterNotOpenedException
- */
- public function testAddRowWithStyleShouldThrowExceptionIfCalledBeforeOpeningWriter()
- {
- $writer = WriterFactory::create(Type::ODS);
- $writer->addRowWithStyle(['ods--11', 'ods--12'], $this->defaultStyle);
- }
-
- /**
- * @return array
- */
- public function dataProviderForInvalidStyle()
- {
- return [
- ['style'],
- [new \stdClass()],
- [null],
- ];
- }
-
- /**
- * @dataProvider dataProviderForInvalidStyle
- * @expectedException \Box\Spout\Common\Exception\InvalidArgumentException
- *
- * @param \Box\Spout\Writer\Style\Style $style
- */
- public function testAddRowWithStyleShouldThrowExceptionIfInvalidStyleGiven($style)
- {
- $fileName = 'test_add_row_with_style_should_throw_exception.ods';
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $writer = WriterFactory::create(Type::ODS);
- $writer->openToFile($resourcePath);
- $writer->addRowWithStyle(['ods--11', 'ods--12'], $style);
- }
-
- /**
- * @dataProvider dataProviderForInvalidStyle
- * @expectedException \Box\Spout\Common\Exception\InvalidArgumentException
- *
- * @param \Box\Spout\Writer\Style\Style $style
- */
- public function testAddRowsWithStyleShouldThrowExceptionIfInvalidStyleGiven($style)
- {
- $fileName = 'test_add_row_with_style_should_throw_exception.ods';
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $writer = WriterFactory::create(Type::ODS);
- $writer->openToFile($resourcePath);
- $writer->addRowsWithStyle([['ods--11', 'ods--12']], $style);
- }
-
- /**
- * @return void
- */
- public function testAddRowWithStyleShouldListAllUsedStylesInCreatedContentXmlFile()
- {
- $fileName = 'test_add_row_with_style_should_list_all_used_fonts.ods';
- $dataRows = [
- ['ods--11', 'ods--12'],
- ['ods--21', 'ods--22'],
- ];
-
- $style = (new StyleBuilder())
- ->setFontBold()
- ->setFontItalic()
- ->setFontUnderline()
- ->setFontStrikethrough()
- ->build();
- $style2 = (new StyleBuilder())
- ->setFontSize(15)
- ->setFontColor(Color::RED)
- ->setFontName('Cambria')
- ->setBackgroundColor(Color::GREEN)
- ->build();
-
- $this->writeToODSFileWithMultipleStyles($dataRows, $fileName, [$style, $style2]);
-
- $cellStyleElements = $this->getCellStyleElementsFromContentXmlFile($fileName);
- $this->assertEquals(3, count($cellStyleElements), 'There should be 3 separate cell styles, including the default one.');
-
- // Second font should contain data from the first created style
- $customFont1Element = $cellStyleElements[1];
- $this->assertFirstChildHasAttributeEquals('bold', $customFont1Element, 'text-properties', 'fo:font-weight');
- $this->assertFirstChildHasAttributeEquals('italic', $customFont1Element, 'text-properties', 'fo:font-style');
- $this->assertFirstChildHasAttributeEquals('solid', $customFont1Element, 'text-properties', 'style:text-underline-style');
- $this->assertFirstChildHasAttributeEquals('solid', $customFont1Element, 'text-properties', 'style:text-line-through-style');
-
- // Third font should contain data from the second created style
- $customFont2Element = $cellStyleElements[2];
- $this->assertFirstChildHasAttributeEquals('15pt', $customFont2Element, 'text-properties', 'fo:font-size');
- $this->assertFirstChildHasAttributeEquals('#' . Color::RED, $customFont2Element, 'text-properties', 'fo:color');
- $this->assertFirstChildHasAttributeEquals('Cambria', $customFont2Element, 'text-properties', 'style:font-name');
- $this->assertFirstChildHasAttributeEquals('#' . Color::GREEN, $customFont2Element, 'table-cell-properties', 'fo:background-color');
- }
-
- /**
- * @return void
- */
- public function testAddRowWithStyleShouldWriteDefaultStyleSettings()
- {
- $fileName = 'test_add_row_with_style_should_write_default_style_settings.ods';
- $dataRow = ['ods--11', 'ods--12'];
-
- $this->writeToODSFile([$dataRow], $fileName, $this->defaultStyle);
-
- $textPropertiesElement = $this->getXmlSectionFromStylesXmlFile($fileName, 'style:text-properties');
- $this->assertEquals(Style::DEFAULT_FONT_SIZE . 'pt', $textPropertiesElement->getAttribute('fo:font-size'));
- $this->assertEquals('#' . Style::DEFAULT_FONT_COLOR, $textPropertiesElement->getAttribute('fo:color'));
- $this->assertEquals(Style::DEFAULT_FONT_NAME, $textPropertiesElement->getAttribute('style:font-name'));
- }
-
- /**
- * @return void
- */
- public function testAddRowWithStyleShouldApplyStyleToCells()
- {
- $fileName = 'test_add_row_with_style_should_apply_style_to_cells.ods';
- $dataRows = [
- ['ods--11'],
- ['ods--21'],
- ['ods--31'],
- ];
- $style = (new StyleBuilder())->setFontBold()->build();
- $style2 = (new StyleBuilder())->setFontSize(15)->build();
-
- $this->writeToODSFileWithMultipleStyles($dataRows, $fileName, [$style, $style2, null]);
-
- $cellDomElements = $this->getCellElementsFromContentXmlFile($fileName);
- $this->assertEquals(3, count($cellDomElements), 'There should be 3 cells with content');
-
- $this->assertEquals('ce2', $cellDomElements[0]->getAttribute('table:style-name'));
- $this->assertEquals('ce3', $cellDomElements[1]->getAttribute('table:style-name'));
- $this->assertEquals('ce1', $cellDomElements[2]->getAttribute('table:style-name'));
- }
-
- /**
- * @return void
- */
- public function testAddRowWithStyleShouldReuseDuplicateStyles()
- {
- $fileName = 'test_add_row_with_style_should_reuse_duplicate_styles.ods';
- $dataRows = [
- ['ods--11'],
- ['ods--21'],
- ];
- $style = (new StyleBuilder())->setFontBold()->build();
-
- $this->writeToODSFile($dataRows, $fileName, $style);
-
- $cellDomElements = $this->getCellElementsFromContentXmlFile($fileName);
- $this->assertEquals(2, count($cellDomElements), 'There should be 2 cells with content');
-
- $this->assertEquals('ce2', $cellDomElements[0]->getAttribute('table:style-name'));
- $this->assertEquals('ce2', $cellDomElements[1]->getAttribute('table:style-name'));
- }
-
- /**
- * @return void
- */
- public function testAddRowWithStyleShouldAddWrapTextAlignmentInfoInStylesXmlFileIfSpecified()
- {
- $fileName = 'test_add_row_with_style_should_add_wrap_text_alignment.ods';
- $dataRows = [
- ['ods--11', 'ods--12'],
- ];
- $style = (new StyleBuilder())->setShouldWrapText()->build();
-
- $this->writeToODSFile($dataRows, $fileName, $style);
-
- $styleElements = $this->getCellStyleElementsFromContentXmlFile($fileName);
- $this->assertEquals(2, count($styleElements), 'There should be 2 styles (default and custom)');
-
- $customStyleElement = $styleElements[1];
- $this->assertFirstChildHasAttributeEquals('wrap', $customStyleElement, 'table-cell-properties', 'fo:wrap-option');
- }
-
- /**
- * @return void
- */
- public function testAddRowWithStyleShouldApplyWrapTextIfCellContainsNewLine()
- {
- $fileName = 'test_add_row_with_style_should_apply_wrap_text_if_new_lines.ods';
- $dataRows = [
- ["ods--11\nods--11"],
- ];
-
- $this->writeToODSFile($dataRows, $fileName, $this->defaultStyle);
-
- $styleElements = $this->getCellStyleElementsFromContentXmlFile($fileName);
- $this->assertEquals(2, count($styleElements), 'There should be 2 styles (default and custom)');
-
- $customStyleElement = $styleElements[1];
- $this->assertFirstChildHasAttributeEquals('wrap', $customStyleElement, 'table-cell-properties', 'fo:wrap-option');
- }
-
- /**
- * @return void
- */
- public function testAddBackgroundColor()
- {
- $fileName = 'test_default_background_style.ods';
- $dataRows = [
- ['defaultBgColor'],
- ];
-
- $style = (new StyleBuilder())->setBackgroundColor(Color::WHITE)->build();
- $this->writeToODSFile($dataRows, $fileName, $style);
-
- $styleElements = $this->getCellStyleElementsFromContentXmlFile($fileName);
- $this->assertEquals(2, count($styleElements), 'There should be 2 styles (default and custom)');
-
- $customStyleElement = $styleElements[1];
- $this->assertFirstChildHasAttributeEquals('#' . Color::WHITE, $customStyleElement, 'table-cell-properties', 'fo:background-color');
- }
-
- /**
- * @return void
- */
- public function testBorders()
- {
- $fileName = 'test_borders.ods';
-
- $dataRows = [
- ['row-with-border-bottom-green-thick-solid'],
- ['row-without-border'],
- ['row-with-border-top-red-thin-dashed'],
- ];
-
- $borderBottomGreenThickSolid = (new BorderBuilder())
- ->setBorderBottom(Color::GREEN, Border::WIDTH_THICK, Border::STYLE_SOLID)->build();
-
-
- $borderTopRedThinDashed = (new BorderBuilder())
- ->setBorderTop(Color::RED, Border::WIDTH_THIN, Border::STYLE_DASHED)->build();
-
- $styles = [
- (new StyleBuilder())->setBorder($borderBottomGreenThickSolid)->build(),
- (new StyleBuilder())->build(),
- (new StyleBuilder())->setBorder($borderTopRedThinDashed)->build(),
- ];
-
- $this->writeToODSFileWithMultipleStyles($dataRows, $fileName, $styles);
-
- $styleElements = $this->getCellStyleElementsFromContentXmlFile($fileName);
-
- $this->assertEquals(3, count($styleElements), 'There should be 3 styles)');
-
- // Use reflection for protected members here
- $widthMap = \ReflectionHelper::getStaticValue('Box\Spout\Writer\ODS\Helper\BorderHelper', 'widthMap');
- $styleMap = \ReflectionHelper::getStaticValue('Box\Spout\Writer\ODS\Helper\BorderHelper', 'styleMap');
-
- $expectedFirst = sprintf(
- '%s %s #%s',
- $widthMap[Border::WIDTH_THICK],
- $styleMap[Border::STYLE_SOLID],
- Color::GREEN
- );
-
- $actualFirst = $styleElements[1]
- ->getElementsByTagName('table-cell-properties')
- ->item(0)
- ->getAttribute('fo:border-bottom');
-
- $this->assertEquals($expectedFirst, $actualFirst);
-
- $expectedThird = sprintf(
- '%s %s #%s',
- $widthMap[Border::WIDTH_THIN],
- $styleMap[Border::STYLE_DASHED],
- Color::RED
- );
-
- $actualThird = $styleElements[2]
- ->getElementsByTagName('table-cell-properties')
- ->item(0)
- ->getAttribute('fo:border-top');
-
- $this->assertEquals($expectedThird, $actualThird);
- }
-
- /**
- * @return void
- */
- public function testSetDefaultRowStyle()
- {
- $fileName = 'test_set_default_row_style.ods';
- $dataRows = [['ods--11']];
-
- $defaultFontSize = 50;
- $defaultStyle = (new StyleBuilder())->setFontSize($defaultFontSize)->build();
-
- $this->writeToODSFileWithDefaultStyle($dataRows, $fileName, $defaultStyle);
-
- $textPropertiesElement = $this->getXmlSectionFromStylesXmlFile($fileName, 'style:text-properties');
- $this->assertEquals($defaultFontSize . 'pt', $textPropertiesElement->getAttribute('fo:font-size'));
- }
-
- /**
- * @param array $allRows
- * @param string $fileName
- * @param \Box\Spout\Writer\Style\Style $style
- * @return Writer
- */
- private function writeToODSFile($allRows, $fileName, $style)
- {
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- /** @var \Box\Spout\Writer\ODS\Writer $writer */
- $writer = WriterFactory::create(Type::ODS);
-
- $writer->openToFile($resourcePath);
- $writer->addRowsWithStyle($allRows, $style);
- $writer->close();
-
- return $writer;
- }
-
- /**
- * @param array $allRows
- * @param string $fileName
- * @param \Box\Spout\Writer\Style\Style|null $defaultStyle
- * @return Writer
- */
- private function writeToODSFileWithDefaultStyle($allRows, $fileName, $defaultStyle)
- {
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- /** @var \Box\Spout\Writer\XLSX\Writer $writer */
- $writer = WriterFactory::create(Type::ODS);
- $writer->setDefaultRowStyle($defaultStyle);
-
- $writer->openToFile($resourcePath);
- $writer->addRows($allRows);
- $writer->close();
-
- return $writer;
- }
-
- /**
- * @param array $allRows
- * @param string $fileName
- * @param \Box\Spout\Writer\Style\Style|null[] $styles
- * @return Writer
- */
- private function writeToODSFileWithMultipleStyles($allRows, $fileName, $styles)
- {
- // there should be as many rows as there are styles passed in
- $this->assertEquals(count($allRows), count($styles));
-
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- /** @var \Box\Spout\Writer\ODS\Writer $writer */
- $writer = WriterFactory::create(Type::ODS);
-
- $writer->openToFile($resourcePath);
- for ($i = 0; $i < count($allRows); $i++) {
- if ($styles[$i] === null) {
- $writer->addRow($allRows[$i]);
- } else {
- $writer->addRowWithStyle($allRows[$i], $styles[$i]);
- }
- }
- $writer->close();
-
- return $writer;
- }
-
- /**
- * @param string $fileName
- * @return \DOMNode[]
- */
- private function getCellElementsFromContentXmlFile($fileName)
- {
- $cellElements = [];
-
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $xmlReader = new XMLReader();
- $xmlReader->openFileInZip($resourcePath, 'content.xml');
-
- while ($xmlReader->read()) {
- if ($xmlReader->isPositionedOnStartingNode('table:table-cell') && $xmlReader->getAttribute('office:value-type') !== null) {
- $cellElements[] = $xmlReader->expand();
- }
- }
-
- $xmlReader->close();
-
- return $cellElements;
- }
-
- /**
- * @param string $fileName
- * @return \DOMNode[]
- */
- private function getCellStyleElementsFromContentXmlFile($fileName)
- {
- $cellStyleElements = [];
-
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $xmlReader = new XMLReader();
- $xmlReader->openFileInZip($resourcePath, 'content.xml');
-
- while ($xmlReader->read()) {
- if ($xmlReader->isPositionedOnStartingNode('style:style') && $xmlReader->getAttribute('style:family') === 'table-cell') {
- $cellStyleElements[] = $xmlReader->expand();
- }
- }
-
- $xmlReader->close();
-
- return $cellStyleElements;
- }
-
- /**
- * @param string $fileName
- * @param string $section
- * @return \DomElement
- */
- private function getXmlSectionFromStylesXmlFile($fileName, $section)
- {
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $xmlReader = new XMLReader();
- $xmlReader->openFileInZip($resourcePath, 'styles.xml');
- $xmlReader->readUntilNodeFound($section);
-
- return $xmlReader->expand();
- }
-
- /**
- * @param string $expectedValue
- * @param \DOMNode $parentElement
- * @param string $childTagName
- * @param string $attributeName
- * @return void
- */
- private function assertFirstChildHasAttributeEquals($expectedValue, $parentElement, $childTagName, $attributeName)
- {
- $this->assertEquals($expectedValue, $parentElement->getElementsByTagName($childTagName)->item(0)->getAttribute($attributeName));
- }
-}
diff --git a/tests/Spout/Writer/Style/BorderTest.php b/tests/Spout/Writer/Style/BorderTest.php
deleted file mode 100644
index 181d8cf..0000000
--- a/tests/Spout/Writer/Style/BorderTest.php
+++ /dev/null
@@ -1,110 +0,0 @@
-addPart(new BorderPart(Border::LEFT))
- ->addPart(new BorderPart(Border::RIGHT))
- ->addPart(new BorderPart(Border::TOP))
- ->addPart(new BorderPart(Border::BOTTOM))
- ->addPart(new BorderPart(Border::LEFT));
-
- $this->assertEquals(4, count($border->getParts()), 'There should never be more than 4 border parts');
- }
-
- /**
- * @return void
- */
- public function testSetParts()
- {
- $border = new Border();
- $border->setParts([
- new BorderPart(Border::LEFT)
- ]);
-
- $this->assertEquals(1, count($border->getParts()), 'It should be possible to set the border parts');
- }
-
- /**
- * @return void
- */
- public function testBorderBuilderFluent()
- {
- $border = (new BorderBuilder())
- ->setBorderBottom()
- ->setBorderTop()
- ->setBorderLeft()
- ->setBorderRight()
- ->build();
- $this->assertEquals(4, count($border->getParts()), 'The border builder exposes a fluent interface');
- }
-
- /**
- * :D :S
- * @return void
- */
- public function testAnyCombinationOfAllowedBorderPartsParams()
- {
- $color = Color::BLACK;
- foreach (BorderPart::getAllowedNames() as $allowedName) {
- foreach (BorderPart::getAllowedStyles() as $allowedStyle) {
- foreach (BorderPart::getAllowedWidths() as $allowedWidth) {
- $borderPart = new BorderPart($allowedName, $color, $allowedWidth, $allowedStyle);
- $border = new Border();
- $border->addPart($borderPart);
- $this->assertEquals(1, count($border->getParts()));
-
- /** @var $part BorderPart */
- $part = $border->getParts()[$allowedName];
-
- $this->assertEquals($allowedStyle, $part->getStyle());
- $this->assertEquals($allowedWidth, $part->getWidth());
- $this->assertEquals($color, $part->getColor());
- }
- }
- }
- }
-}
diff --git a/tests/Spout/Writer/Style/ColorTest.php b/tests/Spout/Writer/Style/ColorTest.php
deleted file mode 100644
index 7dd4587..0000000
--- a/tests/Spout/Writer/Style/ColorTest.php
+++ /dev/null
@@ -1,93 +0,0 @@
-assertEquals($expectedColor, $color);
- }
-
- /**
- * @return array
- */
- public function dataProviderForTestRGBAInvalidColorComponents()
- {
- return [
- [-1, 0, 0],
- [0, -1, 0],
- [0, 0, -1],
- [999, 0, 0],
- [0, 999, 0],
- [0, 0, 999],
- [null, 0, 0],
- [0, null, 0],
- [0, 0, null],
- ['1', 0, 0],
- [0, '1', 0],
- [0, 0, '1'],
- [true, 0, 0],
- [0, true, 0],
- [0, 0, true],
- ];
- }
-
- /**
- * @dataProvider dataProviderForTestRGBAInvalidColorComponents
- * @expectedException \Box\Spout\Writer\Exception\InvalidColorException
- *
- * @param int $red
- * @param int $green
- * @param int $blue
- * @return void
- */
- public function testRGBInvalidColorComponents($red, $green, $blue)
- {
- Color::rgb($red, $green, $blue);
- }
-}
diff --git a/tests/Spout/Writer/Style/StyleTest.php b/tests/Spout/Writer/Style/StyleTest.php
deleted file mode 100644
index 7d3ec36..0000000
--- a/tests/Spout/Writer/Style/StyleTest.php
+++ /dev/null
@@ -1,160 +0,0 @@
-setFontBold()->build();
- $style1->setId(1);
-
- $style2 = (new StyleBuilder())->setFontBold()->build();
- $style2->setId(2);
-
- $this->assertEquals($style1->serialize(), $style2->serialize());
- }
-
- /**
- * @return void
- */
- public function testMergeWithShouldReturnACopy()
- {
- $baseStyle = (new StyleBuilder())->build();
- $currentStyle = (new StyleBuilder())->build();
- $mergedStyle = $currentStyle->mergeWith($baseStyle);
-
- $this->assertNotSame($mergedStyle, $currentStyle);
- }
-
- /**
- * @return void
- */
- public function testMergeWithShouldMergeSetProperties()
- {
- $baseStyle = (new StyleBuilder())->setFontSize(99)->setFontBold()->build();
- $currentStyle = (new StyleBuilder())->setFontName('Font')->setFontUnderline()->build();
- $mergedStyle = $currentStyle->mergeWith($baseStyle);
-
- $this->assertNotEquals(99, $currentStyle->getFontSize());
- $this->assertFalse($currentStyle->isFontBold());
-
- $this->assertEquals(99, $mergedStyle->getFontSize());
- $this->assertTrue($mergedStyle->isFontBold());
- $this->assertEquals('Font', $mergedStyle->getFontName());
- $this->assertTrue($mergedStyle->isFontUnderline());
- }
-
- /**
- * @return void
- */
- public function testMergeWithShouldPreferCurrentStylePropertyIfSetOnCurrentAndOnBase()
- {
- $baseStyle = (new StyleBuilder())->setFontSize(10)->build();
- $currentStyle = (new StyleBuilder())->setFontSize(99)->build();
- $mergedStyle = $currentStyle->mergeWith($baseStyle);
-
- $this->assertEquals(99, $mergedStyle->getFontSize());
- }
-
- /**
- * @return void
- */
- public function testMergeWithShouldPreferCurrentStylePropertyIfSetOnCurrentButNotOnBase()
- {
- $baseStyle = (new StyleBuilder())->build();
- $currentStyle = (new StyleBuilder())->setFontItalic()->setFontStrikethrough()->build();
- $mergedStyle = $currentStyle->mergeWith($baseStyle);
-
- $this->assertFalse($baseStyle->isFontItalic());
- $this->assertFalse($baseStyle->isFontStrikethrough());
-
- $this->assertTrue($mergedStyle->isFontItalic());
- $this->assertTrue($mergedStyle->isFontStrikethrough());
- }
-
- /**
- * @return void
- */
- public function testMergeWithShouldPreferBaseStylePropertyIfSetOnBaseButNotOnCurrent()
- {
- $baseStyle = (new StyleBuilder())
- ->setFontItalic()
- ->setFontUnderline()
- ->setFontStrikethrough()
- ->setShouldWrapText()
- ->build();
- $currentStyle = (new StyleBuilder())->build();
- $mergedStyle = $currentStyle->mergeWith($baseStyle);
-
- $this->assertFalse($currentStyle->isFontUnderline());
- $this->assertTrue($mergedStyle->isFontUnderline());
-
- $this->assertFalse($currentStyle->shouldWrapText());
- $this->assertTrue($mergedStyle->shouldWrapText());
- }
-
- /**
- * @return void
- */
- public function testMergeWithShouldDoNothingIfStylePropertyNotSetOnBaseNorCurrent()
- {
- $baseStyle = (new StyleBuilder())->build();
- $currentStyle = (new StyleBuilder())->build();
- $mergedStyle = $currentStyle->mergeWith($baseStyle);
-
- $this->assertTrue($baseStyle->serialize() === $currentStyle->serialize());
- $this->assertTrue($currentStyle->serialize() === $mergedStyle->serialize());
- }
-
- /**
- * @return void
- */
- public function testMergeWithShouldDoNothingIfStylePropertyNotSetOnCurrentAndIsDefaultValueOnBase()
- {
- $baseStyle = (new StyleBuilder())
- ->setFontName(Style::DEFAULT_FONT_NAME)
- ->setFontSize(Style::DEFAULT_FONT_SIZE)
- ->build();
- $currentStyle = (new StyleBuilder())->build();
- $mergedStyle = $currentStyle->mergeWith($baseStyle);
-
- $this->assertTrue($currentStyle->serialize() === $mergedStyle->serialize());
- }
-
- /**
- * @return void
- */
- public function testStyleBuilderShouldApplyBorders()
- {
- $border = (new BorderBuilder())
- ->setBorderBottom()
- ->build();
- $style = (new StyleBuilder())->setBorder($border)->build();
- $this->assertTrue($style->shouldApplyBorder());
- }
-
- /**
- * @return void
- */
- public function testStyleBuilderShouldMergeBorders()
- {
- $border = (new BorderBuilder())->setBorderBottom(Color::RED, Border::WIDTH_THIN, Border::STYLE_DASHED)->build();
-
- $baseStyle = (new StyleBuilder())->setBorder($border)->build();
- $currentStyle = (new StyleBuilder())->build();
- $mergedStyle = $currentStyle->mergeWith($baseStyle);
-
- $this->assertEquals(null, $currentStyle->getBorder(), 'Current style has no border');
- $this->assertInstanceOf('Box\Spout\Writer\Style\Border', $baseStyle->getBorder(), 'Base style has a border');
- $this->assertInstanceOf('Box\Spout\Writer\Style\Border', $mergedStyle->getBorder(), 'Merged style has a border');
- }
-}
diff --git a/tests/Spout/Writer/WriterFactoryTest.php b/tests/Spout/Writer/WriterFactoryTest.php
deleted file mode 100644
index 528eff3..0000000
--- a/tests/Spout/Writer/WriterFactoryTest.php
+++ /dev/null
@@ -1,21 +0,0 @@
-defaultStyle = (new StyleBuilder())->build();
- }
-
- /**
- * @return void
- */
- public function testRegisterStyleShouldUpdateId()
- {
- $style1 = (new StyleBuilder())->setFontBold()->build();
- $style2 = (new StyleBuilder())->setFontUnderline()->build();
-
- $this->assertEquals(0, $this->defaultStyle->getId(), 'Default style ID should be 0');
- $this->assertNull($style1->getId());
- $this->assertNull($style2->getId());
-
- $styleHelper = new StyleHelper($this->defaultStyle);
- $registeredStyle1 = $styleHelper->registerStyle($style1);
- $registeredStyle2 = $styleHelper->registerStyle($style2);
-
- $this->assertEquals(1, $registeredStyle1->getId());
- $this->assertEquals(2, $registeredStyle2->getId());
- }
-
- /**
- * @return void
- */
- public function testRegisterStyleShouldReuseAlreadyRegisteredStyles()
- {
- $style = (new StyleBuilder())->setFontBold()->build();
-
- $styleHelper = new StyleHelper($this->defaultStyle);
- $registeredStyle1 = $styleHelper->registerStyle($style);
- $registeredStyle2 = $styleHelper->registerStyle($style);
-
- $this->assertEquals(1, $registeredStyle1->getId());
- $this->assertEquals(1, $registeredStyle2->getId());
- }
-
- /**
- * @return void
- */
- public function testShouldApplyStyleOnEmptyCell()
- {
- $styleWithFont = (new StyleBuilder())->setFontBold()->build();
- $styleWithBackground = (new StyleBuilder())->setBackgroundColor(Color::BLUE)->build();
-
- $border = (new BorderBuilder())->setBorderBottom(Color::GREEN)->build();
- $styleWithBorder = (new StyleBuilder())->setBorder($border)->build();
-
- $styleHelper = new StyleHelper($this->defaultStyle);
- $styleHelper->registerStyle($styleWithFont);
- $styleHelper->registerStyle($styleWithBackground);
- $styleHelper->registerStyle($styleWithBorder);
-
- $this->assertFalse($styleHelper->shouldApplyStyleOnEmptyCell($styleWithFont->getId()));
- $this->assertTrue($styleHelper->shouldApplyStyleOnEmptyCell($styleWithBackground->getId()));
- $this->assertTrue($styleHelper->shouldApplyStyleOnEmptyCell($styleWithBorder->getId()));
- }
-
- /**
- * @return void
- */
- public function testApplyExtraStylesIfNeededShouldApplyWrapTextIfCellContainsNewLine()
- {
- $style = clone $this->defaultStyle;
- $styleHelper = new StyleHelper($this->defaultStyle);
-
- $this->assertFalse($style->shouldWrapText());
-
- $updatedStyle = $styleHelper->applyExtraStylesIfNeeded($style, [12, 'single line', "multi\nlines", null]);
-
- $this->assertTrue($updatedStyle->shouldWrapText());
- }
-
- /**
- * @return void
- */
- public function testApplyExtraStylesIfNeededShouldDoNothingIfWrapTextAlreadyApplied()
- {
- $style = (new StyleBuilder())->setShouldWrapText()->build();
- $styleHelper = new StyleHelper($this->defaultStyle);
-
- $this->assertTrue($style->shouldWrapText());
-
- $updatedStyle = $styleHelper->applyExtraStylesIfNeeded($style, ["multi\nlines"]);
-
- $this->assertTrue($updatedStyle->shouldWrapText());
- }
-}
diff --git a/tests/Spout/Writer/XLSX/SheetTest.php b/tests/Spout/Writer/XLSX/SheetTest.php
deleted file mode 100644
index 58c4b05..0000000
--- a/tests/Spout/Writer/XLSX/SheetTest.php
+++ /dev/null
@@ -1,134 +0,0 @@
-writeDataToMulitpleSheetsAndReturnSheets('test_get_sheet_index.xlsx');
-
- $this->assertEquals(2, count($sheets), '2 sheets should have been created');
- $this->assertEquals(0, $sheets[0]->getIndex(), 'The first sheet should be index 0');
- $this->assertEquals(1, $sheets[1]->getIndex(), 'The second sheet should be index 1');
- }
-
- /**
- * @return void
- */
- public function testGetSheetName()
- {
- $sheets = $this->writeDataToMulitpleSheetsAndReturnSheets('test_get_sheet_name.xlsx');
-
- $this->assertEquals(2, count($sheets), '2 sheets should have been created');
- $this->assertEquals('Sheet1', $sheets[0]->getName(), 'Invalid name for the first sheet');
- $this->assertEquals('Sheet2', $sheets[1]->getName(), 'Invalid name for the second sheet');
- }
-
- /**
- * @return void
- */
- public function testSetSheetNameShouldCreateSheetWithCustomName()
- {
- $fileName = 'test_set_name_should_create_sheet_with_custom_name.xlsx';
- $customSheetName = 'CustomName';
- $this->writeDataAndReturnSheetWithCustomName($fileName, $customSheetName);
-
- $this->assertSheetNameEquals($customSheetName, $fileName, "The sheet name should have been changed to '$customSheetName'");
- }
-
- /**
- * @expectedException \Box\Spout\Writer\Exception\InvalidSheetNameException
- * @return void
- */
- public function testSetSheetNameShouldThrowWhenNameIsAlreadyUsed()
- {
- $fileName = 'test_set_name_with_non_unique_name.xlsx';
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $writer = WriterFactory::create(Type::XLSX);
- $writer->openToFile($resourcePath);
-
- $customSheetName = 'Sheet name';
-
- $sheet = $writer->getCurrentSheet();
- $sheet->setName($customSheetName);
-
- $writer->addNewSheetAndMakeItCurrent();
- $sheet = $writer->getCurrentSheet();
- $sheet->setName($customSheetName);
- }
-
- /**
- * @param string $fileName
- * @param string $sheetName
- * @return Sheet
- */
- private function writeDataAndReturnSheetWithCustomName($fileName, $sheetName)
- {
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $writer = WriterFactory::create(Type::XLSX);
- $writer->openToFile($resourcePath);
-
- $sheet = $writer->getCurrentSheet();
- $sheet->setName($sheetName);
-
- $writer->addRow(['xlsx--11', 'xlsx--12']);
- $writer->close();
- }
-
- /**
- * @param string $fileName
- * @return Sheet[]
- */
- private function writeDataToMulitpleSheetsAndReturnSheets($fileName)
- {
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- /** @var \Box\Spout\Writer\XLSX\Writer $writer */
- $writer = WriterFactory::create(Type::XLSX);
- $writer->openToFile($resourcePath);
-
- $writer->addRow(['xlsx--sheet1--11', 'xlsx--sheet1--12']);
- $writer->addNewSheetAndMakeItCurrent();
- $writer->addRow(['xlsx--sheet2--11', 'xlsx--sheet2--12', 'xlsx--sheet2--13']);
-
- $writer->close();
-
- return $writer->getSheets();
- }
-
- /**
- * @param string $expectedName
- * @param string $fileName
- * @param string $message
- * @return void
- */
- private function assertSheetNameEquals($expectedName, $fileName, $message = '')
- {
- $resourcePath = $this->getGeneratedResourcePath($fileName);
- $pathToWorkbookFile = $resourcePath . '#xl/workbook.xml';
- $xmlContents = file_get_contents('zip://' . $pathToWorkbookFile);
-
- $this->assertContains("createUnwritableFolderIfNeeded();
- $filePath = $this->getGeneratedUnwritableResourcePath($fileName);
-
- $writer = WriterFactory::create(Type::XLSX);
- @$writer->openToFile($filePath);
- }
-
- /**
- * @expectedException \Box\Spout\Writer\Exception\WriterNotOpenedException
- */
- public function testAddRowShouldThrowExceptionIfCallAddRowBeforeOpeningWriter()
- {
- $writer = WriterFactory::create(Type::XLSX);
- $writer->addRow(['xlsx--11', 'xlsx--12']);
- }
-
- /**
- * @expectedException \Box\Spout\Writer\Exception\WriterNotOpenedException
- */
- public function testAddRowShouldThrowExceptionIfCalledBeforeOpeningWriter()
- {
- $writer = WriterFactory::create(Type::XLSX);
- $writer->addRows([['xlsx--11', 'xlsx--12']]);
- }
-
- /**
- * @expectedException \Box\Spout\Writer\Exception\WriterAlreadyOpenedException
- */
- public function testSetTempFolderShouldThrowExceptionIfCalledAfterOpeningWriter()
- {
- $fileName = 'file_that_wont_be_written.xlsx';
- $filePath = $this->getGeneratedResourcePath($fileName);
-
- /** @var \Box\Spout\Writer\XLSX\Writer $writer */
- $writer = WriterFactory::create(Type::XLSX);
- $writer->openToFile($filePath);
-
- $writer->setTempFolder('');
- }
-
- /**
- * @expectedException \Box\Spout\Writer\Exception\WriterAlreadyOpenedException
- */
- public function testSetShouldUseInlineStringsShouldThrowExceptionIfCalledAfterOpeningWriter()
- {
- $fileName = 'file_that_wont_be_written.xlsx';
- $filePath = $this->getGeneratedResourcePath($fileName);
-
- /** @var \Box\Spout\Writer\XLSX\Writer $writer */
- $writer = WriterFactory::create(Type::XLSX);
- $writer->openToFile($filePath);
-
- $writer->setShouldUseInlineStrings(true);
- }
-
- /**
- * @expectedException \Box\Spout\Writer\Exception\WriterAlreadyOpenedException
- */
- public function testsetShouldCreateNewSheetsAutomaticallyShouldThrowExceptionIfCalledAfterOpeningWriter()
- {
- $fileName = 'file_that_wont_be_written.xlsx';
- $filePath = $this->getGeneratedResourcePath($fileName);
-
- /** @var \Box\Spout\Writer\XLSX\Writer $writer */
- $writer = WriterFactory::create(Type::XLSX);
- $writer->openToFile($filePath);
-
- $writer->setShouldCreateNewSheetsAutomatically(true);
- }
-
- /**
- * @expectedException \Box\Spout\Common\Exception\InvalidArgumentException
- */
- public function testAddRowShouldThrowExceptionIfUnsupportedDataTypePassedIn()
- {
- $fileName = 'test_add_row_should_throw_exception_if_unsupported_data_type_passed_in.xlsx';
- $dataRows = [
- [str_repeat('a', Worksheet::MAX_CHARACTERS_PER_CELL + 1)],
- ];
-
- $this->writeToXLSXFile($dataRows, $fileName);
- }
-
- /**
- * @expectedException \Box\Spout\Common\Exception\InvalidArgumentException
- */
- public function testAddRowShouldThrowExceptionIfWritingStringExceedingMaxNumberOfCharactersAllowedPerCell()
- {
- $fileName = 'test_add_row_should_throw_exception_if_string_exceeds_max_num_chars_allowed_per_cell.xlsx';
- $dataRows = [
- [new \stdClass()],
- ];
-
- $this->writeToXLSXFile($dataRows, $fileName);
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldCleanupAllFilesIfExceptionIsThrown()
- {
- $fileName = 'test_add_row_should_cleanup_all_files_if_exception_thrown.xlsx';
- $dataRows = [
- ['wrong'],
- [new \stdClass()],
- ];
-
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $this->recreateTempFolder();
- $tempFolderPath = $this->getTempFolderPath();
-
- /** @var \Box\Spout\Writer\XLSX\Writer $writer */
- $writer = WriterFactory::create(Type::XLSX);
- $writer->setTempFolder($tempFolderPath);
- $writer->openToFile($resourcePath);
-
- try {
- $writer->addRows($dataRows);
- $this->fail('Exception should have been thrown');
- } catch (SpoutException $e) {
- $this->assertFalse(file_exists($fileName), 'Output file should have been deleted');
-
- $numFiles = iterator_count(new \FilesystemIterator($tempFolderPath, \FilesystemIterator::SKIP_DOTS));
- $this->assertEquals(0, $numFiles, 'All temp files should have been deleted');
- }
- }
-
- /**
- * @return void
- */
- public function testAddNewSheetAndMakeItCurrent()
- {
- $fileName = 'test_add_new_sheet_and_make_it_current.xlsx';
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $writer = WriterFactory::create(Type::XLSX);
- $writer->openToFile($resourcePath);
- $writer->addNewSheetAndMakeItCurrent();
- $writer->close();
-
- $sheets = $writer->getSheets();
- $this->assertEquals(2, count($sheets), 'There should be 2 sheets');
- $this->assertEquals($sheets[1], $writer->getCurrentSheet(), 'The current sheet should be the second one.');
- }
-
- /**
- * @return void
- */
- public function testSetCurrentSheet()
- {
- $fileName = 'test_set_current_sheet.xlsx';
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $writer = WriterFactory::create(Type::XLSX);
- $writer->openToFile($resourcePath);
-
- $writer->addNewSheetAndMakeItCurrent();
- $writer->addNewSheetAndMakeItCurrent();
-
- $firstSheet = $writer->getSheets()[0];
- $writer->setCurrentSheet($firstSheet);
-
- $writer->close();
-
- $this->assertEquals($firstSheet, $writer->getCurrentSheet(), 'The current sheet should be the first one.');
- }
-
- /**
- * @return void
- */
- public function testCloseShouldNoopWhenWriterIsNotOpened()
- {
- $fileName = 'test_double_close_calls.xlsx';
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $writer = WriterFactory::create(Type::XLSX);
- $writer->close(); // This call should not cause any error
-
- $writer->openToFile($resourcePath);
- $writer->close();
- $writer->close(); // This call should not cause any error
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldWriteGivenDataToSheetUsingInlineStrings()
- {
- $fileName = 'test_add_row_should_write_given_data_to_sheet_using_inline_strings.xlsx';
- $dataRows = [
- ['xlsx--11', 'xlsx--12'],
- ['xlsx--21', 'xlsx--22', 'xlsx--23'],
- ];
-
- $this->writeToXLSXFile($dataRows, $fileName, $shouldUseInlineStrings = true);
-
- foreach ($dataRows as $dataRow) {
- foreach ($dataRow as $cellValue) {
- $this->assertInlineDataWasWrittenToSheet($fileName, 1, $cellValue);
- }
- }
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldWriteGivenDataToTwoSheetsUsingInlineStrings()
- {
- $fileName = 'test_add_row_should_write_given_data_to_two_sheets_using_inline_strings.xlsx';
- $dataRows = [
- ['xlsx--11', 'xlsx--12'],
- ['xlsx--21', 'xlsx--22', 'xlsx--23'],
- ];
-
- $numSheets = 2;
- $this->writeToMultipleSheetsInXLSXFile($dataRows, $numSheets, $fileName, $shouldUseInlineStrings = true);
-
- for ($i = 1; $i <= $numSheets; $i++) {
- foreach ($dataRows as $dataRow) {
- foreach ($dataRow as $cellValue) {
- $this->assertInlineDataWasWrittenToSheet($fileName, $numSheets, $cellValue);
- }
- }
- }
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldWriteGivenDataToSheetUsingSharedStrings()
- {
- $fileName = 'test_add_row_should_write_given_data_to_sheet_using_shared_strings.xlsx';
- $dataRows = [
- ['xlsx--11', 'xlsx--12'],
- ['xlsx--21', 'xlsx--22', 'xlsx--23'],
- ];
-
- $this->writeToXLSXFile($dataRows, $fileName, $shouldUseInlineStrings = false);
-
- foreach ($dataRows as $dataRow) {
- foreach ($dataRow as $cellValue) {
- $this->assertSharedStringWasWritten($fileName, $cellValue);
- }
- }
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldWriteGivenDataToTwoSheetsUsingSharedStrings()
- {
- $fileName = 'test_add_row_should_write_given_data_to_two_sheets_using_shared_strings.xlsx';
- $dataRows = [
- ['xlsx--11', 'xlsx--12'],
- ['xlsx--21', 'xlsx--22', 'xlsx--23'],
- ];
-
- $numSheets = 2;
- $this->writeToMultipleSheetsInXLSXFile($dataRows, $numSheets, $fileName, $shouldUseInlineStrings = false);
-
- for ($i = 1; $i <= $numSheets; $i++) {
- foreach ($dataRows as $dataRow) {
- foreach ($dataRow as $cellValue) {
- $this->assertSharedStringWasWritten($fileName, $cellValue);
- }
- }
- }
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldSupportAssociativeArrays()
- {
- $fileName = 'test_add_row_should_support_associative_arrays.xlsx';
- $dataRows = [
- ['foo' => 'xlsx--11', 'bar' => 'xlsx--12'],
- ];
-
- $this->writeToXLSXFile($dataRows, $fileName);
-
- foreach ($dataRows as $dataRow) {
- foreach ($dataRow as $cellValue) {
- $this->assertInlineDataWasWrittenToSheet($fileName, 1, $cellValue);
- }
- }
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldNotWriteEmptyRows()
- {
- $fileName = 'test_add_row_should_not_write_empty_rows.xlsx';
- $dataRows = [
- [''],
- ['xlsx--21', 'xlsx--22'],
- ['key' => ''],
- [''],
- ['xlsx--51', 'xlsx--52'],
- ];
-
- $this->writeToXLSXFile($dataRows, $fileName);
-
- $this->assertInlineDataWasWrittenToSheet($fileName, 1, 'row r="2"');
- $this->assertInlineDataWasWrittenToSheet($fileName, 1, 'row r="5"');
- $this->assertInlineDataWasNotWrittenToSheet($fileName, 1, 'row r="1"');
- $this->assertInlineDataWasNotWrittenToSheet($fileName, 1, 'row r="3"');
- $this->assertInlineDataWasNotWrittenToSheet($fileName, 1, 'row r="4"');
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldSupportMultipleTypesOfData()
- {
- $fileName = 'test_add_row_should_support_multiple_types_of_data.xlsx';
- $dataRows = [
- ['xlsx--11', true, '', 0, 10.2, null],
- ];
-
- $this->writeToXLSXFile($dataRows, $fileName, $shouldUseInlineStrings = false);
-
- $this->assertSharedStringWasWritten($fileName, 'xlsx--11');
- $this->assertInlineDataWasWrittenToSheet($fileName, 1, 1); // true is converted to 1
- $this->assertInlineDataWasWrittenToSheet($fileName, 1, 0);
- $this->assertInlineDataWasWrittenToSheet($fileName, 1, 10.2);
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldWriteGivenDataToTheCorrectSheet()
- {
- $fileName = 'test_add_row_should_write_given_data_to_the_correct_sheet.xlsx';
- $dataRowsSheet1 = [
- ['xlsx--sheet1--11', 'xlsx--sheet1--12'],
- ['xlsx--sheet1--21', 'xlsx--sheet1--22', 'xlsx--sheet1--23'],
- ];
- $dataRowsSheet2 = [
- ['xlsx--sheet2--11', 'xlsx--sheet2--12'],
- ['xlsx--sheet2--21', 'xlsx--sheet2--22', 'xlsx--sheet2--23'],
- ];
- $dataRowsSheet1Again = [
- ['xlsx--sheet1--31', 'xlsx--sheet1--32'],
- ['xlsx--sheet1--41', 'xlsx--sheet1--42', 'xlsx--sheet1--43'],
- ];
-
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- /** @var \Box\Spout\Writer\XLSX\Writer $writer */
- $writer = WriterFactory::create(Type::XLSX);
- $writer->setShouldUseInlineStrings(true);
-
- $writer->openToFile($resourcePath);
-
- $writer->addRows($dataRowsSheet1);
-
- $writer->addNewSheetAndMakeItCurrent();
- $writer->addRows($dataRowsSheet2);
-
- $firstSheet = $writer->getSheets()[0];
- $writer->setCurrentSheet($firstSheet);
-
- $writer->addRows($dataRowsSheet1Again);
-
- $writer->close();
-
- foreach ($dataRowsSheet1 as $dataRow) {
- foreach ($dataRow as $cellValue) {
- $this->assertInlineDataWasWrittenToSheet($fileName, 1, $cellValue, 'Data should have been written in Sheet 1');
- }
- }
- foreach ($dataRowsSheet2 as $dataRow) {
- foreach ($dataRow as $cellValue) {
- $this->assertInlineDataWasWrittenToSheet($fileName, 2, $cellValue, 'Data should have been written in Sheet 2');
- }
- }
- foreach ($dataRowsSheet1Again as $dataRow) {
- foreach ($dataRow as $cellValue) {
- $this->assertInlineDataWasWrittenToSheet($fileName, 1, $cellValue, 'Data should have been written in Sheet 1');
- }
- }
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldAutomaticallyCreateNewSheetsIfMaxRowsReachedAndOptionTurnedOn()
- {
- $fileName = 'test_add_row_should_automatically_create_new_sheets_if_max_rows_reached_and_option_turned_on.xlsx';
- $dataRows = [
- ['xlsx--sheet1--11', 'xlsx--sheet1--12'],
- ['xlsx--sheet1--21', 'xlsx--sheet1--22', 'xlsx--sheet1--23'],
- ['xlsx--sheet2--11', 'xlsx--sheet2--12'], // this should be written in a new sheet
- ];
-
- // set the maxRowsPerSheet limit to 2
- \ReflectionHelper::setStaticValue('\Box\Spout\Writer\XLSX\Internal\Workbook', 'maxRowsPerWorksheet', 2);
-
- $writer = $this->writeToXLSXFile($dataRows, $fileName, true, $shouldCreateSheetsAutomatically = true);
- $this->assertEquals(2, count($writer->getSheets()), '2 sheets should have been created.');
-
- $this->assertInlineDataWasNotWrittenToSheet($fileName, 1, 'xlsx--sheet2--11');
- $this->assertInlineDataWasWrittenToSheet($fileName, 2, 'xlsx--sheet2--11');
-
- \ReflectionHelper::reset();
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldNotCreateNewSheetsIfMaxRowsReachedAndOptionTurnedOff()
- {
- $fileName = 'test_add_row_should_not_create_new_sheets_if_max_rows_reached_and_option_turned_off.xlsx';
- $dataRows = [
- ['xlsx--sheet1--11', 'xlsx--sheet1--12'],
- ['xlsx--sheet1--21', 'xlsx--sheet1--22', 'xlsx--sheet1--23'],
- ['xlsx--sheet1--31', 'xlsx--sheet1--32'], // this should NOT be written in a new sheet
- ];
-
- // set the maxRowsPerSheet limit to 2
- \ReflectionHelper::setStaticValue('\Box\Spout\Writer\XLSX\Internal\Workbook', 'maxRowsPerWorksheet', 2);
-
- $writer = $this->writeToXLSXFile($dataRows, $fileName, true, $shouldCreateSheetsAutomatically = false);
- $this->assertEquals(1, count($writer->getSheets()), 'Only 1 sheet should have been created.');
-
- $this->assertInlineDataWasNotWrittenToSheet($fileName, 1, 'xlsx--sheet1--31');
-
- \ReflectionHelper::reset();
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldEscapeHtmlSpecialCharacters()
- {
- $fileName = 'test_add_row_should_escape_html_special_characters.xlsx';
- $dataRows = [
- ['I\'m in "great" mood', 'This be escaped & tested'],
- ];
-
- $this->writeToXLSXFile($dataRows, $fileName);
-
- $this->assertInlineDataWasWrittenToSheet($fileName, 1, 'I\'m in "great" mood', 'Quotes should not be escaped');
- $this->assertInlineDataWasWrittenToSheet($fileName, 1, 'This <must> be escaped & tested', '<, > and & should be escaped');
- }
-
- /**
- * @return void
- */
- public function testAddRowShouldEscapeControlCharacters()
- {
- $fileName = 'test_add_row_should_escape_control_characters.xlsx';
- $dataRows = [
- ['control '.chr(21).' character'],
- ];
-
- $this->writeToXLSXFile($dataRows, $fileName);
-
- $this->assertInlineDataWasWrittenToSheet($fileName, 1, 'control _x0015_ character');
- }
-
- /**
- * @return void
- */
- public function testGeneratedFileShouldHaveTheCorrectMimeType()
- {
- $fileName = 'test_mime_type.xlsx';
- $resourcePath = $this->getGeneratedResourcePath($fileName);
- $dataRows = [['foo']];
-
- $this->writeToXLSXFile($dataRows, $fileName);
-
- $finfo = new \finfo(FILEINFO_MIME_TYPE);
- $this->assertEquals('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', $finfo->file($resourcePath));
- }
-
- /**
- * @param array $allRows
- * @param string $fileName
- * @param bool $shouldUseInlineStrings
- * @param bool $shouldCreateSheetsAutomatically
- * @return Writer
- */
- private function writeToXLSXFile($allRows, $fileName, $shouldUseInlineStrings = true, $shouldCreateSheetsAutomatically = true)
- {
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- /** @var \Box\Spout\Writer\XLSX\Writer $writer */
- $writer = WriterFactory::create(Type::XLSX);
- $writer->setShouldUseInlineStrings($shouldUseInlineStrings);
- $writer->setShouldCreateNewSheetsAutomatically($shouldCreateSheetsAutomatically);
-
- $writer->openToFile($resourcePath);
- $writer->addRows($allRows);
- $writer->close();
-
- return $writer;
- }
-
- /**
- * @param array $allRows
- * @param int $numSheets
- * @param string $fileName
- * @param bool $shouldUseInlineStrings
- * @param bool $shouldCreateSheetsAutomatically
- * @return Writer
- */
- private function writeToMultipleSheetsInXLSXFile($allRows, $numSheets, $fileName, $shouldUseInlineStrings = true, $shouldCreateSheetsAutomatically = true)
- {
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- /** @var \Box\Spout\Writer\XLSX\Writer $writer */
- $writer = WriterFactory::create(Type::XLSX);
- $writer->setShouldUseInlineStrings($shouldUseInlineStrings);
- $writer->setShouldCreateNewSheetsAutomatically($shouldCreateSheetsAutomatically);
-
- $writer->openToFile($resourcePath);
- $writer->addRows($allRows);
-
- for ($i = 1; $i < $numSheets; $i++) {
- $writer->addNewSheetAndMakeItCurrent();
- $writer->addRows($allRows);
- }
-
- $writer->close();
-
- return $writer;
- }
-
- /**
- * @param string $fileName
- * @param int $sheetIndex
- * @param mixed $inlineData
- * @param string $message
- * @return void
- */
- private function assertInlineDataWasWrittenToSheet($fileName, $sheetIndex, $inlineData, $message = '')
- {
- $resourcePath = $this->getGeneratedResourcePath($fileName);
- $pathToSheetFile = $resourcePath . '#xl/worksheets/sheet' . $sheetIndex . '.xml';
- $xmlContents = file_get_contents('zip://' . $pathToSheetFile);
-
- $this->assertContains((string)$inlineData, $xmlContents, $message);
- }
-
- /**
- * @param string $fileName
- * @param int $sheetIndex
- * @param mixed $inlineData
- * @param string $message
- * @return void
- */
- private function assertInlineDataWasNotWrittenToSheet($fileName, $sheetIndex, $inlineData, $message = '')
- {
- $resourcePath = $this->getGeneratedResourcePath($fileName);
- $pathToSheetFile = $resourcePath . '#xl/worksheets/sheet' . $sheetIndex . '.xml';
- $xmlContents = file_get_contents('zip://' . $pathToSheetFile);
-
- $this->assertNotContains((string)$inlineData, $xmlContents, $message);
- }
-
- /**
- * @param string $fileName
- * @param string $sharedString
- * @param string $message
- * @return void
- */
- private function assertSharedStringWasWritten($fileName, $sharedString, $message = '')
- {
- $resourcePath = $this->getGeneratedResourcePath($fileName);
- $pathToSharedStringsFile = $resourcePath . '#xl/sharedStrings.xml';
- $xmlContents = file_get_contents('zip://' . $pathToSharedStringsFile);
-
- $this->assertContains($sharedString, $xmlContents, $message);
- }
-}
diff --git a/tests/Spout/Writer/XLSX/WriterWithStyleTest.php b/tests/Spout/Writer/XLSX/WriterWithStyleTest.php
deleted file mode 100644
index e4d1749..0000000
--- a/tests/Spout/Writer/XLSX/WriterWithStyleTest.php
+++ /dev/null
@@ -1,668 +0,0 @@
-defaultStyle = (new StyleBuilder())->build();
- }
-
- /**
- * @expectedException \Box\Spout\Writer\Exception\WriterNotOpenedException
- */
- public function testAddRowWithStyleShouldThrowExceptionIfCallAddRowBeforeOpeningWriter()
- {
- $writer = WriterFactory::create(Type::XLSX);
- $writer->addRowWithStyle(['xlsx--11', 'xlsx--12'], $this->defaultStyle);
- }
-
- /**
- * @expectedException \Box\Spout\Writer\Exception\WriterNotOpenedException
- */
- public function testAddRowWithStyleShouldThrowExceptionIfCalledBeforeOpeningWriter()
- {
- $writer = WriterFactory::create(Type::XLSX);
- $writer->addRowWithStyle(['xlsx--11', 'xlsx--12'], $this->defaultStyle);
- }
-
- /**
- * @return array
- */
- public function dataProviderForInvalidStyle()
- {
- return [
- ['style'],
- [new \stdClass()],
- [null],
- ];
- }
-
- /**
- * @dataProvider dataProviderForInvalidStyle
- * @expectedException \Box\Spout\Common\Exception\InvalidArgumentException
- *
- * @param \Box\Spout\Writer\Style\Style $style
- */
- public function testAddRowWithStyleShouldThrowExceptionIfInvalidStyleGiven($style)
- {
- $fileName = 'test_add_row_with_style_should_throw_exception.xlsx';
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $writer = WriterFactory::create(Type::XLSX);
- $writer->openToFile($resourcePath);
- $writer->addRowWithStyle(['xlsx--11', 'xlsx--12'], $style);
- }
-
- /**
- * @dataProvider dataProviderForInvalidStyle
- * @expectedException \Box\Spout\Common\Exception\InvalidArgumentException
- *
- * @param \Box\Spout\Writer\Style\Style $style
- */
- public function testAddRowsWithStyleShouldThrowExceptionIfInvalidStyleGiven($style)
- {
- $fileName = 'test_add_row_with_style_should_throw_exception.xlsx';
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $writer = WriterFactory::create(Type::XLSX);
- $writer->openToFile($resourcePath);
- $writer->addRowsWithStyle([['xlsx--11', 'xlsx--12']], $style);
- }
-
- /**
- * @return void
- */
- public function testAddRowWithStyleShouldListAllUsedFontsInCreatedStylesXmlFile()
- {
- $fileName = 'test_add_row_with_style_should_list_all_used_fonts.xlsx';
- $dataRows = [
- ['xlsx--11', 'xlsx--12'],
- ['xlsx--21', 'xlsx--22'],
- ];
-
- $style = (new StyleBuilder())
- ->setFontBold()
- ->setFontItalic()
- ->setFontUnderline()
- ->setFontStrikethrough()
- ->build();
- $style2 = (new StyleBuilder())
- ->setFontSize(15)
- ->setFontColor(Color::RED)
- ->setFontName('Cambria')
- ->build();
-
- $this->writeToXLSXFileWithMultipleStyles($dataRows, $fileName, [$style, $style2]);
-
- $fontsDomElement = $this->getXmlSectionFromStylesXmlFile($fileName, 'fonts');
- $this->assertEquals(3, $fontsDomElement->getAttribute('count'), 'There should be 3 fonts, including the default one.');
-
- $fontElements = $fontsDomElement->getElementsByTagName('font');
- $this->assertEquals(3, $fontElements->length, 'There should be 3 associated "font" elements, including the default one.');
- // First font should be the default one
- $defaultFontElement = $fontElements->item(0);
- $this->assertChildrenNumEquals(3, $defaultFontElement, 'The default font should only have 3 properties.');
- $this->assertFirstChildHasAttributeEquals((string) Writer::DEFAULT_FONT_SIZE, $defaultFontElement, 'sz', 'val');
- $this->assertFirstChildHasAttributeEquals(Color::toARGB(Style::DEFAULT_FONT_COLOR), $defaultFontElement, 'color', 'rgb');
- $this->assertFirstChildHasAttributeEquals(Writer::DEFAULT_FONT_NAME, $defaultFontElement, 'name', 'val');
-
- // Second font should contain data from the first created style
- $secondFontElement = $fontElements->item(1);
- $this->assertChildrenNumEquals(7, $secondFontElement, 'The font should only have 7 properties (4 custom styles + 3 default styles).');
- $this->assertChildExists($secondFontElement, 'b');
- $this->assertChildExists($secondFontElement, 'i');
- $this->assertChildExists($secondFontElement, 'u');
- $this->assertChildExists($secondFontElement, 'strike');
- $this->assertFirstChildHasAttributeEquals((string) Writer::DEFAULT_FONT_SIZE, $secondFontElement, 'sz', 'val');
- $this->assertFirstChildHasAttributeEquals(Color::toARGB(Style::DEFAULT_FONT_COLOR), $secondFontElement, 'color', 'rgb');
- $this->assertFirstChildHasAttributeEquals(Writer::DEFAULT_FONT_NAME, $secondFontElement, 'name', 'val');
-
- // Third font should contain data from the second created style
- $thirdFontElement = $fontElements->item(2);
- $this->assertChildrenNumEquals(3, $thirdFontElement, 'The font should only have 3 properties.');
- $this->assertFirstChildHasAttributeEquals('15', $thirdFontElement, 'sz', 'val');
- $this->assertFirstChildHasAttributeEquals(Color::toARGB(Color::RED), $thirdFontElement, 'color', 'rgb');
- $this->assertFirstChildHasAttributeEquals('Cambria', $thirdFontElement, 'name', 'val');
- }
-
- /**
- * @return void
- */
- public function testAddRowWithStyleShouldApplyStyleToCells()
- {
- $fileName = 'test_add_row_with_style_should_apply_style_to_cells.xlsx';
- $dataRows = [
- ['xlsx--11'],
- ['xlsx--21'],
- ['xlsx--31'],
- ];
- $style = (new StyleBuilder())->setFontBold()->build();
- $style2 = (new StyleBuilder())->setFontSize(15)->build();
-
- $this->writeToXLSXFileWithMultipleStyles($dataRows, $fileName, [$style, $style2, null]);
-
- $cellDomElements = $this->getCellElementsFromSheetXmlFile($fileName);
- $this->assertEquals(3, count($cellDomElements), 'There should be 3 cells.');
-
- $this->assertEquals('1', $cellDomElements[0]->getAttribute('s'));
- $this->assertEquals('2', $cellDomElements[1]->getAttribute('s'));
- $this->assertEquals('0', $cellDomElements[2]->getAttribute('s'));
- }
-
- /**
- * @return void
- */
- public function testAddRowWithStyleShouldApplyStyleToEmptyCellsIfNeeded()
- {
- $fileName = 'test_add_row_with_style_should_apply_style_to_empty_cells_if_needed.xlsx';
- $dataRows = [
- ['xlsx--11', '', 'xlsx--13'],
- ['xlsx--21', '', 'xlsx--23'],
- ['xlsx--31', '', 'xlsx--33'],
- ['xlsx--41', '', 'xlsx--43'],
- ];
-
- $styleWithFont = (new StyleBuilder())->setFontBold()->build();
- $styleWithBackground = (new StyleBuilder())->setBackgroundColor(Color::BLUE)->build();
-
- $border = (new BorderBuilder())->setBorderBottom(Color::GREEN)->build();
- $styleWithBorder = (new StyleBuilder())->setBorder($border)->build();
-
- $this->writeToXLSXFileWithMultipleStyles($dataRows, $fileName, [null, $styleWithFont, $styleWithBackground, $styleWithBorder]);
-
- $cellDomElements = $this->getCellElementsFromSheetXmlFile($fileName);
-
- // The first and second rows should not have a reference to the empty cell
- // The other rows should have the reference because style should be applied to them
- // So that's: 2 + 2 + 3 + 3 = 10 cells
- $this->assertEquals(10, count($cellDomElements));
-
- // First row has 2 styled cells
- $this->assertEquals('0', $cellDomElements[0]->getAttribute('s'));
- $this->assertEquals('0', $cellDomElements[1]->getAttribute('s'));
-
- // Second row has 2 styled cells
- $this->assertEquals('1', $cellDomElements[2]->getAttribute('s'));
- $this->assertEquals('1', $cellDomElements[3]->getAttribute('s'));
-
- // Third row has 3 styled cells
- $this->assertEquals('2', $cellDomElements[4]->getAttribute('s'));
- $this->assertEquals('2', $cellDomElements[5]->getAttribute('s'));
- $this->assertEquals('2', $cellDomElements[6]->getAttribute('s'));
-
- // Third row has 3 styled cells
- $this->assertEquals('3', $cellDomElements[7]->getAttribute('s'));
- $this->assertEquals('3', $cellDomElements[8]->getAttribute('s'));
- $this->assertEquals('3', $cellDomElements[9]->getAttribute('s'));
- }
-
- /**
- * @return void
- */
- public function testAddRowWithStyleShouldReuseDuplicateStyles()
- {
- $fileName = 'test_add_row_with_style_should_reuse_duplicate_styles.xlsx';
- $dataRows = [
- ['xlsx--11'],
- ['xlsx--21'],
- ];
- $style = (new StyleBuilder())->setFontBold()->build();
-
- $this->writeToXLSXFile($dataRows, $fileName, $style);
-
- $cellDomElements = $this->getCellElementsFromSheetXmlFile($fileName);
- $this->assertEquals('1', $cellDomElements[0]->getAttribute('s'));
- $this->assertEquals('1', $cellDomElements[1]->getAttribute('s'));
- }
-
- /**
- * @return void
- */
- public function testAddRowWithStyleShouldAddWrapTextAlignmentInfoInStylesXmlFileIfSpecified()
- {
- $fileName = 'test_add_row_with_style_should_add_wrap_text_alignment.xlsx';
- $dataRows = [
- ['xlsx--11', 'xlsx--12'],
- ];
- $style = (new StyleBuilder())->setShouldWrapText()->build();
-
- $this->writeToXLSXFile($dataRows, $fileName, $style);
-
- $cellXfsDomElement = $this->getXmlSectionFromStylesXmlFile($fileName, 'cellXfs');
- $xfElement = $cellXfsDomElement->getElementsByTagName('xf')->item(1);
- $this->assertEquals(1, $xfElement->getAttribute('applyAlignment'));
- $this->assertFirstChildHasAttributeEquals('1', $xfElement, 'alignment', 'wrapText');
- }
-
- /**
- * @return void
- */
- public function testAddRowWithStyleShouldApplyWrapTextIfCellContainsNewLine()
- {
- $fileName = 'test_add_row_with_style_should_apply_wrap_text_if_new_lines.xlsx';
- $dataRows = [
- ["xlsx--11\nxlsx--11"],
- ['xlsx--21'],
- ];
-
- $this->writeToXLSXFile($dataRows, $fileName, $this->defaultStyle);
-
- $cellXfsDomElement = $this->getXmlSectionFromStylesXmlFile($fileName, 'cellXfs');
- $xfElement = $cellXfsDomElement->getElementsByTagName('xf')->item(1);
- $this->assertEquals(1, $xfElement->getAttribute('applyAlignment'));
- $this->assertFirstChildHasAttributeEquals('1', $xfElement, 'alignment', 'wrapText');
- }
-
- /**
- * @return void
- */
- public function testAddBackgroundColor()
- {
- $fileName = 'test_add_background_color.xlsx';
- $dataRows = [
- ["BgColor"],
- ];
- $style = (new StyleBuilder())->setBackgroundColor(Color::WHITE)->build();
- $this->writeToXLSXFile($dataRows, $fileName, $style);
- $fillsDomElement = $this->getXmlSectionFromStylesXmlFile($fileName, 'fills');
- $this->assertEquals(3, $fillsDomElement->getAttribute('count'), 'There should be 3 fills, including the 2 default ones');
-
- $fillsElements = $fillsDomElement->getElementsByTagName('fill');
-
- $thirdFillElement = $fillsElements->item(2); // Zero based
- $fgColor = $thirdFillElement->getElementsByTagName('fgColor')->item(0)->getAttribute('rgb');
-
- $this->assertEquals(Color::WHITE, $fgColor, 'The foreground color should equal white');
-
- $styleXfsElements = $this->getXmlSectionFromStylesXmlFile($fileName, 'cellXfs');
- $this->assertEquals(2, $styleXfsElements->getAttribute('count'), '2 cell xfs present - a default one and a custom one');
-
- $customFillId = $styleXfsElements->lastChild->getAttribute('fillId');
- $this->assertEquals(2, (int)$customFillId, 'The custom fill id should have the index 2');
- }
-
- /**
- * @return void
- */
- public function testReuseBackgroundColorSharedDefinition()
- {
- $fileName = 'test_add_background_color_shared_definition.xlsx';
- $dataRows = [
- ["row-bold-background-red"],
- ["row-background-red"],
- ];
-
- $styles = [
- (new StyleBuilder())->setBackgroundColor(Color::RED)->setFontBold()->build(),
- (new StyleBuilder())->setBackgroundColor(Color::RED)->build()
- ];
-
- $this->writeToXLSXFileWithMultipleStyles($dataRows, $fileName, $styles);
-
- $fillsDomElement = $this->getXmlSectionFromStylesXmlFile($fileName, 'fills');
- $this->assertEquals(
- 3,
- $fillsDomElement->getAttribute('count'),
- 'There should be 3 fills, including the 2 default ones'
- );
-
- $styleXfsElements = $this->getXmlSectionFromStylesXmlFile($fileName, 'cellXfs');
- $this->assertEquals(
- 3,
- $styleXfsElements->getAttribute('count'),
- '3 cell xfs present - a default one and two custom ones'
- );
-
- $firstCustomId = $styleXfsElements->childNodes->item(1)->getAttribute('fillId');
- $this->assertEquals(2, (int)$firstCustomId, 'The first custom fill id should have the index 2');
-
- $secondCustomId = $styleXfsElements->childNodes->item(2)->getAttribute('fillId');
- $this->assertEquals(2, (int)$secondCustomId, 'The second custom fill id should have the index 2');
- }
-
- /**
- * @return void
- */
- public function testBorders()
- {
- $fileName = 'test_borders.xlsx';
-
- $dataRows = [
- ['row-with-border-bottom-green-thick-solid'],
- ['row-without-border'],
- ['row-with-border-top-red-thin-dashed'],
- ];
-
- $borderBottomGreenThickSolid = (new BorderBuilder())
- ->setBorderBottom(Color::GREEN, Border::WIDTH_THICK, Border::STYLE_SOLID)->build();
-
-
- $borderTopRedThinDashed = (new BorderBuilder())
- ->setBorderTop(Color::RED, Border::WIDTH_THIN, Border::STYLE_DASHED)->build();
-
- $styles = [
- (new StyleBuilder())->setBorder($borderBottomGreenThickSolid)->build(),
- (new StyleBuilder())->build(),
- (new StyleBuilder())->setBorder($borderTopRedThinDashed)->build(),
- ];
-
- $this->writeToXLSXFileWithMultipleStyles($dataRows, $fileName, $styles);
- $borderElements = $this->getXmlSectionFromStylesXmlFile($fileName, 'borders');
- $this->assertEquals(3, $borderElements->getAttribute('count'), '3 borders present');
-
- $styleXfsElements = $this->getXmlSectionFromStylesXmlFile($fileName, 'cellXfs');
- $this->assertEquals(3, $styleXfsElements->getAttribute('count'), '3 cell xfs present');
- }
-
- /**
- * @return void
- */
- public function testBordersCorrectOrder()
- {
- // Border should be Left, Right, Top, Bottom
- $fileName = 'test_borders_correct_order.xlsx';
-
- $dataRows = [
- ['I am a teapot'],
- ];
-
- $borders = (new BorderBuilder())
- ->setBorderRight()
- ->setBorderTop()
- ->setBorderLeft()
- ->setBorderBottom()
- ->build();
-
- $style = (new StyleBuilder())->setBorder($borders)->build();
- $this->writeToXLSXFile($dataRows, $fileName, $style);
- $borderElements = $this->getXmlSectionFromStylesXmlFile($fileName, 'borders');
-
- $correctOrdering = [
- 'left', 'right', 'top', 'bottom'
- ];
-
- /** @var $borderNode \DOMElement */
- foreach ($borderElements->childNodes as $borderNode) {
- $borderParts = $borderNode->childNodes;
- $ordering = [];
-
- /** @var $part \DOMText */
- foreach ($borderParts as $part) {
- if ($part instanceof \DOMElement) {
- $ordering[] = $part->nodeName;
- }
- }
-
- $this->assertEquals($correctOrdering, $ordering, 'The border parts are in correct ordering');
- };
- }
-
- /**
- * @return void
- */
- public function testSetDefaultRowStyle()
- {
- $fileName = 'test_set_default_row_style.xlsx';
- $dataRows = [['xlsx--11']];
-
- $defaultFontSize = 50;
- $defaultStyle = (new StyleBuilder())->setFontSize($defaultFontSize)->build();
-
- $this->writeToXLSXFileWithDefaultStyle($dataRows, $fileName, $defaultStyle);
-
- $fontsDomElement = $this->getXmlSectionFromStylesXmlFile($fileName, 'fonts');
- $fontElements = $fontsDomElement->getElementsByTagName('font');
- $this->assertEquals(1, $fontElements->length, 'There should only be the default font.');
-
- $defaultFontElement = $fontElements->item(0);
- $this->assertFirstChildHasAttributeEquals((string) $defaultFontSize, $defaultFontElement, 'sz', 'val');
- }
-
- /**
- * @return void
- */
- public function testReUseBorders()
- {
- $fileName = 'test_reuse_borders.xlsx';
-
- $borderLeft = (new BorderBuilder())->setBorderLeft()->build();
- $borderLeftStyle = (new StyleBuilder())->setBorder($borderLeft)->build();
-
- $borderRight = (new BorderBuilder())->setBorderRight(Color::RED, Border::WIDTH_THICK)->build();
- $borderRightStyle = (new StyleBuilder())->setBorder($borderRight)->build();
-
- $fontStyle = (new StyleBuilder())->setFontBold()->build();
- $emptyStyle = (new StyleBuilder())->build();
-
- $borderRightFontBoldStyle = $borderRightStyle->mergeWith($fontStyle);
-
- $dataRows = [
- ['Border-Left'],
- ['Empty'],
- ['Font-Bold'],
- ['Border-Right'],
- ['Border-Right-Font-Bold'],
- ];
-
- $styles = [
- $borderLeftStyle,
- $emptyStyle,
- $fontStyle,
- $borderRightStyle,
- $borderRightFontBoldStyle
- ];
-
- $this->writeToXLSXFileWithMultipleStyles($dataRows, $fileName, $styles);
- $borderElements = $this->getXmlSectionFromStylesXmlFile($fileName, 'borders');
-
- $this->assertEquals(3, $borderElements->getAttribute('count'), '3 borders in count attribute');
- $this->assertEquals(3, $borderElements->childNodes->length, '3 border childnodes present');
-
- /** @var \DOMElement $firstBorder */
- $firstBorder = $borderElements->childNodes->item(1); // 0 = default border
- $leftStyle = $firstBorder->getElementsByTagName('left')->item(0)->getAttribute('style');
- $this->assertEquals('medium', $leftStyle, 'Style is medium');
-
- /** @var \DOMElement $secondBorder */
- $secondBorder = $borderElements->childNodes->item(2);
- $rightStyle = $secondBorder->getElementsByTagName('right')->item(0)->getAttribute('style');
- $this->assertEquals('thick', $rightStyle, 'Style is thick');
-
- $styleXfsElements = $this->getXmlSectionFromStylesXmlFile($fileName, 'cellXfs');
-
- // A rather relaxed test
- // Where a border is applied - the borderId attribute has to be greater than 0
- $bordersApplied = 0;
- /** @var \DOMElement $node */
- foreach ($styleXfsElements->childNodes as $node) {
- if ($node->getAttribute('applyBorder') == 1) {
- $bordersApplied++;
- $this->assertTrue((int)$node->getAttribute('borderId') > 0, 'BorderId is greater than 0');
- } else {
- $this->assertTrue((int)$node->getAttribute('borderId') === 0, 'BorderId is 0');
- }
- }
-
- $this->assertEquals(3, $bordersApplied, 'Three borders have been applied');
- }
-
- /**
- * @param array $allRows
- * @param string $fileName
- * @param \Box\Spout\Writer\Style\Style $style
- * @return Writer
- */
- private function writeToXLSXFile($allRows, $fileName, $style)
- {
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- /** @var \Box\Spout\Writer\XLSX\Writer $writer */
- $writer = WriterFactory::create(Type::XLSX);
- $writer->setShouldUseInlineStrings(true);
-
- $writer->openToFile($resourcePath);
- $writer->addRowsWithStyle($allRows, $style);
- $writer->close();
-
- return $writer;
- }
-
- /**
- * @param array $allRows
- * @param string $fileName
- * @param \Box\Spout\Writer\Style\Style|null $defaultStyle
- * @return Writer
- */
- private function writeToXLSXFileWithDefaultStyle($allRows, $fileName, $defaultStyle)
- {
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- /** @var \Box\Spout\Writer\XLSX\Writer $writer */
- $writer = WriterFactory::create(Type::XLSX);
- $writer->setShouldUseInlineStrings(true);
- $writer->setDefaultRowStyle($defaultStyle);
-
- $writer->openToFile($resourcePath);
- $writer->addRows($allRows);
- $writer->close();
-
- return $writer;
- }
-
- /**
- * @param array $allRows
- * @param string $fileName
- * @param \Box\Spout\Writer\Style\Style|null[] $styles
- * @return Writer
- */
- private function writeToXLSXFileWithMultipleStyles($allRows, $fileName, $styles)
- {
- // there should be as many rows as there are styles passed in
- $this->assertEquals(count($allRows), count($styles));
-
- $this->createGeneratedFolderIfNeeded($fileName);
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- /** @var \Box\Spout\Writer\XLSX\Writer $writer */
- $writer = WriterFactory::create(Type::XLSX);
- $writer->setShouldUseInlineStrings(true);
-
- $writer->openToFile($resourcePath);
- for ($i = 0; $i < count($allRows); $i++) {
- if ($styles[$i] === null) {
- $writer->addRow($allRows[$i]);
- } else {
- $writer->addRowWithStyle($allRows[$i], $styles[$i]);
- }
- }
- $writer->close();
-
- return $writer;
- }
-
- /**
- * @param string $fileName
- * @param string $section
- * @return \DomElement
- */
- private function getXmlSectionFromStylesXmlFile($fileName, $section)
- {
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $xmlReader = new XMLReader();
- $xmlReader->openFileInZip($resourcePath, 'xl/styles.xml');
- $xmlReader->readUntilNodeFound($section);
-
- $xmlSection = $xmlReader->expand();
-
- $xmlReader->close();
-
- return $xmlSection;
- }
-
- /**
- * @param string $fileName
- * @return \DOMNode[]
- */
- private function getCellElementsFromSheetXmlFile($fileName)
- {
- $cellElements = [];
-
- $resourcePath = $this->getGeneratedResourcePath($fileName);
-
- $xmlReader = new XMLReader();
- $xmlReader->openFileInZip($resourcePath, 'xl/worksheets/sheet1.xml');
-
- while ($xmlReader->read()) {
- if ($xmlReader->isPositionedOnStartingNode('c')) {
- $cellElements[] = $xmlReader->expand();
- }
- }
-
- $xmlReader->close();
-
- return $cellElements;
- }
-
- /**
- * @param string $expectedValue
- * @param \DOMNode $parentElement
- * @param string $childTagName
- * @param string $attributeName
- * @return void
- */
- private function assertFirstChildHasAttributeEquals($expectedValue, $parentElement, $childTagName, $attributeName)
- {
- $this->assertEquals($expectedValue, $parentElement->getElementsByTagName($childTagName)->item(0)->getAttribute($attributeName));
- }
-
- /**
- * @param int $expectedNumber
- * @param \DOMNode $parentElement
- * @param string $message
- * @return void
- */
- private function assertChildrenNumEquals($expectedNumber, $parentElement, $message)
- {
- $this->assertEquals($expectedNumber, $parentElement->getElementsByTagName('*')->length, $message);
- }
-
- /**
- * @param \DOMNode $parentElement
- * @param string $childTagName
- * @return void
- */
- private function assertChildExists($parentElement, $childTagName)
- {
- $this->assertEquals(1, $parentElement->getElementsByTagName($childTagName)->length);
- }
-}
diff --git a/tests/bootstrap.php b/tests/bootstrap.php
deleted file mode 100644
index 902b4e9..0000000
--- a/tests/bootstrap.php
+++ /dev/null
@@ -1,9 +0,0 @@
- |