Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
582da8403d | ||
|
|
8b666fc6cd | ||
|
|
f8aab6eefd | ||
|
|
c4c6dddb20 | ||
|
|
6c97141679 | ||
|
|
9c8cc05364 | ||
|
|
2a9400dfca | ||
|
|
8ef6bdac62 | ||
|
|
46c246e6a4 | ||
|
|
8fd606ae4f | ||
|
|
6767386daf | ||
|
|
3395d3abb3 | ||
|
|
d1c4d563c1 | ||
|
|
01cc8b3da0 | ||
|
|
45980195cd | ||
|
|
a1a1077677 | ||
|
|
16d0290a17 | ||
|
|
f8c39287ad | ||
|
|
118810de22 | ||
|
|
3720c9ea1c | ||
|
|
6124528161 | ||
|
|
818ec2488c | ||
|
|
aa7978146f | ||
|
|
d6e707c5fe | ||
|
|
03ae367fb3 | ||
|
|
ac48dce334 | ||
|
|
e147c580ca | ||
|
|
7615acf398 | ||
|
|
1d38bb00c5 | ||
|
|
79d947a6b3 | ||
|
|
dd3cc5bf47 | ||
|
|
0a5be41c53 | ||
|
|
d2ba6d884c | ||
|
|
e4154dfdc3 | ||
|
|
3f0016f753 | ||
|
|
bc009a3241 | ||
|
|
0f8e7a8f58 | ||
|
|
156fd29a44 | ||
|
|
ef171910b9 | ||
|
|
5949cb2442 | ||
|
|
108a92e259 | ||
|
|
9fb1427944 | ||
|
|
a8f1fba854 | ||
|
|
1812b4f996 | ||
|
|
b4ace972e7 | ||
|
|
c428daff5a | ||
|
|
5908443583 | ||
|
|
050672755d | ||
|
|
e1928eb68a | ||
|
|
9467b5a810 | ||
|
|
2699ffbcae | ||
|
|
3559bc8834 | ||
|
|
506d682e74 | ||
|
|
7efab5576d | ||
|
|
366f121eb0 | ||
|
|
f8d0ac2682 | ||
|
|
82377403ff | ||
|
|
e0c84f77b1 | ||
|
|
b78227c370 | ||
|
|
444308d42c | ||
|
|
353d4e86a5 | ||
|
|
f043f8d4d0 | ||
|
|
c8ddcf5441 | ||
|
|
4a346cef0c | ||
|
|
1c8934790d | ||
|
|
2a1925bc51 | ||
|
|
2183ff6738 | ||
|
|
380ee524a5 | ||
|
|
21263a0730 | ||
|
|
0104714cbd | ||
|
|
611a091290 |
No files matched your search
@@ -7,6 +7,10 @@ php:
|
||||
- 7.0
|
||||
- hhvm
|
||||
|
||||
cache:
|
||||
directories:
|
||||
- $HOME/.composer/cache
|
||||
|
||||
install:
|
||||
- composer install --no-interaction --prefer-source
|
||||
|
||||
|
||||
@@ -7,9 +7,10 @@
|
||||
[](https://packagist.org/packages/box/spout)
|
||||
[](https://packagist.org/packages/box/spout)
|
||||
|
||||
Spout is a PHP library to read and write CSV and XLSX files, in a fast and scalable way.
|
||||
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 10MB).
|
||||
|
||||
Join the community and come discuss about Spout: [](https://gitter.im/box/spout?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -17,16 +18,9 @@ Contrary to other file readers or writers, it is capable of processing very larg
|
||||
|
||||
Spout can be installed directly from [Composer](https://getcomposer.org/).
|
||||
|
||||
Add "box/spout" as a dependency in your project's composer.json file:
|
||||
```json
|
||||
"require": {
|
||||
"box/spout": "~2.0"
|
||||
}
|
||||
Run the following command:
|
||||
```
|
||||
|
||||
Then run the install command from Composer:
|
||||
```
|
||||
php composer.phar install
|
||||
$ composer require box/spout
|
||||
```
|
||||
|
||||
### Manual installation
|
||||
@@ -55,71 +49,51 @@ require_once '[PATH/TO]/src/Spout/Autoloader/autoload.php'; // don't forget to c
|
||||
|
||||
### Reader
|
||||
|
||||
#### How to read a CSV file?
|
||||
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::CSV);
|
||||
$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 ($reader->getRowIterator() as $row) {
|
||||
// do stuff
|
||||
foreach ($sheet->getRowIterator() as $row) {
|
||||
// do stuff with the row
|
||||
}
|
||||
}
|
||||
|
||||
$reader->close();
|
||||
```
|
||||
|
||||
#### How to read a XLSX file?
|
||||
|
||||
```php
|
||||
use Box\Spout\Reader\ReaderFactory;
|
||||
use Box\Spout\Common\Type;
|
||||
|
||||
$reader = ReaderFactory::create(Type::XLSX);
|
||||
$reader->open($filePath);
|
||||
|
||||
foreach ($reader->getSheetIterator() as $sheet) {
|
||||
foreach ($reader->getRowIterator() as $row) {
|
||||
// do stuff
|
||||
}
|
||||
}
|
||||
|
||||
$reader->close();
|
||||
```
|
||||
|
||||
If there are multiple sheets in the file, the reader will read through all of them sequentially.
|
||||
If there are multiple sheets in the file, the reader will read all of them sequentially.
|
||||
|
||||
### Writer
|
||||
|
||||
### How to create a CSV file?
|
||||
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::CSV);
|
||||
$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->close();
|
||||
```
|
||||
|
||||
### How to create a XLSX file?
|
||||
|
||||
```php
|
||||
use Box\Spout\Writer\WriterFactory;
|
||||
use Box\Spout\Common\Type;
|
||||
|
||||
$writer = WriterFactory::create(Type::XLSX);
|
||||
$writer->openToBrowser($fileName); // stream data directly to the browser
|
||||
$writer->addRows($multipleRows); // add multiple rows at a time
|
||||
|
||||
$writer->close();
|
||||
```
|
||||
|
||||
For XLSX files, the number of rows per sheet is limited to 1,048,576 (see [Office OpenXML specs](http://office.microsoft.com/en-us/excel-help/excel-specifications-and-limits-HP010073849.aspx)). By default, once this limit is reached, the writer will automatically create a new sheet and continue writing data into it.
|
||||
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
|
||||
@@ -143,9 +117,74 @@ $reader->setEncoding('UTF-16LE');
|
||||
|
||||
The writer always generate CSV files encoded in UTF-8, with a BOM.
|
||||
|
||||
### Configuring the XLSX writer
|
||||
|
||||
#### Strings storage
|
||||
### Configuring the XLSX and ODS writers
|
||||
|
||||
#### Row styling
|
||||
|
||||
It is possible to apply some formatting options to a row. Spout supports fonts 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()
|
||||
->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();
|
||||
```
|
||||
|
||||
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::setFontSize(Color::BLUE)`<br>`StyleBuilder::setFontSize(Color::rgb(0, 128, 255))`
|
||||
Alignment | Wrap text | `StyleBuilder::setShouldWrapText()`
|
||||
|
||||
|
||||
#### 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)
|
||||
@@ -161,33 +200,14 @@ $writer->setShouldUseInlineStrings(true); // default (and recommended) value
|
||||
$writer->setShouldUseInlineStrings(false); // will use shared strings
|
||||
```
|
||||
|
||||
#### New sheet creation
|
||||
> ##### 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!
|
||||
|
||||
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::XLSX);
|
||||
$writer->setShouldCreateNewSheetsAutomatically(true); // default value
|
||||
$writer->setShouldCreateNewSheetsAutomatically(false); // will stop writing new data when limit is reached
|
||||
```
|
||||
### Playing with sheets
|
||||
|
||||
#### Using custom temporary folder
|
||||
|
||||
Processing XLSX 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);
|
||||
```
|
||||
|
||||
### Playing with XLSX sheets
|
||||
|
||||
When creating a XLSX file, it is possible to control in which sheet the data will be written to.
|
||||
At any point, you can retrieve the current sheet and set the current sheet:
|
||||
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
|
||||
@@ -217,9 +237,19 @@ $sheetName = $sheet->getName();
|
||||
|
||||
// Customizing the sheet name when writing
|
||||
$sheet = $writer->getCurrentSheet();
|
||||
$sheetName = $sheet->setName('My custom name');
|
||||
$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.
|
||||
|
||||
|
||||
### Fluent interface
|
||||
|
||||
Because fluent interfaces are great, you can use them with Spout:
|
||||
@@ -239,8 +269,8 @@ $writer->setTempFolder($customTempFolderPath)
|
||||
|
||||
## Running tests
|
||||
|
||||
On the `master` branch, only unit and functional tests are included. The performance requires 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.
|
||||
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:
|
||||
|
||||
@@ -263,13 +293,15 @@ Same goes with reading. Only one row at a time is stored in memory. A special te
|
||||
|
||||
Here are a few numbers regarding the performance of Spout:
|
||||
|
||||
| | 2,000 rows (6,000 cells) | 200,000 rows (600,000 cells) | 2,000,000 rows (6,000,000 cells) |
|
||||
| :------------------------------- | :----------------------: | :--------------------------: | :------------------------------: |
|
||||
| Read CSV | < 1 second | 4 seconds | 2-3 minutes |
|
||||
| Write CSV | < 1 second | 2 seconds | 2-3 minutes |
|
||||
| Read XLSX (using inline strings) | < 1 second | 35-40 seconds | 18-20 minutes |
|
||||
| Read XLSX (using shared strings) | 1 second | 1-2 minutes | 35-40 minutes |
|
||||
| Write XLSX | 1 second | 20-25 seconds | 8-10 minutes |
|
||||
| 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<br>*inline strings* | < 1 second | 35-40 seconds | 18-20 minutes |
|
||||
| | Read<br>*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?
|
||||
|
||||
@@ -281,6 +313,8 @@ So the larger the file would be, the more memory would be consumed, preventing y
|
||||
|
||||
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:<br>
|
||||
[](https://gitter.im/box/spout?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
|
||||
|
||||
## Copyright and License
|
||||
|
||||
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "box/spout",
|
||||
"description": "PHP Library to read and write CSV and XLSX files, in a fast and scalable way",
|
||||
"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","excel","spreadsheet","scale","memory","stream","ooxml"],
|
||||
"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": [
|
||||
|
||||
Generated
+49
-49
@@ -4,7 +4,7 @@
|
||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
|
||||
"This file is @generated automatically"
|
||||
],
|
||||
"hash": "3c0d36250693792d14bc19f14250fec6",
|
||||
"hash": "0866be323931eaa6e9431b3bbf0a817a",
|
||||
"packages": [],
|
||||
"packages-dev": [
|
||||
{
|
||||
@@ -585,16 +585,16 @@
|
||||
},
|
||||
{
|
||||
"name": "phpspec/prophecy",
|
||||
"version": "v1.4.1",
|
||||
"version": "v1.5.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/phpspec/prophecy.git",
|
||||
"reference": "3132b1f44c7bf2ec4c7eb2d3cb78fdeca760d373"
|
||||
"reference": "4745ded9307786b730d7a60df5cb5a6c43cf95f7"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/phpspec/prophecy/zipball/3132b1f44c7bf2ec4c7eb2d3cb78fdeca760d373",
|
||||
"reference": "3132b1f44c7bf2ec4c7eb2d3cb78fdeca760d373",
|
||||
"url": "https://api.github.com/repos/phpspec/prophecy/zipball/4745ded9307786b730d7a60df5cb5a6c43cf95f7",
|
||||
"reference": "4745ded9307786b730d7a60df5cb5a6c43cf95f7",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -641,20 +641,20 @@
|
||||
"spy",
|
||||
"stub"
|
||||
],
|
||||
"time": "2015-04-27 22:15:08"
|
||||
"time": "2015-08-13 10:07:40"
|
||||
},
|
||||
{
|
||||
"name": "phpunit/php-code-coverage",
|
||||
"version": "2.1.9",
|
||||
"version": "2.2.2",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/sebastianbergmann/php-code-coverage.git",
|
||||
"reference": "5bd48b86cd282da411bb80baac1398ce3fefac41"
|
||||
"reference": "2d7c03c0e4e080901b8f33b2897b0577be18a13c"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/5bd48b86cd282da411bb80baac1398ce3fefac41",
|
||||
"reference": "5bd48b86cd282da411bb80baac1398ce3fefac41",
|
||||
"url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/2d7c03c0e4e080901b8f33b2897b0577be18a13c",
|
||||
"reference": "2d7c03c0e4e080901b8f33b2897b0577be18a13c",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -662,7 +662,7 @@
|
||||
"phpunit/php-file-iterator": "~1.3",
|
||||
"phpunit/php-text-template": "~1.2",
|
||||
"phpunit/php-token-stream": "~1.3",
|
||||
"sebastian/environment": "~1.0",
|
||||
"sebastian/environment": "^1.3.2",
|
||||
"sebastian/version": "~1.0"
|
||||
},
|
||||
"require-dev": {
|
||||
@@ -677,7 +677,7 @@
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "2.1.x-dev"
|
||||
"dev-master": "2.2.x-dev"
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
@@ -703,7 +703,7 @@
|
||||
"testing",
|
||||
"xunit"
|
||||
],
|
||||
"time": "2015-07-26 12:54:47"
|
||||
"time": "2015-08-04 03:42:39"
|
||||
},
|
||||
{
|
||||
"name": "phpunit/php-file-iterator",
|
||||
@@ -836,16 +836,16 @@
|
||||
},
|
||||
{
|
||||
"name": "phpunit/php-token-stream",
|
||||
"version": "1.4.3",
|
||||
"version": "1.4.6",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/sebastianbergmann/php-token-stream.git",
|
||||
"reference": "7a9b0969488c3c54fd62b4d504b3ec758fd005d9"
|
||||
"reference": "3ab72c62e550370a6cd5dc873e1a04ab57562f5b"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/7a9b0969488c3c54fd62b4d504b3ec758fd005d9",
|
||||
"reference": "7a9b0969488c3c54fd62b4d504b3ec758fd005d9",
|
||||
"url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/3ab72c62e550370a6cd5dc873e1a04ab57562f5b",
|
||||
"reference": "3ab72c62e550370a6cd5dc873e1a04ab57562f5b",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -881,20 +881,20 @@
|
||||
"keywords": [
|
||||
"tokenizer"
|
||||
],
|
||||
"time": "2015-06-19 03:43:16"
|
||||
"time": "2015-08-16 08:51:00"
|
||||
},
|
||||
{
|
||||
"name": "phpunit/phpunit",
|
||||
"version": "4.7.7",
|
||||
"version": "4.8.5",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/sebastianbergmann/phpunit.git",
|
||||
"reference": "9b97f9d807b862c2de2a36e86690000801c85724"
|
||||
"reference": "9b7417edaf28059ea63d86be941e6004dbfcc0cc"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/9b97f9d807b862c2de2a36e86690000801c85724",
|
||||
"reference": "9b97f9d807b862c2de2a36e86690000801c85724",
|
||||
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/9b7417edaf28059ea63d86be941e6004dbfcc0cc",
|
||||
"reference": "9b7417edaf28059ea63d86be941e6004dbfcc0cc",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -904,7 +904,7 @@
|
||||
"ext-reflection": "*",
|
||||
"ext-spl": "*",
|
||||
"php": ">=5.3.3",
|
||||
"phpspec/prophecy": "~1.3,>=1.3.1",
|
||||
"phpspec/prophecy": "^1.3.1",
|
||||
"phpunit/php-code-coverage": "~2.1",
|
||||
"phpunit/php-file-iterator": "~1.4",
|
||||
"phpunit/php-text-template": "~1.2",
|
||||
@@ -912,7 +912,7 @@
|
||||
"phpunit/phpunit-mock-objects": "~2.3",
|
||||
"sebastian/comparator": "~1.1",
|
||||
"sebastian/diff": "~1.2",
|
||||
"sebastian/environment": "~1.2",
|
||||
"sebastian/environment": "~1.3",
|
||||
"sebastian/exporter": "~1.2",
|
||||
"sebastian/global-state": "~1.0",
|
||||
"sebastian/version": "~1.0",
|
||||
@@ -927,7 +927,7 @@
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "4.7.x-dev"
|
||||
"dev-master": "4.8.x-dev"
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
@@ -953,24 +953,24 @@
|
||||
"testing",
|
||||
"xunit"
|
||||
],
|
||||
"time": "2015-07-13 11:28:34"
|
||||
"time": "2015-08-19 09:20:57"
|
||||
},
|
||||
{
|
||||
"name": "phpunit/phpunit-mock-objects",
|
||||
"version": "2.3.6",
|
||||
"version": "2.3.7",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/sebastianbergmann/phpunit-mock-objects.git",
|
||||
"reference": "18dfbcb81d05e2296c0bcddd4db96cade75e6f42"
|
||||
"reference": "5e2645ad49d196e020b85598d7c97e482725786a"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/sebastianbergmann/phpunit-mock-objects/zipball/18dfbcb81d05e2296c0bcddd4db96cade75e6f42",
|
||||
"reference": "18dfbcb81d05e2296c0bcddd4db96cade75e6f42",
|
||||
"url": "https://api.github.com/repos/sebastianbergmann/phpunit-mock-objects/zipball/5e2645ad49d196e020b85598d7c97e482725786a",
|
||||
"reference": "5e2645ad49d196e020b85598d7c97e482725786a",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"doctrine/instantiator": "~1.0,>=1.0.2",
|
||||
"doctrine/instantiator": "^1.0.2",
|
||||
"php": ">=5.3.3",
|
||||
"phpunit/php-text-template": "~1.2",
|
||||
"sebastian/exporter": "~1.2"
|
||||
@@ -1009,7 +1009,7 @@
|
||||
"mock",
|
||||
"xunit"
|
||||
],
|
||||
"time": "2015-07-10 06:54:24"
|
||||
"time": "2015-08-19 09:14:08"
|
||||
},
|
||||
{
|
||||
"name": "scrutinizer/ocular",
|
||||
@@ -1165,16 +1165,16 @@
|
||||
},
|
||||
{
|
||||
"name": "sebastian/environment",
|
||||
"version": "1.3.0",
|
||||
"version": "1.3.2",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/sebastianbergmann/environment.git",
|
||||
"reference": "4fe0a44cddd8cc19583a024bdc7374eb2fef0b87"
|
||||
"reference": "6324c907ce7a52478eeeaede764f48733ef5ae44"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/4fe0a44cddd8cc19583a024bdc7374eb2fef0b87",
|
||||
"reference": "4fe0a44cddd8cc19583a024bdc7374eb2fef0b87",
|
||||
"url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/6324c907ce7a52478eeeaede764f48733ef5ae44",
|
||||
"reference": "6324c907ce7a52478eeeaede764f48733ef5ae44",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -1211,7 +1211,7 @@
|
||||
"environment",
|
||||
"hhvm"
|
||||
],
|
||||
"time": "2015-07-26 06:42:57"
|
||||
"time": "2015-08-03 06:14:51"
|
||||
},
|
||||
{
|
||||
"name": "sebastian/exporter",
|
||||
@@ -1420,16 +1420,16 @@
|
||||
},
|
||||
{
|
||||
"name": "symfony/console",
|
||||
"version": "v2.7.2",
|
||||
"version": "v2.7.3",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/symfony/Console.git",
|
||||
"reference": "8cf484449130cabfd98dcb4694ca9945802a21ed"
|
||||
"reference": "d6cf02fe73634c96677e428f840704bfbcaec29e"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/symfony/Console/zipball/8cf484449130cabfd98dcb4694ca9945802a21ed",
|
||||
"reference": "8cf484449130cabfd98dcb4694ca9945802a21ed",
|
||||
"url": "https://api.github.com/repos/symfony/Console/zipball/d6cf02fe73634c96677e428f840704bfbcaec29e",
|
||||
"reference": "d6cf02fe73634c96677e428f840704bfbcaec29e",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -1473,11 +1473,11 @@
|
||||
],
|
||||
"description": "Symfony Console Component",
|
||||
"homepage": "https://symfony.com",
|
||||
"time": "2015-07-09 16:07:40"
|
||||
"time": "2015-07-28 15:18:12"
|
||||
},
|
||||
{
|
||||
"name": "symfony/event-dispatcher",
|
||||
"version": "v2.7.2",
|
||||
"version": "v2.7.3",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/symfony/EventDispatcher.git",
|
||||
@@ -1535,7 +1535,7 @@
|
||||
},
|
||||
{
|
||||
"name": "symfony/process",
|
||||
"version": "v2.7.2",
|
||||
"version": "v2.7.3",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/symfony/Process.git",
|
||||
@@ -1584,16 +1584,16 @@
|
||||
},
|
||||
{
|
||||
"name": "symfony/yaml",
|
||||
"version": "v2.7.2",
|
||||
"version": "v2.7.3",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/symfony/Yaml.git",
|
||||
"reference": "4bfbe0ed3909bfddd75b70c094391ec1f142f860"
|
||||
"reference": "71340e996171474a53f3d29111d046be4ad8a0ff"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/symfony/Yaml/zipball/4bfbe0ed3909bfddd75b70c094391ec1f142f860",
|
||||
"reference": "4bfbe0ed3909bfddd75b70c094391ec1f142f860",
|
||||
"url": "https://api.github.com/repos/symfony/Yaml/zipball/71340e996171474a53f3d29111d046be4ad8a0ff",
|
||||
"reference": "71340e996171474a53f3d29111d046be4ad8a0ff",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -1629,7 +1629,7 @@
|
||||
],
|
||||
"description": "Symfony Yaml Component",
|
||||
"homepage": "https://symfony.com",
|
||||
"time": "2015-07-01 11:25:50"
|
||||
"time": "2015-07-28 14:07:07"
|
||||
}
|
||||
],
|
||||
"aliases": [],
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Common\Escaper;
|
||||
|
||||
/**
|
||||
* Class ODS
|
||||
* Provides functions to escape and unescape data for ODS files
|
||||
*
|
||||
* @package Box\Spout\Common\Escaper
|
||||
*/
|
||||
class ODS implements EscaperInterface
|
||||
{
|
||||
/**
|
||||
* 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)
|
||||
{
|
||||
return htmlspecialchars($string, ENT_QUOTES);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)
|
||||
{
|
||||
return htmlspecialchars_decode($string, ENT_QUOTES);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,9 @@ class XLSX implements EscaperInterface
|
||||
/** @var string[] Control characters to be escaped */
|
||||
protected $controlCharactersEscapingMap;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
$this->controlCharactersEscapingMap = $this->getControlCharactersEscapingMap();
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Common\Exception;
|
||||
|
||||
/**
|
||||
* Class BadUsageException
|
||||
*
|
||||
* @package Box\Spout\Common\Exception
|
||||
*/
|
||||
class BadUsageException extends SpoutException
|
||||
{
|
||||
}
|
||||
@@ -5,6 +5,7 @@ namespace Box\Spout\Common\Exception;
|
||||
/**
|
||||
* Class EncodingConversionException
|
||||
*
|
||||
* @api
|
||||
* @package Box\Spout\Common\Exception
|
||||
*/
|
||||
class EncodingConversionException extends SpoutException
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace Box\Spout\Common\Exception;
|
||||
/**
|
||||
* Class IOException
|
||||
*
|
||||
* @api
|
||||
* @package Box\Spout\Common\Exception
|
||||
*/
|
||||
class IOException extends SpoutException
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace Box\Spout\Common\Exception;
|
||||
/**
|
||||
* Class InvalidArgumentException
|
||||
*
|
||||
* @api
|
||||
* @package Box\Spout\Common\Exception
|
||||
*/
|
||||
class InvalidArgumentException extends SpoutException
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace Box\Spout\Common\Exception;
|
||||
* Class SpoutException
|
||||
*
|
||||
* @package Box\Spout\Common\Exception
|
||||
* @abstract
|
||||
*/
|
||||
abstract class SpoutException extends \Exception
|
||||
{
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace Box\Spout\Common\Exception;
|
||||
/**
|
||||
* Class UnsupportedTypeException
|
||||
*
|
||||
* @api
|
||||
* @package Box\Spout\Common\Exception
|
||||
*/
|
||||
class UnsupportedTypeException extends SpoutException
|
||||
|
||||
@@ -164,7 +164,43 @@ class GlobalFunctionsHelper
|
||||
*/
|
||||
public function file_get_contents($filePath)
|
||||
{
|
||||
return file_get_contents($filePath);
|
||||
$realFilePath = $this->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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Common\Helper;
|
||||
|
||||
/**
|
||||
* Class StringHelper
|
||||
* This class provides helper functions to work with strings and multibyte strings.
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*
|
||||
* @package Box\Spout\Common\Helper
|
||||
*/
|
||||
class StringHelper
|
||||
{
|
||||
/** @var bool Whether the mbstring extension is loaded */
|
||||
protected $hasMbstringSupport;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
$this->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;
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,12 @@ namespace Box\Spout\Common;
|
||||
/**
|
||||
* Class Type
|
||||
* This class references the supported types
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
abstract class Type
|
||||
{
|
||||
const CSV = "csv";
|
||||
const XLSX = "xlsx";
|
||||
const CSV = 'csv';
|
||||
const XLSX = 'xlsx';
|
||||
const ODS = 'ods';
|
||||
}
|
||||
@@ -55,6 +55,7 @@ abstract class AbstractReader implements ReaderInterface
|
||||
* 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
|
||||
@@ -71,7 +72,9 @@ abstract class AbstractReader implements ReaderInterface
|
||||
}
|
||||
|
||||
try {
|
||||
$this->openReader($filePath);
|
||||
// Need to use realpath to fix "Can't open file" on some Windows setup
|
||||
$fileRealPath = realpath($filePath);
|
||||
$this->openReader($fileRealPath);
|
||||
$this->isStreamOpened = true;
|
||||
} catch (\Exception $exception) {
|
||||
throw new IOException("Could not open $filePath for reading! ({$exception->getMessage()})");
|
||||
@@ -92,6 +95,7 @@ abstract class AbstractReader implements ReaderInterface
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
@@ -107,6 +111,7 @@ abstract class AbstractReader implements ReaderInterface
|
||||
/**
|
||||
* Closes the reader, preventing any additional reading
|
||||
*
|
||||
* @api
|
||||
* @return void
|
||||
*/
|
||||
public function close()
|
||||
|
||||
@@ -13,6 +13,12 @@ use Box\Spout\Common\Helper\EncodingHelper;
|
||||
*/
|
||||
class RowIterator implements IteratorInterface
|
||||
{
|
||||
/**
|
||||
* If no value is given to stream_get_line(), it defaults to 8192 (which may be too low).
|
||||
* Alignement with other functions like fgets() is discussed here: https://bugs.php.net/bug.php?id=48421
|
||||
*/
|
||||
const MAX_READ_BYTES_PER_LINE = 32768;
|
||||
|
||||
/** @var resource Pointer to the CSV file to read */
|
||||
protected $filePointer;
|
||||
|
||||
@@ -111,26 +117,28 @@ class RowIterator implements IteratorInterface
|
||||
*/
|
||||
public function next()
|
||||
{
|
||||
$lineData = false;
|
||||
$this->hasReachedEndOfFile = $this->globalFunctionsHelper->feof($this->filePointer);
|
||||
|
||||
if (!$this->hasReachedEndOfFile) {
|
||||
do {
|
||||
$utf8EncodedLineData = $this->getNextUTF8EncodedLine();
|
||||
if ($utf8EncodedLineData !== false) {
|
||||
$lineData = $this->globalFunctionsHelper->str_getcsv($utf8EncodedLineData, $this->fieldDelimiter, $this->fieldEnclosure);
|
||||
}
|
||||
$hasNowReachedEndOfFile = $this->globalFunctionsHelper->feof($this->filePointer);
|
||||
} while (($lineData === false && !$hasNowReachedEndOfFile) || $this->isEmptyLine($lineData));
|
||||
if ($this->hasReachedEndOfFile) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($lineData !== false) {
|
||||
$this->rowDataBuffer = $lineData;
|
||||
$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 = $hasNowReachedEndOfFile;
|
||||
do {
|
||||
$lineData = false;
|
||||
$utf8EncodedLineData = $this->getNextUTF8EncodedLine();
|
||||
if ($utf8EncodedLineData !== false) {
|
||||
$lineData = $this->globalFunctionsHelper->str_getcsv($utf8EncodedLineData, $this->fieldDelimiter, $this->fieldEnclosure);
|
||||
}
|
||||
$hasNowReachedEndOfFile = $this->globalFunctionsHelper->feof($this->filePointer);
|
||||
} while (($lineData === false && !$hasNowReachedEndOfFile) || $this->isEmptyLine($lineData));
|
||||
|
||||
if ($lineData !== false) {
|
||||
$this->rowDataBuffer = $lineData;
|
||||
$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 = $hasNowReachedEndOfFile;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,7 +153,7 @@ class RowIterator implements IteratorInterface
|
||||
{
|
||||
// Read until the EOL delimiter or EOF is reached. The delimiter's encoding needs to match the CSV's encoding.
|
||||
$encodedEOLDelimiter = $this->getEncodedEOLDelimiter();
|
||||
$encodedLineData = $this->globalFunctionsHelper->stream_get_line($this->filePointer, 0, $encodedEOLDelimiter);
|
||||
$encodedLineData = $this->globalFunctionsHelper->stream_get_line($this->filePointer, self::MAX_READ_BYTES_PER_LINE, $encodedEOLDelimiter);
|
||||
|
||||
// If the line could have been read, it can be converted to UTF-8
|
||||
$utf8EncodedLineData = ($encodedLineData !== false) ?
|
||||
|
||||
@@ -11,7 +11,7 @@ use Box\Spout\Reader\SheetInterface;
|
||||
*/
|
||||
class Sheet implements SheetInterface
|
||||
{
|
||||
/** @var RowIterator To iterate over the CSV's rows */
|
||||
/** @var \Box\Spout\Reader\CSV\RowIterator To iterate over the CSV's rows */
|
||||
protected $rowIterator;
|
||||
|
||||
/**
|
||||
@@ -27,7 +27,8 @@ class Sheet implements SheetInterface
|
||||
}
|
||||
|
||||
/**
|
||||
* @return RowIterator
|
||||
* @api
|
||||
* @return \Box\Spout\Reader\CSV\RowIterator
|
||||
*/
|
||||
public function getRowIterator()
|
||||
{
|
||||
|
||||
@@ -12,7 +12,7 @@ use Box\Spout\Reader\IteratorInterface;
|
||||
*/
|
||||
class SheetIterator implements IteratorInterface
|
||||
{
|
||||
/** @var Sheet The CSV unique "sheet" */
|
||||
/** @var \Box\Spout\Reader\CSV\Sheet The CSV unique "sheet" */
|
||||
protected $sheet;
|
||||
|
||||
/** @var bool Whether the unique "sheet" has already been read */
|
||||
@@ -67,7 +67,7 @@ class SheetIterator implements IteratorInterface
|
||||
* Return the current element
|
||||
* @link http://php.net/manual/en/iterator.current.php
|
||||
*
|
||||
* @return Sheet
|
||||
* @return \Box\Spout\Reader\CSV\Sheet
|
||||
*/
|
||||
public function current()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Reader\Exception;
|
||||
|
||||
/**
|
||||
* Class IteratorNotRewindableException
|
||||
*
|
||||
* @api
|
||||
* @package Box\Spout\Reader\Exception
|
||||
*/
|
||||
class IteratorNotRewindableException extends ReaderException
|
||||
{
|
||||
}
|
||||
@@ -5,6 +5,7 @@ namespace Box\Spout\Reader\Exception;
|
||||
/**
|
||||
* Class NoSheetsFoundException
|
||||
*
|
||||
* @api
|
||||
* @package Box\Spout\Reader\Exception
|
||||
*/
|
||||
class NoSheetsFoundException extends ReaderException
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace Box\Spout\Reader\Exception;
|
||||
/**
|
||||
* Class ReaderNotOpenedException
|
||||
*
|
||||
* @api
|
||||
* @package Box\Spout\Reader\Exception
|
||||
*/
|
||||
class ReaderNotOpenedException extends ReaderException
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace Box\Spout\Reader\Exception;
|
||||
/**
|
||||
* Class SharedStringNotFoundException
|
||||
*
|
||||
* @api
|
||||
* @package Box\Spout\Reader\Exception
|
||||
*/
|
||||
class SharedStringNotFoundException extends ReaderException
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Reader\ODS\Helper;
|
||||
|
||||
/**
|
||||
* Class CellValueFormatter
|
||||
* This class provides helper functions to format cell values
|
||||
*
|
||||
* @package Box\Spout\Reader\ODS\Helper
|
||||
*/
|
||||
class CellValueFormatter
|
||||
{
|
||||
/** Definition of all possible cell types */
|
||||
const CELL_TYPE_STRING = 'string';
|
||||
const CELL_TYPE_FLOAT = 'float';
|
||||
const CELL_TYPE_BOOLEAN = 'boolean';
|
||||
const CELL_TYPE_DATE = 'date';
|
||||
const CELL_TYPE_TIME = 'time';
|
||||
const CELL_TYPE_CURRENCY = 'currency';
|
||||
const CELL_TYPE_PERCENTAGE = 'percentage';
|
||||
const CELL_TYPE_VOID = 'void';
|
||||
|
||||
/** Definition of XML nodes names used to parse data */
|
||||
const XML_NODE_P = 'p';
|
||||
const XML_NODE_S = 'text:s';
|
||||
|
||||
/** Definition of XML attribute used to parse data */
|
||||
const XML_ATTRIBUTE_TYPE = 'office:value-type';
|
||||
const XML_ATTRIBUTE_VALUE = 'office:value';
|
||||
const XML_ATTRIBUTE_BOOLEAN_VALUE = 'office:boolean-value';
|
||||
const XML_ATTRIBUTE_DATE_VALUE = 'office:date-value';
|
||||
const XML_ATTRIBUTE_TIME_VALUE = 'office:time-value';
|
||||
const XML_ATTRIBUTE_CURRENCY = 'office:currency';
|
||||
const XML_ATTRIBUTE_C = 'text:c';
|
||||
|
||||
/** @var \Box\Spout\Common\Escaper\ODS Used to unescape XML data */
|
||||
protected $escaper;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
/** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
|
||||
$this->escaper = new \Box\Spout\Common\Escaper\ODS();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the (unescaped) correctly marshalled, cell value associated to the given XML node.
|
||||
* @TODO Add other types !!
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
|
||||
$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);
|
||||
$cellValue = is_int($nodeValue) ? intval($nodeValue) : 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|null The value associated with the cell or NULL if invalid date value
|
||||
*/
|
||||
protected function formatDateCellValue($node)
|
||||
{
|
||||
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|null The value associated with the cell or NULL if invalid time value
|
||||
*/
|
||||
protected function formatTimeCellValue($node)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Reader\ODS;
|
||||
|
||||
use Box\Spout\Common\Exception\IOException;
|
||||
use Box\Spout\Reader\AbstractReader;
|
||||
|
||||
/**
|
||||
* Class Reader
|
||||
* This class provides support to read data from a ODS file
|
||||
*
|
||||
* @package Box\Spout\Reader\ODS
|
||||
*/
|
||||
class Reader extends AbstractReader
|
||||
{
|
||||
/** @var \ZipArchive */
|
||||
protected $zip;
|
||||
|
||||
/** @var SheetIterator To iterator over the ODS sheets */
|
||||
protected $sheetIterator;
|
||||
|
||||
/**
|
||||
* 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);
|
||||
} else {
|
||||
throw new IOException("Could not open $filePath for reading.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an iterator to iterate over sheets.
|
||||
*
|
||||
* @return SheetIterator To iterate over sheets
|
||||
*/
|
||||
public 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Reader\ODS;
|
||||
|
||||
use Box\Spout\Common\Exception\IOException;
|
||||
use Box\Spout\Reader\Exception\IteratorNotRewindableException;
|
||||
use Box\Spout\Reader\Exception\XMLProcessingException;
|
||||
use Box\Spout\Reader\IteratorInterface;
|
||||
use Box\Spout\Reader\ODS\Helper\CellValueFormatter;
|
||||
use Box\Spout\Reader\Wrapper\XMLReader;
|
||||
|
||||
/**
|
||||
* Class RowIterator
|
||||
*
|
||||
* @package Box\Spout\Reader\ODS
|
||||
*/
|
||||
class RowIterator implements IteratorInterface
|
||||
{
|
||||
/** Definition of XML nodes names used to parse data */
|
||||
const XML_NODE_TABLE = 'table:table';
|
||||
const XML_NODE_ROW = 'table:table-row';
|
||||
const XML_NODE_CELL = 'table:table-cell';
|
||||
|
||||
/** Definition of XML attribute used to parse data */
|
||||
const XML_ATTRIBUTE_NUM_COLUMNS_REPEATED = 'table:number-columns-repeated';
|
||||
|
||||
/** @var \Box\Spout\Reader\Wrapper\XMLReader The XMLReader object that will help read sheet's XML data */
|
||||
protected $xmlReader;
|
||||
|
||||
/** @var Helper\CellValueFormatter Helper to format cell values */
|
||||
protected $cellValueFormatter;
|
||||
|
||||
/** @var bool Whether the iterator has already been rewound once */
|
||||
protected $hasAlreadyBeenRewound = false;
|
||||
|
||||
/** @var int Number of read rows */
|
||||
protected $numReadRows = 0;
|
||||
|
||||
/** @var array|null Buffer used to store the row data, while checking if there are more rows to read */
|
||||
protected $rowDataBuffer = null;
|
||||
|
||||
/** @var bool Indicates whether all rows have been read */
|
||||
protected $hasReachedEndOfFile = false;
|
||||
|
||||
/**
|
||||
* @param XMLReader $xmlReader XML Reader, positioned on the "<table:table>" element
|
||||
*/
|
||||
public function __construct($xmlReader)
|
||||
{
|
||||
$this->xmlReader = $xmlReader;
|
||||
$this->cellValueFormatter = new CellValueFormatter();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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->numReadRows = 0;
|
||||
$this->rowDataBuffer = null;
|
||||
$this->hasReachedEndOfFile = false;
|
||||
|
||||
$this->next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if current position is valid
|
||||
* @link http://php.net/manual/en/iterator.valid.php
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
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()
|
||||
{
|
||||
$rowData = [];
|
||||
$cellValue = null;
|
||||
$numColumnsRepeated = 1;
|
||||
$numCellsRead = 0;
|
||||
$hasAlreadyReadOneCell = false;
|
||||
|
||||
try {
|
||||
while ($this->xmlReader->read()) {
|
||||
if ($this->xmlReader->isPositionedOnStartingNode(self::XML_NODE_CELL)) {
|
||||
// Start of a cell description
|
||||
$currentNumColumnsRepeated = $this->getNumColumnsRepeatedForCurrentNode();
|
||||
|
||||
$node = $this->xmlReader->expand();
|
||||
$currentCellValue = $this->getCellValue($node);
|
||||
|
||||
// process cell N only after having read cell N+1 (see below why)
|
||||
if ($hasAlreadyReadOneCell) {
|
||||
for ($i = 0; $i < $numColumnsRepeated; $i++) {
|
||||
$rowData[] = $cellValue;
|
||||
}
|
||||
}
|
||||
|
||||
$cellValue = $currentCellValue;
|
||||
$numColumnsRepeated = $currentNumColumnsRepeated;
|
||||
|
||||
$numCellsRead++;
|
||||
$hasAlreadyReadOneCell = true;
|
||||
|
||||
} else if ($this->xmlReader->isPositionedOnEndingNode(self::XML_NODE_ROW)) {
|
||||
// End of the row description
|
||||
$isEmptyRow = ($numCellsRead <= 1 && empty($cellValue));
|
||||
if ($isEmptyRow) {
|
||||
// skip empty rows
|
||||
$this->next();
|
||||
return;
|
||||
}
|
||||
|
||||
// Only add value if the last read cell is not empty or does not need to repeat cell values.
|
||||
// This is to avoid creating a lot of empty cells, as Excel adds a last empty "<table:table-cell>"
|
||||
// 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 (!empty($cellValue) || $numColumnsRepeated === 1) {
|
||||
for ($i = 0; $i < $numColumnsRepeated; $i++) {
|
||||
$rowData[] = $cellValue;
|
||||
}
|
||||
|
||||
$this->numReadRows++;
|
||||
}
|
||||
break;
|
||||
|
||||
} else if ($this->xmlReader->isPositionedOnEndingNode(self::XML_NODE_TABLE)) {
|
||||
// The closing "</table:table>" marks the end of the file
|
||||
$this->hasReachedEndOfFile = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
} catch (XMLProcessingException $exception) {
|
||||
throw new IOException("The sheet's data cannot be read. [{$exception->getMessage()}]");
|
||||
}
|
||||
|
||||
$this->rowDataBuffer = $rowData;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int The value of "table:number-columns-repeated" attribute of the current node, or 1 if attribute missing
|
||||
*/
|
||||
protected function getNumColumnsRepeatedForCurrentNode()
|
||||
{
|
||||
$numColumnsRepeated = $this->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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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()
|
||||
{
|
||||
$this->xmlReader->close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Reader\ODS;
|
||||
|
||||
use Box\Spout\Reader\SheetInterface;
|
||||
use Box\Spout\Reader\Wrapper\XMLReader;
|
||||
|
||||
/**
|
||||
* Class Sheet
|
||||
* Represents a sheet within a ODS file
|
||||
*
|
||||
* @package Box\Spout\Reader\ODS
|
||||
*/
|
||||
class Sheet implements SheetInterface
|
||||
{
|
||||
/** @var \Box\Spout\Reader\ODS\RowIterator To iterate over sheet's rows */
|
||||
protected $rowIterator;
|
||||
|
||||
/** @var int ID of the sheet */
|
||||
protected $id;
|
||||
|
||||
/** @var int Index of the sheet, based on order of creation (zero-based) */
|
||||
protected $index;
|
||||
|
||||
/** @var string Name of the sheet */
|
||||
protected $name;
|
||||
|
||||
/**
|
||||
* @param XMLReader $xmlReader XML Reader, positioned on the "<table:table>" element
|
||||
* @param int $sheetIndex Index of the sheet, based on order of creation (zero-based)
|
||||
* @param string $sheetName Name of the sheet
|
||||
*/
|
||||
public function __construct($xmlReader, $sheetIndex, $sheetName)
|
||||
{
|
||||
$this->rowIterator = new RowIterator($xmlReader);
|
||||
$this->index = $sheetIndex;
|
||||
$this->name = $sheetName;
|
||||
}
|
||||
|
||||
/**
|
||||
* @api
|
||||
* @return \Box\Spout\Reader\ODS\RowIterator
|
||||
*/
|
||||
public function getRowIterator()
|
||||
{
|
||||
return $this->rowIterator;
|
||||
}
|
||||
|
||||
/**
|
||||
* @api
|
||||
* @return int Index of the sheet, based on order of creation (zero-based)
|
||||
*/
|
||||
public function getIndex()
|
||||
{
|
||||
return $this->index;
|
||||
}
|
||||
|
||||
/**
|
||||
* @api
|
||||
* @return string Name of the sheet
|
||||
*/
|
||||
public function getName()
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Reader\ODS;
|
||||
|
||||
use Box\Spout\Common\Exception\IOException;
|
||||
use Box\Spout\Reader\Exception\XMLProcessingException;
|
||||
use Box\Spout\Reader\IteratorInterface;
|
||||
use Box\Spout\Reader\Wrapper\XMLReader;
|
||||
|
||||
/**
|
||||
* Class SheetIterator
|
||||
* Iterate over ODS sheet.
|
||||
*
|
||||
* @package Box\Spout\Reader\ODS
|
||||
*/
|
||||
class SheetIterator implements IteratorInterface
|
||||
{
|
||||
/** Definition of XML nodes name and attribute used to parse sheet data */
|
||||
const XML_NODE_TABLE = 'table:table';
|
||||
const XML_ATTRIBUTE_TABLE_NAME = 'table:name';
|
||||
|
||||
/** @var string $filePath Path of the file to be read */
|
||||
protected $filePath;
|
||||
|
||||
/** @var XMLReader The XMLReader object that will help read sheet's XML data */
|
||||
protected $xmlReader;
|
||||
|
||||
/** @var \Box\Spout\Common\Escaper\ODS Used to unescape XML data */
|
||||
protected $escaper;
|
||||
|
||||
/** @var bool Whether there are still at least a sheet to be read */
|
||||
protected $hasFoundSheet;
|
||||
|
||||
/** @var int The index of the sheet being read (zero-based) */
|
||||
protected $currentSheetIndex;
|
||||
|
||||
/**
|
||||
* @param string $filePath Path of the file to be read
|
||||
* @throws \Box\Spout\Reader\Exception\NoSheetsFoundException If there are no sheets in the file
|
||||
*/
|
||||
public function __construct($filePath)
|
||||
{
|
||||
$this->filePath = $filePath;
|
||||
$this->xmlReader = new XMLReader();
|
||||
|
||||
/** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
|
||||
$this->escaper = new \Box\Spout\Common\Escaper\ODS();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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();
|
||||
|
||||
$contentXmlFilePath = $this->filePath . '#content.xml';
|
||||
if ($this->xmlReader->open('zip://' . $contentXmlFilePath) === false) {
|
||||
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 boolean
|
||||
*/
|
||||
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);
|
||||
|
||||
return new Sheet($this->xmlReader, $sheetName, $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()
|
||||
{
|
||||
$this->xmlReader->close();
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ class ReaderFactory
|
||||
/**
|
||||
* This creates an instance of the appropriate reader, given the type of the file to be read
|
||||
*
|
||||
* @api
|
||||
* @param string $readerType Type of the reader to instantiate
|
||||
* @return ReaderInterface
|
||||
* @throws \Box\Spout\Common\Exception\UnsupportedTypeException
|
||||
@@ -33,6 +34,9 @@ class ReaderFactory
|
||||
case Type::XLSX:
|
||||
$reader = new XLSX\Reader();
|
||||
break;
|
||||
case Type::ODS:
|
||||
$reader = new ODS\Reader();
|
||||
break;
|
||||
default:
|
||||
throw new UnsupportedTypeException('No readers supporting the given type: ' . $readerType);
|
||||
}
|
||||
|
||||
@@ -151,6 +151,22 @@ class SimpleXMLElement
|
||||
return $doesElementExist ? $this->wrapSimpleXMLElement($realElement) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the immediate children.
|
||||
*
|
||||
* @return array The children
|
||||
*/
|
||||
public function children()
|
||||
{
|
||||
$children = [];
|
||||
|
||||
foreach ($this->simpleXMLElement->children() as $child) {
|
||||
$children[] = $this->wrapSimpleXMLElement($child);
|
||||
}
|
||||
|
||||
return $children;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
|
||||
@@ -26,20 +26,45 @@ class XMLReader extends \XMLReader
|
||||
public function open($URI, $encoding = null, $options = 0)
|
||||
{
|
||||
$wasOpenSuccessful = false;
|
||||
$realPathURI = $this->convertURIToUseRealPath($URI);
|
||||
|
||||
// HHVM does not check if file exists within zip file
|
||||
// @link https://github.com/facebook/hhvm/issues/5779
|
||||
if ($this->isRunningHHVM() && $this->isZipStream($URI)) {
|
||||
if ($this->fileExistsWithinZip($URI)) {
|
||||
$wasOpenSuccessful = parent::open($URI, $encoding, $options|LIBXML_NONET);
|
||||
if ($this->isRunningHHVM() && $this->isZipStream($realPathURI)) {
|
||||
if ($this->fileExistsWithinZip($realPathURI)) {
|
||||
$wasOpenSuccessful = parent::open($realPathURI, $encoding, $options|LIBXML_NONET);
|
||||
}
|
||||
} else {
|
||||
$wasOpenSuccessful = parent::open($URI, $encoding, $options|LIBXML_NONET);
|
||||
$wasOpenSuccessful = parent::open($realPathURI, $encoding, $options|LIBXML_NONET);
|
||||
}
|
||||
|
||||
return $wasOpenSuccessful;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the given URI to use a real path.
|
||||
* This is to avoid issues on some Windows setup.
|
||||
*
|
||||
* @param string $URI URI
|
||||
* @return string The URI using a real path
|
||||
*/
|
||||
protected function convertURIToUseRealPath($URI)
|
||||
{
|
||||
$realPathURI = $URI;
|
||||
|
||||
if ($this->isZipStream($URI)) {
|
||||
if (preg_match('/zip:\/\/(.*)#(.*)/', $URI, $matches)) {
|
||||
$documentPath = $matches[1];
|
||||
$documentInsideZipPath = $matches[2];
|
||||
$realPathURI = 'zip://' . realpath($documentPath) . '#' . $documentInsideZipPath;
|
||||
}
|
||||
} else {
|
||||
$realPathURI = realpath($URI);
|
||||
}
|
||||
|
||||
return $realPathURI;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the given URI is a zip stream.
|
||||
*
|
||||
@@ -104,6 +129,22 @@ class XMLReader extends \XMLReader
|
||||
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)
|
||||
{
|
||||
while (($wasReadSuccessful = $this->read()) && ($this->nodeType !== \XMLReader::ELEMENT || $this->name !== $nodeName)) {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
return $wasReadSuccessful;
|
||||
}
|
||||
|
||||
/**
|
||||
* Move cursor to next node skipping all subtrees
|
||||
* @see \XMLReader::next
|
||||
@@ -122,4 +163,22 @@ class XMLReader extends \XMLReader
|
||||
|
||||
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->nodeType === XMLReader::ELEMENT && $this->name === $nodeName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @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->nodeType === XMLReader::END_ELEMENT && $this->name === $nodeName);
|
||||
}
|
||||
}
|
||||
@@ -71,7 +71,7 @@ class CellHelper
|
||||
{
|
||||
$currentColumnIndex = ord($single_cell_index) - $capitalAAsciiValue;
|
||||
|
||||
if ($columnLength == 1) {
|
||||
if ($columnLength === 1) {
|
||||
$columnIndex += $currentColumnIndex;
|
||||
} else {
|
||||
$columnIndex += pow($step, ($columnLength - 1)) * ($currentColumnIndex + 1);
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Reader\XLSX\Helper;
|
||||
|
||||
/**
|
||||
* Class CellValueFormatter
|
||||
* This class provides helper functions to format cell values
|
||||
*
|
||||
* @package Box\Spout\Reader\XLSX\Helper
|
||||
*/
|
||||
class CellValueFormatter
|
||||
{
|
||||
/** Definition of all possible cell types */
|
||||
const CELL_TYPE_INLINE_STRING = 'inlineStr';
|
||||
const CELL_TYPE_STR = 'str';
|
||||
const CELL_TYPE_SHARED_STRING = 's';
|
||||
const CELL_TYPE_BOOLEAN = 'b';
|
||||
const CELL_TYPE_NUMERIC = 'n';
|
||||
const CELL_TYPE_DATE = 'd';
|
||||
const CELL_TYPE_ERROR = 'e';
|
||||
|
||||
/** Definition of XML nodes names used to parse data */
|
||||
const XML_NODE_VALUE = 'v';
|
||||
const XML_NODE_INLINE_STRING_VALUE = 't';
|
||||
|
||||
/** Definition of XML attributes used to parse data */
|
||||
const XML_ATTRIBUTE_TYPE = 't';
|
||||
const XML_ATTRIBUTE_STYLE_ID = 's';
|
||||
|
||||
/** Constants used for date formatting */
|
||||
const NUM_DAYS_FROM_JAN_1_1900_TO_JAN_1_1970 = 25569; // actually 25567 but accommodating for an Excel bug with some bisextile years
|
||||
const NUM_SECONDS_IN_ONE_DAY = 86400;
|
||||
|
||||
/**
|
||||
* February 29th, 1900 is NOT a leap year but Excel thinks it is...
|
||||
* @see https://en.wikipedia.org/wiki/Year_1900_problem#Microsoft_Excel
|
||||
*/
|
||||
const ERRONEOUS_EXCEL_LEAP_YEAR_DAY = 60;
|
||||
|
||||
/** @var SharedStringsHelper Helper to work with shared strings */
|
||||
protected $sharedStringsHelper;
|
||||
|
||||
/** @var StyleHelper Helper to work with styles */
|
||||
protected $styleHelper;
|
||||
|
||||
/** @var \Box\Spout\Common\Escaper\XLSX Used to unescape XML data */
|
||||
protected $escaper;
|
||||
|
||||
/**
|
||||
* @param SharedStringsHelper $sharedStringsHelper Helper to work with shared strings
|
||||
* @param StyleHelper $styleHelper Helper to work with styles
|
||||
*/
|
||||
public function __construct($sharedStringsHelper, $styleHelper)
|
||||
{
|
||||
$this->sharedStringsHelper = $sharedStringsHelper;
|
||||
$this->styleHelper = $styleHelper;
|
||||
|
||||
/** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
|
||||
$this->escaper = new \Box\Spout\Common\Escaper\XLSX();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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:
|
||||
// <c r="A1" t="inlineStr"><is><t>[INLINE_STRING]</t></is></c>
|
||||
$tNode = $node->getElementsByTagName(self::XML_NODE_INLINE_STRING_VALUE)->item(0);
|
||||
$escapedCellValue = trim($tNode->nodeValue);
|
||||
$cellValue = $this->escaper->unescape($escapedCellValue);
|
||||
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:
|
||||
// <c r="A1" t="s"><v>[SHARED_STRING_INDEX]</v></c>
|
||||
$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));
|
||||
} else {
|
||||
return is_int($nodeValue) ? intval($nodeValue) : 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.
|
||||
*
|
||||
* @param float $nodeValue
|
||||
* @return \DateTime|null The value associated with the cell or NULL if invalid date value
|
||||
*/
|
||||
protected function formatExcelTimestampValue($nodeValue)
|
||||
{
|
||||
$numDaysSince1970Jan1 = $nodeValue - self::NUM_DAYS_FROM_JAN_1_1900_TO_JAN_1_1970;
|
||||
|
||||
// Fix for the erroneous leap year in Excel
|
||||
if ($nodeValue < self::ERRONEOUS_EXCEL_LEAP_YEAR_DAY) {
|
||||
$numDaysSince1970Jan1++;
|
||||
}
|
||||
|
||||
$unixTimestamp = round($numDaysSince1970Jan1 * self::NUM_SECONDS_IN_ONE_DAY);
|
||||
|
||||
try {
|
||||
$cellValue = (new \DateTime())->setTimestamp($unixTimestamp);
|
||||
return $cellValue;
|
||||
} 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.
|
||||
*
|
||||
* @param string $nodeValue
|
||||
* @return \DateTime|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 {
|
||||
$cellValue = new \DateTime($nodeValue);
|
||||
return $cellValue;
|
||||
} catch (\Exception $e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -79,10 +79,11 @@ class SharedStringsHelper
|
||||
{
|
||||
$xmlReader = new XMLReader();
|
||||
$sharedStringIndex = 0;
|
||||
/** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
|
||||
$escaper = new \Box\Spout\Common\Escaper\XLSX();
|
||||
|
||||
$sharedStringsFilePath = $this->getSharedStringsFilePath();
|
||||
if ($xmlReader->open($sharedStringsFilePath, null, LIBXML_NONET) === false) {
|
||||
if ($xmlReader->open($sharedStringsFilePath) === false) {
|
||||
throw new IOException('Could not open "' . self::SHARED_STRINGS_XML_FILE_PATH . '".');
|
||||
}
|
||||
|
||||
@@ -90,9 +91,7 @@ class SharedStringsHelper
|
||||
$sharedStringsUniqueCount = $this->getSharedStringsUniqueCount($xmlReader);
|
||||
$this->cachingStrategy = $this->getBestSharedStringsCachingStrategy($sharedStringsUniqueCount);
|
||||
|
||||
while ($xmlReader->read() && $xmlReader->name !== 'si') {
|
||||
// do nothing until a 'si' tag is reached
|
||||
}
|
||||
$xmlReader->readUntilNodeFound('si');
|
||||
|
||||
while ($xmlReader->name === 'si') {
|
||||
$node = $this->getSimpleXmlElementNodeFromXMLReader($xmlReader);
|
||||
|
||||
@@ -101,7 +101,6 @@ class SheetHelper
|
||||
*/
|
||||
protected function getSheetFromXML($sheetDataXMLFilePath, $sheetIndexZeroBased)
|
||||
{
|
||||
$sheetId = $sheetIndexZeroBased + 1;
|
||||
$sheetName = $this->getDefaultSheetName($sheetDataXMLFilePath);
|
||||
|
||||
/*
|
||||
@@ -123,15 +122,15 @@ class SheetHelper
|
||||
|
||||
if (count($sheetNodes) === 1) {
|
||||
$sheetNode = $sheetNodes[0];
|
||||
$sheetId = (int) $sheetNode->getAttribute('sheetId');
|
||||
$escapedSheetName = $sheetNode->getAttribute('name');
|
||||
|
||||
/** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
|
||||
$escaper = new \Box\Spout\Common\Escaper\XLSX();
|
||||
$sheetName = $escaper->unescape($escapedSheetName);
|
||||
}
|
||||
}
|
||||
|
||||
return new Sheet($this->filePath, $sheetDataXMLFilePath, $this->sharedStringsHelper, $sheetId, $sheetIndexZeroBased, $sheetName);
|
||||
return new Sheet($this->filePath, $sheetDataXMLFilePath, $this->sharedStringsHelper, $sheetIndexZeroBased, $sheetName);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Reader\XLSX\Helper;
|
||||
|
||||
use Box\Spout\Reader\Wrapper\SimpleXMLElement;
|
||||
use Box\Spout\Reader\Wrapper\XMLReader;
|
||||
|
||||
/**
|
||||
* Class StyleHelper
|
||||
* This class provides helper functions related to XLSX styles
|
||||
*
|
||||
* @package Box\Spout\Reader\XLSX\Helper
|
||||
*/
|
||||
class StyleHelper
|
||||
{
|
||||
/** Paths of XML files relative to the XLSX file root */
|
||||
const STYLES_XML_FILE_PATH = 'xl/styles.xml';
|
||||
|
||||
/** Nodes used to find relevant information in the styles XML file */
|
||||
const XML_NODE_NUM_FMTS = 'numFmts';
|
||||
const XML_NODE_NUM_FMT = 'numFmt';
|
||||
const XML_NODE_CELL_XFS = 'cellXfs';
|
||||
const XML_NODE_XF = 'xf';
|
||||
|
||||
/** Attributes used to find relevant information in the styles XML file */
|
||||
const XML_ATTRIBUTE_NUM_FMT_ID = 'numFmtId';
|
||||
const XML_ATTRIBUTE_FORMAT_CODE = 'formatCode';
|
||||
const XML_ATTRIBUTE_APPLY_NUMBER_FORMAT = 'applyNumberFormat';
|
||||
|
||||
/** By convention, default style ID is 0 */
|
||||
const DEFAULT_STYLE_ID = 0;
|
||||
|
||||
/** @var string Path of the XLSX file being read */
|
||||
protected $filePath;
|
||||
|
||||
/** @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;
|
||||
|
||||
/**
|
||||
* @param string $filePath Path of the XLSX file being read
|
||||
*/
|
||||
public function __construct($filePath)
|
||||
{
|
||||
$this->filePath = $filePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the styles.xml file and extract the relevant information from the file.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function extractRelevantInfo()
|
||||
{
|
||||
$this->customNumberFormats = [];
|
||||
$this->stylesAttributes = [];
|
||||
|
||||
$stylesXmlFilePath = $this->filePath .'#' . self::STYLES_XML_FILE_PATH;
|
||||
$xmlReader = new XMLReader();
|
||||
|
||||
if ($xmlReader->open('zip://' . $stylesXmlFilePath)) {
|
||||
while ($xmlReader->read()) {
|
||||
if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_NUM_FMTS)) {
|
||||
$numFmtsNode = new SimpleXMLElement($xmlReader->readOuterXml());
|
||||
$this->extractNumberFormats($numFmtsNode);
|
||||
|
||||
} else if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_CELL_XFS)) {
|
||||
$cellXfsNode = new SimpleXMLElement($xmlReader->readOuterXml());
|
||||
$this->extractStyleAttributes($cellXfsNode);
|
||||
}
|
||||
}
|
||||
|
||||
$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 SimpleXMLElement $numFmtsNode The "numFmts" node
|
||||
* @return void
|
||||
*/
|
||||
protected function extractNumberFormats($numFmtsNode)
|
||||
{
|
||||
foreach ($numFmtsNode->children() as $numFmtNode) {
|
||||
$numFmtId = intval($numFmtNode->getAttribute(self::XML_ATTRIBUTE_NUM_FMT_ID));
|
||||
$formatCode = $numFmtNode->getAttribute(self::XML_ATTRIBUTE_FORMAT_CODE);
|
||||
$this->customNumberFormats[$numFmtId] = $formatCode;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 SimpleXMLElement $cellXfsNode The "cellXfs" node
|
||||
* @return void
|
||||
*/
|
||||
protected function extractStyleAttributes($cellXfsNode)
|
||||
{
|
||||
foreach ($cellXfsNode->children() as $xfNode) {
|
||||
$this->stylesAttributes[] = [
|
||||
self::XML_ATTRIBUTE_NUM_FMT_ID => intval($xfNode->getAttribute(self::XML_ATTRIBUTE_NUM_FMT_ID)),
|
||||
self::XML_ATTRIBUTE_APPLY_NUMBER_FORMAT => !!($xfNode->getAttribute(self::XML_ATTRIBUTE_APPLY_NUMBER_FORMAT)),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
if ($styleId === self::DEFAULT_STYLE_ID || !array_key_exists($styleId, $stylesAttributes)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$styleAttributes = $stylesAttributes[$styleId];
|
||||
|
||||
$applyNumberFormat = $styleAttributes[self::XML_ATTRIBUTE_APPLY_NUMBER_FORMAT];
|
||||
if (!$applyNumberFormat) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$numFmtId = $styleAttributes[self::XML_ATTRIBUTE_NUM_FMT_ID];
|
||||
return $this->doesNumFmtIdIndicateDate($numFmtId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $numFmtId
|
||||
* @return bool Whether the number format ID indicates that the number is a timestamp
|
||||
*/
|
||||
protected function doesNumFmtIdIndicateDate($numFmtId)
|
||||
{
|
||||
return (
|
||||
$this->isNumFmtIdBuiltInDateFormat($numFmtId) ||
|
||||
$this->isNumFmtIdCustomDateFormat($numFmtId)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $numFmtId
|
||||
* @return bool Whether the number format ID indicates that the number is a timestamp
|
||||
*/
|
||||
protected function isNumFmtIdBuiltInDateFormat($numFmtId)
|
||||
{
|
||||
$builtInDateFormatIds = [14, 15, 16, 17, 18, 19, 20, 21, 22, 45, 46, 47];
|
||||
return in_array($numFmtId, $builtInDateFormatIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $numFmtId
|
||||
* @return bool Whether the number format ID indicates that the number is a timestamp
|
||||
*/
|
||||
protected function isNumFmtIdCustomDateFormat($numFmtId)
|
||||
{
|
||||
$customNumberFormats = $this->getCustomNumberFormats();
|
||||
|
||||
if (!array_key_exists($numFmtId, $customNumberFormats)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$customNumberFormat = $customNumberFormats[$numFmtId];
|
||||
|
||||
// Remove extra formatting (what's between [ ], the brackets should not be preceded by a "\")
|
||||
$pattern = '((?<!\\\)\[.+?(?<!\\\)\])';
|
||||
$customNumberFormat = preg_replace($pattern, '', $customNumberFormat);
|
||||
|
||||
// custom date formats contain specific characters to represent the date:
|
||||
// e - yy - m - d - h - s
|
||||
// and all of their variants (yyyy - mm - dd...)
|
||||
$dateFormatCharacters = ['e', 'yy', 'm', 'd', 'h', 's'];
|
||||
|
||||
$hasFoundDateFormatCharacter = false;
|
||||
foreach ($dateFormatCharacters as $dateFormatCharacter) {
|
||||
// character not preceded by "\"
|
||||
$pattern = '/(?<!\\\)' . $dateFormatCharacter . '/';
|
||||
|
||||
if (preg_match($pattern, $customNumberFormat)) {
|
||||
$hasFoundDateFormatCharacter = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $hasFoundDateFormatCharacter;
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@ use Box\Spout\Reader\Exception\XMLProcessingException;
|
||||
use Box\Spout\Reader\IteratorInterface;
|
||||
use Box\Spout\Reader\Wrapper\XMLReader;
|
||||
use Box\Spout\Reader\XLSX\Helper\CellHelper;
|
||||
use Box\Spout\Reader\XLSX\Helper\CellValueFormatter;
|
||||
use Box\Spout\Reader\XLSX\Helper\StyleHelper;
|
||||
|
||||
/**
|
||||
* Class RowIterator
|
||||
@@ -15,28 +17,16 @@ use Box\Spout\Reader\XLSX\Helper\CellHelper;
|
||||
*/
|
||||
class RowIterator implements IteratorInterface
|
||||
{
|
||||
/** Definition of all possible cell types */
|
||||
const CELL_TYPE_INLINE_STRING = 'inlineStr';
|
||||
const CELL_TYPE_STR = 'str';
|
||||
const CELL_TYPE_SHARED_STRING = 's';
|
||||
const CELL_TYPE_BOOLEAN = 'b';
|
||||
const CELL_TYPE_NUMERIC = 'n';
|
||||
const CELL_TYPE_DATE = 'd';
|
||||
const CELL_TYPE_ERROR = 'e';
|
||||
|
||||
/** Definition of XML nodes names used to parse data */
|
||||
const XML_NODE_DIMENSION = 'dimension';
|
||||
const XML_NODE_WORKSHEET = 'worksheet';
|
||||
const XML_NODE_ROW = 'row';
|
||||
const XML_NODE_CELL = 'c';
|
||||
const XML_NODE_VALUE = 'v';
|
||||
const XML_NODE_INLINE_STRING_VALUE = 't';
|
||||
|
||||
/** Definition of XML attributes used to parse data */
|
||||
const XML_ATTRIBUTE_REF = 'ref';
|
||||
const XML_ATTRIBUTE_SPANS = 'spans';
|
||||
const XML_ATTRIBUTE_CELL_INDEX = 'r';
|
||||
const XML_ATTRIBUTE_TYPE = 't';
|
||||
|
||||
/** @var string Path of the XLSX file being read */
|
||||
protected $filePath;
|
||||
@@ -44,14 +34,14 @@ class RowIterator implements IteratorInterface
|
||||
/** @var string $sheetDataXMLFilePath Path of the sheet data XML file as in [Content_Types].xml */
|
||||
protected $sheetDataXMLFilePath;
|
||||
|
||||
/** @var Helper\SharedStringsHelper Helper to work with shared strings */
|
||||
protected $sharedStringsHelper;
|
||||
|
||||
/** @var \Box\Spout\Reader\Wrapper\XMLReader The XMLReader object that will help read sheet's XML data */
|
||||
protected $xmlReader;
|
||||
|
||||
/** @var \Box\Spout\Common\Escaper\XLSX Used to unescape XML data */
|
||||
protected $escaper;
|
||||
/** @var Helper\CellValueFormatter Helper to format cell values */
|
||||
protected $cellValueFormatter;
|
||||
|
||||
/** @var Helper\StyleHelper $styleHelper Helper to work with styles */
|
||||
protected $styleHelper;
|
||||
|
||||
/** @var int Number of read rows */
|
||||
protected $numReadRows = 0;
|
||||
@@ -74,10 +64,11 @@ class RowIterator implements IteratorInterface
|
||||
{
|
||||
$this->filePath = $filePath;
|
||||
$this->sheetDataXMLFilePath = $this->normalizeSheetDataXMLFilePath($sheetDataXMLFilePath);
|
||||
$this->sharedStringsHelper = $sharedStringsHelper;
|
||||
|
||||
$this->xmlReader = new XMLReader();
|
||||
$this->escaper = new \Box\Spout\Common\Escaper\XLSX();
|
||||
|
||||
$this->styleHelper = new StyleHelper($filePath);
|
||||
$this->cellValueFormatter = new CellValueFormatter($sharedStringsHelper, $this->styleHelper);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -137,12 +128,11 @@ class RowIterator implements IteratorInterface
|
||||
*/
|
||||
public function next()
|
||||
{
|
||||
$isInsideRowTag = false;
|
||||
$rowData = [];
|
||||
|
||||
try {
|
||||
while ($this->xmlReader->read()) {
|
||||
if ($this->xmlReader->nodeType == XMLReader::ELEMENT && $this->xmlReader->name === self::XML_NODE_DIMENSION) {
|
||||
if ($this->xmlReader->isPositionedOnStartingNode(self::XML_NODE_DIMENSION)) {
|
||||
// Read dimensions of the sheet
|
||||
$dimensionRef = $this->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)) {
|
||||
@@ -150,9 +140,8 @@ class RowIterator implements IteratorInterface
|
||||
$this->numColumns = CellHelper::getColumnIndexFromCellIndex($lastCellIndex) + 1;
|
||||
}
|
||||
|
||||
} else if ($this->xmlReader->nodeType == XMLReader::ELEMENT && $this->xmlReader->name === self::XML_NODE_ROW) {
|
||||
} else if ($this->xmlReader->isPositionedOnStartingNode(self::XML_NODE_ROW)) {
|
||||
// Start of the row description
|
||||
$isInsideRowTag = true;
|
||||
|
||||
// Read spans info if present
|
||||
$numberOfColumnsForRow = $this->numColumns;
|
||||
@@ -163,7 +152,7 @@ class RowIterator implements IteratorInterface
|
||||
}
|
||||
$rowData = ($numberOfColumnsForRow !== 0) ? array_fill(0, $numberOfColumnsForRow, '') : [];
|
||||
|
||||
} else if ($isInsideRowTag && $this->xmlReader->nodeType == XMLReader::ELEMENT && $this->xmlReader->name === self::XML_NODE_CELL) {
|
||||
} else if ($this->xmlReader->isPositionedOnStartingNode(self::XML_NODE_CELL)) {
|
||||
// Start of a cell description
|
||||
$currentCellIndex = $this->xmlReader->getAttribute(self::XML_ATTRIBUTE_CELL_INDEX);
|
||||
$currentColumnIndex = CellHelper::getColumnIndexFromCellIndex($currentCellIndex);
|
||||
@@ -171,16 +160,17 @@ class RowIterator implements IteratorInterface
|
||||
$node = $this->xmlReader->expand();
|
||||
$rowData[$currentColumnIndex] = $this->getCellValue($node);
|
||||
|
||||
} else if ($this->xmlReader->nodeType == XMLReader::END_ELEMENT && $this->xmlReader->name === self::XML_NODE_ROW) {
|
||||
} else if ($this->xmlReader->isPositionedOnEndingNode(self::XML_NODE_ROW)) {
|
||||
// End of the row description
|
||||
// If needed, we fill the empty cells
|
||||
$rowData = ($this->numColumns !== 0) ? $rowData : CellHelper::fillMissingArrayIndexes($rowData);
|
||||
$this->numReadRows++;
|
||||
break;
|
||||
|
||||
} else if ($this->xmlReader->nodeType == XMLReader::END_ELEMENT && $this->xmlReader->name === self::XML_NODE_WORKSHEET) {
|
||||
} else if ($this->xmlReader->isPositionedOnEndingNode(self::XML_NODE_WORKSHEET)) {
|
||||
// The closing "</worksheet>" marks the end of the file
|
||||
$this->hasReachedEndOfFile = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,110 +181,6 @@ class RowIterator implements IteratorInterface
|
||||
$this->rowDataBuffer = $rowData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
if ($vNode !== null) {
|
||||
return $vNode->nodeValue;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 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:
|
||||
// <c r="A1" t="inlineStr"><is><t>[INLINE_STRING]</t></is></c>
|
||||
$tNode = $node->getElementsByTagName(self::XML_NODE_INLINE_STRING_VALUE)->item(0);
|
||||
$escapedCellValue = trim($tNode->nodeValue);
|
||||
$cellValue = $this->escaper->unescape($escapedCellValue);
|
||||
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:
|
||||
// <c r="A1" t="s"><v>[SHARED_STRING_INDEX]</v></c>
|
||||
$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.
|
||||
*
|
||||
* @param string $nodeValue
|
||||
* @return int|float The value associated with the cell
|
||||
*/
|
||||
protected function formatNumericCellValue($nodeValue)
|
||||
{
|
||||
$cellValue = is_int($nodeValue) ? intval($nodeValue) : floatval($nodeValue);
|
||||
return $cellValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* @param string $nodeValue
|
||||
* @return \DateTime|null The value associated with the cell (null when the cell has an error)
|
||||
*/
|
||||
protected function formatDateCellValue($nodeValue)
|
||||
{
|
||||
// Mitigate thrown Exception on invalid date-time format (http://php.net/manual/en/datetime.construct.php)
|
||||
try {
|
||||
$cellValue = new \DateTime($nodeValue);
|
||||
return $cellValue;
|
||||
} catch (\Exception $e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the (unescaped) correctly marshalled, cell value associated to the given XML node.
|
||||
*
|
||||
@@ -303,30 +189,7 @@ class RowIterator implements IteratorInterface
|
||||
*/
|
||||
protected function getCellValue($node)
|
||||
{
|
||||
// Default cell type is "n"
|
||||
$cellType = $node->getAttribute(self::XML_ATTRIBUTE_TYPE) ?: self::CELL_TYPE_NUMERIC;
|
||||
$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);
|
||||
case self::CELL_TYPE_DATE:
|
||||
return $this->formatDateCellValue($vNodeValue);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
return $this->cellValueFormatter->extractAndFormatNodeValue($node);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -12,12 +12,9 @@ use Box\Spout\Reader\SheetInterface;
|
||||
*/
|
||||
class Sheet implements SheetInterface
|
||||
{
|
||||
/** @var RowIterator To iterate over sheet's rows */
|
||||
/** @var \Box\Spout\Reader\XLSX\RowIterator To iterate over sheet's rows */
|
||||
protected $rowIterator;
|
||||
|
||||
/** @var int ID of the sheet */
|
||||
protected $id;
|
||||
|
||||
/** @var int Index of the sheet, based on order of creation (zero-based) */
|
||||
protected $index;
|
||||
|
||||
@@ -28,20 +25,19 @@ class Sheet implements SheetInterface
|
||||
* @param string $filePath Path of the XLSX file being read
|
||||
* @param string $sheetDataXMLFilePath Path of the sheet data XML file as in [Content_Types].xml
|
||||
* @param Helper\SharedStringsHelper Helper to work with shared strings
|
||||
* @param int $sheetId ID of the sheet
|
||||
* @param int $sheetIndex Index of the sheet, based on order of creation (zero-based)
|
||||
* @param string $sheetName Name of the sheet
|
||||
*/
|
||||
public function __construct($filePath, $sheetDataXMLFilePath, $sharedStringsHelper, $sheetId, $sheetIndex, $sheetName)
|
||||
public function __construct($filePath, $sheetDataXMLFilePath, $sharedStringsHelper, $sheetIndex, $sheetName)
|
||||
{
|
||||
$this->rowIterator = new RowIterator($filePath, $sheetDataXMLFilePath, $sharedStringsHelper);
|
||||
$this->id = $sheetId;
|
||||
$this->index = $sheetIndex;
|
||||
$this->name = $sheetName;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return RowIterator
|
||||
* @api
|
||||
* @return \Box\Spout\Reader\XLSX\RowIterator
|
||||
*/
|
||||
public function getRowIterator()
|
||||
{
|
||||
@@ -49,14 +45,7 @@ class Sheet implements SheetInterface
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int ID of the sheet
|
||||
*/
|
||||
public function getId()
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @api
|
||||
* @return int Index of the sheet, based on order of creation (zero-based)
|
||||
*/
|
||||
public function getIndex()
|
||||
@@ -65,6 +54,7 @@ class Sheet implements SheetInterface
|
||||
}
|
||||
|
||||
/**
|
||||
* @api
|
||||
* @return string Name of the sheet
|
||||
*/
|
||||
public function getName()
|
||||
|
||||
@@ -14,7 +14,7 @@ use Box\Spout\Reader\Exception\NoSheetsFoundException;
|
||||
*/
|
||||
class SheetIterator implements IteratorInterface
|
||||
{
|
||||
/** @var Sheet[] The list of sheet present in the file */
|
||||
/** @var \Box\Spout\Reader\XLSX\Sheet[] The list of sheet present in the file */
|
||||
protected $sheets;
|
||||
|
||||
/** @var int The index of the sheet being read (zero-based) */
|
||||
@@ -79,7 +79,7 @@ class SheetIterator implements IteratorInterface
|
||||
* Return the current element
|
||||
* @link http://php.net/manual/en/iterator.current.php
|
||||
*
|
||||
* @return Sheet
|
||||
* @return \Box\Spout\Reader\XLSX\Sheet
|
||||
*/
|
||||
public function current()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer;
|
||||
|
||||
use Box\Spout\Writer\Exception\WriterNotOpenedException;
|
||||
|
||||
/**
|
||||
* Class AbstractMultiSheetsWriter
|
||||
*
|
||||
* @package Box\Spout\Writer
|
||||
* @abstract
|
||||
*/
|
||||
abstract class AbstractMultiSheetsWriter extends AbstractWriter
|
||||
{
|
||||
/** @var bool Whether new sheets should be automatically created when the max rows limit per sheet is reached */
|
||||
protected $shouldCreateNewSheetsAutomatically = true;
|
||||
|
||||
/**
|
||||
* @return Common\Internal\WorkbookInterface The workbook representing the file to be written
|
||||
*/
|
||||
abstract protected function getWorkbook();
|
||||
|
||||
/**
|
||||
* Sets whether new sheets should be automatically created when the max rows limit per sheet is reached.
|
||||
* This must be set before opening the writer.
|
||||
*
|
||||
* @api
|
||||
* @param bool $shouldCreateNewSheetsAutomatically Whether new sheets should be automatically created when the max rows limit per sheet is reached
|
||||
* @return AbstractMultiSheetsWriter
|
||||
* @throws \Box\Spout\Writer\Exception\WriterAlreadyOpenedException If the writer was already opened
|
||||
*/
|
||||
public function setShouldCreateNewSheetsAutomatically($shouldCreateNewSheetsAutomatically)
|
||||
{
|
||||
$this->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.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,9 @@ namespace Box\Spout\Writer;
|
||||
|
||||
use Box\Spout\Common\Exception\IOException;
|
||||
use Box\Spout\Common\Exception\InvalidArgumentException;
|
||||
use Box\Spout\Writer\Exception\WriterAlreadyOpenedException;
|
||||
use Box\Spout\Writer\Exception\WriterNotOpenedException;
|
||||
use Box\Spout\Writer\Style\StyleBuilder;
|
||||
|
||||
/**
|
||||
* Class AbstractWriter
|
||||
@@ -26,6 +28,12 @@ abstract class AbstractWriter implements WriterInterface
|
||||
/** @var \Box\Spout\Common\Helper\GlobalFunctionsHelper Helper to work with global functions */
|
||||
protected $globalFunctionsHelper;
|
||||
|
||||
/** @var Style\Style Style to be applied to the next written row(s) */
|
||||
protected $rowStyle;
|
||||
|
||||
/** @var Style\Style Default row style. Each writer can have its own default style */
|
||||
protected $defaultRowStyle;
|
||||
|
||||
/** @var string Content-Type value for the header - to be defined by child class */
|
||||
protected static $headerContentType;
|
||||
|
||||
@@ -39,13 +47,13 @@ abstract class AbstractWriter implements WriterInterface
|
||||
|
||||
/**
|
||||
* Adds data to the currently openned writer.
|
||||
* The data must be UTF-8 encoded.
|
||||
*
|
||||
* @param array $dataRow Array containing data to be streamed.
|
||||
* Example $dataRow = ['data1', 1234, null, '', 'data5'];
|
||||
* @param Style\Style $style Style to be applied to the written row
|
||||
* @return void
|
||||
*/
|
||||
abstract protected function addRowToWriter(array $dataRow);
|
||||
abstract protected function addRowToWriter(array $dataRow, $style);
|
||||
|
||||
/**
|
||||
* Closes the streamer, preventing any additional writing.
|
||||
@@ -55,7 +63,16 @@ abstract class AbstractWriter implements WriterInterface
|
||||
abstract protected function closeWriter();
|
||||
|
||||
/**
|
||||
* @param $globalFunctionsHelper
|
||||
*
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
$this->defaultRowStyle = $this->getDefaultRowStyle();
|
||||
$this->resetRowStyleToDefault();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Box\Spout\Common\Helper\GlobalFunctionsHelper $globalFunctionsHelper
|
||||
* @return AbstractWriter
|
||||
*/
|
||||
public function setGlobalFunctionsHelper($globalFunctionsHelper)
|
||||
@@ -68,6 +85,7 @@ abstract class AbstractWriter implements WriterInterface
|
||||
* 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
|
||||
@@ -91,6 +109,7 @@ abstract class AbstractWriter implements WriterInterface
|
||||
*
|
||||
* @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
|
||||
@@ -136,14 +155,28 @@ abstract class AbstractWriter implements WriterInterface
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* The data must be UTF-8 encoded.
|
||||
*
|
||||
* @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
|
||||
@@ -153,7 +186,7 @@ abstract class AbstractWriter implements WriterInterface
|
||||
if ($this->isWriterOpened) {
|
||||
// empty $dataRow should not add an empty line
|
||||
if (!empty($dataRow)) {
|
||||
$this->addRowToWriter($dataRow);
|
||||
$this->addRowToWriter($dataRow, $this->rowStyle);
|
||||
}
|
||||
} else {
|
||||
throw new WriterNotOpenedException('The writer needs to be opened before adding row.');
|
||||
@@ -163,16 +196,40 @@ abstract class AbstractWriter implements WriterInterface
|
||||
}
|
||||
|
||||
/**
|
||||
* Write given data to the output. New data will be appended to end of stream.
|
||||
* The data must be UTF-8 encoded.
|
||||
* 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
|
||||
@@ -193,10 +250,70 @@ abstract class AbstractWriter implements WriterInterface
|
||||
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()
|
||||
|
||||
@@ -32,6 +32,7 @@ class Writer extends AbstractWriter
|
||||
/**
|
||||
* Sets the field delimiter for the CSV
|
||||
*
|
||||
* @api
|
||||
* @param string $fieldDelimiter Character that delimits fields
|
||||
* @return Writer
|
||||
*/
|
||||
@@ -44,6 +45,7 @@ class Writer extends AbstractWriter
|
||||
/**
|
||||
* Sets the field enclosure for the CSV
|
||||
*
|
||||
* @api
|
||||
* @param string $fieldEnclosure Character that enclose fields
|
||||
* @return Writer
|
||||
*/
|
||||
@@ -69,10 +71,11 @@ class Writer extends AbstractWriter
|
||||
*
|
||||
* @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)
|
||||
protected function addRowToWriter(array $dataRow, $style)
|
||||
{
|
||||
$wasWriteSuccessful = $this->globalFunctionsHelper->fputcsv($this->filePointer, $dataRow, $this->fieldDelimiter, $this->fieldEnclosure);
|
||||
if ($wasWriteSuccessful === false) {
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\Common\Helper;
|
||||
|
||||
/**
|
||||
* Class AbstractStyleHelper
|
||||
* This class provides helper functions to manage styles
|
||||
*
|
||||
* @package Box\Spout\Writer\Common\Helper
|
||||
*/
|
||||
abstract class AbstractStyleHelper
|
||||
{
|
||||
/** @var array [SERIALIZED_STYLE] => [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();
|
||||
return array_key_exists($serializedStyle, $this->serializedStyleToStyleIdMappingTable);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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->shouldWrapText()) {
|
||||
return $style;
|
||||
}
|
||||
|
||||
foreach ($dataRow as $cell) {
|
||||
if (is_string($cell) && strpos($cell, "\n") !== false) {
|
||||
$style->setShouldWrapText();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $style;
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,12 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\XLSX\Helper;
|
||||
namespace Box\Spout\Writer\Common\Helper;
|
||||
|
||||
/**
|
||||
* Class CellHelper
|
||||
* This class provides helper functions when working with cells
|
||||
*
|
||||
* @package Box\Spout\Writer\XLSX\Helper
|
||||
* @package Box\Spout\Writer\Common\Helper
|
||||
*/
|
||||
class CellHelper
|
||||
{
|
||||
+41
-2
@@ -1,15 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\XLSX\Helper;
|
||||
namespace Box\Spout\Writer\Common\Helper;
|
||||
|
||||
/**
|
||||
* Class ZipHelper
|
||||
* This class provides helper functions to create zip files
|
||||
*
|
||||
* @package Box\Spout\Writer\XLSX\Helper
|
||||
* @package Box\Spout\Writer\Common\Helper
|
||||
*/
|
||||
class ZipHelper
|
||||
{
|
||||
const ZIP_EXTENSION = '.zip';
|
||||
|
||||
/**
|
||||
* Zips the root folder and streams the contents of the zip into the given stream
|
||||
*
|
||||
* @param string $folderPath Path to the folder to be zipped
|
||||
* @param resource $streamPointer Pointer to the stream to copy the zip
|
||||
* @return void
|
||||
*/
|
||||
public function zipFolderAndCopyToStream($folderPath, $streamPointer)
|
||||
{
|
||||
$zipFilePath = $this->getZipFilePath($folderPath);
|
||||
$this->zipFolder($folderPath, $zipFilePath);
|
||||
$this->copyZipToStream($zipFilePath, $streamPointer);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $folderPathToZip Path to the folder to be zipped
|
||||
* @return string Path where the zip file of the given folder will be created
|
||||
*/
|
||||
public function getZipFilePath($folderPathToZip)
|
||||
{
|
||||
return $folderPathToZip . self::ZIP_EXTENSION;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zips the given folder
|
||||
*
|
||||
@@ -59,4 +84,18 @@ class ZipHelper
|
||||
$realPath = realpath($path);
|
||||
return str_replace(DIRECTORY_SEPARATOR, '/', $realPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Streams the contents of the zip file into the given stream
|
||||
*
|
||||
* @param string $zipFilePath Path to the zip file
|
||||
* @param resource $pointer Pointer to the stream to copy the zip
|
||||
* @return void
|
||||
*/
|
||||
protected function copyZipToStream($zipFilePath, $pointer)
|
||||
{
|
||||
$zipFilePointer = fopen($zipFilePath, 'r');
|
||||
stream_copy_to_stream($zipFilePointer, $pointer);
|
||||
fclose($zipFilePointer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\Common\Internal;
|
||||
|
||||
use Box\Spout\Writer\Exception\SheetNotFoundException;
|
||||
|
||||
/**
|
||||
* Class Workbook
|
||||
* Represents a workbook within a spreadsheet file.
|
||||
* It provides the functions to work with worksheets.
|
||||
*
|
||||
* @package Box\Spout\Writer\Common
|
||||
*/
|
||||
abstract class AbstractWorkbook implements WorkbookInterface
|
||||
{
|
||||
/** @var bool Whether new sheets should be automatically created when the max rows limit per sheet is reached */
|
||||
protected $shouldCreateNewSheetsAutomatically;
|
||||
|
||||
/** @var WorksheetInterface[] Array containing the workbook's sheets */
|
||||
protected $worksheets = [];
|
||||
|
||||
/** @var WorksheetInterface The worksheet where data will be written to */
|
||||
protected $currentWorksheet;
|
||||
|
||||
/**
|
||||
* @param bool $shouldCreateNewSheetsAutomatically
|
||||
* @param \Box\Spout\Writer\Style\Style $defaultRowStyle
|
||||
* @throws \Box\Spout\Common\Exception\IOException If unable to create at least one of the base folders
|
||||
*/
|
||||
public function __construct($shouldCreateNewSheetsAutomatically, $defaultRowStyle)
|
||||
{
|
||||
$this->shouldCreateNewSheetsAutomatically = $shouldCreateNewSheetsAutomatically;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\Common\Internal;
|
||||
|
||||
/**
|
||||
* Interface WorkbookInterface
|
||||
*
|
||||
* @package Box\Spout\Writer\Common\Internal
|
||||
*/
|
||||
interface WorkbookInterface
|
||||
{
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
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();
|
||||
|
||||
/**
|
||||
* @return WorksheetInterface[] All the workbook's sheets
|
||||
*/
|
||||
public function getWorksheets();
|
||||
|
||||
/**
|
||||
* Returns the current sheet
|
||||
*
|
||||
* @return WorksheetInterface The current sheet
|
||||
*/
|
||||
public function getCurrentWorksheet();
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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);
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\Common\Internal;
|
||||
|
||||
/**
|
||||
* Interface WorksheetInterface
|
||||
*
|
||||
* @package Box\Spout\Writer\Common\Internal
|
||||
*/
|
||||
interface WorksheetInterface
|
||||
{
|
||||
/**
|
||||
* @return \Box\Spout\Writer\Common\Sheet The "external" sheet
|
||||
*/
|
||||
public function getExternalSheet();
|
||||
|
||||
/**
|
||||
* @return int The index of the last written row
|
||||
*/
|
||||
public function getLastWrittenRowIndex();
|
||||
|
||||
/**
|
||||
* Adds data to the worksheet.
|
||||
*
|
||||
* @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. 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);
|
||||
|
||||
/**
|
||||
* Closes the worksheet
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function close();
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\Common;
|
||||
|
||||
use Box\Spout\Common\Helper\StringHelper;
|
||||
use Box\Spout\Writer\Exception\InvalidSheetNameException;
|
||||
|
||||
/**
|
||||
* Class Sheet
|
||||
* External representation of a worksheet within a ODS file
|
||||
*
|
||||
* @package Box\Spout\Writer\Common
|
||||
*/
|
||||
class Sheet
|
||||
{
|
||||
const DEFAULT_SHEET_NAME_PREFIX = 'Sheet';
|
||||
|
||||
/** Sheet name should not exceed 31 characters */
|
||||
const MAX_LENGTH_SHEET_NAME = 31;
|
||||
|
||||
/** @var array Invalid characters that cannot be contained in the sheet name */
|
||||
private static $INVALID_CHARACTERS_IN_SHEET_NAME = ['\\', '/', '?', '*', ':', '[', ']'];
|
||||
|
||||
/** @var array Associative array [SHEET_INDEX] => [SHEET_NAME] keeping track of sheets' name to enforce uniqueness */
|
||||
protected static $SHEETS_NAME_USED = [];
|
||||
|
||||
/** @var int Index of the sheet, based on order of creation (zero-based) */
|
||||
protected $index;
|
||||
|
||||
/** @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 of creation (zero-based)
|
||||
*/
|
||||
public function __construct($sheetIndex)
|
||||
{
|
||||
$this->index = $sheetIndex;
|
||||
$this->stringHelper = new StringHelper();
|
||||
$this->setName(self::DEFAULT_SHEET_NAME_PREFIX . ($sheetIndex + 1));
|
||||
}
|
||||
|
||||
/**
|
||||
* @api
|
||||
* @return int Index of the sheet, based on order of creation (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)
|
||||
{
|
||||
if (!$this->isNameValid($name)) {
|
||||
$errorMessage = "The sheet's name is invalid. It did not meet at least one of these requirements:\n";
|
||||
$errorMessage .= " - It should not be blank\n";
|
||||
$errorMessage .= " - It should not exceed 31 characters\n";
|
||||
$errorMessage .= " - It should not contain these characters: \\ / ? * : [ or ]\n";
|
||||
$errorMessage .= " - It should be unique";
|
||||
throw new InvalidSheetNameException($errorMessage);
|
||||
}
|
||||
|
||||
$this->name = $name;
|
||||
self::$SHEETS_NAME_USED[$this->index] = $name;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the given sheet's name is valid.
|
||||
* @see Sheet::setName for validity rules.
|
||||
*
|
||||
* @param string $name
|
||||
* @return bool TRUE if the name is valid, FALSE otherwise.
|
||||
*/
|
||||
protected function isNameValid($name)
|
||||
{
|
||||
if (!is_string($name)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$nameLength = $this->stringHelper->getStringLength($name);
|
||||
|
||||
return (
|
||||
$nameLength > 0 &&
|
||||
$nameLength <= self::MAX_LENGTH_SHEET_NAME &&
|
||||
!$this->doesContainInvalidCharacters($name) &&
|
||||
$this->isNameUnique($name) &&
|
||||
!$this->doesStartOrEndWithSingleQuote($name)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 as $sheetIndex => $sheetName) {
|
||||
if ($sheetIndex !== $this->index && $sheetName === $name) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\Exception;
|
||||
|
||||
/**
|
||||
* Class InvalidColorException
|
||||
*
|
||||
* @api
|
||||
* @package Box\Spout\Writer\Exception
|
||||
*/
|
||||
class InvalidColorException extends WriterException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\Exception;
|
||||
|
||||
/**
|
||||
* Class InvalidSheetNameException
|
||||
*
|
||||
* @api
|
||||
* @package Box\Spout\Writer\Exception
|
||||
*/
|
||||
class InvalidSheetNameException extends WriterException
|
||||
{
|
||||
}
|
||||
@@ -5,6 +5,7 @@ namespace Box\Spout\Writer\Exception;
|
||||
/**
|
||||
* Class SheetNotFoundException
|
||||
*
|
||||
* @api
|
||||
* @package Box\Spout\Writer\Exception
|
||||
*/
|
||||
class SheetNotFoundException extends WriterException
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\Exception;
|
||||
|
||||
/**
|
||||
* Class WriterAlreadyOpenedException
|
||||
*
|
||||
* @api
|
||||
* @package Box\Spout\Writer\Exception
|
||||
*/
|
||||
class WriterAlreadyOpenedException extends WriterException
|
||||
{
|
||||
}
|
||||
@@ -5,6 +5,7 @@ namespace Box\Spout\Writer\Exception;
|
||||
/**
|
||||
* Class WriterNotOpenedException
|
||||
*
|
||||
* @api
|
||||
* @package Box\Spout\Writer\Exception
|
||||
*/
|
||||
class WriterNotOpenedException extends WriterException
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\ODS\Helper;
|
||||
|
||||
use Box\Spout\Writer\Common\Helper\ZipHelper;
|
||||
use Box\Spout\Writer\ODS\Internal\Worksheet;
|
||||
|
||||
/**
|
||||
* Class FileSystemHelper
|
||||
* This class provides helper functions to help with the file system operations
|
||||
* like files/folders creation & deletion for ODS files
|
||||
*
|
||||
* @package Box\Spout\Writer\ODS\Helper
|
||||
*/
|
||||
class FileSystemHelper extends \Box\Spout\Common\Helper\FileSystemHelper
|
||||
{
|
||||
const APP_NAME = 'Spout';
|
||||
const MIMETYPE = 'application/vnd.oasis.opendocument.spreadsheet';
|
||||
|
||||
const META_INF_FOLDER_NAME = 'META-INF';
|
||||
const SHEETS_CONTENT_TEMP_FOLDER_NAME = 'worksheets-temp';
|
||||
|
||||
const MANIFEST_XML_FILE_NAME = 'manifest.xml';
|
||||
const CONTENT_XML_FILE_NAME = 'content.xml';
|
||||
const META_XML_FILE_NAME = 'meta.xml';
|
||||
const MIMETYPE_FILE_NAME = 'mimetype';
|
||||
const STYLES_XML_FILE_NAME = 'styles.xml';
|
||||
|
||||
/** @var string Path to the root folder inside the temp folder where the files to create the ODS will be stored */
|
||||
protected $rootFolder;
|
||||
|
||||
/** @var string Path to the "META-INF" folder inside the root folder */
|
||||
protected $metaInfFolder;
|
||||
|
||||
/** @var string Path to the temp folder, inside the root folder, where specific sheets content will be written to */
|
||||
protected $sheetsContentTempFolder;
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getRootFolder()
|
||||
{
|
||||
return $this->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->baseFolderPath, 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
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0">
|
||||
<manifest:file-entry manifest:full-path="/" manifest:media-type="application/vnd.oasis.opendocument.spreadsheet"/>
|
||||
<manifest:file-entry manifest:full-path="styles.xml" manifest:media-type="text/xml"/>
|
||||
<manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/>
|
||||
<manifest:file-entry manifest:full-path="meta.xml" manifest:media-type="text/xml"/>
|
||||
<manifest:file-entry manifest:full-path="mimetype" manifest:media-type="text/plain"/>
|
||||
<manifest:file-entry manifest:full-path="META-INF/manifest.xml" manifest:media-type="text/xml"/>
|
||||
</manifest:manifest>
|
||||
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 = <<<EOD
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<office:document-meta office:version="1.2" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<office:meta>
|
||||
<dc:creator>$appName</dc:creator>
|
||||
<meta:creation-date>$createdDate</meta:creation-date>
|
||||
<dc:date>$createdDate</dc:date>
|
||||
</office:meta>
|
||||
</office:document-meta>
|
||||
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
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<office:document-content office:version="1.2" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:calcext="urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:msoxl="http://schemas.microsoft.com/office/excel/formula" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
EOD;
|
||||
|
||||
$contentXmlFileContents .= $styleHelper->getContentXmlFontFaceSectionContent();
|
||||
$contentXmlFileContents .= $styleHelper->getContentXmlAutomaticStylesSectionContent(count($worksheets));
|
||||
|
||||
$contentXmlFileContents .= '<office:body><office:spreadsheet>';
|
||||
|
||||
$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 "<table:table>" node, with the final sheet's name
|
||||
fwrite($contentXmlHandle, $worksheet->getTableElementStartAsString());
|
||||
|
||||
$worksheetFilePath = $worksheet->getWorksheetFilePath();
|
||||
$this->copyFileContentsToTarget($worksheetFilePath, $contentXmlHandle);
|
||||
|
||||
fwrite($contentXmlHandle, '</table:table>');
|
||||
}
|
||||
|
||||
$contentXmlFileContents = '</office:spreadsheet></office:body></office:document-content>';
|
||||
|
||||
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();
|
||||
$zipHelper->zipFolderAndCopyToStream($this->rootFolder, $streamPointer);
|
||||
|
||||
// once the zip is copied, remove it
|
||||
$this->deleteFile($zipHelper->getZipFilePath($this->rootFolder));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\ODS\Helper;
|
||||
|
||||
use Box\Spout\Writer\Common\Helper\AbstractStyleHelper;
|
||||
|
||||
/**
|
||||
* Class StyleHelper
|
||||
* This class provides helper functions to manage styles
|
||||
*
|
||||
* @package Box\Spout\Writer\ODS\Helper
|
||||
*/
|
||||
class StyleHelper extends AbstractStyleHelper
|
||||
{
|
||||
/** @var string[] [FONT_NAME] => [] 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
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<office:document-styles office:version="1.2" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:msoxl="http://schemas.microsoft.com/office/excel/formula" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
EOD;
|
||||
|
||||
$content .= $this->getFontFaceSectionContent();
|
||||
$content .= $this->getStylesSectionContent();
|
||||
$content .= $this->getAutomaticStylesSectionContent($numWorksheets);
|
||||
$content .= $this->getMasterStylesSectionContent($numWorksheets);
|
||||
|
||||
$content .= <<<EOD
|
||||
</office:document-styles>
|
||||
EOD;
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the content of the "<office:font-face-decls>" section, inside "styles.xml" file.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getFontFaceSectionContent()
|
||||
{
|
||||
$content = '<office:font-face-decls>';
|
||||
foreach ($this->getUsedFonts() as $fontName) {
|
||||
$content .= '<style:font-face style:name="' . $fontName . '" svg:font-family="' . $fontName . '"/>';
|
||||
}
|
||||
$content .= '</office:font-face-decls>';
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the content of the "<office:styles>" section, inside "styles.xml" file.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getStylesSectionContent()
|
||||
{
|
||||
$defaultStyle = $this->getDefaultStyle();
|
||||
|
||||
return <<<EOD
|
||||
<office:styles>
|
||||
<number:number-style style:name="N0">
|
||||
<number:number number:min-integer-digits="1"/>
|
||||
</number:number-style>
|
||||
<style:style style:data-style-name="N0" style:family="table-cell" style:name="Default">
|
||||
<style:table-cell-properties fo:background-color="transparent" style:vertical-align="automatic"/>
|
||||
<style:text-properties fo:color="#{$defaultStyle->getFontColor()}"
|
||||
fo:font-size="{$defaultStyle->getFontSize()}pt" style:font-size-asian="{$defaultStyle->getFontSize()}pt" style:font-size-complex="{$defaultStyle->getFontSize()}pt"
|
||||
style:font-name="{$defaultStyle->getFontName()}" style:font-name-asian="{$defaultStyle->getFontName()}" style:font-name-complex="{$defaultStyle->getFontName()}"/>
|
||||
</style:style>
|
||||
</office:styles>
|
||||
EOD;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the content of the "<office:automatic-styles>" section, inside "styles.xml" file.
|
||||
*
|
||||
* @param int $numWorksheets Number of worksheets created
|
||||
* @return string
|
||||
*/
|
||||
protected function getAutomaticStylesSectionContent($numWorksheets)
|
||||
{
|
||||
$content = '<office:automatic-styles>';
|
||||
|
||||
for ($i = 1; $i <= $numWorksheets; $i++) {
|
||||
$content .= <<<EOD
|
||||
<style:page-layout style:name="pm$i">
|
||||
<style:page-layout-properties style:first-page-number="continue" style:print="objects charts drawings" style:table-centering="none"/>
|
||||
<style:header-style/>
|
||||
<style:footer-style/>
|
||||
</style:page-layout>
|
||||
EOD;
|
||||
}
|
||||
|
||||
$content .= '</office:automatic-styles>';
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the content of the "<office:master-styles>" section, inside "styles.xml" file.
|
||||
*
|
||||
* @param int $numWorksheets Number of worksheets created
|
||||
* @return string
|
||||
*/
|
||||
protected function getMasterStylesSectionContent($numWorksheets)
|
||||
{
|
||||
$content = '<office:master-styles>';
|
||||
|
||||
for ($i = 1; $i <= $numWorksheets; $i++) {
|
||||
$content .= <<<EOD
|
||||
<style:master-page style:name="mp$i" style:page-layout-name="pm$i">
|
||||
<style:header/>
|
||||
<style:header-left style:display="false"/>
|
||||
<style:footer/>
|
||||
<style:footer-left style:display="false"/>
|
||||
</style:master-page>
|
||||
EOD;
|
||||
}
|
||||
|
||||
$content .= '</office:master-styles>';
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the contents of the "<office:font-face-decls>" section, inside "content.xml" file.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getContentXmlFontFaceSectionContent()
|
||||
{
|
||||
$content = '<office:font-face-decls>';
|
||||
foreach ($this->getUsedFonts() as $fontName) {
|
||||
$content .= '<style:font-face style:name="' . $fontName . '" svg:font-family="' . $fontName . '"/>';
|
||||
}
|
||||
$content .= '</office:font-face-decls>';
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the contents of the "<office:automatic-styles>" section, inside "content.xml" file.
|
||||
*
|
||||
* @param int $numWorksheets Number of worksheets created
|
||||
* @return string
|
||||
*/
|
||||
public function getContentXmlAutomaticStylesSectionContent($numWorksheets)
|
||||
{
|
||||
$content = '<office:automatic-styles>';
|
||||
|
||||
foreach ($this->getRegisteredStyles() as $style) {
|
||||
$content .= $this->getStyleSectionContent($style);
|
||||
}
|
||||
|
||||
$content .= <<<EOD
|
||||
<style:style style:family="table-column" style:name="co1">
|
||||
<style:table-column-properties fo:break-before="auto"/>
|
||||
</style:style>
|
||||
<style:style style:family="table-row" style:name="ro1">
|
||||
<style:table-row-properties fo:break-before="auto" style:row-height="15pt" style:use-optimal-row-height="true"/>
|
||||
</style:style>
|
||||
EOD;
|
||||
|
||||
for ($i = 1; $i <= $numWorksheets; $i++) {
|
||||
$content .= <<<EOD
|
||||
<style:style style:family="table" style:master-page-name="mp$i" style:name="ta$i">
|
||||
<style:table-properties style:writing-mode="lr-tb" table:display="true"/>
|
||||
</style:style>
|
||||
EOD;
|
||||
}
|
||||
|
||||
$content .= '</office:automatic-styles>';
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the contents of the "<style:style>" section, inside "<office:automatic-styles>" section
|
||||
*
|
||||
* @param \Box\Spout\Writer\Style\Style $style
|
||||
* @return string
|
||||
*/
|
||||
protected function getStyleSectionContent($style)
|
||||
{
|
||||
$defaultStyle = $this->getDefaultStyle();
|
||||
$styleIndex = $style->getId() + 1; // 1-based
|
||||
|
||||
$content = '<style:style style:data-style-name="N0" style:family="table-cell" style:name="ce' . $styleIndex . '" style:parent-style-name="Default">';
|
||||
|
||||
if ($style->shouldApplyFont()) {
|
||||
$content .= '<style:text-properties';
|
||||
|
||||
$fontColor = $style->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 .= '/>';
|
||||
}
|
||||
|
||||
if ($style->shouldWrapText()) {
|
||||
$content .= '<style:table-cell-properties fo:wrap-option="wrap" style:vertical-align="automatic"/>';
|
||||
}
|
||||
|
||||
$content .= '</style:style>';
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\ODS\Internal;
|
||||
|
||||
use Box\Spout\Writer\Common\Internal\AbstractWorkbook;
|
||||
use Box\Spout\Writer\ODS\Helper\FileSystemHelper;
|
||||
use Box\Spout\Writer\ODS\Helper\StyleHelper;
|
||||
use Box\Spout\Writer\Common\Sheet;
|
||||
|
||||
/**
|
||||
* Class Workbook
|
||||
* Represents a workbook within a ODS file.
|
||||
* It provides the functions to work with worksheets.
|
||||
*
|
||||
* @package Box\Spout\Writer\ODS\Internal
|
||||
*/
|
||||
class Workbook extends AbstractWorkbook
|
||||
{
|
||||
/**
|
||||
* Maximum number of rows a ODS sheet can contain
|
||||
* @see https://ask.libreoffice.org/en/question/8631/upper-limit-to-number-of-rows-in-calc/
|
||||
*/
|
||||
protected static $maxRowsPerWorksheet = 1048576;
|
||||
|
||||
/** @var \Box\Spout\Writer\ODS\Helper\FileSystemHelper Helper to perform file system operations */
|
||||
protected $fileSystemHelper;
|
||||
|
||||
/** @var \Box\Spout\Writer\ODS\Helper\StyleHelper Helper to apply styles */
|
||||
protected $styleHelper;
|
||||
|
||||
/**
|
||||
* @param string $tempFolder
|
||||
* @param bool $shouldCreateNewSheetsAutomatically
|
||||
* @param \Box\Spout\Writer\Style\Style $defaultRowStyle
|
||||
* @throws \Box\Spout\Common\Exception\IOException If unable to create at least one of the base folders
|
||||
*/
|
||||
public function __construct($tempFolder, $shouldCreateNewSheetsAutomatically, $defaultRowStyle)
|
||||
{
|
||||
parent::__construct($shouldCreateNewSheetsAutomatically, $defaultRowStyle);
|
||||
|
||||
$this->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);
|
||||
|
||||
$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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\ODS\Internal;
|
||||
|
||||
use Box\Spout\Common\Exception\InvalidArgumentException;
|
||||
use Box\Spout\Common\Exception\IOException;
|
||||
use Box\Spout\Common\Helper\StringHelper;
|
||||
use Box\Spout\Writer\Common\Helper\CellHelper;
|
||||
use Box\Spout\Writer\Common\Internal\WorksheetInterface;
|
||||
|
||||
/**
|
||||
* Class Worksheet
|
||||
* Represents a worksheet within a ODS file. The difference with the Sheet object is
|
||||
* that this class provides an interface to write data
|
||||
*
|
||||
* @package Box\Spout\Writer\ODS\Internal
|
||||
*/
|
||||
class Worksheet implements WorksheetInterface
|
||||
{
|
||||
/** @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\Common\Escaper\ODS Strings escaper */
|
||||
protected $stringsEscaper;
|
||||
|
||||
/** @var \Box\Spout\Common\Helper\StringHelper To help with string manipulation */
|
||||
protected $stringHelper;
|
||||
|
||||
/** @var Resource Pointer to the temporary sheet data file (e.g. worksheets-temp/sheet1.xml) */
|
||||
protected $sheetFilePointer;
|
||||
|
||||
/** @var int Maximum number of columns among all the written rows */
|
||||
protected $maxNumColumns = 1;
|
||||
|
||||
/** @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
|
||||
* @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
|
||||
*/
|
||||
public function __construct($externalSheet, $worksheetFilesFolder)
|
||||
{
|
||||
$this->externalSheet = $externalSheet;
|
||||
/** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
|
||||
$this->stringsEscaper = new \Box\Spout\Common\Escaper\ODS();
|
||||
$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 "<table:table>" 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 <table> node as string
|
||||
*/
|
||||
public function getTableElementStartAsString()
|
||||
{
|
||||
$escapedSheetName = $this->stringsEscaper->escape($this->externalSheet->getName());
|
||||
$tableStyleName = 'ta' . ($this->externalSheet->getIndex() + 1);
|
||||
|
||||
$tableElement = '<table:table table:style-name="' . $tableStyleName . '" table:name="' . $escapedSheetName . '">';
|
||||
$tableElement .= '<table:table-column table:default-cell-style-name="ce1" table:style-name="co1" table:number-columns-repeated="' . $this->maxNumColumns . '"/>';
|
||||
|
||||
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)
|
||||
{
|
||||
$styleIndex = ($style->getId() + 1); // 1-based
|
||||
$cellsCount = count($dataRow);
|
||||
$this->maxNumColumns = max($this->maxNumColumns, $cellsCount);
|
||||
|
||||
$data = '<table:table-row table:style-name="ro1">';
|
||||
|
||||
$currentCellIndex = 0;
|
||||
$nextCellIndex = 1;
|
||||
|
||||
for ($i = 0; $i < $cellsCount; $i++) {
|
||||
$currentCellValue = $dataRow[$currentCellIndex];
|
||||
|
||||
if (!array_key_exists($nextCellIndex, $dataRow) || $currentCellValue !== $dataRow[$nextCellIndex]) {
|
||||
$numTimesValueRepeated = ($nextCellIndex - $currentCellIndex);
|
||||
$data .= $this->getCellContent($currentCellValue, $styleIndex, $numTimesValueRepeated);
|
||||
|
||||
$currentCellIndex = $nextCellIndex;
|
||||
}
|
||||
|
||||
$nextCellIndex++;
|
||||
}
|
||||
|
||||
$data .= '</table:table-row>';
|
||||
|
||||
$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 getCellContent($cellValue, $styleIndex, $numTimesValueRepeated)
|
||||
{
|
||||
$data = '<table:table-cell table:style-name="ce' . $styleIndex . '"';
|
||||
|
||||
if ($numTimesValueRepeated !== 1) {
|
||||
$data .= ' table:number-columns-repeated="' . $numTimesValueRepeated . '"';
|
||||
}
|
||||
|
||||
if (CellHelper::isNonEmptyString($cellValue)) {
|
||||
$data .= ' office:value-type="string" calcext:value-type="string">';
|
||||
|
||||
$cellValueLines = explode("\n", $cellValue);
|
||||
foreach ($cellValueLines as $cellValueLine) {
|
||||
$data .= '<text:p>' . $this->stringsEscaper->escape($cellValueLine) . '</text:p>';
|
||||
}
|
||||
|
||||
$data .= '</table:table-cell>';
|
||||
} else if (CellHelper::isBoolean($cellValue)) {
|
||||
$data .= ' office:value-type="boolean" calcext:value-type="boolean" office:boolean-value="' . $cellValue . '">';
|
||||
$data .= '<text:p>' . $cellValue . '</text:p>';
|
||||
$data .= '</table:table-cell>';
|
||||
} else if (CellHelper::isNumeric($cellValue)) {
|
||||
$data .= ' office:value-type="float" calcext:value-type="float" office:value="' . $cellValue . '">';
|
||||
$data .= '<text:p>' . $cellValue . '</text:p>';
|
||||
$data .= '</table:table-cell>';
|
||||
} 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()
|
||||
{
|
||||
fclose($this->sheetFilePointer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\ODS;
|
||||
|
||||
use Box\Spout\Writer\AbstractMultiSheetsWriter;
|
||||
use Box\Spout\Writer\Common;
|
||||
use Box\Spout\Writer\ODS\Internal\Workbook;
|
||||
|
||||
/**
|
||||
* Class Writer
|
||||
* This class provides base support to write data to ODS files
|
||||
*
|
||||
* @package Box\Spout\Writer\ODS
|
||||
*/
|
||||
class Writer extends AbstractMultiSheetsWriter
|
||||
{
|
||||
/** @var string Content-Type value for the header */
|
||||
protected static $headerContentType = 'application/vnd.oasis.opendocument.spreadsheet';
|
||||
|
||||
/** @var string Temporary folder where the files to create the ODS will be stored */
|
||||
protected $tempFolder;
|
||||
|
||||
/** @var Internal\Workbook The workbook for the XLSX file */
|
||||
protected $book;
|
||||
|
||||
/**
|
||||
* Sets a custom temporary folder for creating intermediate files/folders.
|
||||
* This must be set before opening the writer.
|
||||
*
|
||||
* @api
|
||||
* @param string $tempFolder Temporary folder where the files to create the ODS will be stored
|
||||
* @return Writer
|
||||
* @throws \Box\Spout\Writer\Exception\WriterAlreadyOpenedException If the writer was already opened
|
||||
*/
|
||||
public function setTempFolder($tempFolder)
|
||||
{
|
||||
$this->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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\Style;
|
||||
|
||||
use Box\Spout\Writer\Exception\InvalidColorException;
|
||||
|
||||
/**
|
||||
* Class Color
|
||||
* This class provides constants and functions to work with colors
|
||||
*
|
||||
* @package Box\Spout\Writer\Style
|
||||
*/
|
||||
class Color
|
||||
{
|
||||
/** Standard colors - based on Office Online */
|
||||
const BLACK = '000000';
|
||||
const WHITE = 'FFFFFF';
|
||||
const RED = 'FF0000';
|
||||
const DARK_RED = 'C00000';
|
||||
const ORANGE = 'FFC000';
|
||||
const YELLOW = 'FFFF00';
|
||||
const LIGHT_GREEN = '92D040';
|
||||
const GREEN = '00B050';
|
||||
const LIGHT_BLUE = '00B0E0';
|
||||
const BLUE = '0070C0';
|
||||
const DARK_BLUE = '002060';
|
||||
const PURPLE = '7030A0';
|
||||
|
||||
/**
|
||||
* Returns an RGB color from R, G and B values
|
||||
*
|
||||
* @api
|
||||
* @param int $red Red component, 0 - 255
|
||||
* @param int $green Green component, 0 - 255
|
||||
* @param int $blue Blue component, 0 - 255
|
||||
* @return string RGB color
|
||||
*/
|
||||
public static function rgb($red, $green, $blue)
|
||||
{
|
||||
self::throwIfInvalidColorComponentValue($red);
|
||||
self::throwIfInvalidColorComponentValue($green);
|
||||
self::throwIfInvalidColorComponentValue($blue);
|
||||
|
||||
return strtoupper(
|
||||
self::convertColorComponentToHex($red) .
|
||||
self::convertColorComponentToHex($green) .
|
||||
self::convertColorComponentToHex($blue)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Throws an exception is the color component value is outside of bounds (0 - 255)
|
||||
*
|
||||
* @param int $colorComponent
|
||||
* @return void
|
||||
* @throws \Box\Spout\Writer\Exception\InvalidColorException
|
||||
*/
|
||||
protected static function throwIfInvalidColorComponentValue($colorComponent)
|
||||
{
|
||||
if (!is_int($colorComponent) || $colorComponent < 0 || $colorComponent > 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\Style;
|
||||
|
||||
/**
|
||||
* Class Style
|
||||
* Represents a style to be applied to a cell
|
||||
*
|
||||
* @package Box\Spout\Writer\Style
|
||||
*/
|
||||
class Style
|
||||
{
|
||||
/** Default font values */
|
||||
const DEFAULT_FONT_SIZE = 11;
|
||||
const DEFAULT_FONT_COLOR = Color::BLACK;
|
||||
const DEFAULT_FONT_NAME = 'Arial';
|
||||
|
||||
/** @var int|null Style ID */
|
||||
protected $id = null;
|
||||
|
||||
/** @var bool Whether the font should be bold */
|
||||
protected $fontBold = false;
|
||||
/** @var bool Whether the bold property was set */
|
||||
protected $hasSetFontBold = false;
|
||||
|
||||
/** @var bool Whether the font should be italic */
|
||||
protected $fontItalic = false;
|
||||
/** @var bool Whether the italic property was set */
|
||||
protected $hasSetFontItalic = false;
|
||||
|
||||
/** @var bool Whether the font should be underlined */
|
||||
protected $fontUnderline = false;
|
||||
/** @var bool Whether the underline property was set */
|
||||
protected $hasSetFontUnderline = false;
|
||||
|
||||
/** @var bool Whether the font should be struck through */
|
||||
protected $fontStrikethrough = false;
|
||||
/** @var bool Whether the strikethrough property was set */
|
||||
protected $hasSetFontStrikethrough = false;
|
||||
|
||||
/** @var int Font size */
|
||||
protected $fontSize = self::DEFAULT_FONT_SIZE;
|
||||
/** @var bool Whether the font size property was set */
|
||||
protected $hasSetFontSize = false;
|
||||
|
||||
/** @var string Font color */
|
||||
protected $fontColor = self::DEFAULT_FONT_COLOR;
|
||||
/** @var bool Whether the font color property was set */
|
||||
protected $hasSetFontColor = false;
|
||||
|
||||
/** @var string Font name */
|
||||
protected $fontName = self::DEFAULT_FONT_NAME;
|
||||
/** @var bool Whether the font name property was set */
|
||||
protected $hasSetFontName = false;
|
||||
|
||||
/** @var bool Whether specific font properties should be applied */
|
||||
protected $shouldApplyFont = false;
|
||||
|
||||
/** @var bool Whether the text should wrap in the cell (useful for long or multi-lines text) */
|
||||
protected $shouldWrapText = false;
|
||||
/** @var bool Whether the wrap text property was set */
|
||||
protected $hasSetWrapText = false;
|
||||
|
||||
/**
|
||||
* @return int|null
|
||||
*/
|
||||
public function getId()
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @return Style
|
||||
*/
|
||||
public function setId($id)
|
||||
{
|
||||
$this->id = $id;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return boolean
|
||||
*/
|
||||
public function isFontBold()
|
||||
{
|
||||
return $this->fontBold;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Style
|
||||
*/
|
||||
public function setFontBold()
|
||||
{
|
||||
$this->fontBold = true;
|
||||
$this->hasSetFontBold = true;
|
||||
$this->shouldApplyFont = true;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return boolean
|
||||
*/
|
||||
public function isFontItalic()
|
||||
{
|
||||
return $this->fontItalic;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Style
|
||||
*/
|
||||
public function setFontItalic()
|
||||
{
|
||||
$this->fontItalic = true;
|
||||
$this->hasSetFontItalic = true;
|
||||
$this->shouldApplyFont = true;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return boolean
|
||||
*/
|
||||
public function isFontUnderline()
|
||||
{
|
||||
return $this->fontUnderline;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Style
|
||||
*/
|
||||
public function setFontUnderline()
|
||||
{
|
||||
$this->fontUnderline = true;
|
||||
$this->hasSetFontUnderline = true;
|
||||
$this->shouldApplyFont = true;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return boolean
|
||||
*/
|
||||
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 boolean
|
||||
*/
|
||||
public function shouldWrapText()
|
||||
{
|
||||
return $this->shouldWrapText;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Style
|
||||
*/
|
||||
public function setShouldWrapText()
|
||||
{
|
||||
$this->shouldWrapText = true;
|
||||
$this->hasSetWrapText = true;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool Whether specific font properties should be applied
|
||||
*/
|
||||
public function shouldApplyFont()
|
||||
{
|
||||
return $this->shouldApplyFont;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
|
||||
if (!$this->hasSetFontBold && $baseStyle->isFontBold()) {
|
||||
$mergedStyle->setFontBold();
|
||||
}
|
||||
if (!$this->hasSetFontItalic && $baseStyle->isFontItalic()) {
|
||||
$mergedStyle->setFontItalic();
|
||||
}
|
||||
if (!$this->hasSetFontUnderline && $baseStyle->isFontUnderline()) {
|
||||
$mergedStyle->setFontUnderline();
|
||||
}
|
||||
if (!$this->hasSetFontStrikethrough && $baseStyle->isFontStrikethrough()) {
|
||||
$mergedStyle->setFontStrikethrough();
|
||||
}
|
||||
if (!$this->hasSetFontSize && $baseStyle->getFontSize() !== self::DEFAULT_FONT_SIZE) {
|
||||
$mergedStyle->setFontSize($baseStyle->getFontSize());
|
||||
}
|
||||
if (!$this->hasSetFontSize && $baseStyle->getFontColor() !== self::DEFAULT_FONT_COLOR) {
|
||||
$mergedStyle->setFontColor($baseStyle->getFontColor());
|
||||
}
|
||||
if (!$this->hasSetFontName && $baseStyle->getFontName() !== self::DEFAULT_FONT_NAME) {
|
||||
$mergedStyle->setFontName($baseStyle->getFontName());
|
||||
}
|
||||
if (!$this->hasSetWrapText && $baseStyle->shouldWrapText()) {
|
||||
$mergedStyle->setShouldWrapText();
|
||||
}
|
||||
|
||||
return $mergedStyle;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\Style;
|
||||
|
||||
/**
|
||||
* Class StyleBuilder
|
||||
* Builder to create new styles
|
||||
*
|
||||
* @package Box\Spout\Writer\Style
|
||||
*/
|
||||
class StyleBuilder
|
||||
{
|
||||
/** @var Style Style to be created */
|
||||
protected $style;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
$this->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 it's too long or
|
||||
* on multiple lines.
|
||||
*
|
||||
* @api
|
||||
* @return StyleBuilder
|
||||
*/
|
||||
public function setShouldWrapText()
|
||||
{
|
||||
$this->style->setShouldWrapText();
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the configured style. The style is cached and can be reused.
|
||||
*
|
||||
* @api
|
||||
* @return Style
|
||||
*/
|
||||
public function build()
|
||||
{
|
||||
return $this->style;
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ use Box\Spout\Common\Type;
|
||||
/**
|
||||
* Class WriterFactory
|
||||
* This factory is used to create writers, based on the type of the file to be read.
|
||||
* It supports CSV and XLSX formats.
|
||||
* It supports CSV, XLSX and ODS formats.
|
||||
*
|
||||
* @package Box\Spout\Writer
|
||||
*/
|
||||
@@ -18,6 +18,7 @@ class WriterFactory
|
||||
/**
|
||||
* This creates an instance of the appropriate writer, given the type of the file to be read
|
||||
*
|
||||
* @api
|
||||
* @param string $writerType Type of the writer to instantiate
|
||||
* @return WriterInterface
|
||||
* @throws \Box\Spout\Common\Exception\UnsupportedTypeException
|
||||
@@ -33,6 +34,9 @@ class WriterFactory
|
||||
case Type::XLSX:
|
||||
$writer = new XLSX\Writer();
|
||||
break;
|
||||
case Type::ODS:
|
||||
$writer = new ODS\Writer();
|
||||
break;
|
||||
default:
|
||||
throw new UnsupportedTypeException('No writers supporting the given type: ' . $writerType);
|
||||
}
|
||||
|
||||
@@ -40,6 +40,19 @@ interface WriterInterface
|
||||
*/
|
||||
public function addRow(array $dataRow);
|
||||
|
||||
/**
|
||||
* Write given data to the output and apply the given style.
|
||||
* @see addRow
|
||||
*
|
||||
* @param array $dataRow Array of array containing data to be streamed.
|
||||
* @param Style\Style $style Style to be applied to the row.
|
||||
* @return WriterInterface
|
||||
* @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);
|
||||
|
||||
/**
|
||||
* Write given data to the output. New data will be appended to end of stream.
|
||||
*
|
||||
@@ -55,6 +68,19 @@ interface WriterInterface
|
||||
*/
|
||||
public function addRows(array $dataRows);
|
||||
|
||||
/**
|
||||
* Write given data to the output and apply the given style.
|
||||
* @see addRows
|
||||
*
|
||||
* @param array $dataRows Array of array containing data to be streamed.
|
||||
* @param Style\Style $style Style to be applied to the rows.
|
||||
* @return WriterInterface
|
||||
* @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);
|
||||
|
||||
/**
|
||||
* Closes the writer. This will close the streamer as well, preventing new data
|
||||
* to be written to the file.
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Box\Spout\Writer\XLSX\Helper;
|
||||
|
||||
use Box\Spout\Writer\Common\Helper\ZipHelper;
|
||||
use Box\Spout\Writer\XLSX\Internal\Worksheet;
|
||||
|
||||
/**
|
||||
@@ -26,6 +27,7 @@ class FileSystemHelper extends \Box\Spout\Common\Helper\FileSystemHelper
|
||||
const CONTENT_TYPES_XML_FILE_NAME = '[Content_Types].xml';
|
||||
const WORKBOOK_XML_FILE_NAME = 'workbook.xml';
|
||||
const WORKBOOK_RELS_XML_FILE_NAME = 'workbook.xml.rels';
|
||||
const STYLES_XML_FILE_NAME = 'styles.xml';
|
||||
|
||||
/** @var string Path to the root folder inside the temp folder where the files to create the XLSX will be stored */
|
||||
protected $rootFolder;
|
||||
@@ -92,7 +94,7 @@ class FileSystemHelper extends \Box\Spout\Common\Helper\FileSystemHelper
|
||||
*/
|
||||
protected function createRootFolder()
|
||||
{
|
||||
$this->rootFolder = $this->createFolder($this->baseFolderPath, uniqid('xlsx'));
|
||||
$this->rootFolder = $this->createFolder($this->baseFolderPath, uniqid('xlsx', true));
|
||||
return $this;
|
||||
}
|
||||
|
||||
@@ -179,10 +181,10 @@ EOD;
|
||||
*/
|
||||
protected function createCoreXmlFile()
|
||||
{
|
||||
$createdDate = (new \DateTime())->format('c');
|
||||
$createdDate = (new \DateTime())->format(\DateTime::W3C);
|
||||
$coreXmlFileContents = <<<EOD
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<dcterms:created xsi:type="dcterms:W3CDTF">$createdDate</dcterms:created>
|
||||
<dcterms:modified xsi:type="dcterms:W3CDTF">$createdDate</dcterms:modified>
|
||||
<cp:revision>0</cp:revision>
|
||||
@@ -247,15 +249,15 @@ EOD;
|
||||
<Default ContentType="application/xml" Extension="xml"/>
|
||||
<Default ContentType="application/vnd.openxmlformats-package.relationships+xml" Extension="rels"/>
|
||||
<Override ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml" PartName="/xl/workbook.xml"/>
|
||||
|
||||
EOD;
|
||||
|
||||
/** @var Worksheet $worksheet */
|
||||
foreach ($worksheets as $worksheet) {
|
||||
$contentTypesXmlFileContents .= ' <Override ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml" PartName="/xl/worksheets/sheet' . $worksheet->getId() . '.xml"/>' . PHP_EOL;
|
||||
$contentTypesXmlFileContents .= '<Override ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml" PartName="/xl/worksheets/sheet' . $worksheet->getId() . '.xml"/>';
|
||||
}
|
||||
|
||||
$contentTypesXmlFileContents .= <<<EOD
|
||||
<Override ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml" PartName="/xl/styles.xml"/>
|
||||
<Override ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml" PartName="/xl/sharedStrings.xml"/>
|
||||
<Override ContentType="application/vnd.openxmlformats-package.core-properties+xml" PartName="/docProps/core.xml"/>
|
||||
<Override ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml" PartName="/docProps/app.xml"/>
|
||||
@@ -279,16 +281,16 @@ EOD;
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
|
||||
<sheets>
|
||||
|
||||
EOD;
|
||||
|
||||
/** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
|
||||
$escaper = new \Box\Spout\Common\Escaper\XLSX();
|
||||
|
||||
/** @var Worksheet $worksheet */
|
||||
foreach ($worksheets as $worksheet) {
|
||||
$worksheetName = $worksheet->getExternalSheet()->getName();
|
||||
$worksheetId = $worksheet->getId();
|
||||
$workbookXmlFileContents .= ' <sheet name="' . $escaper->escape($worksheetName) . '" sheetId="' . $worksheetId . '" r:id="rIdSheet' . $worksheetId . '"/>' . PHP_EOL;
|
||||
$workbookXmlFileContents .= '<sheet name="' . $escaper->escape($worksheetName) . '" sheetId="' . $worksheetId . '" r:id="rIdSheet' . $worksheetId . '"/>';
|
||||
}
|
||||
|
||||
$workbookXmlFileContents .= <<<EOD
|
||||
@@ -312,14 +314,14 @@ EOD;
|
||||
$workbookRelsXmlFileContents = <<<EOD
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||||
<Relationship Id="rIdStyles" Target="styles.xml" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"/>
|
||||
<Relationship Id="rIdSharedStrings" Target="sharedStrings.xml" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings"/>
|
||||
|
||||
EOD;
|
||||
|
||||
/** @var Worksheet $worksheet */
|
||||
foreach ($worksheets as $worksheet) {
|
||||
$worksheetId = $worksheet->getId();
|
||||
$workbookRelsXmlFileContents .= ' <Relationship Id="rIdSheet' . $worksheetId . '" Target="worksheets/sheet' . $worksheetId . '.xml" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"/>' . PHP_EOL;
|
||||
$workbookRelsXmlFileContents .= '<Relationship Id="rIdSheet' . $worksheetId . '" Target="worksheets/sheet' . $worksheetId . '.xml" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"/>';
|
||||
}
|
||||
|
||||
$workbookRelsXmlFileContents .= '</Relationships>';
|
||||
@@ -329,6 +331,20 @@ EOD;
|
||||
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
|
||||
*
|
||||
@@ -337,42 +353,10 @@ EOD;
|
||||
*/
|
||||
public function zipRootFolderAndCopyToStream($streamPointer)
|
||||
{
|
||||
$this->zipRootFolder();
|
||||
$this->copyZipToStream($streamPointer);
|
||||
$zipHelper = new ZipHelper();
|
||||
$zipHelper->zipFolderAndCopyToStream($this->rootFolder, $streamPointer);
|
||||
|
||||
// once the zip is copied, remove it
|
||||
$this->deleteFile($this->getZipFilePath());
|
||||
}
|
||||
|
||||
/**
|
||||
* Zips the root folder
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function zipRootFolder()
|
||||
{
|
||||
$zipHelper = new ZipHelper();
|
||||
$zipHelper->zipFolder($this->rootFolder, $this->getZipFilePath());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string Path of the zip file created from the root folder
|
||||
*/
|
||||
protected function getZipFilePath()
|
||||
{
|
||||
return $this->rootFolder . '.zip';
|
||||
}
|
||||
|
||||
/**
|
||||
* Streams the contents of the zip 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);
|
||||
$this->deleteFile($zipHelper->getZipFilePath($this->rootFolder));
|
||||
}
|
||||
}
|
||||
@@ -45,9 +45,10 @@ EOD;
|
||||
$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 . '>' . PHP_EOL;
|
||||
$header = self::SHARED_STRINGS_XML_FILE_FIRST_PART_HEADER . ' ' . self::DEFAULT_STRINGS_COUNT_PART . '>';
|
||||
fwrite($this->sharedStringsFilePointer, $header);
|
||||
|
||||
/** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
|
||||
$this->stringsEscaper = new \Box\Spout\Common\Escaper\XLSX();
|
||||
}
|
||||
|
||||
@@ -73,7 +74,7 @@ EOD;
|
||||
*/
|
||||
public function writeString($string)
|
||||
{
|
||||
fwrite($this->sharedStringsFilePointer, ' <si><t xml:space="preserve">' . $this->stringsEscaper->escape($string) . '</t></si>' . PHP_EOL);
|
||||
fwrite($this->sharedStringsFilePointer, '<si><t xml:space="preserve">' . $this->stringsEscaper->escape($string) . '</t></si>');
|
||||
$this->numSharedStrings++;
|
||||
|
||||
// Shared string ID is zero-based
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\XLSX\Helper;
|
||||
|
||||
use Box\Spout\Writer\Common\Helper\AbstractStyleHelper;
|
||||
use Box\Spout\Writer\Style\Color;
|
||||
|
||||
/**
|
||||
* Class StyleHelper
|
||||
* This class provides helper functions to manage styles
|
||||
*
|
||||
* @package Box\Spout\Writer\XLSX\Helper
|
||||
*/
|
||||
class StyleHelper extends AbstractStyleHelper
|
||||
{
|
||||
/**
|
||||
* Returns the content of the "styles.xml" file, given a list of styles.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getStylesXMLFileContent()
|
||||
{
|
||||
$content = <<<EOD
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
|
||||
EOD;
|
||||
|
||||
$content .= $this->getFontsSectionContent();
|
||||
$content .= $this->getFillsSectionContent();
|
||||
$content .= $this->getBordersSectionContent();
|
||||
$content .= $this->getCellStyleXfsSectionContent();
|
||||
$content .= $this->getCellXfsSectionContent();
|
||||
$content .= $this->getCellStylesSectionContent();
|
||||
|
||||
$content .= <<<EOD
|
||||
</styleSheet>
|
||||
EOD;
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the content of the "<fonts>" section.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getFontsSectionContent()
|
||||
{
|
||||
$content = '<fonts count="' . count($this->styleIdToStyleMappingTable) . '">';
|
||||
|
||||
/** @var \Box\Spout\Writer\Style\Style $style */
|
||||
foreach ($this->getRegisteredStyles() as $style) {
|
||||
$content .= '<font>';
|
||||
|
||||
$content .= '<sz val="' . $style->getFontSize() . '"/>';
|
||||
$content .= '<color rgb="' . Color::toARGB($style->getFontColor()) . '"/>';
|
||||
$content .= '<name val="' . $style->getFontName() . '"/>';
|
||||
|
||||
if ($style->isFontBold()) {
|
||||
$content .= '<b/>';
|
||||
}
|
||||
if ($style->isFontItalic()) {
|
||||
$content .= '<i/>';
|
||||
}
|
||||
if ($style->isFontUnderline()) {
|
||||
$content .= '<u/>';
|
||||
}
|
||||
if ($style->isFontStrikethrough()) {
|
||||
$content .= '<strike/>';
|
||||
}
|
||||
|
||||
$content .= '</font>';
|
||||
}
|
||||
|
||||
$content .= '</fonts>';
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the content of the "<fills>" section.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getFillsSectionContent()
|
||||
{
|
||||
return <<<EOD
|
||||
<fills count="1">
|
||||
<fill>
|
||||
<patternFill patternType="none"/>
|
||||
</fill>
|
||||
</fills>
|
||||
EOD;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the content of the "<borders>" section.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getBordersSectionContent()
|
||||
{
|
||||
return <<<EOD
|
||||
<borders count="1">
|
||||
<border>
|
||||
<left/>
|
||||
<right/>
|
||||
<top/>
|
||||
<bottom/>
|
||||
<diagonal/>
|
||||
</border>
|
||||
</borders>
|
||||
EOD;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the content of the "<cellStyleXfs>" section.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getCellStyleXfsSectionContent()
|
||||
{
|
||||
return <<<EOD
|
||||
<cellStyleXfs count="1">
|
||||
<xf borderId="0" fillId="0" fontId="0" numFmtId="0"/>
|
||||
</cellStyleXfs>
|
||||
EOD;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the content of the "<cellXfs>" section.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getCellXfsSectionContent()
|
||||
{
|
||||
$registeredStyles = $this->getRegisteredStyles();
|
||||
|
||||
$content = '<cellXfs count="' . count($registeredStyles) . '">';
|
||||
|
||||
foreach ($registeredStyles as $style) {
|
||||
$content .= '<xf numFmtId="0" fontId="' . $style->getId() . '" fillId="0" borderId="0" xfId="0"';
|
||||
|
||||
if ($style->shouldApplyFont()) {
|
||||
$content .= ' applyFont="1"';
|
||||
}
|
||||
|
||||
if ($style->shouldWrapText()) {
|
||||
$content .= ' applyAlignment="1">';
|
||||
$content .= '<alignment wrapText="1"/>';
|
||||
$content .= '</xf>';
|
||||
} else {
|
||||
$content .= '/>';
|
||||
}
|
||||
}
|
||||
|
||||
$content .= '</cellXfs>';
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the content of the "<cellStyles>" section.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getCellStylesSectionContent()
|
||||
{
|
||||
return <<<EOD
|
||||
<cellStyles count="1">
|
||||
<cellStyle builtinId="0" name="Normal" xfId="0"/>
|
||||
</cellStyles>
|
||||
EOD;
|
||||
}
|
||||
}
|
||||
@@ -2,19 +2,20 @@
|
||||
|
||||
namespace Box\Spout\Writer\XLSX\Internal;
|
||||
|
||||
use Box\Spout\Writer\Exception\SheetNotFoundException;
|
||||
use Box\Spout\Writer\Common\Internal\AbstractWorkbook;
|
||||
use Box\Spout\Writer\XLSX\Helper\FileSystemHelper;
|
||||
use Box\Spout\Writer\XLSX\Helper\SharedStringsHelper;
|
||||
use Box\Spout\Writer\XLSX\Sheet;
|
||||
use Box\Spout\Writer\XLSX\Helper\StyleHelper;
|
||||
use Box\Spout\Writer\Common\Sheet;
|
||||
|
||||
/**
|
||||
* Class Book
|
||||
* Class Workbook
|
||||
* Represents a workbook within a XLSX file.
|
||||
* It provides the functions to work with worksheets.
|
||||
*
|
||||
* @package Box\Spout\Writer\XLSX\Internal
|
||||
*/
|
||||
class Workbook
|
||||
class Workbook extends AbstractWorkbook
|
||||
{
|
||||
/**
|
||||
* Maximum number of rows a XLSX sheet can contain
|
||||
@@ -25,40 +26,54 @@ class Workbook
|
||||
/** @var bool Whether inline or shared strings should be used */
|
||||
protected $shouldUseInlineStrings;
|
||||
|
||||
/** @var bool Whether new sheets should be automatically created when the max rows limit per sheet is reached */
|
||||
protected $shouldCreateNewSheetsAutomatically;
|
||||
|
||||
/** @var \Box\Spout\Writer\XLSX\Helper\FileSystemHelper Helper to perform file system operations */
|
||||
protected $fileSystemHelper;
|
||||
|
||||
/** @var \Box\Spout\Writer\XLSX\Helper\SharedStringsHelper Helper to write shared strings */
|
||||
protected $sharedStringsHelper;
|
||||
|
||||
/** @var Worksheet[] Array containing the workbook's sheets */
|
||||
protected $worksheets = [];
|
||||
|
||||
/** @var Worksheet The worksheet where data will be written to */
|
||||
protected $currentWorksheet;
|
||||
/** @var \Box\Spout\Writer\XLSX\Helper\StyleHelper Helper to apply styles */
|
||||
protected $styleHelper;
|
||||
|
||||
/**
|
||||
* @param string $tempFolder
|
||||
* @param bool $shouldUseInlineStrings
|
||||
* @param bool $shouldCreateNewSheetsAutomatically
|
||||
* @param \Box\Spout\Writer\Style\Style $defaultRowStyle
|
||||
* @throws \Box\Spout\Common\Exception\IOException If unable to create at least one of the base folders
|
||||
*/
|
||||
public function __construct($tempFolder, $shouldUseInlineStrings, $shouldCreateNewSheetsAutomatically)
|
||||
public function __construct($tempFolder, $shouldUseInlineStrings, $shouldCreateNewSheetsAutomatically, $defaultRowStyle)
|
||||
{
|
||||
parent::__construct($shouldCreateNewSheetsAutomatically, $defaultRowStyle);
|
||||
|
||||
$this->shouldUseInlineStrings = $shouldUseInlineStrings;
|
||||
$this->shouldCreateNewSheetsAutomatically = $shouldCreateNewSheetsAutomatically;
|
||||
|
||||
$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.
|
||||
*
|
||||
@@ -77,125 +92,6 @@ class Workbook
|
||||
return $worksheet;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 Worksheet 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 Worksheet[] All the workbook's sheets
|
||||
*/
|
||||
public function getWorksheets()
|
||||
{
|
||||
return $this->worksheets;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current sheet
|
||||
*
|
||||
* @return Worksheet 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\XLSX\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 Worksheet $worksheet
|
||||
* @return void
|
||||
*/
|
||||
protected function setCurrentWorksheet($worksheet)
|
||||
{
|
||||
$this->currentWorksheet = $worksheet;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the worksheet associated to the given external sheet.
|
||||
*
|
||||
* @param \Box\Spout\Writer\XLSX\Sheet $sheet
|
||||
* @return Worksheet|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.
|
||||
* Example $dataRow = ['data1', 1234, null, '', 'data5'];
|
||||
* @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)
|
||||
{
|
||||
$currentWorksheet = $this->getCurrentWorksheet();
|
||||
$hasReachedMaxRows = $this->hasCurrentWorkseetReachedMaxRows();
|
||||
|
||||
// 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();
|
||||
$currentWorksheet->addRow($dataRow);
|
||||
} else {
|
||||
// otherwise, do nothing as the data won't be read anyways
|
||||
}
|
||||
} else {
|
||||
$currentWorksheet->addRow($dataRow);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool Whether the current worksheet has reached the maximum number of rows per sheet.
|
||||
*/
|
||||
protected function hasCurrentWorkseetReachedMaxRows()
|
||||
{
|
||||
$currentWorksheet = $this->getCurrentWorksheet();
|
||||
return ($currentWorksheet->getLastWrittenRowIndex() >= self::$maxRowsPerWorksheet);
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the workbook and all its associated sheets.
|
||||
* All the necessary files are written to disk and zipped together to create the XLSX file.
|
||||
@@ -206,7 +102,10 @@ class Workbook
|
||||
*/
|
||||
public function close($finalFilePointer)
|
||||
{
|
||||
foreach ($this->worksheets as $worksheet) {
|
||||
/** @var Worksheet[] $worksheets */
|
||||
$worksheets = $this->worksheets;
|
||||
|
||||
foreach ($worksheets as $worksheet) {
|
||||
$worksheet->close();
|
||||
}
|
||||
|
||||
@@ -214,9 +113,10 @@ class Workbook
|
||||
|
||||
// Finish creating all the necessary files before zipping everything together
|
||||
$this->fileSystemHelper
|
||||
->createContentTypesFile($this->worksheets)
|
||||
->createWorkbookFile($this->worksheets)
|
||||
->createWorkbookRelsFile($this->worksheets)
|
||||
->createContentTypesFile($worksheets)
|
||||
->createWorkbookFile($worksheets)
|
||||
->createWorkbookRelsFile($worksheets)
|
||||
->createStylesFile($this->styleHelper)
|
||||
->zipRootFolderAndCopyToStream($finalFilePointer);
|
||||
|
||||
$this->cleanupTempFolder();
|
||||
|
||||
@@ -4,7 +4,8 @@ namespace Box\Spout\Writer\XLSX\Internal;
|
||||
|
||||
use Box\Spout\Common\Exception\InvalidArgumentException;
|
||||
use Box\Spout\Common\Exception\IOException;
|
||||
use Box\Spout\Writer\XLSX\Helper\CellHelper;
|
||||
use Box\Spout\Writer\Common\Helper\CellHelper;
|
||||
use Box\Spout\Writer\Common\Internal\WorksheetInterface;
|
||||
|
||||
/**
|
||||
* Class Worksheet
|
||||
@@ -13,14 +14,14 @@ use Box\Spout\Writer\XLSX\Helper\CellHelper;
|
||||
*
|
||||
* @package Box\Spout\Writer\XLSX\Internal
|
||||
*/
|
||||
class Worksheet
|
||||
class Worksheet implements WorksheetInterface
|
||||
{
|
||||
const SHEET_XML_FILE_HEADER = <<<EOD
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
|
||||
EOD;
|
||||
|
||||
/** @var \Box\Spout\Writer\XLSX\Sheet The "external" sheet */
|
||||
/** @var \Box\Spout\Writer\Common\Sheet The "external" sheet */
|
||||
protected $externalSheet;
|
||||
|
||||
/** @var string Path to the XML file that will contain the sheet data */
|
||||
@@ -38,11 +39,11 @@ EOD;
|
||||
/** @var Resource Pointer to the sheet data file (e.g. xl/worksheets/sheet1.xml) */
|
||||
protected $sheetFilePointer;
|
||||
|
||||
/** @var int */
|
||||
/** @var int Index of the last written row */
|
||||
protected $lastWrittenRowIndex = 0;
|
||||
|
||||
/**
|
||||
* @param \Box\Spout\Writer\XLSX\Sheet $externalSheet The associated "external" sheet
|
||||
* @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 bool $shouldUseInlineStrings Whether inline or shared strings should be used
|
||||
@@ -54,6 +55,7 @@ EOD;
|
||||
$this->sharedStringsHelper = $sharedStringsHelper;
|
||||
$this->shouldUseInlineStrings = $shouldUseInlineStrings;
|
||||
|
||||
/** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
|
||||
$this->stringsEscaper = new \Box\Spout\Common\Escaper\XLSX();
|
||||
|
||||
$this->worksheetFilePath = $worksheetFilesFolder . '/' . strtolower($this->externalSheet->getName()) . '.xml';
|
||||
@@ -71,12 +73,25 @@ EOD;
|
||||
$this->sheetFilePointer = fopen($this->worksheetFilePath, 'w');
|
||||
$this->throwIfSheetFilePointerIsNotAvailable();
|
||||
|
||||
fwrite($this->sheetFilePointer, self::SHEET_XML_FILE_HEADER . PHP_EOL);
|
||||
fwrite($this->sheetFilePointer, ' <sheetData>' . PHP_EOL);
|
||||
fwrite($this->sheetFilePointer, self::SHEET_XML_FILE_HEADER);
|
||||
fwrite($this->sheetFilePointer, '<sheetData>');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Box\Spout\Writer\XLSX\Sheet The "external" sheet
|
||||
* 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()
|
||||
{
|
||||
@@ -100,51 +115,42 @@ EOD;
|
||||
return $this->externalSheet->getIndex() + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds data to the worksheet.
|
||||
*
|
||||
* @param array $dataRow Array containing data to be written.
|
||||
* @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)
|
||||
public function addRow($dataRow, $style)
|
||||
{
|
||||
$cellNumber = 0;
|
||||
$rowIndex = $this->lastWrittenRowIndex + 1;
|
||||
$numCells = count($dataRow);
|
||||
|
||||
$data = ' <row r="' . $rowIndex . '" spans="1:' . $numCells . '">' . PHP_EOL;
|
||||
$data = '<row r="' . $rowIndex . '" spans="1:' . $numCells . '">';
|
||||
|
||||
foreach($dataRow as $cellValue) {
|
||||
$columnIndex = CellHelper::getCellIndexFromColumnIndex($cellNumber);
|
||||
$data .= ' <c r="' . $columnIndex . $rowIndex . '"';
|
||||
$data .= '<c r="' . $columnIndex . $rowIndex . '"';
|
||||
$data .= ' s="' . $style->getId() . '"';
|
||||
|
||||
if (CellHelper::isNonEmptyString($cellValue)) {
|
||||
if ($this->shouldUseInlineStrings) {
|
||||
$data .= ' t="inlineStr"><is><t>' . $this->stringsEscaper->escape($cellValue) . '</t></is></c>' . PHP_EOL;
|
||||
$data .= ' t="inlineStr"><is><t>' . $this->stringsEscaper->escape($cellValue) . '</t></is></c>';
|
||||
} else {
|
||||
$sharedStringId = $this->sharedStringsHelper->writeString($cellValue);
|
||||
$data .= ' t="s"><v>' . $sharedStringId . '</v></c>' . PHP_EOL;
|
||||
$data .= ' t="s"><v>' . $sharedStringId . '</v></c>';
|
||||
}
|
||||
} else if (CellHelper::isNumeric($cellValue) || CellHelper::isBoolean($cellValue)) {
|
||||
$data .= '><v>' . $cellValue . '</v></c>' . PHP_EOL;
|
||||
} else if (CellHelper::isBoolean($cellValue)) {
|
||||
$data .= ' t="b"><v>' . $cellValue . '</v></c>';
|
||||
} else if (CellHelper::isNumeric($cellValue)) {
|
||||
$data .= '><v>' . $cellValue . '</v></c>';
|
||||
} else if (empty($cellValue)) {
|
||||
$data .= '/>' . PHP_EOL;
|
||||
$data .= '/>';
|
||||
} else {
|
||||
throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cellValue));
|
||||
}
|
||||
@@ -152,7 +158,7 @@ EOD;
|
||||
$cellNumber++;
|
||||
}
|
||||
|
||||
$data .= ' </row>' . PHP_EOL;
|
||||
$data .= '</row>';
|
||||
|
||||
$wasWriteSuccessful = fwrite($this->sheetFilePointer, $data);
|
||||
if ($wasWriteSuccessful === false) {
|
||||
@@ -170,7 +176,7 @@ EOD;
|
||||
*/
|
||||
public function close()
|
||||
{
|
||||
fwrite($this->sheetFilePointer, ' </sheetData>' . PHP_EOL);
|
||||
fwrite($this->sheetFilePointer, '</sheetData>');
|
||||
fwrite($this->sheetFilePointer, '</worksheet>');
|
||||
fclose($this->sheetFilePointer);
|
||||
}
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\XLSX;
|
||||
|
||||
/**
|
||||
* Class Sheet
|
||||
* Represents a worksheet within a XLSX file
|
||||
*
|
||||
* @package Box\Spout\Writer\XLSX
|
||||
*/
|
||||
class Sheet
|
||||
{
|
||||
const DEFAULT_SHEET_NAME_PREFIX = 'Sheet';
|
||||
|
||||
/** @var int Index of the sheet, based on order of creation (zero-based) */
|
||||
protected $index;
|
||||
|
||||
/** @var string Name of the sheet */
|
||||
protected $name;
|
||||
|
||||
/**
|
||||
* @param int $sheetIndex Index of the sheet, based on order of creation (zero-based)
|
||||
*/
|
||||
public function __construct($sheetIndex)
|
||||
{
|
||||
$this->index = $sheetIndex;
|
||||
$this->name = self::DEFAULT_SHEET_NAME_PREFIX . ($sheetIndex + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int Index of the sheet, based on order of creation (zero-based)
|
||||
*/
|
||||
public function getIndex()
|
||||
{
|
||||
return $this->index;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string Name of the sheet
|
||||
*/
|
||||
public function getName()
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $name Name of the sheet
|
||||
* @return Sheet
|
||||
*/
|
||||
public function setName($name)
|
||||
{
|
||||
$this->name = $name;
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
namespace Box\Spout\Writer\XLSX;
|
||||
|
||||
use Box\Spout\Writer\AbstractWriter;
|
||||
use Box\Spout\Writer\Exception\WriterNotOpenedException;
|
||||
use Box\Spout\Writer\AbstractMultiSheetsWriter;
|
||||
use Box\Spout\Writer\Style\StyleBuilder;
|
||||
use Box\Spout\Writer\XLSX\Internal\Workbook;
|
||||
|
||||
/**
|
||||
@@ -12,8 +12,12 @@ use Box\Spout\Writer\XLSX\Internal\Workbook;
|
||||
*
|
||||
* @package Box\Spout\Writer\XLSX
|
||||
*/
|
||||
class Writer extends AbstractWriter
|
||||
class Writer extends AbstractMultiSheetsWriter
|
||||
{
|
||||
/** Default style font values */
|
||||
const DEFAULT_FONT_SIZE = 12;
|
||||
const DEFAULT_FONT_NAME = 'Calibri';
|
||||
|
||||
/** @var string Content-Type value for the header */
|
||||
protected static $headerContentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
|
||||
|
||||
@@ -23,44 +27,40 @@ class Writer extends AbstractWriter
|
||||
/** @var bool Whether inline or shared strings should be used - inline string is more memory efficient */
|
||||
protected $shouldUseInlineStrings = true;
|
||||
|
||||
/** @var bool Whether new sheets should be automatically created when the max rows limit per sheet is reached */
|
||||
protected $shouldCreateNewSheetsAutomatically = true;
|
||||
|
||||
/** @var Internal\Workbook The workbook for the XLSX file */
|
||||
protected $book;
|
||||
|
||||
/** @var int */
|
||||
protected $highestRowIndex = 0;
|
||||
|
||||
/**
|
||||
* Sets a custom temporary folder for creating intermediate files/folders.
|
||||
* This must be set before opening the writer.
|
||||
*
|
||||
* @api
|
||||
* @param string $tempFolder Temporary folder where the files to create the XLSX will be stored
|
||||
* @return Writer
|
||||
* @throws \Box\Spout\Writer\Exception\WriterAlreadyOpenedException If the writer was already opened
|
||||
*/
|
||||
public function setTempFolder($tempFolder)
|
||||
{
|
||||
$this->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->shouldUseInlineStrings = $shouldUseInlineStrings;
|
||||
return $this;
|
||||
}
|
||||
$this->throwIfWriterAlreadyOpened('Writer must be configured before opening it.');
|
||||
|
||||
/**
|
||||
* @param bool $shouldCreateNewSheetsAutomatically Whether new sheets should be automatically created when the max rows limit per sheet is reached
|
||||
* @return Writer
|
||||
*/
|
||||
public function setShouldCreateNewSheetsAutomatically($shouldCreateNewSheetsAutomatically)
|
||||
{
|
||||
$this->shouldCreateNewSheetsAutomatically = $shouldCreateNewSheetsAutomatically;
|
||||
$this->shouldUseInlineStrings = $shouldUseInlineStrings;
|
||||
return $this;
|
||||
}
|
||||
|
||||
@@ -74,84 +74,17 @@ class Writer extends AbstractWriter
|
||||
{
|
||||
if (!$this->book) {
|
||||
$tempFolder = ($this->tempFolder) ? : sys_get_temp_dir();
|
||||
$this->book = new Workbook($tempFolder, $this->shouldUseInlineStrings, $this->shouldCreateNewSheetsAutomatically);
|
||||
$this->book = new Workbook($tempFolder, $this->shouldUseInlineStrings, $this->shouldCreateNewSheetsAutomatically, $this->defaultRowStyle);
|
||||
$this->book->addNewSheetAndMakeItCurrent();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all the workbook's sheets
|
||||
*
|
||||
* @return Sheet[] All the workbook's sheets
|
||||
* @throws \Box\Spout\Writer\Exception\WriterNotOpenedException If the writer has not been opened yet
|
||||
* @return Internal\Workbook The workbook representing the file to be written
|
||||
*/
|
||||
public function getSheets()
|
||||
protected function getWorkbook()
|
||||
{
|
||||
$this->throwIfBookIsNotAvailable();
|
||||
|
||||
$externalSheets = [];
|
||||
$worksheets = $this->book->getWorksheets();
|
||||
|
||||
/** @var Internal\Worksheet $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.
|
||||
*
|
||||
* @return 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->book->addNewSheetAndMakeItCurrent();
|
||||
|
||||
return $worksheet->getExternalSheet();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current sheet
|
||||
*
|
||||
* @return 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->book->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).
|
||||
*
|
||||
* @param 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->book->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->book) {
|
||||
throw new WriterNotOpenedException('The writer must be opened before performing this action.');
|
||||
}
|
||||
return $this->book;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -161,14 +94,28 @@ class Writer extends AbstractWriter
|
||||
*
|
||||
* @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)
|
||||
protected function addRowToWriter(array $dataRow, $style)
|
||||
{
|
||||
$this->throwIfBookIsNotAvailable();
|
||||
$this->book->addRowToCurrentWorksheet($dataRow);
|
||||
$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();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -34,6 +34,7 @@ class XLSXTest extends \PHPUnit_Framework_TestCase
|
||||
*/
|
||||
public function testEscape($stringToEscape, $expectedEscapedString)
|
||||
{
|
||||
/** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
|
||||
$escaper = new \Box\Spout\Common\Escaper\XLSX();
|
||||
$escapedString = $escaper->escape($stringToEscape);
|
||||
|
||||
@@ -65,6 +66,7 @@ class XLSXTest extends \PHPUnit_Framework_TestCase
|
||||
*/
|
||||
public function testUnescape($stringToUnescape, $expectedUnescapedString)
|
||||
{
|
||||
/** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
|
||||
$escaper = new \Box\Spout\Common\Escaper\XLSX();
|
||||
$unescapedString = $escaper->unescape($stringToUnescape);
|
||||
|
||||
|
||||
@@ -142,6 +142,29 @@ class ReaderTest extends \PHPUnit_Framework_TestCase
|
||||
$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
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,388 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Reader\ODS;
|
||||
|
||||
use Box\Spout\Common\Exception\IOException;
|
||||
use Box\Spout\Common\Type;
|
||||
use Box\Spout\Reader\ReaderFactory;
|
||||
use Box\Spout\TestUsingResource;
|
||||
|
||||
/**
|
||||
* Class ReaderTest
|
||||
*
|
||||
* @package Box\Spout\Reader\ODS
|
||||
*/
|
||||
class ReaderTest extends \PHPUnit_Framework_TestCase
|
||||
{
|
||||
use TestUsingResource;
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function dataProviderForTestReadShouldThrowException()
|
||||
{
|
||||
return [
|
||||
['/path/to/fake/file.ods'],
|
||||
['file_corrupted.ods'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider dataProviderForTestReadShouldThrowException
|
||||
* @expectedException \Box\Spout\Common\Exception\IOException
|
||||
*
|
||||
* @param string $filePath
|
||||
* @return void
|
||||
*/
|
||||
public function testReadShouldThrowException($filePath)
|
||||
{
|
||||
// using @ to prevent warnings/errors from being displayed
|
||||
@$this->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 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 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 testReadShouldSkipEmptyRow()
|
||||
{
|
||||
$allRows = $this->getAllRowsForFile('sheet_with_empty_row.ods');
|
||||
$this->assertEquals(2, count($allRows), 'There should be only 2 rows, because the empty row is skipped');
|
||||
|
||||
$expectedRows = [
|
||||
['ods--11', 'ods--12', 'ods--13'],
|
||||
// row skipped here
|
||||
['ods--21', 'ods--22', 'ods--23'],
|
||||
];
|
||||
$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 testReadShouldBeProtectedAgainstBillionLaughAttack()
|
||||
{
|
||||
$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);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $fileName
|
||||
* @return array All the read rows the given file
|
||||
*/
|
||||
private function getAllRowsForFile($fileName)
|
||||
{
|
||||
$allRows = [];
|
||||
$resourcePath = $this->getResourcePath($fileName);
|
||||
|
||||
$reader = ReaderFactory::create(Type::ODS);
|
||||
$reader->open($resourcePath);
|
||||
|
||||
foreach ($reader->getSheetIterator() as $sheetIndex => $sheet) {
|
||||
foreach ($sheet->getRowIterator() as $rowIndex => $row) {
|
||||
$allRows[] = $row;
|
||||
}
|
||||
}
|
||||
|
||||
$reader->close();
|
||||
|
||||
return $allRows;
|
||||
}
|
||||
}
|
||||
@@ -163,4 +163,39 @@ class XMLReaderTest extends \PHPUnit_Framework_TestCase
|
||||
|
||||
$this->assertEquals($expectedResult, $isZipStream);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function dataProviderForTestConvertURIToUseRealPath()
|
||||
{
|
||||
$tempFolder = realpath(sys_get_temp_dir());
|
||||
|
||||
return [
|
||||
['/../../../' . $tempFolder . '/test.xlsx', $tempFolder . '/test.xlsx'],
|
||||
[$tempFolder . '/test.xlsx', $tempFolder . '/test.xlsx'],
|
||||
['zip://' . $tempFolder . '/test.xlsx#test.xml', 'zip://' . $tempFolder . '/test.xlsx#test.xml'],
|
||||
['zip:///../../../' . $tempFolder . '/test.xlsx#test.xml', 'zip://' . $tempFolder . '/test.xlsx#test.xml'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider dataProviderForTestConvertURIToUseRealPath
|
||||
*
|
||||
* @param string $URI
|
||||
* @param string $expectedConvertedURI
|
||||
* @return void
|
||||
*/
|
||||
public function testConvertURIToUseRealPath($URI, $expectedConvertedURI)
|
||||
{
|
||||
$tempFolder = sys_get_temp_dir();
|
||||
touch($tempFolder . '/test.xlsx');
|
||||
|
||||
$xmlReader = new XMLReader();
|
||||
$convertedURI = \ReflectionHelper::callMethodOnObject($xmlReader, 'convertURIToUseRealPath', $URI);
|
||||
|
||||
$this->assertEquals($expectedConvertedURI, $convertedURI);
|
||||
|
||||
unlink($tempFolder . '/test.xlsx');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Reader\XLSX\Helper;
|
||||
|
||||
/**
|
||||
* Class StyleHelperTest
|
||||
*
|
||||
* @package Box\Spout\Reader\XLSX\Helper
|
||||
*/
|
||||
class StyleHelperTest extends \PHPUnit_Framework_TestCase
|
||||
{
|
||||
|
||||
/**
|
||||
* @param array $styleAttributes
|
||||
* @param array|void $customNumberFormats
|
||||
* @return StyleHelper
|
||||
*/
|
||||
private function getStyleHelperMock($styleAttributes, $customNumberFormats = [])
|
||||
{
|
||||
/** @var StyleHelper $styleHelper */
|
||||
$styleHelper = $this->getMockBuilder('\Box\Spout\Reader\XLSX\Helper\StyleHelper')
|
||||
->setMethods(['getCustomNumberFormats', 'getStylesAttributes'])
|
||||
->disableOriginalConstructor()
|
||||
->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 testShouldFormatNumericValueAsDateWhenStyleIdNotListed()
|
||||
{
|
||||
$styleHelper = $this->getStyleHelperMock([['applyNumberFormat' => true]]);
|
||||
$shouldFormatAsDate = $styleHelper->shouldFormatNumericValueAsDate(1);
|
||||
$this->assertFalse($shouldFormatAsDate);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function testShouldFormatNumericValueAsDateWhenShouldNotApplyNumberFormat()
|
||||
{
|
||||
$styleHelper = $this->getStyleHelperMock([[], ['applyNumberFormat' => false]]);
|
||||
$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 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],
|
||||
['[$-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\-yy;@', true],
|
||||
['m/d/yyyy;@', true],
|
||||
['[$-409]m/d/yy\--h:mm;@', true],
|
||||
['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);
|
||||
}
|
||||
}
|
||||
@@ -113,6 +113,52 @@ class ReaderTest extends \PHPUnit_Framework_TestCase
|
||||
$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
|
||||
*/
|
||||
@@ -173,12 +219,13 @@ class ReaderTest extends \PHPUnit_Framework_TestCase
|
||||
*/
|
||||
public function testReadShouldSkipEmptyRows()
|
||||
{
|
||||
$allRows = $this->getAllRowsForFile('sheet_with_empty_rows.xlsx');
|
||||
$allRows = $this->getAllRowsForFile('sheet_with_empty_row.xlsx');
|
||||
|
||||
$this->assertEquals(2, count($allRows), 'There should be only 2 rows, because the empty row is skipped');
|
||||
|
||||
$expectedRows = [
|
||||
['s1--A1', 's1--B1', 's1--C1', 's1--D1', 's1--E1'],
|
||||
// skipped row here
|
||||
['s1--A3', 's1--B3', 's1--C3', 's1--D3', 's1--E3'],
|
||||
];
|
||||
$this->assertEquals($expectedRows, $allRows);
|
||||
|
||||
@@ -24,11 +24,9 @@ class SheetTest extends \PHPUnit_Framework_TestCase
|
||||
|
||||
$this->assertEquals('CustomName1', $sheets[0]->getName());
|
||||
$this->assertEquals(0, $sheets[0]->getIndex());
|
||||
$this->assertEquals(1, $sheets[0]->getId());
|
||||
|
||||
$this->assertEquals('CustomName2', $sheets[1]->getName());
|
||||
$this->assertEquals(1, $sheets[1]->getIndex());
|
||||
$this->assertEquals(2, $sheets[1]->getId());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -10,13 +10,13 @@ namespace Box\Spout;
|
||||
trait TestUsingResource {
|
||||
|
||||
/** @var string Path to the test resources folder */
|
||||
private $resourcesPath = 'tests/resources/';
|
||||
private $resourcesPath = 'tests/resources';
|
||||
|
||||
/** @var string Path to the test generated resources folder */
|
||||
private $generatedResourcesPath = 'tests/resources/generated/';
|
||||
private $generatedResourcesPath = 'tests/resources/generated';
|
||||
|
||||
/** @var string Path to the test resources folder, that does not have writing permissions */
|
||||
private $generatedUnwritableResourcesPath = 'tests/resources/generated/unwritable/';
|
||||
private $generatedUnwritableResourcesPath = 'tests/resources/generated/unwritable';
|
||||
|
||||
/**
|
||||
* @param string $resourceName
|
||||
@@ -25,7 +25,7 @@ trait TestUsingResource {
|
||||
protected function getResourcePath($resourceName)
|
||||
{
|
||||
$resourceType = pathinfo($resourceName, PATHINFO_EXTENSION);
|
||||
$resourcePath = $this->resourcesPath . strtolower($resourceType) . '/' . $resourceName;
|
||||
$resourcePath = realpath($this->resourcesPath) . '/' . strtolower($resourceType) . '/' . $resourceName;
|
||||
|
||||
return (file_exists($resourcePath) ? $resourcePath : null);
|
||||
}
|
||||
@@ -37,7 +37,7 @@ trait TestUsingResource {
|
||||
protected function getGeneratedResourcePath($resourceName)
|
||||
{
|
||||
$resourceType = pathinfo($resourceName, PATHINFO_EXTENSION);
|
||||
$generatedResourcePath = $this->generatedResourcesPath . strtolower($resourceType) . '/' . $resourceName;
|
||||
$generatedResourcePath = realpath($this->generatedResourcesPath) . '/' . strtolower($resourceType) . '/' . $resourceName;
|
||||
|
||||
return $generatedResourcePath;
|
||||
}
|
||||
@@ -49,7 +49,7 @@ trait TestUsingResource {
|
||||
protected function createGeneratedFolderIfNeeded($resourceName)
|
||||
{
|
||||
$resourceType = pathinfo($resourceName, PATHINFO_EXTENSION);
|
||||
$generatedResourcePathForType = $this->generatedResourcesPath . strtolower($resourceType);
|
||||
$generatedResourcePathForType = $this->generatedResourcesPath . '/' . strtolower($resourceType);
|
||||
|
||||
if (!file_exists($generatedResourcePathForType)) {
|
||||
mkdir($generatedResourcePathForType, 0777, true);
|
||||
@@ -62,7 +62,7 @@ trait TestUsingResource {
|
||||
*/
|
||||
protected function getGeneratedUnwritableResourcePath($resourceName)
|
||||
{
|
||||
return $this->generatedUnwritableResourcesPath . $resourceName;
|
||||
return realpath($this->generatedUnwritableResourcesPath) . '/' . $resourceName;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+2
-2
@@ -1,11 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\XLSX\Helper;
|
||||
namespace Box\Spout\Writer\Common\Helper;
|
||||
|
||||
/**
|
||||
* Class CellHelperTest
|
||||
*
|
||||
* @package Box\Spout\Writer\XLSX\Helper
|
||||
* @package Box\Spout\Writer\Common\Helper
|
||||
*/
|
||||
class CellHelperTest extends \PHPUnit_Framework_TestCase
|
||||
{
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\Common;
|
||||
|
||||
/**
|
||||
* Class SheetTest
|
||||
*
|
||||
* @package Box\Spout\Writer\Common
|
||||
*/
|
||||
class SheetTest extends \PHPUnit_Framework_TestCase
|
||||
{
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function testGetSheetName()
|
||||
{
|
||||
$sheets = [new Sheet(0), new Sheet(1)];
|
||||
|
||||
$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()
|
||||
{
|
||||
$customSheetName = 'CustomName';
|
||||
$sheet = new Sheet(0);
|
||||
$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))->setName($customSheetName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function testSetSheetNameShouldNotThrowWhenSettingSameNameAsCurrentOne()
|
||||
{
|
||||
$customSheetName = 'Sheet name';
|
||||
$sheet = new Sheet(0);
|
||||
$sheet->setName($customSheetName);
|
||||
$sheet->setName($customSheetName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @expectedException \Box\Spout\Writer\Exception\InvalidSheetNameException
|
||||
* @return void
|
||||
*/
|
||||
public function testSetSheetNameShouldThrowWhenNameIsAlreadyUsed()
|
||||
{
|
||||
$customSheetName = 'Sheet name';
|
||||
|
||||
$sheet = new Sheet(0);
|
||||
$sheet->setName($customSheetName);
|
||||
|
||||
$sheet = new Sheet(1);
|
||||
$sheet->setName($customSheetName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\ODS\Helper;
|
||||
|
||||
use Box\Spout\Writer\Style\StyleBuilder;
|
||||
|
||||
/**
|
||||
* Class StyleHelperTest
|
||||
*
|
||||
* @package Box\Spout\Writer\ODS\Helper
|
||||
*/
|
||||
class StyleHelperTest extends \PHPUnit_Framework_TestCase
|
||||
{
|
||||
/** @var \Box\Spout\Writer\Style\Style */
|
||||
protected $defaultStyle;
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function setUp()
|
||||
{
|
||||
$this->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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\ODS;
|
||||
|
||||
use Box\Spout\Common\Type;
|
||||
use Box\Spout\TestUsingResource;
|
||||
use Box\Spout\Writer\Common\Sheet;
|
||||
use Box\Spout\Writer\WriterFactory;
|
||||
|
||||
/**
|
||||
* Class SheetTest
|
||||
*
|
||||
* @package Box\Spout\Writer\ODS
|
||||
*/
|
||||
class SheetTest extends \PHPUnit_Framework_TestCase
|
||||
{
|
||||
use TestUsingResource;
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function testGetSheetIndex()
|
||||
{
|
||||
$sheets = $this->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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,509 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\ODS;
|
||||
|
||||
use Box\Spout\Common\Type;
|
||||
use Box\Spout\Reader\Wrapper\XMLReader;
|
||||
use Box\Spout\TestUsingResource;
|
||||
use Box\Spout\Writer\WriterFactory;
|
||||
|
||||
/**
|
||||
* Class WriterTest
|
||||
*
|
||||
* @package Box\Spout\Writer\ODS
|
||||
*/
|
||||
class WriterTest extends \PHPUnit_Framework_TestCase
|
||||
{
|
||||
use TestUsingResource;
|
||||
|
||||
/**
|
||||
* @expectedException \Box\Spout\Common\Exception\IOException
|
||||
*/
|
||||
public function testAddRowShouldThrowExceptionIfCannotOpenAFileForWriting()
|
||||
{
|
||||
$fileName = 'file_that_wont_be_written.ods';
|
||||
$this->createUnwritableFolderIfNeeded($fileName);
|
||||
$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 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 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 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 <must> be escaped & tested'],
|
||||
];
|
||||
|
||||
$this->writeToODSFile($dataRows, $fileName);
|
||||
|
||||
$this->assertValueWasWritten($fileName, 'I'm in "great" mood', 'Quotes should 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');
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 = "<text:p>$value</text:p>";
|
||||
|
||||
$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 = "<text:p>$value</text:p>";
|
||||
|
||||
$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);
|
||||
$pathToSheetFile = $resourcePath . '#content.xml';
|
||||
|
||||
$xmlReader = new XMLReader();
|
||||
$xmlReader->open('zip://' . $pathToSheetFile);
|
||||
$xmlReader->readUntilNodeFound('table:table');
|
||||
|
||||
for ($i = 1; $i < $sheetIndex; $i++) {
|
||||
$xmlReader->readUntilNodeFound('table:table');
|
||||
}
|
||||
|
||||
return $xmlReader;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\ODS;
|
||||
|
||||
use Box\Spout\Common\Type;
|
||||
use Box\Spout\Reader\Wrapper\XMLReader;
|
||||
use Box\Spout\TestUsingResource;
|
||||
use Box\Spout\Writer\Style\Color;
|
||||
use Box\Spout\Writer\Style\Style;
|
||||
use Box\Spout\Writer\Style\StyleBuilder;
|
||||
use Box\Spout\Writer\WriterFactory;
|
||||
|
||||
/**
|
||||
* Class WriterWithStyleTest
|
||||
*
|
||||
* @package Box\Spout\Writer\ODS
|
||||
*/
|
||||
class WriterWithStyleTest extends \PHPUnit_Framework_TestCase
|
||||
{
|
||||
use TestUsingResource;
|
||||
|
||||
/** @var \Box\Spout\Writer\Style\Style */
|
||||
protected $defaultStyle;
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function setUp()
|
||||
{
|
||||
$this->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')
|
||||
->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');
|
||||
}
|
||||
|
||||
/**
|
||||
* @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');
|
||||
}
|
||||
|
||||
/**
|
||||
* @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[] $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);
|
||||
$pathToStylesXmlFile = $resourcePath . '#content.xml';
|
||||
|
||||
$xmlReader = new \XMLReader();
|
||||
$xmlReader->open('zip://' . $pathToStylesXmlFile);
|
||||
|
||||
while ($xmlReader->read()) {
|
||||
if ($xmlReader->nodeType === \XMLReader::ELEMENT && $xmlReader->name === 'table:table-cell' && $xmlReader->getAttribute('office:value-type') !== null) {
|
||||
$cellElements[] = $xmlReader->expand();
|
||||
}
|
||||
}
|
||||
|
||||
return $cellElements;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $fileName
|
||||
* @return \DOMNode[]
|
||||
*/
|
||||
private function getCellStyleElementsFromContentXmlFile($fileName)
|
||||
{
|
||||
$cellStyleElements = [];
|
||||
|
||||
$resourcePath = $this->getGeneratedResourcePath($fileName);
|
||||
$pathToStylesXmlFile = $resourcePath . '#content.xml';
|
||||
|
||||
$xmlReader = new \XMLReader();
|
||||
$xmlReader->open('zip://' . $pathToStylesXmlFile);
|
||||
|
||||
while ($xmlReader->read()) {
|
||||
if ($xmlReader->nodeType === \XMLReader::ELEMENT && $xmlReader->name === 'style:style' && $xmlReader->getAttribute('style:family') === 'table-cell') {
|
||||
$cellStyleElements[] = $xmlReader->expand();
|
||||
}
|
||||
}
|
||||
|
||||
return $cellStyleElements;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $fileName
|
||||
* @param string $section
|
||||
* @return \DomElement
|
||||
*/
|
||||
private function getXmlSectionFromStylesXmlFile($fileName, $section)
|
||||
{
|
||||
$resourcePath = $this->getGeneratedResourcePath($fileName);
|
||||
$pathToStylesXmlFile = $resourcePath . '#styles.xml';
|
||||
|
||||
$xmlReader = new XMLReader();
|
||||
$xmlReader->open('zip://' . $pathToStylesXmlFile);
|
||||
$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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\Style;
|
||||
|
||||
/**
|
||||
* Class ColorTest
|
||||
*
|
||||
* @package Box\Spout\Writer\Style
|
||||
*/
|
||||
class ColorTest extends \PHPUnit_Framework_TestCase
|
||||
{
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function dataProviderForTestRGB()
|
||||
{
|
||||
|
||||
return [
|
||||
[0, 0, 0, Color::BLACK],
|
||||
[255, 255, 255, Color::WHITE],
|
||||
[255, 0, 0, Color::RED],
|
||||
[192, 0, 0, Color::DARK_RED],
|
||||
[255, 192, 0, Color::ORANGE],
|
||||
[255, 255, 0, Color::YELLOW],
|
||||
[146, 208, 64, Color::LIGHT_GREEN],
|
||||
[0, 176, 80, Color::GREEN],
|
||||
[0, 176, 224, Color::LIGHT_BLUE],
|
||||
[0, 112, 192, Color::BLUE],
|
||||
[0, 32, 96, Color::DARK_BLUE],
|
||||
[112, 48, 160, Color::PURPLE],
|
||||
[0, 0, 0, '000000'],
|
||||
[255, 255, 255, 'FFFFFF'],
|
||||
[255, 0, 0, 'FF0000'],
|
||||
[0, 128, 0, '008000'],
|
||||
[0, 255, 0, '00FF00'],
|
||||
[0, 0, 255, '0000FF'],
|
||||
[128, 22, 43, '80162B'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider dataProviderForTestRGB
|
||||
*
|
||||
* @param int $red
|
||||
* @param int $green
|
||||
* @param int $blue
|
||||
* @param string $expectedColor
|
||||
* @return void
|
||||
*/
|
||||
public function testRGB($red, $green, $blue, $expectedColor)
|
||||
{
|
||||
$color = Color::rgb($red, $green, $blue);
|
||||
$this->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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\Style;
|
||||
|
||||
/**
|
||||
* Class StyleTest
|
||||
*
|
||||
* @package Box\Spout\Writer\Style
|
||||
*/
|
||||
class StyleTest extends \PHPUnit_Framework_TestCase
|
||||
{
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function testSerializeShouldNotTakeIntoAccountId()
|
||||
{
|
||||
$style1 = (new StyleBuilder())->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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\XLSX\Helper;
|
||||
|
||||
use Box\Spout\Writer\Style\StyleBuilder;
|
||||
|
||||
/**
|
||||
* Class StyleHelperTest
|
||||
*
|
||||
* @package Box\Spout\Writer\XLSX\Helper
|
||||
*/
|
||||
class StyleHelperTest extends \PHPUnit_Framework_TestCase
|
||||
{
|
||||
/** @var \Box\Spout\Writer\Style\Style */
|
||||
protected $defaultStyle;
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function setUp()
|
||||
{
|
||||
$this->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());
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace Box\Spout\Writer\XLSX;
|
||||
|
||||
use Box\Spout\Common\Type;
|
||||
use Box\Spout\TestUsingResource;
|
||||
use Box\Spout\Writer\Common\Sheet;
|
||||
use Box\Spout\Writer\WriterFactory;
|
||||
|
||||
/**
|
||||
@@ -20,7 +21,7 @@ class SheetTest extends \PHPUnit_Framework_TestCase
|
||||
*/
|
||||
public function testGetSheetIndex()
|
||||
{
|
||||
$sheets = $this->writeDataAndReturnSheets('test_get_sheet_index.xlsx');
|
||||
$sheets = $this->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');
|
||||
@@ -32,7 +33,7 @@ class SheetTest extends \PHPUnit_Framework_TestCase
|
||||
*/
|
||||
public function testGetSheetName()
|
||||
{
|
||||
$sheets = $this->writeDataAndReturnSheets('test_get_sheet_name.xlsx');
|
||||
$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');
|
||||
@@ -45,27 +46,60 @@ class SheetTest extends \PHPUnit_Framework_TestCase
|
||||
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 = 'CustomName';
|
||||
$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();
|
||||
|
||||
$this->assertSheetNameEquals($customSheetName, $resourcePath, "The sheet name should have been changed to '$customSheetName'");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $fileName
|
||||
* @return Sheet[]
|
||||
*/
|
||||
private function writeDataAndReturnSheets($fileName)
|
||||
private function writeDataToMulitpleSheetsAndReturnSheets($fileName)
|
||||
{
|
||||
$this->createGeneratedFolderIfNeeded($fileName);
|
||||
$resourcePath = $this->getGeneratedResourcePath($fileName);
|
||||
@@ -85,15 +119,16 @@ class SheetTest extends \PHPUnit_Framework_TestCase
|
||||
|
||||
/**
|
||||
* @param string $expectedName
|
||||
* @param string $resourcePath
|
||||
* @param string $fileName
|
||||
* @param string $message
|
||||
* @return void
|
||||
*/
|
||||
private function assertSheetNameEquals($expectedName, $resourcePath, $message = '')
|
||||
private function assertSheetNameEquals($expectedName, $fileName, $message = '')
|
||||
{
|
||||
$resourcePath = $this->getGeneratedResourcePath($fileName);
|
||||
$pathToWorkbookFile = $resourcePath . '#xl/workbook.xml';
|
||||
$xmlContents = file_get_contents('zip://' . $pathToWorkbookFile);
|
||||
|
||||
$this->assertContains('<sheet name="' . $expectedName . '"', $xmlContents, $message);
|
||||
$this->assertContains("<sheet name=\"$expectedName\"", $xmlContents, $message);
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,9 @@ use Box\Spout\TestUsingResource;
|
||||
use Box\Spout\Writer\WriterFactory;
|
||||
|
||||
/**
|
||||
* Class XLSXTest
|
||||
* Class WriterTest
|
||||
*
|
||||
* @package Box\Spout\Writer
|
||||
* @package Box\Spout\Writer\XLSX
|
||||
*/
|
||||
class WriterTest extends \PHPUnit_Framework_TestCase
|
||||
{
|
||||
@@ -26,8 +26,6 @@ class WriterTest extends \PHPUnit_Framework_TestCase
|
||||
|
||||
$writer = WriterFactory::create(Type::XLSX);
|
||||
@$writer->openToFile($filePath);
|
||||
$writer->addRow(['xlsx--11', 'xlsx--12']);
|
||||
$writer->close();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -37,17 +35,60 @@ class WriterTest extends \PHPUnit_Framework_TestCase
|
||||
{
|
||||
$writer = WriterFactory::create(Type::XLSX);
|
||||
$writer->addRow(['xlsx--11', 'xlsx--12']);
|
||||
$writer->close();
|
||||
}
|
||||
|
||||
/**
|
||||
* @expectedException \Box\Spout\Writer\Exception\WriterNotOpenedException
|
||||
*/
|
||||
public function testAddRowShouldThrowExceptionIfCallAddRowsBeforeOpeningWriter()
|
||||
public function testAddRowShouldThrowExceptionIfCalledBeforeOpeningWriter()
|
||||
{
|
||||
$writer = WriterFactory::create(Type::XLSX);
|
||||
$writer->addRows([['xlsx--11', 'xlsx--12']]);
|
||||
$writer->close();
|
||||
}
|
||||
|
||||
/**
|
||||
* @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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -128,7 +169,7 @@ class WriterTest extends \PHPUnit_Framework_TestCase
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function testAddRowShouldWriteGivenDataToTwoSheetUsingInlineStrings()
|
||||
public function testAddRowShouldWriteGivenDataToTwoSheetsUsingInlineStrings()
|
||||
{
|
||||
$fileName = 'test_add_row_should_write_given_data_to_two_sheets_using_inline_strings.xlsx';
|
||||
$dataRows = [
|
||||
@@ -171,7 +212,7 @@ class WriterTest extends \PHPUnit_Framework_TestCase
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function testAddRowShouldWriteGivenDataToTwoSheetUsingSharedStrings()
|
||||
public function testAddRowShouldWriteGivenDataToTwoSheetsUsingSharedStrings()
|
||||
{
|
||||
$fileName = 'test_add_row_should_write_given_data_to_two_sheets_using_shared_strings.xlsx';
|
||||
$dataRows = [
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\XLSX;
|
||||
|
||||
use Box\Spout\Common\Type;
|
||||
use Box\Spout\Reader\Wrapper\XMLReader;
|
||||
use Box\Spout\TestUsingResource;
|
||||
use Box\Spout\Writer\Style\Color;
|
||||
use Box\Spout\Writer\Style\Style;
|
||||
use Box\Spout\Writer\Style\StyleBuilder;
|
||||
use Box\Spout\Writer\WriterFactory;
|
||||
|
||||
/**
|
||||
* Class WriterWithStyleTest
|
||||
*
|
||||
* @package Box\Spout\Writer\XLSX
|
||||
*/
|
||||
class WriterWithStyleTest extends \PHPUnit_Framework_TestCase
|
||||
{
|
||||
use TestUsingResource;
|
||||
|
||||
/** @var \Box\Spout\Writer\Style\Style */
|
||||
protected $defaultStyle;
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function setUp()
|
||||
{
|
||||
$this->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 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');
|
||||
}
|
||||
|
||||
/**
|
||||
* @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[] $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);
|
||||
$pathToStylesXmlFile = $resourcePath . '#xl/styles.xml';
|
||||
|
||||
$xmlReader = new XMLReader();
|
||||
$xmlReader->open('zip://' . $pathToStylesXmlFile);
|
||||
$xmlReader->readUntilNodeFound($section);
|
||||
|
||||
return $xmlReader->expand();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $fileName
|
||||
* @return \DOMNode[]
|
||||
*/
|
||||
private function getCellElementsFromSheetXmlFile($fileName)
|
||||
{
|
||||
$cellElements = [];
|
||||
|
||||
$resourcePath = $this->getGeneratedResourcePath($fileName);
|
||||
$pathToStylesXmlFile = $resourcePath . '#xl/worksheets/sheet1.xml';
|
||||
|
||||
$xmlReader = new \XMLReader();
|
||||
$xmlReader->open('zip://' . $pathToStylesXmlFile);
|
||||
|
||||
while ($xmlReader->read()) {
|
||||
if ($xmlReader->nodeType === \XMLReader::ELEMENT && $xmlReader->name === 'c') {
|
||||
$cellElements[] = $xmlReader->expand();
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -3,3 +3,6 @@ require_once(dirname(__DIR__) . '/vendor/autoload.php');
|
||||
|
||||
require_once(dirname(__DIR__) . '/tests/Spout/TestUsingResource.php');
|
||||
require_once(dirname(__DIR__) . '/tests/Spout/ReflectionHelper.php');
|
||||
|
||||
// Make sure a timezone is set to be able to work with dates
|
||||
date_default_timezone_set('UTC');
|
||||
@@ -0,0 +1,2 @@
|
||||
|
||||
|
||||
|
|
Whitespace-only changes.
|
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user