Compare commits

...
36 Commits
Author SHA1 Message Date
Adrien Loison c6e943041e Merge pull request #31 from box/bump_version_to_1.0.6
Bump version to 1.0.6
2015-04-29 01:10:43 -07:00
Adrien Loison 502dd54c81 Bump version to 1.0.6 2015-04-29 01:06:16 -07:00
Adrien Loison c6cfc4c80f Merge pull request #30 from box/allow_custom_sheet_name_xlsx_writer
Allow custom sheet name in the XLSX writer
2015-04-29 01:04:22 -07:00
Adrien Loison d02013c82e Allow custom sheet name in the XLSX writer
Added setter
Added test
Updated README
2015-04-29 01:01:59 -07:00
Adrien Loison 71d9c18a81 Merge pull request #29 from box/expose_sheet_xlsx_reader
Expose a Sheet object on Reader::XLSX::nextSheet()
2015-04-29 00:32:12 -07:00
Adrien Loison e9ec4e745c Expose a Sheet object on Reader::XLSX::nextSheet()
Added Sheet class for the XLSX reader that exposes basic sheet info, such as name or ID.
When retrieving the sheet data XML, added extra XML parsing to retrieve sheet data.
Added test
2015-04-29 00:27:45 -07:00
Adrien Loison e58284d27b Merge pull request #25 from box/bump_version_to_1.0.5
Bump version to 1.0.5
2015-04-16 15:22:08 -07:00
Adrien Loison 27a47f509f Bump version to 1.0.5 2015-04-16 15:05:41 -07:00
Adrien Loison 8aeb883ebc Merge pull request #23 from box/add_hhvm_and_nightly_in_travis
Add HHVM and PHP nighly in Travis
2015-04-16 15:04:07 -07:00
Adrien Loison 05c504e72c Add HHVM and PHP nighly in Travis 2015-04-16 14:56:07 -07:00
Adrien Loison abbc158877 Merge pull request #24 from box/add_improve_test_coverage
Add and improve test coverage
2015-04-16 14:55:42 -07:00
Adrien Loison 3f3461b002 Add and improve test coverage 2015-04-16 14:51:48 -07:00
Adrien Loison 2074781852 Merge pull request #22 from box/bump_version_to_1.0.4
Bump version to 1.0.4
2015-04-16 13:17:24 -07:00
Adrien Loison fd5cfc5440 Bump version to 1.0.4 2015-04-16 13:13:05 -07:00
Adrien Loison a538813827 Merge pull request #21 from box/fix_empty_shared_string_bug
Fix empty shared string bug
2015-04-16 13:08:56 -07:00
Adrien Loison 3e5ef284a5 Fix empty shared string bug
Replaced !$sharedString by $sharedString === null to avoid the case
when $sharedString = ''
2015-04-16 13:00:02 -07:00
Adrien Loison f770f38967 Merge pull request #19 from box/bump_version_to_1.0.3
Bump version to 1.0.3
2015-04-14 20:20:34 -07:00
Adrien Loison 0edd9c434f Merge pull request #20 from box/add_editorconfig
Add .editorconfig
2015-04-14 20:20:21 -07:00
Adrien Loison 3c9bf12a5f Add .editorconfig 2015-04-14 20:16:41 -07:00
Adrien Loison 69c1436625 Bump version to 1.0.3 2015-04-14 20:01:24 -07:00
Adrien Loison af940069bc Merge pull request #18 from box/better_guess_cell_type
Better guess the cell type based on its value
2015-04-14 19:58:38 -07:00
Adrien Loison d6155a4243 Better guess the cell type based on its value 2015-04-14 19:52:56 -07:00
Adrien Loison 538f6109ad Merge pull request #15 from box/add_test_for_skipping_empty_rows
Add test for skipping empty rows
2015-04-03 22:49:40 -07:00
Adrien Loison 93cdd398dd Add test for skipping empty rows 2015-04-03 22:45:09 -07:00
Adrien Loison 66e5792a7e Merge pull request #14 from box/bump_version_to_1.0.2
Bump version to 1.0.2
2015-04-03 22:29:18 -07:00
Adrien Loison d4dbc32a53 Bump version to 1.0.2 2015-04-03 22:28:49 -07:00
Adrien Loison 09eac62c22 Merge pull request #13 from box/random_fixes
Random fixes
2015-04-03 22:24:56 -07:00
Adrien Loison 7bb5e02d2c Fix Typo in CSV Reader 2015-04-03 22:09:25 -07:00
Adrien Loison aebdd1acd7 Empty $dataRow should not create an empty rw 2015-04-03 22:08:55 -07:00
Adrien Loison 41a449f245 Merge pull request #12 from box/fix_dir_separator_bug_on_windows
Fix DIRECTORY_SEPARATOR bug occurring on Windows
2015-04-03 21:17:49 -07:00
Adrien Loison 39c72a91b4 Fix DIRECTORY_SEPARATOR bug occurring on Windows
Fixes #3:
The sheetN.xml files location is dynamically retrieved when parsing
[Content_Types].xml. In this file, the location is like "/xl/worksheets/sheet1.xml".

Because the zip stream wrapper expects the zip entry name to be like
"xl/worksheets/sheet1/xml" (without the first "/"), this first "/"
needs to be trimmed. It was trimmed using:
  ltrim($this->dataXmlFilePath, DIRECTORY_SEPARATOR);
which obvisously does not work on Windows platform where DIRECTORY_SEPARATOR is "\".
Replacing DIRECTORY_SEPARATOR by '/' solves this issue.
2015-04-03 21:10:30 -07:00
Adrien Loison 4ca1fc5851 Merge pull request #8 from box/add_multiline_strings_support
Add support for multiline strings
2015-03-30 22:21:47 -07:00
Adrien Loison 419544a85f Update README.md 2015-03-27 17:05:17 -07:00
Adrien Loison 6e11a043c1 Add support for multiline strings
Escaped line feed characters in shared strings before processing them.
This makes every string remain on one single line and therefore allow
fast retrieval
Replaced usages of "\n" by PHP_EOL
Added test for multiline strings
2015-03-27 16:54:56 -07:00
Adrien Loison c24cdbb9be Merge pull request #7 from box/document_utf8_use
Document the use of UTF-8 by default
2015-03-26 15:36:17 -07:00
Adrien Loison 18f6e64910 Document the use of UTF-8 by default 2015-03-26 15:13:47 -07:00
34 changed files with 770 additions and 90 deletions

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
insert_final_newline = true
[{.travis.yml}]
indent_size = 2
[*.md]
trim_trailing_whitespace = false
+1
View File
@@ -1,4 +1,5 @@
/tests/resources/generated
/tests/coverage
/vendor
composer.lock
/.idea
+2
View File
@@ -4,6 +4,8 @@ php:
- 5.4
- 5.5
- 5.6
- nightly
- hhvm
install:
- composer self-update
+18 -1
View File
@@ -149,7 +149,7 @@ $writer->setShouldCreateNewSheetsAutomatically(true); // default value
$writer->setShouldCreateNewSheetsAutomatically(false); // will stop writing new data when limit is reached
```
### Using custom temporary folder
#### 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
@@ -180,6 +180,23 @@ It is also possible to retrieve all the sheets currently created:
$sheets = $writer->getSheets();
```
If you rely on the sheet's name in your application, you can access it and customize it this way:
```php
// Accessing the sheet name when reading
while ($reader->hasNextSheet()) {
$sheet = $reader->nextSheet();
$sheetName = $sheet->getName();
}
// Accessing the sheet name when writing
$sheet = $writer->getCurrentSheet();
$sheetName = $sheet->getName();
// Customizing the sheet name when writing
$sheet = $writer->getCurrentSheet();
$sheetName = $sheet->setName('My custom name');
```
### Fluent interface
Because fluent interfaces are great, you can use them with Spout:
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "box/spout",
"description": "PHP Library to read and write CSV and XLSX files, in a fast and scalable way",
"type": "library",
"version": "1.0.1",
"version": "1.0.6",
"keywords": ["php","read","write","csv","xlsx","excel","spreadsheet","scale","memory","stream","ooxml"],
"license": "Apache-2.0",
"homepage": "https://www.github.com/box/spout",
+10
View File
@@ -14,4 +14,14 @@
</testsuite>
</testsuites>
<logging>
<log type="coverage-html" target="tests/coverage/"/>
</logging>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
</phpunit>
+4
View File
@@ -13,6 +13,8 @@ class CSV implements EscaperInterface
/**
* Escapes the given string to make it compatible with CSV
*
* @codeCoverageIgnore
*
* @param string $string The string to escape
* @return string The escaped string
*/
@@ -24,6 +26,8 @@ class CSV implements EscaperInterface
/**
* Unescapes the given string to make it compatible with CSV
*
* @codeCoverageIgnore
*
* @param string $string The string to unescape
* @return string The unescaped string
*/
+1 -1
View File
@@ -27,7 +27,7 @@ class XLSX implements EscaperInterface
public function escape($string)
{
$escapedString = $this->escapeControlCharacters($string);
$escapedString = htmlspecialchars($escapedString, ENT_QUOTES, 'utf-8');
$escapedString = htmlspecialchars($escapedString, ENT_QUOTES);
return $escapedString;
}
@@ -6,6 +6,8 @@ namespace Box\Spout\Common\Helper;
* Class GlobalFunctionsHelper
* This class wraps global functions to facilitate testing
*
* @codeCoverageIgnore
*
* @package Box\Spout\Common\Helper
*/
class GlobalFunctionsHelper
@@ -117,7 +119,7 @@ class GlobalFunctionsHelper
* Wrapper around global function file_exists()
* @see file_exists()
*
* @param string $filename
* @param string $fileName
* @return bool
*/
public function file_exists($fileName)
@@ -125,11 +127,23 @@ class GlobalFunctionsHelper
return file_exists($fileName);
}
/**
* Wrapper around global function file_get_contents()
* @see file_get_contents()
*
* @param string $filePath
* @return bool
*/
public function file_get_contents($filePath)
{
return file_get_contents($filePath);
}
/**
* Wrapper around global function is_readable()
* @see is_readable()
*
* @param string $filename
* @param string $fileName
* @return bool
*/
public function is_readable($fileName)
@@ -142,11 +156,12 @@ class GlobalFunctionsHelper
* @see basename()
*
* @param string $path
* @param string|void $suffix
* @return string
*/
public function basename($path)
public function basename($path, $suffix = null)
{
return basename($path);
return basename($path, $suffix);
}
/**
+1 -1
View File
@@ -52,7 +52,7 @@ class CSV extends AbstractReader
* The file must be UTF-8 encoded.
* @TODO add encoding detection/conversion
*
* @param string $filePath Path of the XLSX file to be read
* @param string $filePath Path of the CSV file to be read
* @return void
* @throws \Box\Spout\Common\Exception\IOException
*/
+1 -1
View File
@@ -25,7 +25,7 @@ class CellHelper
{
$existingIndexes = array_keys($dataArray);
$newIndexes = array_fill_keys(range(min($existingIndexes), max($existingIndexes)), $fillValue);
$newIndexes = array_fill_keys(range(0, max($existingIndexes)), $fillValue);
$dataArray += $newIndexes;
ksort($dataArray);
@@ -31,6 +31,9 @@ class SharedStringsHelper
*/
const MAX_NUM_STRINGS_PER_TEMP_FILE = 10000;
/** Value to use to escape the line feed character ("\n") */
const ESCAPED_LINE_FEED_CHARACTER = '_x000A_';
/** @var string Path of the XLSX file being read */
protected $filePath;
@@ -80,7 +83,6 @@ class SharedStringsHelper
* Please note that SimpleXML does not provide such a functionality but since it is faster
* and more handy to parse few XML nodes, it is used in combination with XMLReader for that purpose.
*
* @param string $filePath
* @return void
* @throws \Box\Spout\Common\Exception\IOException If sharedStrings.xml can't be read
*/
@@ -120,7 +122,12 @@ class SharedStringsHelper
}
$unescapedTextValue = $escaper->unescape($textValue);
$this->writeSharedStringToTempFile($unescapedTextValue, $sharedStringIndex);
// The shared string retrieval logic expects each cell data to be on one line only
// Encoding the line feed character allows to preserve this assumption
$lineFeedEncodedTextValue = $this->escapeLineFeed($unescapedTextValue);
$this->writeSharedStringToTempFile($lineFeedEncodedTextValue, $sharedStringIndex);
$sharedStringIndex++;
@@ -246,16 +253,39 @@ class SharedStringsHelper
$sharedString = null;
if (array_key_exists($indexInFile, $this->inMemoryTempFileContents)) {
$sharedString = $this->inMemoryTempFileContents[$indexInFile];
$escapedSharedString = $this->inMemoryTempFileContents[$indexInFile];
$sharedString = $this->unescapeLineFeed($escapedSharedString);
}
if (!$sharedString) {
if ($sharedString === null) {
throw new SharedStringNotFoundException("Shared string not found for index: $sharedStringIndex");
}
return rtrim($sharedString, PHP_EOL);
}
/**
* Escapes the line feed character (\n)
*
* @param string $unescapedString
* @return string
*/
private function escapeLineFeed($unescapedString)
{
return str_replace("\n", self::ESCAPED_LINE_FEED_CHARACTER, $unescapedString);
}
/**
* Unescapes the line feed character (\n)
*
* @param string $escapedString
* @return string
*/
private function unescapeLineFeed($escapedString)
{
return str_replace(self::ESCAPED_LINE_FEED_CHARACTER, "\n", $escapedString);
}
/**
* Deletes the created temporary folder and all its contents
*
+145 -10
View File
@@ -3,6 +3,7 @@
namespace Box\Spout\Reader\Helper\XLSX;
use Box\Spout\Reader\Internal\XLSX\Worksheet;
use Box\Spout\Reader\Sheet;
/**
* Class WorksheetHelper
@@ -12,11 +13,18 @@ use Box\Spout\Reader\Internal\XLSX\Worksheet;
*/
class WorksheetHelper
{
/** Path of Content_Types XML file inside the XLSX file */
const CONTENT_TYPES_XML_FILE_PATH = '[Content_Types].xml';
/** Extension for XML files */
const XML_EXTENSION = '.xml';
/** Main namespace for the [Content_Types].xml file */
/** Paths of XML files relative to the XLSX file root */
const CONTENT_TYPES_XML_FILE_PATH = '[Content_Types].xml';
const WORKBOOK_XML_RELS_FILE_PATH = 'xl/_rels/workbook.xml.rels';
const WORKBOOK_XML_FILE_PATH = 'xl/workbook.xml';
/** Namespaces for the XML files */
const MAIN_NAMESPACE_FOR_CONTENT_TYPES_XML = 'http://schemas.openxmlformats.org/package/2006/content-types';
const MAIN_NAMESPACE_FOR_WORKBOOK_XML_RELS = 'http://schemas.openxmlformats.org/package/2006/relationships';
const MAIN_NAMESPACE_FOR_WORKBOOK_XML = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main';
/** Value of the Override attribute used in [Content_Types].xml to define worksheets */
const OVERRIDE_CONTENT_TYPES_ATTRIBUTE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml';
@@ -24,12 +32,23 @@ class WorksheetHelper
/** @var string Path of the XLSX file being read */
protected $filePath;
/** @var \Box\Spout\Common\Helper\GlobalFunctionsHelper Helper to work with global functions */
protected $globalFunctionsHelper;
/** @var \SimpleXMLElement XML element representing the workbook.xml.rels file */
protected $workbookXMLRelsAsXMLElement;
/** @var \SimpleXMLElement XML element representing the workbook.xml file */
protected $workbookXMLAsXMLElement;
/**
* @param string $filePath Path of the XLSX file being read
* @param \Box\Spout\Common\Helper\GlobalFunctionsHelper $globalFunctionsHelper
*/
public function __construct($filePath)
public function __construct($filePath, $globalFunctionsHelper)
{
$this->filePath = $filePath;
$this->globalFunctionsHelper = $globalFunctionsHelper;
}
/**
@@ -42,23 +61,139 @@ class WorksheetHelper
{
$worksheets = [];
$xmlContents = file_get_contents('zip://' . $this->filePath . '#' . self::CONTENT_TYPES_XML_FILE_PATH);
$contentTypes = new \SimpleXMLElement($xmlContents);
$contentTypes->registerXPathNamespace('ns', self::MAIN_NAMESPACE_FOR_CONTENT_TYPES_XML);
$contentTypesAsXMLElement = $this->getFileAsXMLElementWithNamespace(
self::CONTENT_TYPES_XML_FILE_PATH,
self::MAIN_NAMESPACE_FOR_CONTENT_TYPES_XML
);
// find all nodes defining a worksheet
$sheetNodes = $contentTypes->xpath('//ns:Override[@ContentType="' . self::OVERRIDE_CONTENT_TYPES_ATTRIBUTE . '"]');
$sheetNodes = $contentTypesAsXMLElement->xpath('//ns:Override[@ContentType="' . self::OVERRIDE_CONTENT_TYPES_ATTRIBUTE . '"]');
for ($i = 0; $i < count($sheetNodes); $i++) {
$sheetNode = $sheetNodes[$i];
$sheetDataXMLFilePath = (string) $sheetNode->attributes()->PartName;
$worksheets[] = new Worksheet($i, $sheetDataXMLFilePath);
$sheet = $this->getSheet($sheetDataXMLFilePath, $i);
$worksheets[] = new Worksheet($sheet, $i, $sheetDataXMLFilePath);
}
return $worksheets;
}
/**
* Returns an instance of a sheet, given the path of its data XML file.
* We first look at "xl/_rels/workbook.xml.rels" to find the relationship ID of the sheet.
* Then we look at "xl/worbook.xml" to find the sheet entry associated to the found ID.
* The entry contains the ID and name of the sheet.
*
* If this piece of data can't be found by parsing the different XML files, the ID will default
* to the sheet index, based on order in [Content_Types].xml. Similarly, the sheet's name will
* default to the data sheet XML file name ("xl/worksheets/sheet2.xml" => "sheet2").
*
* @param string $sheetDataXMLFilePath Path of the sheet data XML file as in [Content_Types].xml
* @param int $sheetNumberZeroBased Index of the sheet, based on order in [Content_Types].xml (zero-based)
* @return \Box\Spout\Reader\Sheet Sheet instance
*/
protected function getSheet($sheetDataXMLFilePath, $sheetNumberZeroBased)
{
$sheetId = $sheetNumberZeroBased + 1;
$sheetName = $this->getDefaultSheetName($sheetDataXMLFilePath);
/*
* In [Content_Types].xml, the path is "/xl/worksheets/sheet1.xml"
* In workbook.xml.rels, it is only "worksheets/sheet1.xml"
*/
$sheetDataXMLFilePathInWorkbookXMLRels = ltrim($sheetDataXMLFilePath, '/xl/');
// find the node associated to the given file path
$workbookXMLResElement = $this->getWorkbookXMLRelsAsXMLElement();
$relationshipNodes = $workbookXMLResElement->xpath('//ns:Relationship[@Target="' . $sheetDataXMLFilePathInWorkbookXMLRels . '"]');
if (count($relationshipNodes) === 1) {
$relationshipNode = $relationshipNodes[0];
$sheetId = (string) $relationshipNode->attributes()->Id;
$workbookXMLElement = $this->getWorkbookXMLAsXMLElement();
$sheetNodes = $workbookXMLElement->xpath('//ns:sheet[@r:id="' . $sheetId . '"]');
if (count($sheetNodes) === 1) {
$sheetNode = $sheetNodes[0];
$sheetId = (int) $sheetNode->attributes()->sheetId;
$escapedSheetName = (string) $sheetNode->attributes()->name;
$escaper = new \Box\Spout\Common\Escaper\XLSX();
$sheetName = $escaper->unescape($escapedSheetName);
}
}
return new Sheet($sheetId, $sheetNumberZeroBased, $sheetName);
}
/**
* Returns the default name of the sheet whose data is located
* at the given path.
*
* @param $sheetDataXMLFilePath
* @return string The default sheet name
*/
protected function getDefaultSheetName($sheetDataXMLFilePath)
{
return $this->globalFunctionsHelper->basename($sheetDataXMLFilePath, self::XML_EXTENSION);
}
/**
* Returns a representation of the workbook.xml.rels file, ready to be parsed.
* The returned value is cached.
*
* @return \SimpleXMLElement XML element representating the workbook.xml.rels file
*/
protected function getWorkbookXMLRelsAsXMLElement()
{
if (!$this->workbookXMLRelsAsXMLElement) {
$this->workbookXMLRelsAsXMLElement = $this->getFileAsXMLElementWithNamespace(
self::WORKBOOK_XML_RELS_FILE_PATH,
self::MAIN_NAMESPACE_FOR_WORKBOOK_XML_RELS
);
}
return $this->workbookXMLRelsAsXMLElement;
}
/**
* Returns a representation of the workbook.xml file, ready to be parsed.
* The returned value is cached.
*
* @return \SimpleXMLElement XML element representating the workbook.xml.rels file
*/
protected function getWorkbookXMLAsXMLElement()
{
if (!$this->workbookXMLAsXMLElement) {
$this->workbookXMLAsXMLElement = $this->getFileAsXMLElementWithNamespace(
self::WORKBOOK_XML_FILE_PATH,
self::MAIN_NAMESPACE_FOR_WORKBOOK_XML
);
}
return $this->workbookXMLAsXMLElement;
}
/**
* Loads the contents of the given file in an XML parser and register the given XPath namespace.
*
* @param string $xmlFilePath The path of the XML file inside the XLSX file
* @param string $mainNamespace The main XPath namespace to register
* @return \SimpleXMLElement The XML element representing the file
*/
protected function getFileAsXMLElementWithNamespace($xmlFilePath, $mainNamespace)
{
$xmlContents = $this->globalFunctionsHelper->file_get_contents('zip://' . $this->filePath . '#' . $xmlFilePath);
$xmlElement = new \SimpleXMLElement($xmlContents);
$xmlElement->registerXPathNamespace('ns', $mainNamespace);
return $xmlElement;
}
/**
* Returns whether another worksheet exists after the current worksheet.
* The order is determined by the order of appearance in the [Content_Types].xml file.
+16 -3
View File
@@ -10,18 +10,23 @@ namespace Box\Spout\Reader\Internal\XLSX;
*/
class Worksheet
{
/** @var \Box\Spout\Reader\Sheet The "external" sheet */
protected $externalSheet;
/** @var int Worksheet number, based on the order of appareance in [Content_Types].xml (zero-based) */
protected $worksheetNumber;
/** @var string Path of the XML file containing the worksheet data */
protected $dataXmlFilePath;
/**
/**\
* @param \Box\Spout\Reader\Sheet $externalSheet The associated "external" sheet
* @param int $worksheetNumber Worksheet number, based on the order of appareance in [Content_Types].xml (zero-based)
* @param string $dataXmlFilePath Path of the XML file containing the worksheet data
*/
public function __construct($worksheetNumber, $dataXmlFilePath)
public function __construct($externalSheet, $worksheetNumber, $dataXmlFilePath)
{
$this->externalSheet = $externalSheet;
$this->worksheetNumber = $worksheetNumber;
$this->dataXmlFilePath = $dataXmlFilePath;
}
@@ -31,7 +36,15 @@ class Worksheet
*/
public function getDataXmlFilePath()
{
return ltrim($this->dataXmlFilePath, DIRECTORY_SEPARATOR);
return ltrim($this->dataXmlFilePath, '/');
}
/**
* @return \Box\Spout\Reader\Sheet The "external" sheet
*/
public function getExternalSheet()
{
return $this->externalSheet;
}
/**
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace Box\Spout\Reader;
/**
* Class Sheet
* Represents a worksheet within a XLSX file
*
* @package Box\Spout\Reader
*/
class Sheet
{
/** @var int ID of the sheet */
protected $id;
/** @var int Number of the sheet, based on order of creation (zero-based) */
protected $number;
/** @var string Name of the sheet */
protected $name;
/**
* @param int $sheetId ID of the sheet
* @param int $sheetNumber Number of the sheet, based on order of creation (zero-based)
* @param string $sheetName Name of the sheet
*/
function __construct($sheetId, $sheetNumber, $sheetName)
{
$this->id = $sheetId;
$this->number = $sheetNumber;
$this->name = $sheetName;
}
/**
* @return int ID of the sheet
*/
public function getId()
{
return $this->id;
}
/**
* @return int Number of the sheet, based on order of creation (zero-based)
*/
public function getNumber()
{
return $this->number;
}
/**
* @return string Name of the sheet
*/
public function getName()
{
return $this->name;
}
}
+19 -17
View File
@@ -76,7 +76,7 @@ class XLSX extends AbstractReader
$this->extractSharedStrings($filePath);
// Fetch all available worksheets
$this->worksheetHelper = new WorksheetHelper($filePath);
$this->worksheetHelper = new WorksheetHelper($filePath, $this->globalFunctionsHelper);
$this->worksheets = $this->worksheetHelper->getWorksheets($filePath);
if (count($this->worksheets) === 0) {
@@ -119,29 +119,31 @@ class XLSX extends AbstractReader
* Moves the pointer to the current worksheet.
* Moving to another worksheet will stop the reading in the current worksheet.
*
* @return void
* @return \Box\Spout\Reader\Sheet The next sheet
* @throws Exception\ReaderNotOpenedException If the stream was not opened first
* @throws Exception\EndOfWorksheetsReachedException If there is no more worksheets to read
*/
public function nextSheet()
{
if ($this->hasNextSheet()) {
if ($this->currentWorksheet === null) {
$nextWorksheet = $this->worksheets[0];
} else {
$currentWorksheetNumber = $this->currentWorksheet->getWorksheetNumber();
$nextWorksheet = $this->worksheets[$currentWorksheetNumber + 1];
}
$this->initXmlReaderForWorksheetData($nextWorksheet);
$this->currentWorksheet = $nextWorksheet;
// make sure that we are ready to read more rows
$this->hasReachedEndOfFile = false;
$this->emptyRowDataBuffer();
} else {
if (!$this->hasNextSheet()) {
throw new EndOfWorksheetsReachedException('End of worksheets was reached. Cannot read more worksheets.');
}
if ($this->currentWorksheet === null) {
$nextWorksheet = $this->worksheets[0];
} else {
$currentWorksheetNumber = $this->currentWorksheet->getWorksheetNumber();
$nextWorksheet = $this->worksheets[$currentWorksheetNumber + 1];
}
$this->initXmlReaderForWorksheetData($nextWorksheet);
$this->currentWorksheet = $nextWorksheet;
// make sure that we are ready to read more rows
$this->hasReachedEndOfFile = false;
$this->emptyRowDataBuffer();
return $this->currentWorksheet->getExternalSheet();
}
/**
+16 -6
View File
@@ -39,6 +39,7 @@ 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'];
@@ -88,6 +89,8 @@ abstract class AbstractWriter implements WriterInterface
* Inits the writer and opens it to accept data.
* By using this method, the data will be outputted directly to the browser.
*
* @codeCoverageIgnore
*
* @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 \Box\Spout\Writer\AbstractWriter
* @throws \Box\Spout\Common\Exception\IOException If the writer cannot be opened
@@ -135,9 +138,11 @@ 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.
*
* @param array $dataRow Array containing data to be streamed.
* Example $dataRow = ['data1', 1234, null, '', 'data5'];
* If empty, no data is added (i.e. not even as a blank row)
* Example: $dataRow = ['data1', 1234, null, '', 'data5', false];
*
* @return \Box\Spout\Writer\AbstractWriter
* @throws \Box\Spout\Writer\Exception\WriterNotOpenedException If this function is called before opening the writer
@@ -146,7 +151,10 @@ abstract class AbstractWriter implements WriterInterface
public function addRow(array $dataRow)
{
if ($this->isWriterOpened) {
$this->addRowToWriter($dataRow);
// empty $dataRow should not add an empty line
if (!empty($dataRow)) {
$this->addRowToWriter($dataRow);
}
} else {
throw new WriterNotOpenedException('The writer needs to be opened before adding row.');
}
@@ -156,12 +164,14 @@ 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.
*
* @param array $dataRows Array of array containing data to be streamed.
* Example $dataRow = [
* ['data11', 12, , '', 'data13'],
* ['data21', 'data22', null],
* ];
* 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 \Box\Spout\Writer\AbstractWriter
* @throws \Box\Spout\Common\Exception\InvalidArgumentException If the input param is not valid
@@ -34,4 +34,38 @@ class CellHelper
return $cellIndex;
}
/**
* @param $value
* @return bool Whether the given value is a non empty string
*/
public static function isNonEmptyString($value)
{
return (gettype($value) === 'string' && $value !== '');
}
/**
* Returns whether the given value is numeric.
* A numeric value is from type "integer" or "double" ("float" is not returned by gettype).
*
* @param $value
* @return bool Whether the given value is numeric
*/
public static function isNumeric($value)
{
$valueType = gettype($value);
return ($valueType === 'integer' || $valueType === 'double');
}
/**
* Returns whether the given value is boolean.
* "true"/"false" and 0/1 are not booleans.
*
* @param $value
* @return bool Whether the given value is boolean
*/
public static function isBoolean($value)
{
return gettype($value) === 'boolean';
}
}
@@ -5,7 +5,6 @@ namespace Box\Spout\Writer\Internal\XLSX;
use Box\Spout\Writer\Exception\SheetNotFoundException;
use Box\Spout\Writer\Helper\XLSX\FileSystemHelper;
use Box\Spout\Writer\Helper\XLSX\SharedStringsHelper;
use Box\Spout\Writer\Helper\XLSX\ZipHelper;
use Box\Spout\Writer\Sheet;
/**
+16 -13
View File
@@ -2,6 +2,7 @@
namespace Box\Spout\Writer\Internal\XLSX;
use Box\Spout\Common\Exception\InvalidArgumentException;
use Box\Spout\Common\Exception\IOException;
use Box\Spout\Writer\Helper\XLSX\CellHelper;
@@ -42,7 +43,8 @@ EOD;
/**
* @param \Box\Spout\Writer\Sheet $externalSheet The associated "external" sheet
* @param string $tempFolder Temporary folder where the files to create the XLSX will be stored
* @param string $worksheetFilesFolder Temporary folder where the files to create the XLSX will be stored
* @param \Box\Spout\Writer\Helper\XLSX\SharedStringsHelper $sharedStringsHelper Helper for shared strings
* @param bool $shouldUseInlineStrings Whether inline or shared strings should be used
* @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
*/
@@ -95,7 +97,7 @@ EOD;
public function getId()
{
// sheet number is zero-based, while ID is 1-based
return $this->externalSheet->getSheetNumber() + 1;
return $this->externalSheet->getNumber() + 1;
}
/**
@@ -118,6 +120,7 @@ EOD;
* Example $dataRow = ['data1', 1234, null, '', 'data5'];
* @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)
{
@@ -131,19 +134,19 @@ EOD;
$columnIndex = CellHelper::getCellIndexFromColumnIndex($cellNumber);
$data .= ' <c r="' . $columnIndex . $rowIndex . '"';
if (empty($cellValue)) {
if (CellHelper::isNonEmptyString($cellValue)) {
if ($this->shouldUseInlineStrings) {
$data .= ' t="inlineStr"><is><t>' . $this->stringsEscaper->escape($cellValue) . '</t></is></c>' . PHP_EOL;
} else {
$sharedStringId = $this->sharedStringsHelper->writeString($cellValue);
$data .= ' t="s"><v>' . $sharedStringId . '</v></c>' . PHP_EOL;
}
} else if (CellHelper::isNumeric($cellValue) || CellHelper::isBoolean($cellValue)) {
$data .= '><v>' . $cellValue . '</v></c>' . PHP_EOL;
} else if (empty($cellValue)) {
$data .= '/>' . PHP_EOL;
} else {
if (is_numeric($cellValue)) {
$data .= '><v>' . $cellValue . '</v></c>' . PHP_EOL;
} else {
if ($this->shouldUseInlineStrings) {
$data .= ' t="inlineStr"><is><t>' . $this->stringsEscaper->escape($cellValue) . '</t></is></c>' . PHP_EOL;
} else {
$sharedStringId = $this->sharedStringsHelper->writeString($cellValue);
$data .= ' t="s"><v>' . $sharedStringId . '</v></c>' . PHP_EOL;
}
}
throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cellValue));
}
$cellNumber++;
+11 -1
View File
@@ -30,7 +30,7 @@ class Sheet
/**
* @return int Number of the sheet, based on order of creation (zero-based)
*/
public function getSheetNumber()
public function getNumber()
{
return $this->sheetNumber;
}
@@ -42,4 +42,14 @@ class Sheet
{
return $this->name;
}
/**
* @param string $name Name of the sheet
* @return \Box\Spout\Writer\Sheet
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
}
@@ -0,0 +1,60 @@
<?php
namespace Box\Spout\Reader\Helper\XLSX;
/**
* Class CellHelperTest
*
* @package Box\Spout\Reader\Helper\XLSX
*/
class CellHelperTest extends \PHPUnit_Framework_TestCase
{
/**
* @return void
*/
public function testFillMissingArrayIndexes()
{
$arrayToFill = [1 => 1, 3 => 3];
$filledArray = CellHelper::fillMissingArrayIndexes($arrayToFill, 'FILL');
$expectedFilledArray = ['FILL', 1, 'FILL', 3];
$this->assertEquals($expectedFilledArray, $filledArray);
}
/**
* @return array
*/
public function dataProviderForTestGetColumnIndexFromCellIndex()
{
return [
['A1', 0],
['Z3', 25],
['AA5', 26],
['AB24', 27],
['BC5', 54],
['BCZ99', 1455],
];
}
/**
* @dataProvider dataProviderForTestGetColumnIndexFromCellIndex
*
* @param string $cellIndex
* @param int $expectedColumnIndex
* @return void
*/
public function testGetColumnIndexFromCellIndex($cellIndex, $expectedColumnIndex)
{
$this->assertEquals($expectedColumnIndex, CellHelper::getColumnIndexFromCellIndex($cellIndex));
}
/**
* @expectedException \Box\Spout\Common\Exception\InvalidArgumentException
*
* @return void
*/
public function testGetColumnIndexFromCellIndexShouldThrowIfInvalidCellIndex()
{
CellHelper::getColumnIndexFromCellIndex('InvalidCellIndex');
}
}
@@ -46,7 +46,7 @@ class SharedStringsHelperTest extends \PHPUnit_Framework_TestCase
$this->assertEquals(1, count($filesInTempFolder), 'One temp file should have been created in the temp folder.');
$tempFileContents = file_get_contents($filesInTempFolder[0]);
$tempFileContentsPerLine = explode("\n", $tempFileContents);
$tempFileContentsPerLine = explode(PHP_EOL, $tempFileContents);
$this->assertEquals('s1--A1', $tempFileContentsPerLine[0]);
$this->assertEquals('s1--E5', $tempFileContentsPerLine[24]);
@@ -96,4 +96,23 @@ class SharedStringsHelperTest extends \PHPUnit_Framework_TestCase
$sharedString = $this->sharedStringsHelper->getStringAtIndex(24);
$this->assertEquals('s1--E5', $sharedString);
}
/**
* @return void
*/
public function testGetStringAtIndexShouldWorkWithMultilineStrings()
{
$resourcePath = $this->getResourcePath('one_sheet_with_shared_multiline_strings.xlsx');
$sharedStringsHelper = new SharedStringsHelper($resourcePath);
$sharedStringsHelper->extractSharedStrings();
$sharedString = $sharedStringsHelper->getStringAtIndex(0);
$this->assertEquals("s1\nA1", $sharedString);
$sharedString = $sharedStringsHelper->getStringAtIndex(24);
$this->assertEquals("s1\nE5", $sharedString);
$sharedStringsHelper->cleanup();
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace Box\Spout\Reader;
/**
* Class ReaderFactoryTest
*
* @package Box\Spout\Writer
*/
class ReaderFactoryTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \Box\Spout\Common\Exception\UnsupportedTypeException
*
* @return void
*/
public function testCreateReaderShouldThrowWithUnsupportedType()
{
ReaderFactory::create('unsupportedType');
}
}
+53 -1
View File
@@ -140,6 +140,32 @@ class XLSXTest extends \PHPUnit_Framework_TestCase
$this->assertEquals($expectedRows, $allRows);
}
/**
* @return void
*/
public function testReadShouldSupportEmptySharedString()
{
$allRows = $this->getAllRowsForFile('sheet_with_empty_shared_string.xlsx');
$expectedRows = [
['s1--A1', '', 's1--C1'],
];
$this->assertEquals($expectedRows, $allRows);
}
/**
* @return void
*/
public function testReadShouldPreserveSpaceIfSpecified()
{
$allRows = $this->getAllRowsForFile('sheet_with_preserve_space_shared_strings.xlsx');
$expectedRows = [
[' s1--A1', 's1--B1 ', ' s1--C1 '],
];
$this->assertEquals($expectedRows, $allRows);
}
/**
* @return void
*/
@@ -158,7 +184,7 @@ class XLSXTest extends \PHPUnit_Framework_TestCase
{
$allRows = $this->getAllRowsForFile('billion_laughs_test_file.xlsx');
$expectedMaxMemoryUsage = 10 * 1024 * 1024; // 10MB
$expectedMaxMemoryUsage = 20 * 1024 * 1024; // 20MB
$this->assertLessThan($expectedMaxMemoryUsage, memory_get_peak_usage(true), 'Entities should not be expanded and therefore consume all the memory.');
$expectedFirstRow = ['s1--A1', 's1--B1', 's1--C1', 's1--D1', 's1--E1'];
@@ -174,6 +200,32 @@ class XLSXTest extends \PHPUnit_Framework_TestCase
$this->assertEquals([], $allRows, 'Sheet with no cells should be correctly processed.');
}
/**
* @return void
*/
public function testNextSheetShouldReturnCorrectSheetInfos()
{
$resourcePath = $this->getResourcePath('two_sheets_with_custom_names.xlsx');
$reader = ReaderFactory::create(Type::XLSX);
$reader->open($resourcePath);
/** @var \Box\Spout\Reader\Sheet[] $sheets */
$sheets = [];
while ($reader->hasNextSheet()) {
$sheets[] = $reader->nextSheet();
}
$reader->close();
$this->assertEquals('CustomName1', $sheets[0]->getName());
$this->assertEquals(0, $sheets[0]->getNumber());
$this->assertEquals(1, $sheets[0]->getId());
$this->assertEquals('CustomName2', $sheets[1]->getName());
$this->assertEquals(1, $sheets[1]->getNumber());
$this->assertEquals(2, $sheets[1]->getId());
}
/**
* @param string $fileName
* @return array All the read rows the given file
+27 -1
View File
@@ -49,6 +49,16 @@ class CSVTest extends \PHPUnit_Framework_TestCase
$writer->close();
}
/**
* @expectedException \Box\Spout\Common\Exception\InvalidArgumentException
*/
public function testAddRowsShouldThrowExceptionIfRowsAreNotArrayOfArrays()
{
$writer = WriterFactory::create(Type::CSV);
$writer->addRows(['csv--11', 'csv--12']);
$writer->close();
}
/**
* @return void
*/
@@ -76,6 +86,22 @@ class CSVTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('csv--11,,csv--13', $writtenContent, 'The null values should be replaced by empty values');
}
/**
* @return void
*/
public function testWriteShouldSkipEmptyRows()
{
$allRows = [
['csv--11', 'csv--12'],
[],
['csv--31', 'csv--32'],
];
$writtenContent = $this->writeToCsvFileAndReturnWrittenContent($allRows, 'csv_with_empty_rows.csv');
$writtenContent = $this->trimWrittenContent($writtenContent);
$this->assertEquals("csv--11,csv--12\ncsv--31,csv--32", $writtenContent, 'Empty rows should be skipped');
}
/**
* @return void
*/
@@ -135,6 +161,6 @@ class CSVTest extends \PHPUnit_Framework_TestCase
private function trimWrittenContent($writtenContent)
{
// remove line feeds and UTF-8 BOM
return trim($writtenContent, "\n" . CSV::UTF8_BOM);
return trim($writtenContent, PHP_EOL . CSV::UTF8_BOM);
}
}
@@ -34,4 +34,62 @@ class CellHelperTest extends \PHPUnit_Framework_TestCase
{
$this->assertEquals($expectedCellIndex, CellHelper::getCellIndexFromColumnIndex($columnIndex));
}
/**
* @return array
*/
public function testIsNonEmptyString()
{
$this->assertTrue(CellHelper::isNonEmptyString("string"));
$this->assertFalse(CellHelper::isNonEmptyString(""));
$this->assertFalse(CellHelper::isNonEmptyString(0));
$this->assertFalse(CellHelper::isNonEmptyString(1));
$this->assertFalse(CellHelper::isNonEmptyString(true));
$this->assertFalse(CellHelper::isNonEmptyString(false));
$this->assertFalse(CellHelper::isNonEmptyString(["string"]));
$this->assertFalse(CellHelper::isNonEmptyString(new \stdClass()));
$this->assertFalse(CellHelper::isNonEmptyString(null));
}
/**
* @return array
*/
public function testIsNumeric()
{
$this->assertTrue(CellHelper::isNumeric(0));
$this->assertTrue(CellHelper::isNumeric(10));
$this->assertTrue(CellHelper::isNumeric(10.1));
$this->assertTrue(CellHelper::isNumeric(10.10000000000000000000001));
$this->assertTrue(CellHelper::isNumeric(0x539));
$this->assertTrue(CellHelper::isNumeric(02471));
$this->assertTrue(CellHelper::isNumeric(0b10100111001));
$this->assertTrue(CellHelper::isNumeric(1337e0));
$this->assertFalse(CellHelper::isNumeric("0"));
$this->assertFalse(CellHelper::isNumeric("42"));
$this->assertFalse(CellHelper::isNumeric(true));
$this->assertFalse(CellHelper::isNumeric([2]));
$this->assertFalse(CellHelper::isNumeric(new \stdClass()));
$this->assertFalse(CellHelper::isNumeric(null));
}
/**
* @return array
*/
public function testIsBoolean()
{
$this->assertTrue(CellHelper::isBoolean(true));
$this->assertTrue(CellHelper::isBoolean(false));
$this->assertFalse(CellHelper::isBoolean(0));
$this->assertFalse(CellHelper::isBoolean(1));
$this->assertFalse(CellHelper::isBoolean("0"));
$this->assertFalse(CellHelper::isBoolean("1"));
$this->assertFalse(CellHelper::isBoolean("true"));
$this->assertFalse(CellHelper::isBoolean("false"));
$this->assertFalse(CellHelper::isBoolean([true]));
$this->assertFalse(CellHelper::isBoolean(new \stdClass()));
$this->assertFalse(CellHelper::isBoolean(null));
}
}
+2 -2
View File
@@ -22,8 +22,8 @@ class SheetTest extends \PHPUnit_Framework_TestCase
$sheets = $this->writeDataAndReturnSheets('test_get_sheet_number.xlsx');
$this->assertEquals(2, count($sheets), '2 sheets should have been created');
$this->assertEquals(0, $sheets[0]->getSheetNumber(), 'The first sheet should be number 0');
$this->assertEquals(1, $sheets[1]->getSheetNumber(), 'The second sheet should be number 1');
$this->assertEquals(0, $sheets[0]->getNumber(), 'The first sheet should be number 0');
$this->assertEquals(1, $sheets[1]->getNumber(), 'The second sheet should be number 1');
}
/**
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace Box\Spout\Writer;
/**
* Class WriterFactoryTest
*
* @package Box\Spout\Writer
*/
class WriterFactoryTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \Box\Spout\Common\Exception\UnsupportedTypeException
*
* @return void
*/
public function testCreateWriterShouldThrowWithUnsupportedType()
{
WriterFactory::create('unsupportedType');
}
}
+87 -21
View File
@@ -49,6 +49,19 @@ class XLSXTest extends \PHPUnit_Framework_TestCase
$writer->close();
}
/**
* @expectedException \Box\Spout\Common\Exception\InvalidArgumentException
*/
public function testAddRowShouldThrowExceptionIfUnsupportedDataTypePassedIn()
{
$fileName = 'test_add_row_should_throw_exception_if_unsupported_data_type_passed_in.xlsx';
$dataRows = [
[new \stdClass()],
];
$this->writeToXLSXFile($dataRows, $fileName);
}
/**
* @return void
*/
@@ -96,7 +109,7 @@ class XLSXTest extends \PHPUnit_Framework_TestCase
*/
public function testAddRowShouldWriteGivenDataToSheetUsingInlineStrings()
{
$fileName = 'test_add_row_should_write_given_data_to_sheet.xlsx';
$fileName = 'test_add_row_should_write_given_data_to_sheet_using_inline_strings.xlsx';
$dataRows = [
['xlsx--11', 'xlsx--12'],
['xlsx--21', 'xlsx--22', 'xlsx--23'],
@@ -106,7 +119,7 @@ class XLSXTest extends \PHPUnit_Framework_TestCase
foreach ($dataRows as $dataRow) {
foreach ($dataRow as $cellValue) {
$this->assertInlineStringWasWrittenToSheet($fileName, 1, $cellValue);
$this->assertInlineDataWasWrittenToSheet($fileName, 1, $cellValue);
}
}
}
@@ -116,7 +129,7 @@ class XLSXTest extends \PHPUnit_Framework_TestCase
*/
public function testAddRowShouldWriteGivenDataToTwoSheetUsingInlineStrings()
{
$fileName = 'test_add_row_should_write_given_data_to_sheet.xlsx';
$fileName = 'test_add_row_should_write_given_data_to_two_sheets_using_inline_strings.xlsx';
$dataRows = [
['xlsx--11', 'xlsx--12'],
['xlsx--21', 'xlsx--22', 'xlsx--23'],
@@ -128,7 +141,7 @@ class XLSXTest extends \PHPUnit_Framework_TestCase
for ($i = 1; $i <= $numSheets; $i++) {
foreach ($dataRows as $dataRow) {
foreach ($dataRow as $cellValue) {
$this->assertInlineStringWasWrittenToSheet($fileName, $numSheets, $cellValue);
$this->assertInlineDataWasWrittenToSheet($fileName, $numSheets, $cellValue);
}
}
}
@@ -139,7 +152,7 @@ class XLSXTest extends \PHPUnit_Framework_TestCase
*/
public function testAddRowShouldWriteGivenDataToSheetUsingSharedStrings()
{
$fileName = 'test_add_row_should_write_given_data_to_sheet.xlsx';
$fileName = 'test_add_row_should_write_given_data_to_sheet_using_shared_strings.xlsx';
$dataRows = [
['xlsx--11', 'xlsx--12'],
['xlsx--21', 'xlsx--22', 'xlsx--23'],
@@ -159,7 +172,7 @@ class XLSXTest extends \PHPUnit_Framework_TestCase
*/
public function testAddRowShouldWriteGivenDataToTwoSheetUsingSharedStrings()
{
$fileName = 'test_add_row_should_write_given_data_to_two_sheet_using_shared_strings.xlsx';
$fileName = 'test_add_row_should_write_given_data_to_two_sheets_using_shared_strings.xlsx';
$dataRows = [
['xlsx--11', 'xlsx--12'],
['xlsx--21', 'xlsx--22', 'xlsx--23'],
@@ -177,6 +190,24 @@ class XLSXTest extends \PHPUnit_Framework_TestCase
}
}
/**
* @return void
*/
public function testAddRowShouldSupportMultipleTypesOfData()
{
$fileName = 'test_add_row_should_support_multiple_types_of_data.xlsx';
$dataRows = [
['xlsx--11', true, '', 0, 10.2, null],
];
$this->writeToXLSXFile($dataRows, $fileName, $shouldUseInlineStrings = false);
$this->assertSharedStringWasWritten($fileName, 'xlsx--11');
$this->assertInlineDataWasWrittenToSheet($fileName, 1, 1); // true is converted to 1
$this->assertInlineDataWasWrittenToSheet($fileName, 1, 0);
$this->assertInlineDataWasWrittenToSheet($fileName, 1, 10.2);
}
/**
* @return void
*/
@@ -219,17 +250,17 @@ class XLSXTest extends \PHPUnit_Framework_TestCase
foreach ($dataRowsSheet1 as $dataRow) {
foreach ($dataRow as $cellValue) {
$this->assertInlineStringWasWrittenToSheet($fileName, 1, $cellValue, 'Data should have been written in Sheet 1');
$this->assertInlineDataWasWrittenToSheet($fileName, 1, $cellValue, 'Data should have been written in Sheet 1');
}
}
foreach ($dataRowsSheet2 as $dataRow) {
foreach ($dataRow as $cellValue) {
$this->assertInlineStringWasWrittenToSheet($fileName, 2, $cellValue, 'Data should have been written in Sheet 2');
$this->assertInlineDataWasWrittenToSheet($fileName, 2, $cellValue, 'Data should have been written in Sheet 2');
}
}
foreach ($dataRowsSheet1Again as $dataRow) {
foreach ($dataRow as $cellValue) {
$this->assertInlineStringWasWrittenToSheet($fileName, 1, $cellValue, 'Data should have been written in Sheet 1');
$this->assertInlineDataWasWrittenToSheet($fileName, 1, $cellValue, 'Data should have been written in Sheet 1');
}
}
}
@@ -252,8 +283,8 @@ class XLSXTest extends \PHPUnit_Framework_TestCase
$writer = $this->writeToXLSXFile($dataRows, $fileName, true, $shouldCreateSheetsAutomatically = true);
$this->assertEquals(2, count($writer->getSheets()), '2 sheets should have been created.');
$this->assertInlineStringWasNotWrittenToSheet($fileName, 1, 'xlsx--sheet2--11');
$this->assertInlineStringWasWrittenToSheet($fileName, 2, 'xlsx--sheet2--11');
$this->assertInlineDataWasNotWrittenToSheet($fileName, 1, 'xlsx--sheet2--11');
$this->assertInlineDataWasWrittenToSheet($fileName, 2, 'xlsx--sheet2--11');
\ReflectionHelper::reset();
}
@@ -276,7 +307,7 @@ class XLSXTest extends \PHPUnit_Framework_TestCase
$writer = $this->writeToXLSXFile($dataRows, $fileName, true, $shouldCreateSheetsAutomatically = false);
$this->assertEquals(1, count($writer->getSheets()), 'Only 1 sheet should have been created.');
$this->assertInlineStringWasNotWrittenToSheet($fileName, 1, 'xlsx--sheet1--31');
$this->assertInlineDataWasNotWrittenToSheet($fileName, 1, 'xlsx--sheet1--31');
\ReflectionHelper::reset();
}
@@ -293,8 +324,8 @@ class XLSXTest extends \PHPUnit_Framework_TestCase
$this->writeToXLSXFile($dataRows, $fileName);
$this->assertInlineStringWasWrittenToSheet($fileName, 1, 'I&#039;m in &quot;great&quot; mood', 'Quotes should be escaped');
$this->assertInlineStringWasWrittenToSheet($fileName, 1, 'This &lt;must&gt; be escaped &amp; tested', '<, > and & should be escaped');
$this->assertInlineDataWasWrittenToSheet($fileName, 1, 'I&#039;m in &quot;great&quot; mood', 'Quotes should be escaped');
$this->assertInlineDataWasWrittenToSheet($fileName, 1, 'This &lt;must&gt; be escaped &amp; tested', '<, > and & should be escaped');
}
/**
@@ -309,9 +340,30 @@ class XLSXTest extends \PHPUnit_Framework_TestCase
$this->writeToXLSXFile($dataRows, $fileName);
$this->assertInlineStringWasWrittenToSheet($fileName, 1, 'control&#039;s _x0015_ &quot;character&quot;');
$this->assertInlineDataWasWrittenToSheet($fileName, 1, 'control&#039;s _x0015_ &quot;character&quot;');
}
/**
* @return void
*/
public function testSetNameShouldCreateSheetWithCustomName()
{
$fileName = 'test_set_name_should_create_sheet_with_custom_name.xlsx';
$this->createGeneratedFolderIfNeeded($fileName);
$resourcePath = $this->getGeneratedResourcePath($fileName);
$writer = WriterFactory::create(Type::XLSX);
$writer->openToFile($resourcePath);
$customSheetName = 'CustomName';
$sheet = $writer->getCurrentSheet();
$sheet->setName($customSheetName);
$writer->addRow(['xlsx--11', 'xlsx--12']);
$writer->close();
$this->assertSheetNameEquals($customSheetName, $resourcePath, "The sheet name should have been changed to '$customSheetName'");
}
/**
* @param array $allRows
@@ -371,33 +423,33 @@ class XLSXTest extends \PHPUnit_Framework_TestCase
/**
* @param string $fileName
* @param int $sheetNumber
* @param string $inlineString
* @param mixed $inlineData
* @param string $message
* @return void
*/
private function assertInlineStringWasWrittenToSheet($fileName, $sheetNumber, $inlineString, $message = '')
private function assertInlineDataWasWrittenToSheet($fileName, $sheetNumber, $inlineData, $message = '')
{
$resourcePath = $this->getGeneratedResourcePath($fileName);
$pathToSheetFile = $resourcePath . '#xl/worksheets/sheet' . $sheetNumber . '.xml';
$xmlContents = file_get_contents('zip://' . $pathToSheetFile);
$this->assertContains($inlineString, $xmlContents, $message);
$this->assertContains((string)$inlineData, $xmlContents, $message);
}
/**
* @param string $fileName
* @param int $sheetNumber
* @param string $inlineString
* @param mixed $inlineData
* @param string $message
* @return void
*/
private function assertInlineStringWasNotWrittenToSheet($fileName, $sheetNumber, $inlineString, $message = '')
private function assertInlineDataWasNotWrittenToSheet($fileName, $sheetNumber, $inlineData, $message = '')
{
$resourcePath = $this->getGeneratedResourcePath($fileName);
$pathToSheetFile = $resourcePath . '#xl/worksheets/sheet' . $sheetNumber . '.xml';
$xmlContents = file_get_contents('zip://' . $pathToSheetFile);
$this->assertNotContains($inlineString, $xmlContents, $message);
$this->assertNotContains((string)$inlineData, $xmlContents, $message);
}
/**
@@ -414,4 +466,18 @@ class XLSXTest extends \PHPUnit_Framework_TestCase
$this->assertContains($sharedString, $xmlContents, $message);
}
/**
* @param string $expectedName
* @param string $resourcePath
* @param string $message
* @return void
*/
private function assertSheetNameEquals($expectedName, $resourcePath, $message = '')
{
$pathToWorkbookFile = $resourcePath . '#xl/workbook.xml';
$xmlContents = file_get_contents('zip://' . $pathToWorkbookFile);
$this->assertContains('<sheet name="' . $expectedName . '"', $xmlContents, $message);
}
}