diff --git a/.gitattributes b/.gitattributes index 5305c97..3e98f80 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,11 +1,11 @@ -# Ignore all test and documentation for archive +# Ignore all test, documentation and dot files for archive /tests export-ignore /.editorconfig export-ignore /.gitattributes export-ignore /.gitignore export-ignore +/.php_cs.dist export-ignore /.scrutinizer.yml export-ignore /.travis.yml export-ignore -/composer.lock export-ignore /CONTRIBUTING.md export-ignore /logo.png export-ignore /phpunit.xml export-ignore diff --git a/.gitignore b/.gitignore index 16e0c78..048320b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,8 @@ +/.idea +*.iml + /tests/resources/generated /tests/coverage /vendor -/.idea -*.iml -composer.lock +/composer.lock +/.php_cs.cache diff --git a/.php_cs.dist b/.php_cs.dist new file mode 100644 index 0000000..f2a404c --- /dev/null +++ b/.php_cs.dist @@ -0,0 +1,58 @@ +setRiskyAllowed(true) + ->setRules([ + '@Symfony' => true, + 'align_multiline_comment' => false, + 'array_syntax' => ['syntax' => 'short'], + 'binary_operator_spaces' => ['align_double_arrow' => true, 'align_equals' => null], + 'blank_line_before_statement' => ['statements' => ['return']], + 'combine_consecutive_unsets' => true, + 'concat_space' => ['spacing' => 'one'], + 'declare_equal_normalize' => ['space' => 'single'], + 'heredoc_to_nowdoc' => true, + 'is_null' => ['use_yoda_style' => false], + 'method_argument_space' => ['ensure_fully_multiline' => true], + 'modernize_types_casting' => true, + 'no_break_comment' => ['comment_text' => 'do nothing'], + 'no_empty_phpdoc' => false, + 'no_null_property_initialization' => true, + 'no_short_echo_tag' => true, + 'no_superfluous_elseif' => true, + 'no_unneeded_control_parentheses' => ['statements' => ['break', 'clone', 'continue', 'echo_print', 'switch_case', 'yield']], + 'no_unneeded_curly_braces' => true, + 'no_unneeded_final_method' => true, + 'no_useless_else' => false, + 'no_useless_return' => true, + 'ordered_imports' => true, + 'phpdoc_add_missing_param_annotation' => true, + 'phpdoc_align' => false, + 'phpdoc_annotation_without_dot' => false, + 'phpdoc_no_empty_return' => false, + 'phpdoc_order' => true, + 'phpdoc_summary' => false, + 'phpdoc_types_order' => ['null_adjustment' => 'always_last', 'sort_algorithm' => 'none'], + 'phpdoc_separation' => false, + 'pre_increment' => false, + 'protected_to_private' => true, + 'psr4' => true, + 'return_type_declaration' => ['space_before' => 'one'], + 'semicolon_after_instruction' => true, + 'simplified_null_return' => false, + 'single_line_comment_style' => ['comment_types' => ['hash']], + 'strict_comparison' => true, + 'void_return' => true, + ]); + +$config->setFinder( + PhpCsFixer\Finder::create() + ->exclude('vendor') + ->in(__DIR__) + ->name('*.php') +); + +$cacheDir = getenv('TRAVIS') ? getenv('HOME') . '/.php-cs-fixer' : __DIR__; +$config->setCacheFile($cacheDir . '/.php_cs.cache'); + +return $config; diff --git a/.travis.yml b/.travis.yml index 2bdc52c..22976cc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,27 +1,60 @@ +dist: trusty +sudo: false + language: php -dist: trusty - -php: - - 5.6 - - 7.0 - - 7.1 - - hhvm-3.6 +matrix: + include: + - php: 5.6 + env: WITH_PHPUNIT=true + - php: 5.6 + env: WITH_CS=true + - php: 7.0 + env: WITH_PHPUNIT=true + - php: 7.1 + env: WITH_PHPUNIT=true WITH_COVERAGE=true + - php: hhvm-3.6 + env: WITH_PHPUNIT=true cache: directories: - $HOME/.composer/cache + - $HOME/.php-cs-fixer + +before_install: + - | + if [[ "$WITH_COVERAGE" != "true" ]]; then + phpenv config-rm xdebug.ini + fi + if [[ "$WITH_CS" != "true" ]]; then + composer remove friendsofphp/php-cs-fixer --dev --no-update + fi + - composer validate install: - composer install --no-interaction --prefer-source -script: +before_script: + - mkdir -p "$HOME/.php-cs-fixer" - mkdir -p build/logs - - php vendor/bin/phpunit --coverage-clover=build/logs/coverage.clover + +script: + - | + if [[ "$WITH_CS" == "true" ]]; then + vendor/bin/php-cs-fixer fix --config=.php_cs.dist --verbose --diff --dry-run + fi + - | + if [[ "$WITH_PHPUNIT" == "true" ]]; then + if [[ "$WITH_COVERAGE" == "true" ]]; then + vendor/bin/phpunit --coverage-clover=build/logs/coverage.clover + else + vendor/bin/phpunit --no-coverage + fi + fi after_script: - | - if [[ "$TRAVIS_PHP_VERSION" = '7.1' ]]; then + if [[ "$WITH_COVERAGE" == "true" ]]; then wget https://scrutinizer-ci.com/ocular.phar php ocular.phar code-coverage:upload --format=php-clover build/logs/coverage.clover fi diff --git a/composer.json b/composer.json index 53bea00..b1eaf23 100644 --- a/composer.json +++ b/composer.json @@ -17,7 +17,8 @@ "ext-xmlreader" : "*" }, "require-dev": { - "phpunit/phpunit": "^5.7.0" + "phpunit/phpunit": "^5.7.0", + "friendsofphp/php-cs-fixer": "^2.5.0" }, "suggest": { "ext-iconv": "To handle non UTF-8 CSV files (if \"php-intl\" is not already installed or is too limited)", diff --git a/src/Spout/Autoloader/Psr4Autoloader.php b/src/Spout/Autoloader/Psr4Autoloader.php index 67cccc3..9dcc374 100644 --- a/src/Spout/Autoloader/Psr4Autoloader.php +++ b/src/Spout/Autoloader/Psr4Autoloader.php @@ -5,8 +5,6 @@ namespace Box\Spout\Autoloader; /** * Class Psr4Autoloader * @see https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md#class-example - * - * @package Box\Spout\Autoloader */ class Psr4Autoloader { @@ -16,7 +14,7 @@ class Psr4Autoloader * * @var array */ - protected $prefixes = array(); + protected $prefixes = []; /** * Register loader with SPL autoloader stack. @@ -25,7 +23,7 @@ class Psr4Autoloader */ public function register() { - spl_autoload_register(array($this, 'loadClass')); + spl_autoload_register([$this, 'loadClass']); } /** @@ -49,7 +47,7 @@ class Psr4Autoloader // initialize the namespace prefix array if (isset($this->prefixes[$prefix]) === false) { - $this->prefixes[$prefix] = array(); + $this->prefixes[$prefix] = []; } // retain the base directory for the namespace prefix @@ -75,7 +73,6 @@ class Psr4Autoloader // work backwards through the namespace names of the fully-qualified // class name to find a mapped file name while (false !== $pos = strrpos($prefix, '\\')) { - // retain the trailing namespace separator in the prefix $prefix = substr($class, 0, $pos + 1); @@ -114,7 +111,6 @@ class Psr4Autoloader // look through base directories for this namespace prefix foreach ($this->prefixes[$prefix] as $baseDir) { - // replace the namespace prefix with the base directory, // replace namespace separators with directory separators // in the relative class name, append with .php @@ -143,8 +139,10 @@ class Psr4Autoloader { if (file_exists($file)) { require $file; + return true; } + return false; } } diff --git a/src/Spout/Autoloader/autoload.php b/src/Spout/Autoloader/autoload.php index 73ee519..e08ee34 100644 --- a/src/Spout/Autoloader/autoload.php +++ b/src/Spout/Autoloader/autoload.php @@ -5,7 +5,7 @@ namespace Box\Spout\Autoloader; require_once 'Psr4Autoloader.php'; /** - * @var string $srcBaseDirectory + * @var string * Full path to "src/Spout" which is what we want "Box\Spout" to map to. */ $srcBaseDirectory = dirname(dirname(__FILE__)); diff --git a/src/Spout/Common/Creator/HelperFactory.php b/src/Spout/Common/Creator/HelperFactory.php new file mode 100644 index 0000000..2277f2c --- /dev/null +++ b/src/Spout/Common/Creator/HelperFactory.php @@ -0,0 +1,49 @@ +canUseIconv()) { $convertedString = $this->globalFunctionsHelper->iconv($string, $sourceEncoding, $targetEncoding); - } else if ($this->canUseMbString()) { + } elseif ($this->canUseMbString()) { $convertedString = $this->globalFunctionsHelper->mb_convert_encoding($string, $sourceEncoding, $targetEncoding); } else { throw new EncodingConversionException("The conversion from $sourceEncoding to $targetEncoding is not supported. Please install \"iconv\" or \"PHP Intl\"."); diff --git a/src/Spout/Common/Escaper/CSV.php b/src/Spout/Common/Helper/Escaper/CSV.php similarity index 90% rename from src/Spout/Common/Escaper/CSV.php rename to src/Spout/Common/Helper/Escaper/CSV.php index 4bc2d1a..26777e8 100644 --- a/src/Spout/Common/Escaper/CSV.php +++ b/src/Spout/Common/Helper/Escaper/CSV.php @@ -1,12 +1,10 @@ escapableControlCharactersPattern = $this->getEscapableControlCharactersPattern(); - $this->controlCharactersEscapingMap = $this->getControlCharactersEscapingMap(); - $this->controlCharactersEscapingReverseMap = array_flip($this->controlCharactersEscapingMap); + if (!$this->isAlreadyInitialized) { + $this->escapableControlCharactersPattern = $this->getEscapableControlCharactersPattern(); + $this->controlCharactersEscapingMap = $this->getControlCharactersEscapingMap(); + $this->controlCharactersEscapingReverseMap = array_flip($this->controlCharactersEscapingMap); + + $this->isAlreadyInitialized = true; + } } /** @@ -41,6 +42,8 @@ class XLSX implements EscaperInterface */ public function escape($string) { + $this->initIfNeeded(); + $escapedString = $this->escapeControlCharacters($string); // @NOTE: Using ENT_NOQUOTES as only XML entities ('<', '>', '&') need to be encoded. // Single and double quotes can be left as is. @@ -57,6 +60,8 @@ class XLSX implements EscaperInterface */ public function unescape($string) { + $this->initIfNeeded(); + // ============== // = WARNING = // ============== @@ -88,7 +93,7 @@ class XLSX implements EscaperInterface * "\t", "\r" and "\n" don't need to be escaped. * * NOTE: the logic has been adapted from the XlsxWriter library (BSD License) - * @link https://github.com/jmcnamara/XlsxWriter/blob/f1e610f29/xlsxwriter/sharedstrings.py#L89 + * @see https://github.com/jmcnamara/XlsxWriter/blob/f1e610f29/xlsxwriter/sharedstrings.py#L89 * * @return string[] */ @@ -101,7 +106,7 @@ class XLSX implements EscaperInterface $character = chr($charValue); if (preg_match("/{$this->escapableControlCharactersPattern}/", $character)) { $charHexValue = dechex($charValue); - $escapedChar = '_x' . sprintf('%04s' , strtoupper($charHexValue)) . '_'; + $escapedChar = '_x' . sprintf('%04s', strtoupper($charHexValue)) . '_'; $controlCharactersEscapingMap[$escapedChar] = $character; } } @@ -117,7 +122,7 @@ class XLSX implements EscaperInterface * So "\0" -> _x0000_ and "_x0000_" -> _x005F_x0000_. * * NOTE: the logic has been adapted from the XlsxWriter library (BSD License) - * @link https://github.com/jmcnamara/XlsxWriter/blob/f1e610f29/xlsxwriter/sharedstrings.py#L89 + * @see https://github.com/jmcnamara/XlsxWriter/blob/f1e610f29/xlsxwriter/sharedstrings.py#L89 * * @param string $string String to escape * @return string @@ -131,7 +136,7 @@ class XLSX implements EscaperInterface return $escapedString; } - return preg_replace_callback("/({$this->escapableControlCharactersPattern})/", function($matches) { + return preg_replace_callback("/({$this->escapableControlCharactersPattern})/", function ($matches) { return $this->controlCharactersEscapingReverseMap[$matches[0]]; }, $escapedString); } @@ -155,7 +160,7 @@ class XLSX implements EscaperInterface * So "_x0000_" -> "\0" and "_x005F_x0000_" -> "_x0000_" * * NOTE: the logic has been adapted from the XlsxWriter library (BSD License) - * @link https://github.com/jmcnamara/XlsxWriter/blob/f1e610f29/xlsxwriter/sharedstrings.py#L89 + * @see https://github.com/jmcnamara/XlsxWriter/blob/f1e610f29/xlsxwriter/sharedstrings.py#L89 * * @param string $string String to unescape * @return string diff --git a/src/Spout/Common/Helper/FileSystemHelper.php b/src/Spout/Common/Helper/FileSystemHelper.php index 11428ab..b1bff8f 100644 --- a/src/Spout/Common/Helper/FileSystemHelper.php +++ b/src/Spout/Common/Helper/FileSystemHelper.php @@ -8,8 +8,6 @@ use Box\Spout\Common\Exception\IOException; * Class FileSystemHelper * This class provides helper functions to help with the file system operations * like files/folders creation & deletion - * - * @package Box\Spout\Common\Helper */ class FileSystemHelper implements FileSystemHelperInterface { @@ -29,8 +27,8 @@ class FileSystemHelper implements FileSystemHelperInterface * * @param string $parentFolderPath The parent folder path under which the folder is going to be created * @param string $folderName The name of the folder to create - * @return string Path of the created folder * @throws \Box\Spout\Common\Exception\IOException If unable to create the folder or if the folder path is not inside of the base folder + * @return string Path of the created folder */ public function createFolder($parentFolderPath, $folderName) { @@ -53,8 +51,8 @@ class FileSystemHelper implements FileSystemHelperInterface * @param string $parentFolderPath The parent folder path where the file is going to be created * @param string $fileName The name of the file to create * @param string $fileContents The contents of the file to create - * @return string Path of the created file * @throws \Box\Spout\Common\Exception\IOException If unable to create the file or if the file path is not inside of the base folder + * @return string Path of the created file */ public function createFileWithContents($parentFolderPath, $fileName, $fileContents) { @@ -74,8 +72,8 @@ class FileSystemHelper implements FileSystemHelperInterface * Delete the file at the given path * * @param string $filePath Path of the file to delete - * @return void * @throws \Box\Spout\Common\Exception\IOException If the file path is not inside of the base folder + * @return void */ public function deleteFile($filePath) { @@ -90,8 +88,8 @@ class FileSystemHelper implements FileSystemHelperInterface * Delete the folder at the given path as well as all its contents * * @param string $folderPath Path of the folder to delete - * @return void * @throws \Box\Spout\Common\Exception\IOException If the folder path is not inside of the base folder + * @return void */ public function deleteFolderRecursively($folderPath) { @@ -119,8 +117,8 @@ class FileSystemHelper implements FileSystemHelperInterface * should occur is not inside the base folder. * * @param string $operationFolderPath The path of the folder where the I/O operation should occur - * @return void * @throws \Box\Spout\Common\Exception\IOException If the folder where the I/O operation should occur is not inside the base folder + * @return void */ protected function throwIfOperationNotInBaseFolder($operationFolderPath) { diff --git a/src/Spout/Common/Helper/FileSystemHelperInterface.php b/src/Spout/Common/Helper/FileSystemHelperInterface.php index 7036a05..53c7dd9 100644 --- a/src/Spout/Common/Helper/FileSystemHelperInterface.php +++ b/src/Spout/Common/Helper/FileSystemHelperInterface.php @@ -6,8 +6,6 @@ namespace Box\Spout\Common\Helper; * Class FileSystemHelperInterface * This interface describes helper functions to help with the file system operations * like files/folders creation & deletion - * - * @package Box\Spout\Common\Helper */ interface FileSystemHelperInterface { @@ -16,8 +14,8 @@ interface FileSystemHelperInterface * * @param string $parentFolderPath The parent folder path under which the folder is going to be created * @param string $folderName The name of the folder to create - * @return string Path of the created folder * @throws \Box\Spout\Common\Exception\IOException If unable to create the folder or if the folder path is not inside of the base folder + * @return string Path of the created folder */ public function createFolder($parentFolderPath, $folderName); @@ -28,8 +26,8 @@ interface FileSystemHelperInterface * @param string $parentFolderPath The parent folder path where the file is going to be created * @param string $fileName The name of the file to create * @param string $fileContents The contents of the file to create - * @return string Path of the created file * @throws \Box\Spout\Common\Exception\IOException If unable to create the file or if the file path is not inside of the base folder + * @return string Path of the created file */ public function createFileWithContents($parentFolderPath, $fileName, $fileContents); @@ -37,8 +35,8 @@ interface FileSystemHelperInterface * Delete the file at the given path * * @param string $filePath Path of the file to delete - * @return void * @throws \Box\Spout\Common\Exception\IOException If the file path is not inside of the base folder + * @return void */ public function deleteFile($filePath); @@ -46,8 +44,8 @@ interface FileSystemHelperInterface * Delete the folder at the given path as well as all its contents * * @param string $folderPath Path of the folder to delete - * @return void * @throws \Box\Spout\Common\Exception\IOException If the folder path is not inside of the base folder + * @return void */ public function deleteFolderRecursively($folderPath); } diff --git a/src/Spout/Common/Helper/GlobalFunctionsHelper.php b/src/Spout/Common/Helper/GlobalFunctionsHelper.php index c5d6e31..608854a 100644 --- a/src/Spout/Common/Helper/GlobalFunctionsHelper.php +++ b/src/Spout/Common/Helper/GlobalFunctionsHelper.php @@ -7,8 +7,6 @@ namespace Box\Spout\Common\Helper; * This class wraps global functions to facilitate testing * * @codeCoverageIgnore - * - * @package Box\Spout\Common\Helper */ class GlobalFunctionsHelper { @@ -30,7 +28,7 @@ class GlobalFunctionsHelper * @see fgets() * * @param resource $handle - * @param int|void $length + * @param int|null $length * @return string */ public function fgets($handle, $length = null) @@ -81,9 +79,9 @@ class GlobalFunctionsHelper * @see fgetcsv() * * @param resource $handle - * @param int|void $length - * @param string|void $delimiter - * @param string|void $enclosure + * @param int|null $length + * @param string|null $delimiter + * @param string|null $enclosure * @return array */ public function fgetcsv($handle, $length = null, $delimiter = null, $enclosure = null) @@ -97,8 +95,8 @@ class GlobalFunctionsHelper * * @param resource $handle * @param array $fields - * @param string|void $delimiter - * @param string|void $enclosure + * @param string|null $delimiter + * @param string|null $enclosure * @return int */ public function fputcsv($handle, array $fields, $delimiter = null, $enclosure = null) @@ -165,6 +163,7 @@ class GlobalFunctionsHelper public function file_get_contents($filePath) { $realFilePath = $this->convertToUseRealPath($filePath); + return file_get_contents($realFilePath); } @@ -207,7 +206,7 @@ class GlobalFunctionsHelper * Wrapper around global function feof() * @see feof() * - * @param resource + * @param resource $handle * @return bool */ public function feof($handle) @@ -232,7 +231,7 @@ class GlobalFunctionsHelper * @see basename() * * @param string $path - * @param string|void $suffix + * @param string|null $suffix * @return string */ public function basename($path, $suffix = null) diff --git a/src/Spout/Common/Helper/StringHelper.php b/src/Spout/Common/Helper/StringHelper.php index 273104e..c698815 100644 --- a/src/Spout/Common/Helper/StringHelper.php +++ b/src/Spout/Common/Helper/StringHelper.php @@ -7,8 +7,6 @@ namespace Box\Spout\Common\Helper; * This class provides helper functions to work with strings and multibyte strings. * * @codeCoverageIgnore - * - * @package Box\Spout\Common\Helper */ class StringHelper { @@ -50,6 +48,7 @@ class StringHelper public function getCharFirstOccurrencePosition($char, $string) { $position = $this->hasMbstringSupport ? mb_strpos($string, $char) : strpos($string, $char); + return ($position !== false) ? $position : -1; } @@ -66,6 +65,7 @@ class StringHelper public function getCharLastOccurrencePosition($char, $string) { $position = $this->hasMbstringSupport ? mb_strrpos($string, $char) : strrpos($string, $char); + return ($position !== false) ? $position : -1; } } diff --git a/src/Spout/Writer/Common/Manager/OptionsManagerAbstract.php b/src/Spout/Common/Manager/OptionsManagerAbstract.php similarity index 91% rename from src/Spout/Writer/Common/Manager/OptionsManagerAbstract.php rename to src/Spout/Common/Manager/OptionsManagerAbstract.php index 7b9e176..20eb14e 100644 --- a/src/Spout/Writer/Common/Manager/OptionsManagerAbstract.php +++ b/src/Spout/Common/Manager/OptionsManagerAbstract.php @@ -1,12 +1,9 @@ init(); - } - - /** - * Initializes the singleton - * @return void - */ - protected function init() {} - - final private function __wakeup() {} - final private function __clone() {} -} diff --git a/src/Spout/Reader/CSV/Creator/EntityFactory.php b/src/Spout/Reader/CSV/Creator/EntityFactory.php new file mode 100644 index 0000000..a305ef9 --- /dev/null +++ b/src/Spout/Reader/CSV/Creator/EntityFactory.php @@ -0,0 +1,65 @@ +helperFactory = $helperFactory; + } + + /** + * @param resource $filePointer Pointer to the CSV file to read + * @param OptionsManagerInterface $optionsManager + * @param GlobalFunctionsHelper $globalFunctionsHelper + * @return SheetIterator + */ + public function createSheetIterator($filePointer, $optionsManager, $globalFunctionsHelper) + { + $rowIterator = $this->createRowIterator($filePointer, $optionsManager, $globalFunctionsHelper); + $sheet = $this->createSheet($rowIterator); + + return new SheetIterator($sheet); + } + + /** + * @param RowIterator $rowIterator + * @return Sheet + */ + private function createSheet($rowIterator) + { + return new Sheet($rowIterator); + } + + /** + * @param resource $filePointer Pointer to the CSV file to read + * @param OptionsManagerInterface $optionsManager + * @param GlobalFunctionsHelper $globalFunctionsHelper + * @return RowIterator + */ + private function createRowIterator($filePointer, $optionsManager, $globalFunctionsHelper) + { + $encodingHelper = $this->helperFactory->createEncodingHelper($globalFunctionsHelper); + + return new RowIterator($filePointer, $optionsManager, $encodingHelper, $globalFunctionsHelper); + } +} diff --git a/src/Spout/Reader/CSV/Manager/OptionsManager.php b/src/Spout/Reader/CSV/Manager/OptionsManager.php new file mode 100644 index 0000000..befefe3 --- /dev/null +++ b/src/Spout/Reader/CSV/Manager/OptionsManager.php @@ -0,0 +1,40 @@ +setOption(Options::SHOULD_FORMAT_DATES, false); + $this->setOption(Options::SHOULD_PRESERVE_EMPTY_ROWS, false); + $this->setOption(Options::FIELD_DELIMITER, ','); + $this->setOption(Options::FIELD_ENCLOSURE, '"'); + $this->setOption(Options::ENCODING, EncodingHelper::ENCODING_UTF8); + } +} diff --git a/src/Spout/Reader/CSV/Reader.php b/src/Spout/Reader/CSV/Reader.php index 648a12d..ec43405 100644 --- a/src/Spout/Reader/CSV/Reader.php +++ b/src/Spout/Reader/CSV/Reader.php @@ -2,16 +2,16 @@ namespace Box\Spout\Reader\CSV; -use Box\Spout\Reader\AbstractReader; use Box\Spout\Common\Exception\IOException; +use Box\Spout\Reader\Common\Entity\Options; +use Box\Spout\Reader\CSV\Creator\EntityFactory; +use Box\Spout\Reader\ReaderAbstract; /** * Class Reader * This class provides support to read data from a CSV file. - * - * @package Box\Spout\Reader\CSV */ -class Reader extends AbstractReader +class Reader extends ReaderAbstract { /** @var resource Pointer to the file to be written */ protected $filePointer; @@ -22,19 +22,6 @@ class Reader extends AbstractReader /** @var string Original value for the "auto_detect_line_endings" INI value */ protected $originalAutoDetectLineEndings; - /** - * Returns the reader's current options - * - * @return ReaderOptions - */ - protected function getOptions() - { - if (!isset($this->options)) { - $this->options = new ReaderOptions(); - } - return $this->options; - } - /** * Sets the field delimiter for the CSV. * Needs to be called before opening the reader. @@ -44,7 +31,8 @@ class Reader extends AbstractReader */ public function setFieldDelimiter($fieldDelimiter) { - $this->getOptions()->setFieldDelimiter($fieldDelimiter); + $this->optionsManager->setOption(Options::FIELD_DELIMITER, $fieldDelimiter); + return $this; } @@ -57,7 +45,8 @@ class Reader extends AbstractReader */ public function setFieldEnclosure($fieldEnclosure) { - $this->getOptions()->setFieldEnclosure($fieldEnclosure); + $this->optionsManager->setOption(Options::FIELD_ENCLOSURE, $fieldEnclosure); + return $this; } @@ -70,20 +59,8 @@ class Reader extends AbstractReader */ public function setEncoding($encoding) { - $this->getOptions()->setEncoding($encoding); - return $this; - } + $this->optionsManager->setOption(Options::ENCODING, $encoding); - /** - * Sets the EOL for the CSV. - * Needs to be called before opening the reader. - * - * @param string $endOfLineCharacter used to properly get lines from the CSV file. - * @return Reader - */ - public function setEndOfLineCharacter($endOfLineCharacter) - { - $this->getOptions()->setEndOfLineCharacter($endOfLineCharacter); return $this; } @@ -102,8 +79,8 @@ class Reader extends AbstractReader * If setEncoding() was not called, it assumes that the file is encoded in UTF-8. * * @param string $filePath Path of the CSV file to be read - * @return void * @throws \Box\Spout\Common\Exception\IOException + * @return void */ protected function openReader($filePath) { @@ -115,9 +92,12 @@ class Reader extends AbstractReader throw new IOException("Could not open file $filePath for reading."); } - $this->sheetIterator = new SheetIterator( + /** @var EntityFactory $entityFactory */ + $entityFactory = $this->entityFactory; + + $this->sheetIterator = $entityFactory->createSheetIterator( $this->filePointer, - $this->getOptions(), + $this->optionsManager, $this->globalFunctionsHelper ); } @@ -132,7 +112,6 @@ class Reader extends AbstractReader return $this->sheetIterator; } - /** * Closes the reader. To be used after reading the file. * diff --git a/src/Spout/Reader/CSV/ReaderOptions.php b/src/Spout/Reader/CSV/ReaderOptions.php deleted file mode 100644 index 9a1adb8..0000000 --- a/src/Spout/Reader/CSV/ReaderOptions.php +++ /dev/null @@ -1,110 +0,0 @@ -fieldDelimiter; - } - - /** - * Sets the field delimiter for the CSV. - * Needs to be called before opening the reader. - * - * @param string $fieldDelimiter Character that delimits fields - * @return ReaderOptions - */ - public function setFieldDelimiter($fieldDelimiter) - { - $this->fieldDelimiter = $fieldDelimiter; - return $this; - } - - /** - * @return string - */ - public function getFieldEnclosure() - { - return $this->fieldEnclosure; - } - - /** - * Sets the field enclosure for the CSV. - * Needs to be called before opening the reader. - * - * @param string $fieldEnclosure Character that enclose fields - * @return ReaderOptions - */ - public function setFieldEnclosure($fieldEnclosure) - { - $this->fieldEnclosure = $fieldEnclosure; - return $this; - } - - /** - * @return string - */ - public function getEncoding() - { - return $this->encoding; - } - - /** - * Sets the encoding of the CSV file to be read. - * Needs to be called before opening the reader. - * - * @param string $encoding Encoding of the CSV file to be read - * @return ReaderOptions - */ - public function setEncoding($encoding) - { - $this->encoding = $encoding; - return $this; - } - - /** - * @return string EOL for the CSV - */ - public function getEndOfLineCharacter() - { - return $this->endOfLineCharacter; - } - - /** - * Sets the EOL for the CSV. - * Needs to be called before opening the reader. - * - * @param string $endOfLineCharacter used to properly get lines from the CSV file. - * @return ReaderOptions - */ - public function setEndOfLineCharacter($endOfLineCharacter) - { - $this->endOfLineCharacter = $endOfLineCharacter; - return $this; - } -} diff --git a/src/Spout/Reader/CSV/RowIterator.php b/src/Spout/Reader/CSV/RowIterator.php index a2a6672..d1ac3f6 100644 --- a/src/Spout/Reader/CSV/RowIterator.php +++ b/src/Spout/Reader/CSV/RowIterator.php @@ -2,14 +2,13 @@ namespace Box\Spout\Reader\CSV; -use Box\Spout\Reader\IteratorInterface; use Box\Spout\Common\Helper\EncodingHelper; +use Box\Spout\Reader\Common\Entity\Options; +use Box\Spout\Reader\IteratorInterface; /** * Class RowIterator * Iterate over CSV rows. - * - * @package Box\Spout\Reader\CSV */ class RowIterator implements IteratorInterface { @@ -25,7 +24,7 @@ class RowIterator implements IteratorInterface 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; + protected $rowDataBuffer; /** @var bool Indicates whether all rows have been read */ protected $hasReachedEndOfFile = false; @@ -39,9 +38,6 @@ class RowIterator implements IteratorInterface /** @var string Encoding of the CSV file to be read */ protected $encoding; - /** @var string End of line delimiter, given by the user as input. */ - protected $inputEOLDelimiter; - /** @var bool Whether empty rows should be returned or skipped */ protected $shouldPreserveEmptyRows; @@ -51,30 +47,26 @@ class RowIterator implements IteratorInterface /** @var \Box\Spout\Common\Helper\EncodingHelper Helper to work with different encodings */ protected $encodingHelper; - /** @var string End of line delimiter, encoded using the same encoding as the CSV */ - protected $encodedEOLDelimiter; - /** * @param resource $filePointer Pointer to the CSV file to read - * @param \Box\Spout\Reader\CSV\ReaderOptions $options + * @param \Box\Spout\Common\Manager\OptionsManagerInterface $optionsManager + * @param \Box\Spout\Common\Helper\EncodingHelper $encodingHelper * @param \Box\Spout\Common\Helper\GlobalFunctionsHelper $globalFunctionsHelper */ - public function __construct($filePointer, $options, $globalFunctionsHelper) + public function __construct($filePointer, $optionsManager, $encodingHelper, $globalFunctionsHelper) { $this->filePointer = $filePointer; - $this->fieldDelimiter = $options->getFieldDelimiter(); - $this->fieldEnclosure = $options->getFieldEnclosure(); - $this->encoding = $options->getEncoding(); - $this->inputEOLDelimiter = $options->getEndOfLineCharacter(); - $this->shouldPreserveEmptyRows = $options->shouldPreserveEmptyRows(); + $this->fieldDelimiter = $optionsManager->getOption(Options::FIELD_DELIMITER); + $this->fieldEnclosure = $optionsManager->getOption(Options::FIELD_ENCLOSURE); + $this->encoding = $optionsManager->getOption(Options::ENCODING); + $this->shouldPreserveEmptyRows = $optionsManager->getOption(Options::SHOULD_PRESERVE_EMPTY_ROWS); + $this->encodingHelper = $encodingHelper; $this->globalFunctionsHelper = $globalFunctionsHelper; - - $this->encodingHelper = new EncodingHelper($globalFunctionsHelper); } /** * Rewind the Iterator to the first element - * @link http://php.net/manual/en/iterator.rewind.php + * @see http://php.net/manual/en/iterator.rewind.php * * @return void */ @@ -104,7 +96,7 @@ class RowIterator implements IteratorInterface /** * Checks if current position is valid - * @link http://php.net/manual/en/iterator.valid.php + * @see http://php.net/manual/en/iterator.valid.php * * @return bool */ @@ -115,10 +107,10 @@ class RowIterator implements IteratorInterface /** * Move forward to next element. Reads data for the next unprocessed row. - * @link http://php.net/manual/en/iterator.next.php + * @see http://php.net/manual/en/iterator.next.php * - * @return void * @throws \Box\Spout\Common\Exception\EncodingConversionException If unable to convert data to UTF-8 + * @return void */ public function next() { @@ -130,8 +122,8 @@ class RowIterator implements IteratorInterface } /** - * @return void * @throws \Box\Spout\Common\Exception\EncodingConversionException If unable to convert data to UTF-8 + * @return void */ protected function readDataForNextRow() { @@ -171,8 +163,8 @@ class RowIterator implements IteratorInterface * As fgetcsv() does not manage correctly encoding for non UTF-8 data, * we remove manually whitespace with ltrim or rtrim (depending on the order of the bytes) * - * @return array|false The row for the current file pointer, encoded in UTF-8 or FALSE if nothing to read * @throws \Box\Spout\Common\Exception\EncodingConversionException If unable to convert data to UTF-8 + * @return array|false The row for the current file pointer, encoded in UTF-8 or FALSE if nothing to read */ protected function getNextUTF8EncodedRow() { @@ -182,7 +174,7 @@ class RowIterator implements IteratorInterface } foreach ($encodedRowData as $cellIndex => $cellValue) { - switch($this->encoding) { + switch ($this->encoding) { case EncodingHelper::ENCODING_UTF16_LE: case EncodingHelper::ENCODING_UTF32_LE: // remove whitespace from the beginning of a string as fgetcsv() add extra whitespace when it try to explode non UTF-8 data @@ -202,21 +194,6 @@ class RowIterator implements IteratorInterface return $encodedRowData; } - /** - * Returns the end of line delimiter, encoded using the same encoding as the CSV. - * The return value is cached. - * - * @return string - */ - protected function getEncodedEOLDelimiter() - { - if (!isset($this->encodedEOLDelimiter)) { - $this->encodedEOLDelimiter = $this->encodingHelper->attemptConversionFromUTF8($this->inputEOLDelimiter, $this->encoding); - } - - return $this->encodedEOLDelimiter; - } - /** * @param array|bool $lineData Array containing the cells value for the line * @return bool Whether the given line is empty @@ -228,7 +205,7 @@ class RowIterator implements IteratorInterface /** * Return the current element from the buffer - * @link http://php.net/manual/en/iterator.current.php + * @see http://php.net/manual/en/iterator.current.php * * @return array|null */ @@ -239,7 +216,7 @@ class RowIterator implements IteratorInterface /** * Return the key of the current element - * @link http://php.net/manual/en/iterator.key.php + * @see http://php.net/manual/en/iterator.key.php * * @return int */ diff --git a/src/Spout/Reader/CSV/Sheet.php b/src/Spout/Reader/CSV/Sheet.php index 9a688db..3453ffb 100644 --- a/src/Spout/Reader/CSV/Sheet.php +++ b/src/Spout/Reader/CSV/Sheet.php @@ -6,8 +6,6 @@ use Box\Spout\Reader\SheetInterface; /** * Class Sheet - * - * @package Box\Spout\Reader\CSV */ class Sheet implements SheetInterface { @@ -15,13 +13,11 @@ class Sheet implements SheetInterface protected $rowIterator; /** - * @param resource $filePointer Pointer to the CSV file to read - * @param \Box\Spout\Reader\CSV\ReaderOptions $options - * @param \Box\Spout\Common\Helper\GlobalFunctionsHelper $globalFunctionsHelper + * @param RowIterator $rowIterator Corresponding row iterator */ - public function __construct($filePointer, $options, $globalFunctionsHelper) + public function __construct(RowIterator $rowIterator) { - $this->rowIterator = new RowIterator($filePointer, $options, $globalFunctionsHelper); + $this->rowIterator = $rowIterator; } /** diff --git a/src/Spout/Reader/CSV/SheetIterator.php b/src/Spout/Reader/CSV/SheetIterator.php index 58a9480..69eb58a 100644 --- a/src/Spout/Reader/CSV/SheetIterator.php +++ b/src/Spout/Reader/CSV/SheetIterator.php @@ -7,8 +7,6 @@ use Box\Spout\Reader\IteratorInterface; /** * Class SheetIterator * Iterate over CSV unique "sheet". - * - * @package Box\Spout\Reader\CSV */ class SheetIterator implements IteratorInterface { @@ -19,18 +17,16 @@ class SheetIterator implements IteratorInterface protected $hasReadUniqueSheet = false; /** - * @param resource $filePointer - * @param \Box\Spout\Reader\CSV\ReaderOptions $options - * @param \Box\Spout\Common\Helper\GlobalFunctionsHelper $globalFunctionsHelper + * @param Sheet $sheet Corresponding unique sheet */ - public function __construct($filePointer, $options, $globalFunctionsHelper) + public function __construct($sheet) { - $this->sheet = new Sheet($filePointer, $options, $globalFunctionsHelper); + $this->sheet = $sheet; } /** * Rewind the Iterator to the first element - * @link http://php.net/manual/en/iterator.rewind.php + * @see http://php.net/manual/en/iterator.rewind.php * * @return void */ @@ -41,7 +37,7 @@ class SheetIterator implements IteratorInterface /** * Checks if current position is valid - * @link http://php.net/manual/en/iterator.valid.php + * @see http://php.net/manual/en/iterator.valid.php * * @return bool */ @@ -52,7 +48,7 @@ class SheetIterator implements IteratorInterface /** * Move forward to next element - * @link http://php.net/manual/en/iterator.next.php + * @see http://php.net/manual/en/iterator.next.php * * @return void */ @@ -63,7 +59,7 @@ class SheetIterator implements IteratorInterface /** * Return the current element - * @link http://php.net/manual/en/iterator.current.php + * @see http://php.net/manual/en/iterator.current.php * * @return \Box\Spout\Reader\CSV\Sheet */ @@ -74,7 +70,7 @@ class SheetIterator implements IteratorInterface /** * Return the key of the current element - * @link http://php.net/manual/en/iterator.key.php + * @see http://php.net/manual/en/iterator.key.php * * @return int */ diff --git a/src/Spout/Reader/Common/Creator/EntityFactoryInterface.php b/src/Spout/Reader/Common/Creator/EntityFactoryInterface.php new file mode 100644 index 0000000..78b7754 --- /dev/null +++ b/src/Spout/Reader/Common/Creator/EntityFactoryInterface.php @@ -0,0 +1,10 @@ +shouldFormatDates = $shouldFormatDates; + return $this; } @@ -53,6 +52,7 @@ class ReaderOptions public function setShouldPreserveEmptyRows($shouldPreserveEmptyRows) { $this->shouldPreserveEmptyRows = $shouldPreserveEmptyRows; + return $this; } } diff --git a/src/Spout/Reader/Common/XMLProcessor.php b/src/Spout/Reader/Common/XMLProcessor.php index d8a1da8..3b2d848 100644 --- a/src/Spout/Reader/Common/XMLProcessor.php +++ b/src/Spout/Reader/Common/XMLProcessor.php @@ -7,8 +7,6 @@ use Box\Spout\Reader\Wrapper\XMLReader; /** * Class XMLProcessor * Helps process XML files - * - * @package Box\Spout\Reader\Common */ class XMLProcessor { @@ -24,14 +22,12 @@ class XMLProcessor const PROCESSING_CONTINUE = 1; const PROCESSING_STOP = 2; - /** @var \Box\Spout\Reader\Wrapper\XMLReader The XMLReader object that will help read sheet's XML data */ protected $xmlReader; /** @var array Registered callbacks */ private $callbacks = []; - /** * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XMLReader object */ @@ -90,8 +86,8 @@ class XMLProcessor * Resumes the reading of the XML file where it was left off. * Stops whenever a callback indicates that reading should stop or at the end of the file. * - * @return void * @throws \Box\Spout\Reader\Exception\XMLProcessingException + * @return void */ public function readUntilStopped() { diff --git a/src/Spout/Reader/Exception/IteratorNotRewindableException.php b/src/Spout/Reader/Exception/IteratorNotRewindableException.php index a030c12..cb6cb2a 100644 --- a/src/Spout/Reader/Exception/IteratorNotRewindableException.php +++ b/src/Spout/Reader/Exception/IteratorNotRewindableException.php @@ -6,7 +6,6 @@ namespace Box\Spout\Reader\Exception; * Class IteratorNotRewindableException * * @api - * @package Box\Spout\Reader\Exception */ class IteratorNotRewindableException extends ReaderException { diff --git a/src/Spout/Reader/Exception/NoSheetsFoundException.php b/src/Spout/Reader/Exception/NoSheetsFoundException.php index 38d8772..71c6655 100644 --- a/src/Spout/Reader/Exception/NoSheetsFoundException.php +++ b/src/Spout/Reader/Exception/NoSheetsFoundException.php @@ -6,7 +6,6 @@ namespace Box\Spout\Reader\Exception; * Class NoSheetsFoundException * * @api - * @package Box\Spout\Reader\Exception */ class NoSheetsFoundException extends ReaderException { diff --git a/src/Spout/Reader/Exception/ReaderException.php b/src/Spout/Reader/Exception/ReaderException.php index ee9ca79..4b38192 100644 --- a/src/Spout/Reader/Exception/ReaderException.php +++ b/src/Spout/Reader/Exception/ReaderException.php @@ -7,7 +7,6 @@ use Box\Spout\Common\Exception\SpoutException; /** * Class ReaderException * - * @package Box\Spout\Reader\Exception * @abstract */ abstract class ReaderException extends SpoutException diff --git a/src/Spout/Reader/Exception/ReaderNotOpenedException.php b/src/Spout/Reader/Exception/ReaderNotOpenedException.php index 8f94de3..9418d9a 100644 --- a/src/Spout/Reader/Exception/ReaderNotOpenedException.php +++ b/src/Spout/Reader/Exception/ReaderNotOpenedException.php @@ -6,7 +6,6 @@ namespace Box\Spout\Reader\Exception; * Class ReaderNotOpenedException * * @api - * @package Box\Spout\Reader\Exception */ class ReaderNotOpenedException extends ReaderException { diff --git a/src/Spout/Reader/Exception/SharedStringNotFoundException.php b/src/Spout/Reader/Exception/SharedStringNotFoundException.php index b494612..106c566 100644 --- a/src/Spout/Reader/Exception/SharedStringNotFoundException.php +++ b/src/Spout/Reader/Exception/SharedStringNotFoundException.php @@ -6,7 +6,6 @@ namespace Box\Spout\Reader\Exception; * Class SharedStringNotFoundException * * @api - * @package Box\Spout\Reader\Exception */ class SharedStringNotFoundException extends ReaderException { diff --git a/src/Spout/Reader/Exception/XMLProcessingException.php b/src/Spout/Reader/Exception/XMLProcessingException.php index 70f630b..ee2602b 100644 --- a/src/Spout/Reader/Exception/XMLProcessingException.php +++ b/src/Spout/Reader/Exception/XMLProcessingException.php @@ -4,8 +4,6 @@ namespace Box\Spout\Reader\Exception; /** * Class XMLProcessingException - * - * @package Box\Spout\Reader\Exception */ class XMLProcessingException extends ReaderException { diff --git a/src/Spout/Reader/IteratorInterface.php b/src/Spout/Reader/IteratorInterface.php index 7d58e28..4a9305d 100644 --- a/src/Spout/Reader/IteratorInterface.php +++ b/src/Spout/Reader/IteratorInterface.php @@ -4,8 +4,6 @@ namespace Box\Spout\Reader; /** * Interface IteratorInterface - * - * @package Box\Spout\Reader */ interface IteratorInterface extends \Iterator { diff --git a/src/Spout/Reader/ODS/Creator/EntityFactory.php b/src/Spout/Reader/ODS/Creator/EntityFactory.php new file mode 100644 index 0000000..3af756a --- /dev/null +++ b/src/Spout/Reader/ODS/Creator/EntityFactory.php @@ -0,0 +1,96 @@ +helperFactory = $helperFactory; + } + + /** + * @param string $filePath Path of the file to be read + * @param \Box\Spout\Common\Manager\OptionsManagerInterface $optionsManager Reader's options manager + * @return SheetIterator + */ + public function createSheetIterator($filePath, $optionsManager) + { + $escaper = $this->helperFactory->createStringsEscaper(); + $settingsHelper = $this->helperFactory->createSettingsHelper($this); + + return new SheetIterator($filePath, $optionsManager, $escaper, $settingsHelper, $this); + } + + /** + * @param XMLReader $xmlReader XML Reader + * @param int $sheetIndex Index of the sheet, based on order in the workbook (zero-based) + * @param string $sheetName Name of the sheet + * @param bool $isSheetActive Whether the sheet was defined as active + * @param \Box\Spout\Common\Manager\OptionsManagerInterface $optionsManager Reader's options manager + * @return Sheet + */ + public function createSheet($xmlReader, $sheetIndex, $sheetName, $isSheetActive, $optionsManager) + { + $rowIterator = $this->createRowIterator($xmlReader, $optionsManager); + + return new Sheet($rowIterator, $sheetIndex, $sheetName, $isSheetActive); + } + + /** + * @param XMLReader $xmlReader XML Reader + * @param \Box\Spout\Common\Manager\OptionsManagerInterface $optionsManager Reader's options manager + * @return RowIterator + */ + private function createRowIterator($xmlReader, $optionsManager) + { + $shouldFormatDates = $optionsManager->getOption(Options::SHOULD_FORMAT_DATES); + $cellValueFormatter = $this->helperFactory->createCellValueFormatter($shouldFormatDates); + $xmlProcessor = $this->createXMLProcessor($xmlReader); + + return new RowIterator($xmlReader, $optionsManager, $cellValueFormatter, $xmlProcessor); + } + + /** + * @return XMLReader + */ + public function createXMLReader() + { + return new XMLReader(); + } + + /** + * @param $xmlReader + * @return XMLProcessor + */ + private function createXMLProcessor($xmlReader) + { + return new XMLProcessor($xmlReader); + } + + /** + * @return \ZipArchive + */ + public function createZipArchive() + { + return new \ZipArchive(); + } +} diff --git a/src/Spout/Reader/ODS/Creator/HelperFactory.php b/src/Spout/Reader/ODS/Creator/HelperFactory.php new file mode 100644 index 0000000..6f128bd --- /dev/null +++ b/src/Spout/Reader/ODS/Creator/HelperFactory.php @@ -0,0 +1,42 @@ +createStringsEscaper(); + + return new CellValueFormatter($shouldFormatDates, $escaper); + } + + /** + * @param EntityFactory $entityFactory + * @return SettingsHelper + */ + public function createSettingsHelper($entityFactory) + { + return new SettingsHelper($entityFactory); + } + + /** + * @return \Box\Spout\Common\Helper\Escaper\ODS + */ + public function createStringsEscaper() + { + /* @noinspection PhpUnnecessaryFullyQualifiedNameInspection */ + return new \Box\Spout\Common\Helper\Escaper\ODS(); + } +} diff --git a/src/Spout/Reader/ODS/Helper/CellValueFormatter.php b/src/Spout/Reader/ODS/Helper/CellValueFormatter.php index 0c91410..87a2909 100644 --- a/src/Spout/Reader/ODS/Helper/CellValueFormatter.php +++ b/src/Spout/Reader/ODS/Helper/CellValueFormatter.php @@ -5,8 +5,6 @@ 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 { @@ -38,18 +36,17 @@ class CellValueFormatter /** @var bool Whether date/time values should be returned as PHP objects or be formatted as strings */ protected $shouldFormatDates; - /** @var \Box\Spout\Common\Escaper\ODS Used to unescape XML data */ + /** @var \Box\Spout\Common\Helper\Escaper\ODS Used to unescape XML data */ protected $escaper; /** * @param bool $shouldFormatDates Whether date/time values should be returned as PHP objects or be formatted as strings + * @param \Box\Spout\Common\Helper\Escaper\ODS $escaper Used to unescape XML data */ - public function __construct($shouldFormatDates) + public function __construct($shouldFormatDates, $escaper) { $this->shouldFormatDates = $shouldFormatDates; - - /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */ - $this->escaper = \Box\Spout\Common\Escaper\ODS::getInstance(); + $this->escaper = $escaper; } /** @@ -101,11 +98,11 @@ class CellValueFormatter foreach ($pNode->childNodes as $childNode) { if ($childNode instanceof \DOMText) { $currentPValue .= $childNode->nodeValue; - } else if ($childNode->nodeName === self::XML_NODE_S) { + } elseif ($childNode->nodeName === self::XML_NODE_S) { $spaceAttribute = $childNode->getAttribute(self::XML_ATTRIBUTE_C); - $numSpaces = (!empty($spaceAttribute)) ? intval($spaceAttribute) : 1; + $numSpaces = (!empty($spaceAttribute)) ? (int) $spaceAttribute : 1; $currentPValue .= str_repeat(' ', $numSpaces); - } else if ($childNode->nodeName === self::XML_NODE_A || $childNode->nodeName === self::XML_NODE_SPAN) { + } elseif ($childNode->nodeName === self::XML_NODE_A || $childNode->nodeName === self::XML_NODE_SPAN) { $currentPValue .= $childNode->nodeValue; } } @@ -115,6 +112,7 @@ class CellValueFormatter $escapedCellValue = implode("\n", $pNodeValues); $cellValue = $this->escaper->unescape($escapedCellValue); + return $cellValue; } @@ -127,9 +125,11 @@ class CellValueFormatter protected function formatFloatCellValue($node) { $nodeValue = $node->getAttribute(self::XML_ATTRIBUTE_VALUE); - $nodeIntValue = intval($nodeValue); - // The "==" is intentionally not a "===" because only the value matters, not the type - $cellValue = ($nodeIntValue == $nodeValue) ? $nodeIntValue : floatval($nodeValue); + + $nodeIntValue = (int) $nodeValue; + $nodeFloatValue = (float) $nodeValue; + $cellValue = ((float) $nodeIntValue === $nodeFloatValue) ? $nodeIntValue : $nodeFloatValue; + return $cellValue; } @@ -142,9 +142,8 @@ class CellValueFormatter protected function formatBooleanCellValue($node) { $nodeValue = $node->getAttribute(self::XML_ATTRIBUTE_BOOLEAN_VALUE); - // !! is similar to boolval() - $cellValue = !!$nodeValue; - return $cellValue; + + return (bool) $nodeValue; } /** @@ -163,16 +162,18 @@ class CellValueFormatter if ($this->shouldFormatDates) { // The date is already formatted in the "p" tag $nodeWithValueAlreadyFormatted = $node->getElementsByTagName(self::XML_NODE_P)->item(0); - return $nodeWithValueAlreadyFormatted->nodeValue; + $cellValue = $nodeWithValueAlreadyFormatted->nodeValue; } else { // otherwise, get it from the "date-value" attribute try { $nodeValue = $node->getAttribute(self::XML_ATTRIBUTE_DATE_VALUE); - return new \DateTime($nodeValue); + $cellValue = new \DateTime($nodeValue); } catch (\Exception $e) { - return null; + $cellValue = null; } } + + return $cellValue; } /** @@ -191,16 +192,18 @@ class CellValueFormatter if ($this->shouldFormatDates) { // The date is already formatted in the "p" tag $nodeWithValueAlreadyFormatted = $node->getElementsByTagName(self::XML_NODE_P)->item(0); - return $nodeWithValueAlreadyFormatted->nodeValue; + $cellValue = $nodeWithValueAlreadyFormatted->nodeValue; } else { // otherwise, get it from the "time-value" attribute try { $nodeValue = $node->getAttribute(self::XML_ATTRIBUTE_TIME_VALUE); - return new \DateInterval($nodeValue); + $cellValue = new \DateInterval($nodeValue); } catch (\Exception $e) { - return null; + $cellValue = null; } } + + return $cellValue; } /** diff --git a/src/Spout/Reader/ODS/Helper/SettingsHelper.php b/src/Spout/Reader/ODS/Helper/SettingsHelper.php index a5388ef..9a2b8f7 100644 --- a/src/Spout/Reader/ODS/Helper/SettingsHelper.php +++ b/src/Spout/Reader/ODS/Helper/SettingsHelper.php @@ -3,13 +3,11 @@ namespace Box\Spout\Reader\ODS\Helper; use Box\Spout\Reader\Exception\XMLProcessingException; -use Box\Spout\Reader\Wrapper\XMLReader; +use Box\Spout\Reader\ODS\Creator\EntityFactory; /** * Class SettingsHelper * This class provides helper functions to extract data from the "settings.xml" file. - * - * @package Box\Spout\Reader\ODS\Helper */ class SettingsHelper { @@ -20,13 +18,24 @@ class SettingsHelper const XML_ATTRIBUTE_CONFIG_NAME = 'config:name'; const XML_ATTRIBUTE_VALUE_ACTIVE_TABLE = 'ActiveTable'; + /** @var EntityFactory Factory to create entities */ + private $entityFactory; + + /** + * @param EntityFactory $entityFactory Factory to create entities + */ + public function __construct($entityFactory) + { + $this->entityFactory = $entityFactory; + } + /** * @param string $filePath Path of the file to be read * @return string|null Name of the sheet that was defined as active or NULL if none found */ public function getActiveSheetName($filePath) { - $xmlReader = new XMLReader(); + $xmlReader = $this->entityFactory->createXMLReader(); if ($xmlReader->openFileInZip($filePath, self::SETTINGS_XML_FILE_PATH) === false) { return null; } diff --git a/src/Spout/Reader/ODS/Manager/OptionsManager.php b/src/Spout/Reader/ODS/Manager/OptionsManager.php new file mode 100644 index 0000000..102eccb --- /dev/null +++ b/src/Spout/Reader/ODS/Manager/OptionsManager.php @@ -0,0 +1,33 @@ +setOption(Options::SHOULD_FORMAT_DATES, false); + $this->setOption(Options::SHOULD_PRESERVE_EMPTY_ROWS, false); + } +} diff --git a/src/Spout/Reader/ODS/Reader.php b/src/Spout/Reader/ODS/Reader.php index dbdc47b..2e8ba28 100644 --- a/src/Spout/Reader/ODS/Reader.php +++ b/src/Spout/Reader/ODS/Reader.php @@ -3,15 +3,14 @@ namespace Box\Spout\Reader\ODS; use Box\Spout\Common\Exception\IOException; -use Box\Spout\Reader\AbstractReader; +use Box\Spout\Reader\ODS\Creator\EntityFactory; +use Box\Spout\Reader\ReaderAbstract; /** * Class Reader * This class provides support to read data from a ODS file - * - * @package Box\Spout\Reader\ODS */ -class Reader extends AbstractReader +class Reader extends ReaderAbstract { /** @var \ZipArchive */ protected $zip; @@ -19,19 +18,6 @@ class Reader extends AbstractReader /** @var SheetIterator To iterator over the ODS sheets */ protected $sheetIterator; - /** - * Returns the reader's current options - * - * @return ReaderOptions - */ - protected function getOptions() - { - if (!isset($this->options)) { - $this->options = new ReaderOptions(); - } - return $this->options; - } - /** * Returns whether stream wrappers are supported * @@ -46,16 +32,21 @@ class Reader extends AbstractReader * 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 + * @return void */ protected function openReader($filePath) { - $this->zip = new \ZipArchive(); + /** @var EntityFactory $entityFactory */ + $entityFactory = $this->entityFactory; + + $this->zip = $entityFactory->createZipArchive(); if ($this->zip->open($filePath) === true) { - $this->sheetIterator = new SheetIterator($filePath, $this->getOptions()); + /** @var EntityFactory $entityFactory */ + $entityFactory = $this->entityFactory; + $this->sheetIterator = $entityFactory->createSheetIterator($filePath, $this->optionsManager); } else { throw new IOException("Could not open $filePath for reading."); } diff --git a/src/Spout/Reader/ODS/ReaderOptions.php b/src/Spout/Reader/ODS/ReaderOptions.php deleted file mode 100644 index 2d29640..0000000 --- a/src/Spout/Reader/ODS/ReaderOptions.php +++ /dev/null @@ -1,14 +0,0 @@ -" element - * @param \Box\Spout\Reader\ODS\ReaderOptions $options Reader's current options + * @param \Box\Spout\Common\Manager\OptionsManagerInterface $optionsManager Reader's options manager + * @param CellValueFormatter $cellValueFormatter Helper to format cell values + * @param XMLProcessor $xmlProcessor Helper to process XML files */ - public function __construct($xmlReader, $options) + public function __construct($xmlReader, $optionsManager, $cellValueFormatter, $xmlProcessor) { $this->xmlReader = $xmlReader; - $this->shouldPreserveEmptyRows = $options->shouldPreserveEmptyRows(); - $this->cellValueFormatter = new CellValueFormatter($options->shouldFormatDates()); + $this->shouldPreserveEmptyRows = $optionsManager->getOption(Options::SHOULD_PRESERVE_EMPTY_ROWS); + $this->cellValueFormatter = $cellValueFormatter; // Register all callbacks to process different nodes when reading the XML file - $this->xmlProcessor = new XMLProcessor($this->xmlReader); + $this->xmlProcessor = $xmlProcessor; $this->xmlProcessor->registerCallback(self::XML_NODE_ROW, XMLProcessor::NODE_TYPE_START, [$this, 'processRowStartingNode']); $this->xmlProcessor->registerCallback(self::XML_NODE_CELL, XMLProcessor::NODE_TYPE_START, [$this, 'processCellStartingNode']); $this->xmlProcessor->registerCallback(self::XML_NODE_ROW, XMLProcessor::NODE_TYPE_END, [$this, 'processRowEndingNode']); @@ -91,10 +91,10 @@ class RowIterator implements IteratorInterface /** * 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 + * @see http://php.net/manual/en/iterator.rewind.php * - * @return void * @throws \Box\Spout\Reader\Exception\IteratorNotRewindableException If the iterator is rewound more than once + * @return void */ public function rewind() { @@ -116,7 +116,7 @@ class RowIterator implements IteratorInterface /** * Checks if current position is valid - * @link http://php.net/manual/en/iterator.valid.php + * @see http://php.net/manual/en/iterator.valid.php * * @return bool */ @@ -127,11 +127,11 @@ class RowIterator implements IteratorInterface /** * Move forward to next element. Empty rows will be skipped. - * @link http://php.net/manual/en/iterator.next.php + * @see 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 + * @return void */ public function next() { @@ -162,9 +162,9 @@ class RowIterator implements IteratorInterface } /** - * @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 + * @return void */ protected function readDataForNextRow() { @@ -275,7 +275,8 @@ class RowIterator implements IteratorInterface protected function getNumRowsRepeatedForCurrentNode($xmlReader) { $numRowsRepeated = $xmlReader->getAttribute(self::XML_ATTRIBUTE_NUM_ROWS_REPEATED); - return ($numRowsRepeated !== null) ? intval($numRowsRepeated) : 1; + + return ($numRowsRepeated !== null) ? (int) $numRowsRepeated : 1; } /** @@ -285,7 +286,8 @@ class RowIterator implements IteratorInterface protected function getNumColumnsRepeatedForCurrentNode($xmlReader) { $numColumnsRepeated = $xmlReader->getAttribute(self::XML_ATTRIBUTE_NUM_COLUMNS_REPEATED); - return ($numColumnsRepeated !== null) ? intval($numColumnsRepeated) : 1; + + return ($numColumnsRepeated !== null) ? (int) $numColumnsRepeated : 1; } /** @@ -306,7 +308,7 @@ class RowIterator implements IteratorInterface * row data yet (as we still need to apply the "num-columns-repeated" attribute). * * @param array $rowData - * @param string|int|float|bool|\DateTime|\DateInterval|null The value of the last read cell + * @param string|int|float|bool|\DateTime|\DateInterval|null $lastReadCellValue The value of the last read cell * @return bool Whether the row is empty */ protected function isEmptyRow($rowData, $lastReadCellValue) @@ -319,7 +321,7 @@ class RowIterator implements IteratorInterface /** * Return the current element, from the buffer. - * @link http://php.net/manual/en/iterator.current.php + * @see http://php.net/manual/en/iterator.current.php * * @return array|null */ @@ -330,7 +332,7 @@ class RowIterator implements IteratorInterface /** * Return the key of the current element - * @link http://php.net/manual/en/iterator.key.php + * @see http://php.net/manual/en/iterator.key.php * * @return int */ @@ -339,7 +341,6 @@ class RowIterator implements IteratorInterface return $this->lastRowIndexProcessed; } - /** * Cleans up what was created to iterate over the object. * diff --git a/src/Spout/Reader/ODS/Sheet.php b/src/Spout/Reader/ODS/Sheet.php index 794ad3a..31879c8 100644 --- a/src/Spout/Reader/ODS/Sheet.php +++ b/src/Spout/Reader/ODS/Sheet.php @@ -3,13 +3,10 @@ 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 { @@ -29,15 +26,14 @@ class Sheet implements SheetInterface protected $isActive; /** - * @param XMLReader $xmlReader XML Reader, positioned on the "" element + * @param RowIterator $rowIterator The corresponding row iterator * @param int $sheetIndex Index of the sheet, based on order in the workbook (zero-based) * @param string $sheetName Name of the sheet * @param bool $isSheetActive Whether the sheet was defined as active - * @param \Box\Spout\Reader\ODS\ReaderOptions $options Reader's current options */ - public function __construct($xmlReader, $sheetIndex, $sheetName, $isSheetActive, $options) + public function __construct($rowIterator, $sheetIndex, $sheetName, $isSheetActive) { - $this->rowIterator = new RowIterator($xmlReader, $options); + $this->rowIterator = $rowIterator; $this->index = $sheetIndex; $this->name = $sheetName; $this->isActive = $isSheetActive; diff --git a/src/Spout/Reader/ODS/SheetIterator.php b/src/Spout/Reader/ODS/SheetIterator.php index 995c136..3c6dd4e 100644 --- a/src/Spout/Reader/ODS/SheetIterator.php +++ b/src/Spout/Reader/ODS/SheetIterator.php @@ -5,14 +5,13 @@ 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\ODS\Creator\EntityFactory; use Box\Spout\Reader\ODS\Helper\SettingsHelper; use Box\Spout\Reader\Wrapper\XMLReader; /** * Class SheetIterator * Iterate over ODS sheet. - * - * @package Box\Spout\Reader\ODS */ class SheetIterator implements IteratorInterface { @@ -25,13 +24,16 @@ class SheetIterator implements IteratorInterface /** @var string $filePath Path of the file to be read */ protected $filePath; - /** @var \Box\Spout\Reader\ODS\ReaderOptions Reader's current options */ - protected $options; + /** @var \Box\Spout\Common\Manager\OptionsManagerInterface Reader's options manager */ + protected $optionsManager; + + /** @var EntityFactory $entityFactory Factory to create entities */ + protected $entityFactory; /** @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 */ + /** @var \Box\Spout\Common\Helper\Escaper\ODS Used to unescape XML data */ protected $escaper; /** @var bool Whether there are still at least a sheet to be read */ @@ -45,28 +47,27 @@ class SheetIterator implements IteratorInterface /** * @param string $filePath Path of the file to be read - * @param \Box\Spout\Reader\ODS\ReaderOptions $options Reader's current options - * @throws \Box\Spout\Reader\Exception\NoSheetsFoundException If there are no sheets in the file + * @param \Box\Spout\Common\Manager\OptionsManagerInterface $optionsManager + * @param \Box\Spout\Common\Helper\Escaper\ODS $escaper Used to unescape XML data + * @param SettingsHelper $settingsHelper Helper to get data from "settings.xml" + * @param EntityFactory $entityFactory Factory to create entities */ - public function __construct($filePath, $options) + public function __construct($filePath, $optionsManager, $escaper, $settingsHelper, $entityFactory) { $this->filePath = $filePath; - $this->options = $options; - $this->xmlReader = new XMLReader(); - - /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */ - $this->escaper = \Box\Spout\Common\Escaper\ODS::getInstance(); - - $settingsHelper = new SettingsHelper(); + $this->optionsManager = $optionsManager; + $this->entityFactory = $entityFactory; + $this->xmlReader = $entityFactory->createXMLReader(); + $this->escaper = $escaper; $this->activeSheetName = $settingsHelper->getActiveSheetName($filePath); } /** * Rewind the Iterator to the first element - * @link http://php.net/manual/en/iterator.rewind.php + * @see 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 + * @return void */ public function rewind() { @@ -80,15 +81,15 @@ class SheetIterator implements IteratorInterface 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()}]"); - } + 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 + * @see http://php.net/manual/en/iterator.valid.php * * @return bool */ @@ -99,7 +100,7 @@ class SheetIterator implements IteratorInterface /** * Move forward to next element - * @link http://php.net/manual/en/iterator.next.php + * @see http://php.net/manual/en/iterator.next.php * * @return void */ @@ -114,7 +115,7 @@ class SheetIterator implements IteratorInterface /** * Return the current element - * @link http://php.net/manual/en/iterator.current.php + * @see http://php.net/manual/en/iterator.current.php * * @return \Box\Spout\Reader\ODS\Sheet */ @@ -124,7 +125,7 @@ class SheetIterator implements IteratorInterface $sheetName = $this->escaper->unescape($escapedSheetName); $isActiveSheet = $this->isActiveSheet($sheetName, $this->currentSheetIndex, $this->activeSheetName); - return new Sheet($this->xmlReader, $this->currentSheetIndex, $sheetName, $isActiveSheet, $this->options); + return $this->entityFactory->createSheet($this->xmlReader, $this->currentSheetIndex, $sheetName, $isActiveSheet, $this->optionsManager); } /** @@ -132,7 +133,7 @@ class SheetIterator implements IteratorInterface * * @param string $sheetName Name of the current sheet * @param int $sheetIndex Index of the current sheet - * @param string|null Name of the sheet that was defined as active or NULL if none defined + * @param string|null $activeSheetName Name of the sheet that was defined as active or NULL if none defined * @return bool Whether the current sheet was defined as the active one */ private function isActiveSheet($sheetName, $sheetIndex, $activeSheetName) @@ -147,7 +148,7 @@ class SheetIterator implements IteratorInterface /** * Return the key of the current element - * @link http://php.net/manual/en/iterator.key.php + * @see http://php.net/manual/en/iterator.key.php * * @return int */ diff --git a/src/Spout/Reader/AbstractReader.php b/src/Spout/Reader/ReaderAbstract.php similarity index 82% rename from src/Spout/Reader/AbstractReader.php rename to src/Spout/Reader/ReaderAbstract.php index 880efbd..e8ee5f0 100644 --- a/src/Spout/Reader/AbstractReader.php +++ b/src/Spout/Reader/ReaderAbstract.php @@ -3,31 +3,30 @@ namespace Box\Spout\Reader; use Box\Spout\Common\Exception\IOException; +use Box\Spout\Common\Helper\GlobalFunctionsHelper; +use Box\Spout\Common\Manager\OptionsManagerInterface; +use Box\Spout\Reader\Common\Creator\EntityFactoryInterface; +use Box\Spout\Reader\Common\Entity\Options; use Box\Spout\Reader\Exception\ReaderNotOpenedException; /** - * Class AbstractReader + * Class ReaderAbstract * - * @package Box\Spout\Reader * @abstract */ -abstract class AbstractReader implements ReaderInterface +abstract class ReaderAbstract implements ReaderInterface { /** @var bool Indicates whether the stream is currently open */ protected $isStreamOpened = false; + /** @var EntityFactoryInterface Factory to create entities */ + protected $entityFactory; + /** @var \Box\Spout\Common\Helper\GlobalFunctionsHelper Helper to work with global functions */ protected $globalFunctionsHelper; - /** @var \Box\Spout\Reader\Common\ReaderOptions Reader's customized options */ - protected $options; - - /** - * Returns the reader's current options - * - * @return \Box\Spout\Reader\Common\ReaderOptions - */ - abstract protected function getOptions(); + /** @var OptionsManagerInterface Writer options manager */ + protected $optionsManager; /** * Returns whether stream wrappers are supported @@ -47,25 +46,30 @@ abstract class AbstractReader implements ReaderInterface /** * Returns an iterator to iterate over sheets. * - * @return \Iterator To iterate over sheets + * @return IteratorInterface To iterate over sheets */ abstract protected function getConcreteSheetIterator(); /** * Closes the reader. To be used after reading the file. * - * @return AbstractReader + * @return ReaderAbstract */ abstract protected function closeReader(); /** - * @param \Box\Spout\Common\Helper\GlobalFunctionsHelper $globalFunctionsHelper - * @return AbstractReader + * @param OptionsManagerInterface $optionsManager + * @param GlobalFunctionsHelper $globalFunctionsHelper + * @param EntityFactoryInterface $entityFactory */ - public function setGlobalFunctionsHelper($globalFunctionsHelper) - { + public function __construct( + OptionsManagerInterface $optionsManager, + GlobalFunctionsHelper $globalFunctionsHelper, + EntityFactoryInterface $entityFactory + ) { + $this->optionsManager = $optionsManager; $this->globalFunctionsHelper = $globalFunctionsHelper; - return $this; + $this->entityFactory = $entityFactory; } /** @@ -73,11 +77,12 @@ abstract class AbstractReader implements ReaderInterface * * @api * @param bool $shouldFormatDates - * @return AbstractReader + * @return ReaderAbstract */ public function setShouldFormatDates($shouldFormatDates) { - $this->getOptions()->setShouldFormatDates($shouldFormatDates); + $this->optionsManager->setOption(Options::SHOULD_FORMAT_DATES, $shouldFormatDates); + return $this; } @@ -86,11 +91,12 @@ abstract class AbstractReader implements ReaderInterface * * @api * @param bool $shouldPreserveEmptyRows - * @return AbstractReader + * @return ReaderAbstract */ public function setShouldPreserveEmptyRows($shouldPreserveEmptyRows) { - $this->getOptions()->setShouldPreserveEmptyRows($shouldPreserveEmptyRows); + $this->optionsManager->setOption(Options::SHOULD_PRESERVE_EMPTY_ROWS, $shouldPreserveEmptyRows); + return $this; } @@ -100,8 +106,8 @@ abstract class AbstractReader implements ReaderInterface * * @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 + * @return void */ public function open($filePath) { @@ -113,7 +119,8 @@ abstract class AbstractReader implements ReaderInterface // we skip the checks if the provided file path points to a PHP stream if (!$this->globalFunctionsHelper->file_exists($filePath)) { throw new IOException("Could not open $filePath for reading! File does not exist."); - } else if (!$this->globalFunctionsHelper->is_readable($filePath)) { + } + if (!$this->globalFunctionsHelper->is_readable($filePath)) { throw new IOException("Could not open $filePath for reading! File is not readable."); } } @@ -157,6 +164,7 @@ abstract class AbstractReader implements ReaderInterface if (preg_match('/^(\w+):\/\//', $filePath, $matches)) { $streamScheme = $matches[1]; } + return $streamScheme; } @@ -183,6 +191,7 @@ abstract class AbstractReader implements ReaderInterface protected function isSupportedStreamWrapper($filePath) { $streamScheme = $this->getStreamWrapperScheme($filePath); + return ($streamScheme !== null) ? in_array($streamScheme, $this->globalFunctionsHelper->stream_get_wrappers()) : true; @@ -197,6 +206,7 @@ abstract class AbstractReader implements ReaderInterface protected function isPhpStream($filePath) { $streamScheme = $this->getStreamWrapperScheme($filePath); + return ($streamScheme === 'php'); } @@ -204,8 +214,8 @@ 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 + * @return \Iterator To iterate over sheets */ public function getSheetIterator() { diff --git a/src/Spout/Reader/ReaderFactory.php b/src/Spout/Reader/ReaderFactory.php index 93a52cb..fb68f49 100644 --- a/src/Spout/Reader/ReaderFactory.php +++ b/src/Spout/Reader/ReaderFactory.php @@ -2,16 +2,15 @@ namespace Box\Spout\Reader; +use Box\Spout\Common\Creator\HelperFactory; use Box\Spout\Common\Exception\UnsupportedTypeException; -use Box\Spout\Common\Helper\GlobalFunctionsHelper; use Box\Spout\Common\Type; +use Box\Spout\Reader\XLSX\Manager\SharedStringsCaching\CachingStrategyFactory; /** * Class ReaderFactory * This factory is used to create readers, based on the type of the file to be read. * It supports CSV and XLSX formats. - * - * @package Box\Spout\Reader */ class ReaderFactory { @@ -20,29 +19,57 @@ class ReaderFactory * * @api * @param string $readerType Type of the reader to instantiate - * @return ReaderInterface * @throws \Box\Spout\Common\Exception\UnsupportedTypeException + * @return ReaderInterface */ public static function create($readerType) { - $reader = null; - switch ($readerType) { - case Type::CSV: - $reader = new CSV\Reader(); - break; - case Type::XLSX: - $reader = new XLSX\Reader(); - break; - case Type::ODS: - $reader = new ODS\Reader(); - break; + case Type::CSV: return self::getCSVReader(); + case Type::XLSX: return self::getXLSXReader(); + case Type::ODS: return self::getODSReader(); default: throw new UnsupportedTypeException('No readers supporting the given type: ' . $readerType); } + } - $reader->setGlobalFunctionsHelper(new GlobalFunctionsHelper()); + /** + * @return CSV\Reader + */ + private static function getCSVReader() + { + $optionsManager = new CSV\Manager\OptionsManager(); + $helperFactory = new HelperFactory(); + $entityFactory = new CSV\Creator\EntityFactory($helperFactory); + $globalFunctionsHelper = $helperFactory->createGlobalFunctionsHelper(); - return $reader; + return new CSV\Reader($optionsManager, $globalFunctionsHelper, $entityFactory); + } + + /** + * @return XLSX\Reader + */ + private static function getXLSXReader() + { + $optionsManager = new XLSX\Manager\OptionsManager(); + $helperFactory = new XLSX\Creator\HelperFactory(); + $managerFactory = new XLSX\Creator\ManagerFactory($helperFactory, new CachingStrategyFactory()); + $entityFactory = new XLSX\Creator\EntityFactory($managerFactory, $helperFactory); + $globalFunctionsHelper = $helperFactory->createGlobalFunctionsHelper(); + + return new XLSX\Reader($optionsManager, $globalFunctionsHelper, $entityFactory, $managerFactory); + } + + /** + * @return ODS\Reader + */ + private static function getODSReader() + { + $optionsManager = new ODS\Manager\OptionsManager(); + $helperFactory = new ODS\Creator\HelperFactory(); + $entityFactory = new ODS\Creator\EntityFactory($helperFactory); + $globalFunctionsHelper = $helperFactory->createGlobalFunctionsHelper(); + + return new ODS\Reader($optionsManager, $globalFunctionsHelper, $entityFactory); } } diff --git a/src/Spout/Reader/ReaderInterface.php b/src/Spout/Reader/ReaderInterface.php index 8ecde30..74bcc4a 100644 --- a/src/Spout/Reader/ReaderInterface.php +++ b/src/Spout/Reader/ReaderInterface.php @@ -4,8 +4,6 @@ namespace Box\Spout\Reader; /** * Interface ReaderInterface - * - * @package Box\Spout\Reader */ interface ReaderInterface { @@ -14,16 +12,16 @@ interface ReaderInterface * that the file exists and is readable. * * @param string $filePath Path of the file to be read - * @return void * @throws \Box\Spout\Common\Exception\IOException + * @return void */ public function open($filePath); /** * Returns an iterator to iterate over sheets. * - * @return \Iterator To iterate over sheets * @throws \Box\Spout\Reader\Exception\ReaderNotOpenedException If called before opening the reader + * @return \Iterator To iterate over sheets */ public function getSheetIterator(); diff --git a/src/Spout/Reader/SheetInterface.php b/src/Spout/Reader/SheetInterface.php index bc19078..d0a115d 100644 --- a/src/Spout/Reader/SheetInterface.php +++ b/src/Spout/Reader/SheetInterface.php @@ -4,15 +4,13 @@ namespace Box\Spout\Reader; /** * Interface SheetInterface - * - * @package Box\Spout\Reader */ interface SheetInterface { /** * Returns an iterator to iterate over the sheet's rows. * - * @return \Iterator + * @return IteratorInterface */ public function getRowIterator(); } diff --git a/src/Spout/Reader/Wrapper/XMLInternalErrorsHelper.php b/src/Spout/Reader/Wrapper/XMLInternalErrorsHelper.php index 8b4464a..7047a94 100644 --- a/src/Spout/Reader/Wrapper/XMLInternalErrorsHelper.php +++ b/src/Spout/Reader/Wrapper/XMLInternalErrorsHelper.php @@ -6,8 +6,6 @@ use Box\Spout\Reader\Exception\XMLProcessingException; /** * Trait XMLInternalErrorsHelper - * - * @package Box\Spout\Reader\Wrapper */ trait XMLInternalErrorsHelper { @@ -30,8 +28,8 @@ trait XMLInternalErrorsHelper * Throws an XMLProcessingException if an error occured. * It also always resets the "libxml_use_internal_errors" setting back to its initial value. * - * @return void * @throws \Box\Spout\Reader\Exception\XMLProcessingException + * @return void */ protected function resetXMLInternalErrorsSettingAndThrowIfXMLErrorOccured() { @@ -57,7 +55,7 @@ trait XMLInternalErrorsHelper * Returns the error message for the last XML error that occured. * @see libxml_get_last_error * - * @return String|null Last XML error message or null if no error + * @return string|null Last XML error message or null if no error */ private function getLastXMLErrorMessage() { @@ -78,5 +76,4 @@ trait XMLInternalErrorsHelper { libxml_use_internal_errors($this->initialUseInternalErrorsValue); } - } diff --git a/src/Spout/Reader/Wrapper/XMLReader.php b/src/Spout/Reader/Wrapper/XMLReader.php index 2e20327..c50f5c0 100644 --- a/src/Spout/Reader/Wrapper/XMLReader.php +++ b/src/Spout/Reader/Wrapper/XMLReader.php @@ -1,15 +1,11 @@ isPositionedOnNode($nodeName, XMLReader::ELEMENT); + return $this->isPositionedOnNode($nodeName, self::ELEMENT); } /** @@ -146,7 +142,7 @@ class XMLReader extends \XMLReader */ public function isPositionedOnEndingNode($nodeName) { - return $this->isPositionedOnNode($nodeName, XMLReader::END_ELEMENT); + return $this->isPositionedOnNode($nodeName, self::END_ELEMENT); } /** diff --git a/src/Spout/Reader/XLSX/Creator/EntityFactory.php b/src/Spout/Reader/XLSX/Creator/EntityFactory.php new file mode 100644 index 0000000..18fe3ef --- /dev/null +++ b/src/Spout/Reader/XLSX/Creator/EntityFactory.php @@ -0,0 +1,126 @@ +managerFactory = $managerFactory; + $this->helperFactory = $helperFactory; + } + + /** + * @param string $filePath Path of the file to be read + * @param \Box\Spout\Common\Manager\OptionsManagerInterface $optionsManager Reader's options manager + * @param SharedStringsManager $sharedStringsManager Manages shared strings + * @return SheetIterator + */ + public function createSheetIterator($filePath, $optionsManager, $sharedStringsManager) + { + $sheetManager = $this->managerFactory->createSheetManager($filePath, $optionsManager, $sharedStringsManager, $this); + + return new SheetIterator($sheetManager); + } + + /** + * @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 int $sheetIndex Index of the sheet, based on order in the workbook (zero-based) + * @param string $sheetName Name of the sheet + * @param bool $isSheetActive Whether the sheet was defined as active + * @param \Box\Spout\Common\Manager\OptionsManagerInterface $optionsManager Reader's options manager + * @param SharedStringsManager $sharedStringsManager Manages shared strings + * @return Sheet + */ + public function createSheet( + $filePath, + $sheetDataXMLFilePath, + $sheetIndex, + $sheetName, + $isSheetActive, + $optionsManager, + $sharedStringsManager + ) { + $rowIterator = $this->createRowIterator($filePath, $sheetDataXMLFilePath, $optionsManager, $sharedStringsManager); + + return new Sheet($rowIterator, $sheetIndex, $sheetName, $isSheetActive); + } + + /** + * @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 \Box\Spout\Common\Manager\OptionsManagerInterface $optionsManager Reader's options manager + * @param SharedStringsManager $sharedStringsManager Manages shared strings + * @return RowIterator + */ + private function createRowIterator($filePath, $sheetDataXMLFilePath, $optionsManager, $sharedStringsManager) + { + $xmlReader = $this->createXMLReader(); + $xmlProcessor = $this->createXMLProcessor($xmlReader); + + $styleManager = $this->managerFactory->createStyleManager($filePath, $this); + $shouldFormatDates = $optionsManager->getOption(Options::SHOULD_FORMAT_DATES); + $cellValueFormatter = $this->helperFactory->createCellValueFormatter($sharedStringsManager, $styleManager, $shouldFormatDates); + + $shouldPreserveEmptyRows = $optionsManager->getOption(Options::SHOULD_PRESERVE_EMPTY_ROWS); + + return new RowIterator( + $filePath, + $sheetDataXMLFilePath, + $shouldPreserveEmptyRows, + $xmlReader, + $xmlProcessor, + $cellValueFormatter + ); + } + + /** + * @return \ZipArchive + */ + public function createZipArchive() + { + return new \ZipArchive(); + } + + /** + * @return XMLReader + */ + public function createXMLReader() + { + return new XMLReader(); + } + + /** + * @param $xmlReader + * @return XMLProcessor + */ + public function createXMLProcessor($xmlReader) + { + return new XMLProcessor($xmlReader); + } +} diff --git a/src/Spout/Reader/XLSX/Creator/HelperFactory.php b/src/Spout/Reader/XLSX/Creator/HelperFactory.php new file mode 100644 index 0000000..6546712 --- /dev/null +++ b/src/Spout/Reader/XLSX/Creator/HelperFactory.php @@ -0,0 +1,37 @@ +createStringsEscaper(); + + return new CellValueFormatter($sharedStringsManager, $styleManager, $shouldFormatDates, $escaper); + } + + /** + * @return Escaper\XLSX + */ + public function createStringsEscaper() + { + /* @noinspection PhpUnnecessaryFullyQualifiedNameInspection */ + return new Escaper\XLSX(); + } +} diff --git a/src/Spout/Reader/XLSX/Creator/ManagerFactory.php b/src/Spout/Reader/XLSX/Creator/ManagerFactory.php new file mode 100644 index 0000000..497b130 --- /dev/null +++ b/src/Spout/Reader/XLSX/Creator/ManagerFactory.php @@ -0,0 +1,66 @@ +helperFactory = $helperFactory; + $this->cachingStrategyFactory = $cachingStrategyFactory; + } + + /** + * @param string $filePath Path of the XLSX file being read + * @param string $tempFolder Temporary folder where the temporary files to store shared strings will be stored + * @param EntityFactory $entityFactory Factory to create entities + * @return SharedStringsManager + */ + public function createSharedStringsManager($filePath, $tempFolder, $entityFactory) + { + return new SharedStringsManager($filePath, $tempFolder, $entityFactory, $this->helperFactory, $this->cachingStrategyFactory); + } + + /** + * @param string $filePath Path of the XLSX file being read + * @param \Box\Spout\Common\Manager\OptionsManagerInterface $optionsManager Reader's options manager + * @param \Box\Spout\Reader\XLSX\Manager\SharedStringsManager $sharedStringsManager Manages shared strings + * @param EntityFactory $entityFactory Factory to create entities + * @return SheetManager + */ + public function createSheetManager($filePath, $optionsManager, $sharedStringsManager, $entityFactory) + { + $escaper = $this->helperFactory->createStringsEscaper(); + + return new SheetManager($filePath, $optionsManager, $sharedStringsManager, $escaper, $entityFactory); + } + + /** + * @param string $filePath Path of the XLSX file being read + * @param EntityFactory $entityFactory Factory to create entities + * @return StyleManager + */ + public function createStyleManager($filePath, $entityFactory) + { + return new StyleManager($filePath, $entityFactory); + } +} diff --git a/src/Spout/Reader/XLSX/Helper/CellHelper.php b/src/Spout/Reader/XLSX/Helper/CellHelper.php index 6077839..9346f16 100644 --- a/src/Spout/Reader/XLSX/Helper/CellHelper.php +++ b/src/Spout/Reader/XLSX/Helper/CellHelper.php @@ -7,8 +7,6 @@ use Box\Spout\Common\Exception\InvalidArgumentException; /** * Class CellHelper * This class provides helper functions when working with cells - * - * @package Box\Spout\Reader\XLSX\Helper */ class CellHelper { @@ -26,7 +24,7 @@ class CellHelper * Calling fillMissingArrayIndexes($dataArray, 'FILL') will return this array: ['FILL', 1, 'FILL', 3] * * @param array $dataArray The array to fill - * @param string|void $fillValue optional + * @param string $fillValue optional * @return array */ public static function fillMissingArrayIndexes($dataArray, $fillValue = '') @@ -51,8 +49,8 @@ class CellHelper * The mapping is zero based, so that A1 maps to 0, B2 maps to 1, Z13 to 25 and AA4 to 26. * * @param string $cellIndex The Excel cell index ('A1', 'BC13', ...) - * @return int * @throws \Box\Spout\Common\Exception\InvalidArgumentException When the given cell index is invalid + * @return int */ public static function getColumnIndexFromCellIndex($cellIndex) { diff --git a/src/Spout/Reader/XLSX/Helper/CellValueFormatter.php b/src/Spout/Reader/XLSX/Helper/CellValueFormatter.php index b4c6256..aaebfa6 100644 --- a/src/Spout/Reader/XLSX/Helper/CellValueFormatter.php +++ b/src/Spout/Reader/XLSX/Helper/CellValueFormatter.php @@ -2,11 +2,12 @@ namespace Box\Spout\Reader\XLSX\Helper; +use Box\Spout\Reader\XLSX\Manager\SharedStringsManager; +use Box\Spout\Reader\XLSX\Manager\StyleManager; + /** * Class CellValueFormatter * This class provides helper functions to format cell values - * - * @package Box\Spout\Reader\XLSX\Helper */ class CellValueFormatter { @@ -38,31 +39,30 @@ class CellValueFormatter */ const ERRONEOUS_EXCEL_LEAP_YEAR_DAY = 60; - /** @var SharedStringsHelper Helper to work with shared strings */ - protected $sharedStringsHelper; + /** @var SharedStringsManager Manages shared strings */ + protected $sharedStringsManager; - /** @var StyleHelper Helper to work with styles */ - protected $styleHelper; + /** @var StyleManager Manages styles */ + protected $styleManager; /** @var bool Whether date/time values should be returned as PHP objects or be formatted as strings */ protected $shouldFormatDates; - /** @var \Box\Spout\Common\Escaper\XLSX Used to unescape XML data */ + /** @var \Box\Spout\Common\Helper\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 + * @param SharedStringsManager $sharedStringsManager Manages shared strings + * @param StyleManager $styleManager Manages styles * @param bool $shouldFormatDates Whether date/time values should be returned as PHP objects or be formatted as strings + * @param \Box\Spout\Common\Helper\Escaper\XLSX $escaper Used to unescape XML data */ - public function __construct($sharedStringsHelper, $styleHelper, $shouldFormatDates) + public function __construct($sharedStringsManager, $styleManager, $shouldFormatDates, $escaper) { - $this->sharedStringsHelper = $sharedStringsHelper; - $this->styleHelper = $styleHelper; + $this->sharedStringsManager = $sharedStringsManager; + $this->styleManager = $styleManager; $this->shouldFormatDates = $shouldFormatDates; - - /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */ - $this->escaper = \Box\Spout\Common\Escaper\XLSX::getInstance(); + $this->escaper = $escaper; } /** @@ -75,7 +75,7 @@ class CellValueFormatter { // 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)); + $cellStyleId = (int) $node->getAttribute(self::XML_ATTRIBUTE_STYLE_ID); $vNodeValue = $this->getVNodeValue($node); if (($vNodeValue === '') && ($cellType !== self::CELL_TYPE_INLINE_STRING)) { @@ -111,6 +111,7 @@ class CellValueFormatter // 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 : ''; } @@ -126,6 +127,7 @@ class CellValueFormatter // [INLINE_STRING] $tNode = $node->getElementsByTagName(self::XML_NODE_INLINE_STRING_VALUE)->item(0); $cellValue = $this->escaper->unescape($tNode->nodeValue); + return $cellValue; } @@ -139,9 +141,10 @@ class CellValueFormatter { // shared strings are formatted this way: // [SHARED_STRING_INDEX] - $sharedStringIndex = intval($nodeValue); - $escapedCellValue = $this->sharedStringsHelper->getStringAtIndex($sharedStringIndex); + $sharedStringIndex = (int) $nodeValue; + $escapedCellValue = $this->sharedStringsManager->getStringAtIndex($sharedStringIndex); $cellValue = $this->escaper->unescape($escapedCellValue); + return $cellValue; } @@ -155,6 +158,7 @@ class CellValueFormatter { $escapedCellValue = trim($nodeValue); $cellValue = $this->escaper->unescape($escapedCellValue); + return $cellValue; } @@ -170,14 +174,17 @@ class CellValueFormatter { // 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); + $shouldFormatAsDate = $this->styleManager->shouldFormatNumericValueAsDate($cellStyleId); if ($shouldFormatAsDate) { - return $this->formatExcelTimestampValue(floatval($nodeValue), $cellStyleId); + $cellValue = $this->formatExcelTimestampValue((float) $nodeValue, $cellStyleId); } else { - $nodeIntValue = intval($nodeValue); - return ($nodeIntValue == $nodeValue) ? $nodeIntValue : floatval($nodeValue); + $nodeIntValue = (int) $nodeValue; + $nodeFloatValue = (float) $nodeValue; + $cellValue = ((float) $nodeIntValue === $nodeFloatValue) ? $nodeIntValue : $nodeFloatValue; } + + return $cellValue; } /** @@ -198,14 +205,16 @@ class CellValueFormatter if ($nodeValue >= 1) { // Values greater than 1 represent "dates". The value 1.0 representing the "base" date: 1900-01-01. - return $this->formatExcelTimestampValueAsDateValue($nodeValue, $cellStyleId); - } else if ($nodeValue >= 0) { + $cellValue = $this->formatExcelTimestampValueAsDateValue($nodeValue, $cellStyleId); + } elseif ($nodeValue >= 0) { // Values between 0 and 1 represent "times". - return $this->formatExcelTimestampValueAsTimeValue($nodeValue, $cellStyleId); + $cellValue = $this->formatExcelTimestampValueAsTimeValue($nodeValue, $cellStyleId); } else { // invalid date - return null; + $cellValue = null; } + + return $cellValue; } /** @@ -228,12 +237,14 @@ class CellValueFormatter $dateObj->setTime($hours, $minutes, $seconds); if ($this->shouldFormatDates) { - $styleNumberFormatCode = $this->styleHelper->getNumberFormatCode($cellStyleId); + $styleNumberFormatCode = $this->styleManager->getNumberFormatCode($cellStyleId); $phpDateFormat = DateFormatHelper::toPHPDateFormat($styleNumberFormatCode); - return $dateObj->format($phpDateFormat); + $cellValue = $dateObj->format($phpDateFormat); } else { - return $dateObj; + $cellValue = $dateObj; } + + return $cellValue; } /** @@ -253,19 +264,21 @@ class CellValueFormatter try { $dateObj = \DateTime::createFromFormat('|Y-m-d', '1899-12-31'); - $dateObj->modify('+' . intval($nodeValue) . 'days'); + $dateObj->modify('+' . (int) $nodeValue . 'days'); $dateObj->modify('+' . $secondsRemainder . 'seconds'); if ($this->shouldFormatDates) { - $styleNumberFormatCode = $this->styleHelper->getNumberFormatCode($cellStyleId); + $styleNumberFormatCode = $this->styleManager->getNumberFormatCode($cellStyleId); $phpDateFormat = DateFormatHelper::toPHPDateFormat($styleNumberFormatCode); - return $dateObj->format($phpDateFormat); + $cellValue = $dateObj->format($phpDateFormat); } else { - return $dateObj; + $cellValue = $dateObj; } } catch (\Exception $e) { - return null; + $cellValue = null; } + + return $cellValue; } /** @@ -276,9 +289,7 @@ class CellValueFormatter */ protected function formatBooleanCellValue($nodeValue) { - // !! is similar to boolval() - $cellValue = !!$nodeValue; - return $cellValue; + return (bool) $nodeValue; } /** @@ -292,9 +303,11 @@ class CellValueFormatter { // Mitigate thrown Exception on invalid date-time format (http://php.net/manual/en/datetime.construct.php) try { - return ($this->shouldFormatDates) ? $nodeValue : new \DateTime($nodeValue); + $cellValue = ($this->shouldFormatDates) ? $nodeValue : new \DateTime($nodeValue); } catch (\Exception $e) { - return null; + $cellValue = null; } + + return $cellValue; } } diff --git a/src/Spout/Reader/XLSX/Helper/DateFormatHelper.php b/src/Spout/Reader/XLSX/Helper/DateFormatHelper.php index 9dba4c6..1618af7 100644 --- a/src/Spout/Reader/XLSX/Helper/DateFormatHelper.php +++ b/src/Spout/Reader/XLSX/Helper/DateFormatHelper.php @@ -5,8 +5,6 @@ namespace Box\Spout\Reader\XLSX\Helper; /** * Class DateFormatHelper * This class provides helper functions to format Excel dates - * - * @package Box\Spout\Reader\XLSX\Helper */ class DateFormatHelper { @@ -104,9 +102,10 @@ class DateFormatHelper // Finally, to have the date format compatible with the DateTime::format() function, we need to escape // all characters that are inside double quotes (and double quotes must be removed). // For instance, ["Day " dd] should become [\D\a\y\ dd] - $phpDateFormat = preg_replace_callback('/"(.+?)"/', function($matches) { + $phpDateFormat = preg_replace_callback('/"(.+?)"/', function ($matches) { $stringToEscape = $matches[1]; $letters = preg_split('//u', $stringToEscape, -1, PREG_SPLIT_NO_EMPTY); + return '\\' . implode('\\', $letters); }, $phpDateFormat); diff --git a/src/Spout/Reader/XLSX/Manager/OptionsManager.php b/src/Spout/Reader/XLSX/Manager/OptionsManager.php new file mode 100644 index 0000000..7677c22 --- /dev/null +++ b/src/Spout/Reader/XLSX/Manager/OptionsManager.php @@ -0,0 +1,35 @@ +setOption(Options::TEMP_FOLDER, sys_get_temp_dir()); + $this->setOption(Options::SHOULD_FORMAT_DATES, false); + $this->setOption(Options::SHOULD_PRESERVE_EMPTY_ROWS, false); + } +} diff --git a/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyFactory.php b/src/Spout/Reader/XLSX/Manager/SharedStringsCaching/CachingStrategyFactory.php similarity index 81% rename from src/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyFactory.php rename to src/Spout/Reader/XLSX/Manager/SharedStringsCaching/CachingStrategyFactory.php index 36e0bfe..4aaba3a 100644 --- a/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyFactory.php +++ b/src/Spout/Reader/XLSX/Manager/SharedStringsCaching/CachingStrategyFactory.php @@ -1,11 +1,11 @@ isInMemoryStrategyUsageSafe($sharedStringsUniqueCount)) { return new InMemoryStrategy($sharedStringsUniqueCount); } else { - return new FileBasedStrategy($tempFolder, self::MAX_NUM_STRINGS_PER_TEMP_FILE); + return new FileBasedStrategy($tempFolder, self::MAX_NUM_STRINGS_PER_TEMP_FILE, $helperFactory); } } @@ -109,11 +86,13 @@ class CachingStrategyFactory if ($memoryAvailable === -1) { // if cannot get memory limit or if memory limit set as unlimited, don't trust and play safe - return ($sharedStringsUniqueCount < self::MAX_NUM_STRINGS_PER_TEMP_FILE); + $isInMemoryStrategyUsageSafe = ($sharedStringsUniqueCount < self::MAX_NUM_STRINGS_PER_TEMP_FILE); } else { $memoryNeeded = $sharedStringsUniqueCount * self::AMOUNT_MEMORY_NEEDED_PER_STRING_IN_KB; - return ($memoryAvailable > $memoryNeeded); + $isInMemoryStrategyUsageSafe = ($memoryAvailable > $memoryNeeded); } + + return $isInMemoryStrategyUsageSafe; } /** @@ -132,7 +111,7 @@ class CachingStrategyFactory } if (preg_match('/(\d+)([bkmgt])b?/', $memoryLimitFormatted, $matches)) { - $amount = intval($matches[1]); + $amount = (int) ($matches[1]); $unit = $matches[2]; switch ($unit) { diff --git a/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyInterface.php b/src/Spout/Reader/XLSX/Manager/SharedStringsCaching/CachingStrategyInterface.php similarity index 90% rename from src/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyInterface.php rename to src/Spout/Reader/XLSX/Manager/SharedStringsCaching/CachingStrategyInterface.php index 631222a..479b0b5 100644 --- a/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyInterface.php +++ b/src/Spout/Reader/XLSX/Manager/SharedStringsCaching/CachingStrategyInterface.php @@ -1,11 +1,9 @@ fileSystemHelper = new FileSystemHelper($rootTempFolder); - $this->tempFolder = $this->fileSystemHelper->createFolder($rootTempFolder, uniqid('sharedstrings')); + $this->fileSystemHelper = $helperFactory->createFileSystemHelper($tempFolder); + $this->tempFolder = $this->fileSystemHelper->createFolder($tempFolder, uniqid('sharedstrings')); $this->maxNumStringsPerTempFile = $maxNumStringsPerTempFile; - $this->globalFunctionsHelper = new GlobalFunctionsHelper(); + $this->globalFunctionsHelper = $helperFactory->createGlobalFunctionsHelper(); $this->tempFilePointer = null; } @@ -99,7 +96,8 @@ class FileBasedStrategy implements CachingStrategyInterface */ protected function getSharedStringTempFilePath($sharedStringIndex) { - $numTempFile = intval($sharedStringIndex / $this->maxNumStringsPerTempFile); + $numTempFile = (int) ($sharedStringIndex / $this->maxNumStringsPerTempFile); + return $this->tempFolder . '/sharedstrings' . $numTempFile; } @@ -117,13 +115,12 @@ class FileBasedStrategy implements CachingStrategyInterface } } - /** * Returns the string located at the given index from the cache. * * @param int $sharedStringIndex Index of the shared string in the sharedStrings.xml file - * @return string The shared string at the given index * @throws \Box\Spout\Reader\Exception\SharedStringNotFoundException If no shared string found for the given index + * @return string The shared string at the given index */ public function getStringAtIndex($sharedStringIndex) { diff --git a/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/InMemoryStrategy.php b/src/Spout/Reader/XLSX/Manager/SharedStringsCaching/InMemoryStrategy.php similarity index 95% rename from src/Spout/Reader/XLSX/Helper/SharedStringsCaching/InMemoryStrategy.php rename to src/Spout/Reader/XLSX/Manager/SharedStringsCaching/InMemoryStrategy.php index c6a5321..a16d4de 100644 --- a/src/Spout/Reader/XLSX/Helper/SharedStringsCaching/InMemoryStrategy.php +++ b/src/Spout/Reader/XLSX/Manager/SharedStringsCaching/InMemoryStrategy.php @@ -1,6 +1,6 @@ filePath = $filePath; $this->tempFolder = $tempFolder; + $this->entityFactory = $entityFactory; + $this->helperFactory = $helperFactory; + $this->cachingStrategyFactory = $cachingStrategyFactory; } /** @@ -61,7 +76,7 @@ class SharedStringsHelper public function hasSharedStrings() { $hasSharedStrings = false; - $zip = new \ZipArchive(); + $zip = $this->entityFactory->createZipArchive(); if ($zip->open($this->filePath) === true) { $hasSharedStrings = ($zip->locateName(self::SHARED_STRINGS_XML_FILE_PATH) !== false); @@ -81,12 +96,12 @@ class SharedStringsHelper * The XML file can be really big with sheets containing a lot of data. That is why * we need to use a XML reader that provides streaming like the XMLReader library. * - * @return void * @throws \Box\Spout\Common\Exception\IOException If sharedStrings.xml can't be read + * @return void */ public function extractSharedStrings() { - $xmlReader = new XMLReader(); + $xmlReader = $this->entityFactory->createXMLReader(); $sharedStringIndex = 0; if ($xmlReader->openFileInZip($this->filePath, self::SHARED_STRINGS_XML_FILE_PATH) === false) { @@ -108,7 +123,6 @@ class SharedStringsHelper } $this->cachingStrategy->closeCache(); - } catch (XMLProcessingException $exception) { throw new IOException("The sharedStrings.xml file is invalid and cannot be read. [{$exception->getMessage()}]"); } @@ -120,8 +134,8 @@ class SharedStringsHelper * Returns the shared strings unique count, as specified in tag. * * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XMLReader instance - * @return int|null Number of unique shared strings in the sharedStrings.xml file * @throws \Box\Spout\Common\Exception\IOException If sharedStrings.xml is invalid and can't be read + * @return int|null Number of unique shared strings in the sharedStrings.xml file */ protected function getSharedStringsUniqueCount($xmlReader) { @@ -140,7 +154,7 @@ class SharedStringsHelper $uniqueCount = $xmlReader->getAttribute(self::XML_ATTRIBUTE_COUNT); } - return ($uniqueCount !== null) ? intval($uniqueCount) : null; + return ($uniqueCount !== null) ? (int) $uniqueCount : null; } /** @@ -151,8 +165,8 @@ class SharedStringsHelper */ protected function getBestSharedStringsCachingStrategy($sharedStringsUniqueCount) { - return CachingStrategyFactory::getInstance() - ->getBestCachingStrategy($sharedStringsUniqueCount, $this->tempFolder); + return $this->cachingStrategyFactory + ->createBestCachingStrategy($sharedStringsUniqueCount, $this->tempFolder, $this->helperFactory); } /** @@ -193,6 +207,7 @@ class SharedStringsHelper protected function shouldExtractTextNodeValue($textNode) { $parentTagName = $textNode->parentNode->localName; + return ($parentTagName === self::XML_NODE_SI || $parentTagName === self::XML_NODE_R); } @@ -205,6 +220,7 @@ class SharedStringsHelper protected function shouldPreserveWhitespace($textNode) { $spaceValue = $textNode->getAttribute(self::XML_ATTRIBUTE_XML_SPACE); + return ($spaceValue === self::XML_ATTRIBUTE_VALUE_PRESERVE); } @@ -212,8 +228,8 @@ class SharedStringsHelper * Returns the shared string at the given index, using the previously chosen caching strategy. * * @param int $sharedStringIndex Index of the shared string in the sharedStrings.xml file - * @return string The shared string at the given index * @throws \Box\Spout\Reader\Exception\SharedStringNotFoundException If no shared string found for the given index + * @return string The shared string at the given index */ public function getStringAtIndex($sharedStringIndex) { diff --git a/src/Spout/Reader/XLSX/Helper/SheetHelper.php b/src/Spout/Reader/XLSX/Manager/SheetManager.php similarity index 71% rename from src/Spout/Reader/XLSX/Helper/SheetHelper.php rename to src/Spout/Reader/XLSX/Manager/SheetManager.php index b74ba01..a848948 100644 --- a/src/Spout/Reader/XLSX/Helper/SheetHelper.php +++ b/src/Spout/Reader/XLSX/Manager/SheetManager.php @@ -1,17 +1,15 @@ filePath = $filePath; - $this->options = $options; - $this->sharedStringsHelper = $sharedStringsHelper; - $this->globalFunctionsHelper = $globalFunctionsHelper; + $this->optionsManager = $optionsManager; + $this->sharedStringsManager = $sharedStringsManager; + $this->escaper = $escaper; + $this->entityFactory = $entityFactory; } /** @@ -68,18 +75,19 @@ class SheetHelper $sheetIndex = 0; $activeSheetIndex = 0; // By default, the first sheet is active - $xmlReader = new XMLReader(); + $xmlReader = $this->entityFactory->createXMLReader(); + if ($xmlReader->openFileInZip($this->filePath, self::WORKBOOK_XML_FILE_PATH)) { while ($xmlReader->read()) { if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_WORKBOOK_VIEW)) { // The "workbookView" node is located before "sheet" nodes, ensuring that // the active sheet is known before parsing sheets data. $activeSheetIndex = (int) $xmlReader->getAttribute(self::XML_ATTRIBUTE_ACTIVE_TAB); - } else if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_SHEET)) { + } elseif ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_SHEET)) { $isSheetActive = ($sheetIndex === $activeSheetIndex); $sheets[] = $this->getSheetFromSheetXMLNode($xmlReader, $sheetIndex, $isSheetActive); $sheetIndex++; - } else if ($xmlReader->isPositionedOnEndingNode(self::XML_NODE_SHEETS)) { + } elseif ($xmlReader->isPositionedOnEndingNode(self::XML_NODE_SHEETS)) { // stop reading once all sheets have been read break; } @@ -105,17 +113,18 @@ class SheetHelper { $sheetId = $xmlReaderOnSheetNode->getAttribute(self::XML_ATTRIBUTE_R_ID); $escapedSheetName = $xmlReaderOnSheetNode->getAttribute(self::XML_ATTRIBUTE_NAME); - - /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */ - $escaper = \Box\Spout\Common\Escaper\XLSX::getInstance(); - $sheetName = $escaper->unescape($escapedSheetName); + $sheetName = $this->escaper->unescape($escapedSheetName); $sheetDataXMLFilePath = $this->getSheetDataXMLFilePathForSheetId($sheetId); - return new Sheet( - $this->filePath, $sheetDataXMLFilePath, - $sheetIndexZeroBased, $sheetName, $isSheetActive, - $this->options, $this->sharedStringsHelper + return $this->entityFactory->createSheet( + $this->filePath, + $sheetDataXMLFilePath, + $sheetIndexZeroBased, + $sheetName, + $isSheetActive, + $this->optionsManager, + $this->sharedStringsManager ); } @@ -128,7 +137,7 @@ class SheetHelper $sheetDataXMLFilePath = ''; // find the file path of the sheet, by looking at the "workbook.xml.res" file - $xmlReader = new XMLReader(); + $xmlReader = $this->entityFactory->createXMLReader(); if ($xmlReader->openFileInZip($this->filePath, self::WORKBOOK_XML_RELS_FILE_PATH)) { while ($xmlReader->read()) { if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_RELATIONSHIP)) { diff --git a/src/Spout/Reader/XLSX/Helper/StyleHelper.php b/src/Spout/Reader/XLSX/Manager/StyleManager.php similarity index 91% rename from src/Spout/Reader/XLSX/Helper/StyleHelper.php rename to src/Spout/Reader/XLSX/Manager/StyleManager.php index 000adab..b36661b 100644 --- a/src/Spout/Reader/XLSX/Helper/StyleHelper.php +++ b/src/Spout/Reader/XLSX/Manager/StyleManager.php @@ -1,16 +1,14 @@ filePath = $filePath; + $this->entityFactory = $entityFactory; $this->builtinNumFmtIdIndicatingDates = array_keys(self::$builtinNumFmtIdToNumFormatMapping); } @@ -107,14 +110,13 @@ class StyleHelper $this->customNumberFormats = []; $this->stylesAttributes = []; - $xmlReader = new XMLReader(); + $xmlReader = $this->entityFactory->createXMLReader(); if ($xmlReader->openFileInZip($this->filePath, self::STYLES_XML_FILE_PATH)) { while ($xmlReader->read()) { if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_NUM_FMTS)) { $this->extractNumberFormats($xmlReader); - - } else if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_CELL_XFS)) { + } elseif ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_CELL_XFS)) { $this->extractStyleAttributes($xmlReader); } } @@ -135,10 +137,10 @@ class StyleHelper { while ($xmlReader->read()) { if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_NUM_FMT)) { - $numFmtId = intval($xmlReader->getAttribute(self::XML_ATTRIBUTE_NUM_FMT_ID)); + $numFmtId = (int) ($xmlReader->getAttribute(self::XML_ATTRIBUTE_NUM_FMT_ID)); $formatCode = $xmlReader->getAttribute(self::XML_ATTRIBUTE_FORMAT_CODE); $this->customNumberFormats[$numFmtId] = $formatCode; - } else if ($xmlReader->isPositionedOnEndingNode(self::XML_NODE_NUM_FMTS)) { + } elseif ($xmlReader->isPositionedOnEndingNode(self::XML_NODE_NUM_FMTS)) { // Once done reading "numFmts" node's children break; } @@ -158,16 +160,16 @@ class StyleHelper while ($xmlReader->read()) { if ($xmlReader->isPositionedOnStartingNode(self::XML_NODE_XF)) { $numFmtId = $xmlReader->getAttribute(self::XML_ATTRIBUTE_NUM_FMT_ID); - $normalizedNumFmtId = ($numFmtId !== null) ? intval($numFmtId) : null; + $normalizedNumFmtId = ($numFmtId !== null) ? (int) $numFmtId : null; $applyNumberFormat = $xmlReader->getAttribute(self::XML_ATTRIBUTE_APPLY_NUMBER_FORMAT); - $normalizedApplyNumberFormat = ($applyNumberFormat !== null) ? !!$applyNumberFormat : null; + $normalizedApplyNumberFormat = ($applyNumberFormat !== null) ? (bool) $applyNumberFormat : null; $this->stylesAttributes[] = [ - self::XML_ATTRIBUTE_NUM_FMT_ID => $normalizedNumFmtId, + self::XML_ATTRIBUTE_NUM_FMT_ID => $normalizedNumFmtId, self::XML_ATTRIBUTE_APPLY_NUMBER_FORMAT => $normalizedApplyNumberFormat, ]; - } else if ($xmlReader->isPositionedOnEndingNode(self::XML_NODE_CELL_XFS)) { + } elseif ($xmlReader->isPositionedOnEndingNode(self::XML_NODE_CELL_XFS)) { // Once done reading "cellXfs" node's children break; } diff --git a/src/Spout/Reader/XLSX/Reader.php b/src/Spout/Reader/XLSX/Reader.php index 76e8e32..eb44cce 100644 --- a/src/Spout/Reader/XLSX/Reader.php +++ b/src/Spout/Reader/XLSX/Reader.php @@ -3,38 +3,46 @@ namespace Box\Spout\Reader\XLSX; use Box\Spout\Common\Exception\IOException; -use Box\Spout\Reader\AbstractReader; -use Box\Spout\Reader\XLSX\Helper\SharedStringsHelper; +use Box\Spout\Common\Helper\GlobalFunctionsHelper; +use Box\Spout\Common\Manager\OptionsManagerInterface; +use Box\Spout\Reader\Common\Creator\EntityFactoryInterface; +use Box\Spout\Reader\Common\Entity\Options; +use Box\Spout\Reader\ReaderAbstract; +use Box\Spout\Reader\XLSX\Creator\EntityFactory; +use Box\Spout\Reader\XLSX\Creator\ManagerFactory; /** * Class Reader * This class provides support to read data from a XLSX file - * - * @package Box\Spout\Reader\XLSX */ -class Reader extends AbstractReader +class Reader extends ReaderAbstract { + /** @var ManagerFactory */ + protected $managerFactory; + /** @var \ZipArchive */ protected $zip; - /** @var \Box\Spout\Reader\XLSX\Helper\SharedStringsHelper Helper to work with shared strings */ - protected $sharedStringsHelper; + /** @var \Box\Spout\Reader\XLSX\Manager\SharedStringsManager Manages shared strings */ + protected $sharedStringsManager; /** @var SheetIterator To iterator over the XLSX sheets */ protected $sheetIterator; - /** - * Returns the reader's current options - * - * @return ReaderOptions + * @param OptionsManagerInterface $optionsManager + * @param GlobalFunctionsHelper $globalFunctionsHelper + * @param EntityFactoryInterface $entityFactory + * @param ManagerFactory $managerFactory */ - protected function getOptions() - { - if (!isset($this->options)) { - $this->options = new ReaderOptions(); - } - return $this->options; + public function __construct( + OptionsManagerInterface $optionsManager, + GlobalFunctionsHelper $globalFunctionsHelper, + EntityFactoryInterface $entityFactory, + ManagerFactory $managerFactory + ) { + parent::__construct($optionsManager, $globalFunctionsHelper, $entityFactory); + $this->managerFactory = $managerFactory; } /** @@ -43,7 +51,8 @@ class Reader extends AbstractReader */ public function setTempFolder($tempFolder) { - $this->getOptions()->setTempFolder($tempFolder); + $this->optionsManager->setOption(Options::TEMP_FOLDER, $tempFolder); + return $this; } @@ -63,23 +72,27 @@ class Reader extends AbstractReader * and fetches all the available sheets. * * @param string $filePath Path of the file to be read - * @return void * @throws \Box\Spout\Common\Exception\IOException If the file at the given path or its content cannot be read * @throws \Box\Spout\Reader\Exception\NoSheetsFoundException If there are no sheets in the file + * @return void */ protected function openReader($filePath) { - $this->zip = new \ZipArchive(); + /** @var EntityFactory $entityFactory */ + $entityFactory = $this->entityFactory; + + $this->zip = $entityFactory->createZipArchive(); if ($this->zip->open($filePath) === true) { - $this->sharedStringsHelper = new SharedStringsHelper($filePath, $this->getOptions()->getTempFolder()); + $tempFolder = $this->optionsManager->getOption(Options::TEMP_FOLDER); + $this->sharedStringsManager = $this->managerFactory->createSharedStringsManager($filePath, $tempFolder, $entityFactory); - if ($this->sharedStringsHelper->hasSharedStrings()) { + if ($this->sharedStringsManager->hasSharedStrings()) { // Extracts all the strings from the sheets for easy access in the future - $this->sharedStringsHelper->extractSharedStrings(); + $this->sharedStringsManager->extractSharedStrings(); } - $this->sheetIterator = new SheetIterator($filePath, $this->getOptions(), $this->sharedStringsHelper, $this->globalFunctionsHelper); + $this->sheetIterator = $entityFactory->createSheetIterator($filePath, $this->optionsManager, $this->sharedStringsManager, $this->globalFunctionsHelper); } else { throw new IOException("Could not open $filePath for reading."); } @@ -106,8 +119,8 @@ class Reader extends AbstractReader $this->zip->close(); } - if ($this->sharedStringsHelper) { - $this->sharedStringsHelper->cleanup(); + if ($this->sharedStringsManager) { + $this->sharedStringsManager->cleanup(); } } } diff --git a/src/Spout/Reader/XLSX/ReaderOptions.php b/src/Spout/Reader/XLSX/ReaderOptions.php deleted file mode 100644 index 5f78c5d..0000000 --- a/src/Spout/Reader/XLSX/ReaderOptions.php +++ /dev/null @@ -1,33 +0,0 @@ -tempFolder; - } - - /** - * @param string|null $tempFolder Temporary folder where the temporary files will be created - * @return ReaderOptions - */ - public function setTempFolder($tempFolder) - { - $this->tempFolder = $tempFolder; - return $this; - } -} diff --git a/src/Spout/Reader/XLSX/RowIterator.php b/src/Spout/Reader/XLSX/RowIterator.php index 45069b3..aa406d8 100644 --- a/src/Spout/Reader/XLSX/RowIterator.php +++ b/src/Spout/Reader/XLSX/RowIterator.php @@ -3,18 +3,15 @@ namespace Box\Spout\Reader\XLSX; use Box\Spout\Common\Exception\IOException; +use Box\Spout\Reader\Common\XMLProcessor; 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; -use Box\Spout\Reader\Common\XMLProcessor; /** * Class RowIterator - * - * @package Box\Spout\Reader\XLSX */ class RowIterator implements IteratorInterface { @@ -45,9 +42,6 @@ class RowIterator implements IteratorInterface /** @var Helper\CellValueFormatter Helper to format cell values */ protected $cellValueFormatter; - /** @var Helper\StyleHelper $styleHelper Helper to work with styles */ - protected $styleHelper; - /** * TODO: This variable can be deleted when row indices get preserved * @var int Number of read rows @@ -58,7 +52,7 @@ class RowIterator implements IteratorInterface protected $currentlyProcessedRowData = []; /** @var array|null Buffer used to store the row data, while checking if there are more rows to read */ - protected $rowDataBuffer = null; + protected $rowDataBuffer; /** @var bool Indicates whether all rows have been read */ protected $hasReachedEndOfFile = false; @@ -81,23 +75,21 @@ class RowIterator implements IteratorInterface /** * @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 \Box\Spout\Reader\XLSX\ReaderOptions $options Reader's current options - * @param Helper\SharedStringsHelper $sharedStringsHelper Helper to work with shared strings + * @param bool $shouldPreserveEmptyRows Whether empty rows should be preserved + * @param XMLReader $xmlReader XML Reader + * @param XMLProcessor $xmlProcessor Helper to process XML files + * @param CellValueFormatter $cellValueFormatter Helper to format cell values */ - public function __construct($filePath, $sheetDataXMLFilePath, $options, $sharedStringsHelper) + public function __construct($filePath, $sheetDataXMLFilePath, $shouldPreserveEmptyRows, $xmlReader, $xmlProcessor, $cellValueFormatter) { $this->filePath = $filePath; $this->sheetDataXMLFilePath = $this->normalizeSheetDataXMLFilePath($sheetDataXMLFilePath); - - $this->xmlReader = new XMLReader(); - - $this->styleHelper = new StyleHelper($filePath); - $this->cellValueFormatter = new CellValueFormatter($sharedStringsHelper, $this->styleHelper, $options->shouldFormatDates()); - - $this->shouldPreserveEmptyRows = $options->shouldPreserveEmptyRows(); + $this->xmlReader = $xmlReader; + $this->cellValueFormatter = $cellValueFormatter; + $this->shouldPreserveEmptyRows = $shouldPreserveEmptyRows; // Register all callbacks to process different nodes when reading the XML file - $this->xmlProcessor = new XMLProcessor($this->xmlReader); + $this->xmlProcessor = $xmlProcessor; $this->xmlProcessor->registerCallback(self::XML_NODE_DIMENSION, XMLProcessor::NODE_TYPE_START, [$this, 'processDimensionStartingNode']); $this->xmlProcessor->registerCallback(self::XML_NODE_ROW, XMLProcessor::NODE_TYPE_START, [$this, 'processRowStartingNode']); $this->xmlProcessor->registerCallback(self::XML_NODE_CELL, XMLProcessor::NODE_TYPE_START, [$this, 'processCellStartingNode']); @@ -119,10 +111,10 @@ class RowIterator implements IteratorInterface * Rewind the Iterator to the first element. * Initializes the XMLReader object that reads the associated sheet data. * The XMLReader is configured to be safe from billion laughs attack. - * @link http://php.net/manual/en/iterator.rewind.php + * @see http://php.net/manual/en/iterator.rewind.php * - * @return void * @throws \Box\Spout\Common\Exception\IOException If the sheet data XML cannot be read + * @return void */ public function rewind() { @@ -144,7 +136,7 @@ class RowIterator implements IteratorInterface /** * Checks if current position is valid - * @link http://php.net/manual/en/iterator.valid.php + * @see http://php.net/manual/en/iterator.valid.php * * @return bool */ @@ -155,11 +147,11 @@ class RowIterator implements IteratorInterface /** * Move forward to next element. Reads data describing the next unprocessed row. - * @link http://php.net/manual/en/iterator.next.php + * @see 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 + * @return void */ public function next() { @@ -194,9 +186,9 @@ class RowIterator implements IteratorInterface } /** - * @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 + * @return void */ protected function readDataForNextRow() { @@ -243,7 +235,7 @@ class RowIterator implements IteratorInterface $spans = $xmlReader->getAttribute(self::XML_ATTRIBUTE_SPANS); // returns '1:5' for instance if ($spans) { list(, $numberOfColumnsForRow) = explode(':', $spans); - $numberOfColumnsForRow = intval($numberOfColumnsForRow); + $numberOfColumnsForRow = (int) $numberOfColumnsForRow; } $this->currentlyProcessedRowData = ($numberOfColumnsForRow !== 0) ? array_fill(0, $numberOfColumnsForRow, '') : []; @@ -303,8 +295,8 @@ class RowIterator implements IteratorInterface /** * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XMLReader object, positioned on a "" node - * @return int Row index * @throws \Box\Spout\Common\Exception\InvalidArgumentException When the given cell index is invalid + * @return int Row index */ protected function getRowIndex($xmlReader) { @@ -312,14 +304,14 @@ class RowIterator implements IteratorInterface $currentRowIndex = $xmlReader->getAttribute(self::XML_ATTRIBUTE_ROW_INDEX); return ($currentRowIndex !== null) ? - intval($currentRowIndex) : + (int) $currentRowIndex : $this->lastRowIndexProcessed + 1; } /** * @param \Box\Spout\Reader\Wrapper\XMLReader $xmlReader XMLReader object, positioned on a "" node - * @return int Column index * @throws \Box\Spout\Common\Exception\InvalidArgumentException When the given cell index is invalid + * @return int Column index */ protected function getColumnIndex($xmlReader) { @@ -353,7 +345,7 @@ class RowIterator implements IteratorInterface /** * Return the current element, either an empty row or from the buffer. - * @link http://php.net/manual/en/iterator.current.php + * @see http://php.net/manual/en/iterator.current.php * * @return array|null */ @@ -378,7 +370,7 @@ class RowIterator implements IteratorInterface /** * Return the key of the current element. Here, the row index. - * @link http://php.net/manual/en/iterator.key.php + * @see http://php.net/manual/en/iterator.key.php * * @return int */ @@ -392,7 +384,6 @@ class RowIterator implements IteratorInterface $this->numReadRows; } - /** * Cleans up what was created to iterate over the object. * diff --git a/src/Spout/Reader/XLSX/Sheet.php b/src/Spout/Reader/XLSX/Sheet.php index 9baaef2..bff1fb4 100644 --- a/src/Spout/Reader/XLSX/Sheet.php +++ b/src/Spout/Reader/XLSX/Sheet.php @@ -7,8 +7,6 @@ use Box\Spout\Reader\SheetInterface; /** * Class Sheet * Represents a sheet within a XLSX file - * - * @package Box\Spout\Reader\XLSX */ class Sheet implements SheetInterface { @@ -25,17 +23,14 @@ class Sheet implements SheetInterface protected $isActive; /** - * @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 RowIterator $rowIterator The corresponding row iterator * @param int $sheetIndex Index of the sheet, based on order in the workbook (zero-based) * @param string $sheetName Name of the sheet * @param bool $isSheetActive Whether the sheet was defined as active - * @param \Box\Spout\Reader\XLSX\ReaderOptions $options Reader's current options - * @param Helper\SharedStringsHelper Helper to work with shared strings */ - public function __construct($filePath, $sheetDataXMLFilePath, $sheetIndex, $sheetName, $isSheetActive, $options, $sharedStringsHelper) + public function __construct($rowIterator, $sheetIndex, $sheetName, $isSheetActive) { - $this->rowIterator = new RowIterator($filePath, $sheetDataXMLFilePath, $options, $sharedStringsHelper); + $this->rowIterator = $rowIterator; $this->index = $sheetIndex; $this->name = $sheetName; $this->isActive = $isSheetActive; diff --git a/src/Spout/Reader/XLSX/SheetIterator.php b/src/Spout/Reader/XLSX/SheetIterator.php index 7ba07d3..d9ed17c 100644 --- a/src/Spout/Reader/XLSX/SheetIterator.php +++ b/src/Spout/Reader/XLSX/SheetIterator.php @@ -2,15 +2,13 @@ namespace Box\Spout\Reader\XLSX; -use Box\Spout\Reader\IteratorInterface; -use Box\Spout\Reader\XLSX\Helper\SheetHelper; use Box\Spout\Reader\Exception\NoSheetsFoundException; +use Box\Spout\Reader\IteratorInterface; +use Box\Spout\Reader\XLSX\Manager\SheetManager; /** * Class SheetIterator * Iterate over XLSX sheet. - * - * @package Box\Spout\Reader\XLSX */ class SheetIterator implements IteratorInterface { @@ -21,17 +19,13 @@ class SheetIterator implements IteratorInterface protected $currentSheetIndex; /** - * @param string $filePath Path of the file to be read - * @param \Box\Spout\Reader\XLSX\ReaderOptions $options Reader's current options - * @param \Box\Spout\Reader\XLSX\Helper\SharedStringsHelper $sharedStringsHelper - * @param \Box\Spout\Common\Helper\GlobalFunctionsHelper $globalFunctionsHelper + * @param SheetManager $sheetManager Manages sheets * @throws \Box\Spout\Reader\Exception\NoSheetsFoundException If there are no sheets in the file */ - public function __construct($filePath, $options, $sharedStringsHelper, $globalFunctionsHelper) + public function __construct($sheetManager) { // Fetch all available sheets - $sheetHelper = new SheetHelper($filePath, $options, $sharedStringsHelper, $globalFunctionsHelper); - $this->sheets = $sheetHelper->getSheets(); + $this->sheets = $sheetManager->getSheets(); if (count($this->sheets) === 0) { throw new NoSheetsFoundException('The file must contain at least one sheet.'); @@ -40,7 +34,7 @@ class SheetIterator implements IteratorInterface /** * Rewind the Iterator to the first element - * @link http://php.net/manual/en/iterator.rewind.php + * @see http://php.net/manual/en/iterator.rewind.php * * @return void */ @@ -51,7 +45,7 @@ class SheetIterator implements IteratorInterface /** * Checks if current position is valid - * @link http://php.net/manual/en/iterator.valid.php + * @see http://php.net/manual/en/iterator.valid.php * * @return bool */ @@ -62,7 +56,7 @@ class SheetIterator implements IteratorInterface /** * Move forward to next element - * @link http://php.net/manual/en/iterator.next.php + * @see http://php.net/manual/en/iterator.next.php * * @return void */ @@ -79,7 +73,7 @@ class SheetIterator implements IteratorInterface /** * Return the current element - * @link http://php.net/manual/en/iterator.current.php + * @see http://php.net/manual/en/iterator.current.php * * @return \Box\Spout\Reader\XLSX\Sheet */ @@ -90,7 +84,7 @@ class SheetIterator implements IteratorInterface /** * Return the key of the current element - * @link http://php.net/manual/en/iterator.key.php + * @see http://php.net/manual/en/iterator.key.php * * @return int */ diff --git a/src/Spout/Writer/CSV/Manager/OptionsManager.php b/src/Spout/Writer/CSV/Manager/OptionsManager.php index 502ce94..8acee69 100644 --- a/src/Spout/Writer/CSV/Manager/OptionsManager.php +++ b/src/Spout/Writer/CSV/Manager/OptionsManager.php @@ -2,19 +2,17 @@ namespace Box\Spout\Writer\CSV\Manager; +use Box\Spout\Common\Manager\OptionsManagerAbstract; use Box\Spout\Writer\Common\Entity\Options; -use Box\Spout\Writer\Common\Manager\OptionsManagerAbstract; /** * Class OptionsManager * CSV Writer options manager - * - * @package Box\Spout\Writer\CSV\Manager */ class OptionsManager extends OptionsManagerAbstract { /** - * @inheritdoc + * {@inheritdoc} */ protected function getSupportedOptions() { @@ -26,7 +24,7 @@ class OptionsManager extends OptionsManagerAbstract } /** - * @inheritdoc + * {@inheritdoc} */ protected function setDefaultOptions() { @@ -34,4 +32,4 @@ class OptionsManager extends OptionsManagerAbstract $this->setOption(Options::FIELD_ENCLOSURE, '"'); $this->setOption(Options::SHOULD_ADD_BOM, true); } -} \ No newline at end of file +} diff --git a/src/Spout/Writer/CSV/Writer.php b/src/Spout/Writer/CSV/Writer.php index a17f5e3..5808d5f 100644 --- a/src/Spout/Writer/CSV/Writer.php +++ b/src/Spout/Writer/CSV/Writer.php @@ -2,17 +2,15 @@ namespace Box\Spout\Writer\CSV; -use Box\Spout\Writer\WriterAbstract; use Box\Spout\Common\Exception\IOException; use Box\Spout\Common\Helper\EncodingHelper; use Box\Spout\Writer\Common\Entity\Options; use Box\Spout\Writer\Common\Entity\Row; +use Box\Spout\Writer\WriterAbstract; /** * Class Writer * This class provides support to write data to CSV files - * - * @package Box\Spout\Writer\CSV */ class Writer extends WriterAbstract { @@ -35,6 +33,7 @@ class Writer extends WriterAbstract public function setFieldDelimiter($fieldDelimiter) { $this->optionsManager->setOption(Options::FIELD_DELIMITER, $fieldDelimiter); + return $this; } @@ -48,6 +47,7 @@ class Writer extends WriterAbstract public function setFieldEnclosure($fieldEnclosure) { $this->optionsManager->setOption(Options::FIELD_ENCLOSURE, $fieldEnclosure); + return $this; } @@ -61,6 +61,7 @@ class Writer extends WriterAbstract public function setShouldAddBOM($shouldAddBOM) { $this->optionsManager->setOption(Options::SHOULD_ADD_BOM, (bool) $shouldAddBOM); + return $this; } diff --git a/src/Spout/Writer/Common/Creator/EntityFactory.php b/src/Spout/Writer/Common/Creator/EntityFactory.php index e2e9e08..fd8c1ca 100644 --- a/src/Spout/Writer/Common/Creator/EntityFactory.php +++ b/src/Spout/Writer/Common/Creator/EntityFactory.php @@ -3,32 +3,19 @@ namespace Box\Spout\Writer\Common\Creator; use Box\Spout\Writer\Common\Entity\Row; +use Box\Spout\Writer\Common\Entity\Cell; use Box\Spout\Writer\Common\Entity\Sheet; use Box\Spout\Writer\Common\Entity\Style\Style; use Box\Spout\Writer\Common\Entity\Workbook; use Box\Spout\Writer\Common\Entity\Worksheet; +use Box\Spout\Writer\Common\Manager\SheetManager; /** * Class EntityFactory * Factory to create entities - * - * @package Box\Spout\Writer\Common\Creator */ class EntityFactory { - /** @var ManagerFactory */ - private $managerFactory; - - /** - * EntityFactory constructor. - * - * @param ManagerFactory $managerFactory - */ - public function __construct(ManagerFactory $managerFactory) - { - $this->managerFactory = $managerFactory; - } - /** * @return Workbook */ @@ -50,14 +37,31 @@ class EntityFactory /** * @param int $sheetIndex Index of the sheet, based on order in the workbook (zero-based) * @param string $associatedWorkbookId ID of the sheet's associated workbook + * @param SheetManager $sheetManager To manage sheets * @return Sheet */ - public function createSheet($sheetIndex, $associatedWorkbookId) + public function createSheet($sheetIndex, $associatedWorkbookId, $sheetManager) { - $sheetManager = $this->managerFactory->createSheetManager(); return new Sheet($sheetIndex, $associatedWorkbookId, $sheetManager); } + /** + * @param mixed $cellValue + * @return Cell + */ + public function createCell($cellValue) + { + return new Cell($cellValue); + } + + /** + * @return \ZipArchive + */ + public function createZipArchive() + { + return new \ZipArchive(); + } + /** * @param array $cells * @param Style|null $style @@ -68,4 +72,4 @@ class EntityFactory $rowManager = $this->managerFactory->createRowManager(); return new Row($cells, $style, $rowManager); } -} \ No newline at end of file +} diff --git a/src/Spout/Writer/Common/Creator/ManagerFactory.php b/src/Spout/Writer/Common/Creator/ManagerFactory.php deleted file mode 100644 index 79aa0ff..0000000 --- a/src/Spout/Writer/Common/Creator/ManagerFactory.php +++ /dev/null @@ -1,45 +0,0 @@ -border->addPart(new BorderPart(Border::TOP, $color, $width, $style)); + return $this; } /** - * @param string|void $color Border A RGB color code - * @param string|void $width Border width @see BorderPart::allowedWidths - * @param string|void $style Border style @see BorderPart::allowedStyles + * @param string $color Border A RGB color code + * @param string $width Border width @see BorderPart::allowedWidths + * @param string $style Border style @see BorderPart::allowedStyles * @return BorderBuilder */ public function setBorderRight($color = Color::BLACK, $width = Border::WIDTH_MEDIUM, $style = Border::STYLE_SOLID) { $this->border->addPart(new BorderPart(Border::RIGHT, $color, $width, $style)); + return $this; } /** - * @param string|void $color Border A RGB color code - * @param string|void $width Border width @see BorderPart::allowedWidths - * @param string|void $style Border style @see BorderPart::allowedStyles + * @param string $color Border A RGB color code + * @param string $width Border width @see BorderPart::allowedWidths + * @param string $style Border style @see BorderPart::allowedStyles * @return BorderBuilder */ public function setBorderBottom($color = Color::BLACK, $width = Border::WIDTH_MEDIUM, $style = Border::STYLE_SOLID) { $this->border->addPart(new BorderPart(Border::BOTTOM, $color, $width, $style)); + return $this; } /** - * @param string|void $color Border A RGB color code - * @param string|void $width Border width @see BorderPart::allowedWidths - * @param string|void $style Border style @see BorderPart::allowedStyles + * @param string $color Border A RGB color code + * @param string $width Border width @see BorderPart::allowedWidths + * @param string $style Border style @see BorderPart::allowedStyles * @return BorderBuilder */ public function setBorderLeft($color = Color::BLACK, $width = Border::WIDTH_MEDIUM, $style = Border::STYLE_SOLID) { $this->border->addPart(new BorderPart(Border::LEFT, $color, $width, $style)); + return $this; } diff --git a/src/Spout/Writer/Common/Creator/Style/StyleBuilder.php b/src/Spout/Writer/Common/Creator/Style/StyleBuilder.php index 34e40d7..1a8c710 100644 --- a/src/Spout/Writer/Common/Creator/Style/StyleBuilder.php +++ b/src/Spout/Writer/Common/Creator/Style/StyleBuilder.php @@ -8,8 +8,6 @@ use Box\Spout\Writer\Common\Entity\Style\Style; /** * Class StyleBuilder * Builder to create new styles - * - * @package Box\Spout\Writer\Common\Creator\Style */ class StyleBuilder { @@ -33,6 +31,7 @@ class StyleBuilder public function setFontBold() { $this->style->setFontBold(); + return $this; } @@ -45,6 +44,7 @@ class StyleBuilder public function setFontItalic() { $this->style->setFontItalic(); + return $this; } @@ -57,6 +57,7 @@ class StyleBuilder public function setFontUnderline() { $this->style->setFontUnderline(); + return $this; } @@ -69,6 +70,7 @@ class StyleBuilder public function setFontStrikethrough() { $this->style->setFontStrikethrough(); + return $this; } @@ -82,6 +84,7 @@ class StyleBuilder public function setFontSize($fontSize) { $this->style->setFontSize($fontSize); + return $this; } @@ -95,6 +98,7 @@ class StyleBuilder public function setFontColor($fontColor) { $this->style->setFontColor($fontColor); + return $this; } @@ -108,6 +112,7 @@ class StyleBuilder public function setFontName($fontName) { $this->style->setFontName($fontName); + return $this; } @@ -121,6 +126,7 @@ class StyleBuilder public function setShouldWrapText($shouldWrap = true) { $this->style->setShouldWrapText($shouldWrap); + return $this; } @@ -133,6 +139,7 @@ class StyleBuilder public function setBorder(Border $border) { $this->style->setBorder($border); + return $this; } @@ -146,6 +153,7 @@ class StyleBuilder public function setBackgroundColor($color) { $this->style->setBackgroundColor($color); + return $this; } diff --git a/src/Spout/Writer/Common/Entity/Cell.php b/src/Spout/Writer/Common/Entity/Cell.php index fa2d350..fe4e02e 100644 --- a/src/Spout/Writer/Common/Entity/Cell.php +++ b/src/Spout/Writer/Common/Entity/Cell.php @@ -8,8 +8,6 @@ use Box\Spout\Writer\Common\Manager\Style\StyleMerger; /** * Class Cell - * - * @package Box\Spout\Writer\Common\Entity */ class Cell { @@ -48,13 +46,13 @@ class Cell * The value of this cell * @var mixed|null */ - protected $value = null; + protected $value; /** * The cell type * @var int|null */ - protected $type = null; + protected $type; /** * The cell style @@ -132,15 +130,18 @@ class Cell { if (CellHelper::isBoolean($value)) { return self::TYPE_BOOLEAN; - } elseif (CellHelper::isEmpty($value)) { - return self::TYPE_EMPTY; - } elseif (CellHelper::isNumeric($this->getValue())) { - return self::TYPE_NUMERIC; - } elseif (CellHelper::isNonEmptyString($value)) { - return self::TYPE_STRING; - } else { - return self::TYPE_ERROR; } + if (CellHelper::isEmpty($value)) { + return self::TYPE_EMPTY; + } + if (CellHelper::isNumeric($this->getValue())) { + return self::TYPE_NUMERIC; + } + if (CellHelper::isNonEmptyString($value)) { + return self::TYPE_STRING; + } + + return self::TYPE_ERROR; } /** @@ -197,7 +198,7 @@ class Cell */ public function __toString() { - return (string)$this->value; + return (string) $this->value; } /** diff --git a/src/Spout/Writer/Common/Entity/Options.php b/src/Spout/Writer/Common/Entity/Options.php index 2641f72..d7152bb 100644 --- a/src/Spout/Writer/Common/Entity/Options.php +++ b/src/Spout/Writer/Common/Entity/Options.php @@ -4,9 +4,7 @@ namespace Box\Spout\Writer\Common\Entity; /** * Class Options - * Writer' options holder - * - * @package Box\Spout\Writer\Common\Entity + * Writers' options holder */ abstract class Options { diff --git a/src/Spout/Writer/Common/Entity/Sheet.php b/src/Spout/Writer/Common/Entity/Sheet.php index 44afd6c..ddb9d60 100644 --- a/src/Spout/Writer/Common/Entity/Sheet.php +++ b/src/Spout/Writer/Common/Entity/Sheet.php @@ -7,8 +7,6 @@ use Box\Spout\Writer\Common\Manager\SheetManager; /** * Class Sheet * External representation of a worksheet - * - * @package Box\Spout\Writer\Common\Entity */ class Sheet { @@ -29,7 +27,7 @@ class Sheet /** * @param int $sheetIndex Index of the sheet, based on order in the workbook (zero-based) * @param string $associatedWorkbookId ID of the sheet's associated workbook - * @param SheetManager $sheetManager + * @param SheetManager $sheetManager To manage sheets */ public function __construct($sheetIndex, $associatedWorkbookId, SheetManager $sheetManager) { @@ -77,8 +75,8 @@ class Sheet * * @api * @param string $name Name of the sheet - * @return Sheet * @throws \Box\Spout\Writer\Exception\InvalidSheetNameException If the sheet's name is invalid. + * @return Sheet */ public function setName($name) { diff --git a/src/Spout/Writer/Common/Entity/Style/Border.php b/src/Spout/Writer/Common/Entity/Style/Border.php index 7046897..ba5d1a2 100644 --- a/src/Spout/Writer/Common/Entity/Style/Border.php +++ b/src/Spout/Writer/Common/Entity/Style/Border.php @@ -4,8 +4,6 @@ namespace Box\Spout\Writer\Common\Entity\Style; /** * Class Border - * - * @package \Box\Spout\Writer\Common\Entity\Style */ class Border { @@ -28,7 +26,7 @@ class Border private $parts = []; /** - * @param array|void $borderParts + * @param array $borderParts */ public function __construct(array $borderParts = []) { @@ -37,7 +35,7 @@ class Border /** * @param string $name The name of the border part - * @return null|BorderPart + * @return BorderPart|null */ public function getPart($name) { @@ -81,6 +79,7 @@ class Border public function addPart(BorderPart $borderPart) { $this->parts[$borderPart->getName()] = $borderPart; + return $this; } } diff --git a/src/Spout/Writer/Common/Entity/Style/BorderPart.php b/src/Spout/Writer/Common/Entity/Style/BorderPart.php index 66a08c1..cbc6a62 100644 --- a/src/Spout/Writer/Common/Entity/Style/BorderPart.php +++ b/src/Spout/Writer/Common/Entity/Style/BorderPart.php @@ -8,8 +8,6 @@ use Box\Spout\Writer\Exception\Border\InvalidWidthException; /** * Class BorderPart - * - * @package \Box\Spout\Writer\Common\Entity\Style */ class BorderPart { @@ -41,7 +39,7 @@ class BorderPart 'solid', 'dashed', 'dotted', - 'double' + 'double', ]; /** diff --git a/src/Spout/Writer/Common/Entity/Style/Color.php b/src/Spout/Writer/Common/Entity/Style/Color.php index 356f606..6b3682e 100644 --- a/src/Spout/Writer/Common/Entity/Style/Color.php +++ b/src/Spout/Writer/Common/Entity/Style/Color.php @@ -7,8 +7,6 @@ use Box\Spout\Writer\Exception\InvalidColorException; /** * Class Color * This class provides constants and functions to work with colors - * - * @package Box\Spout\Writer\Common\Entity\Style */ class Color { @@ -52,8 +50,8 @@ class Color * 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 + * @return void */ protected static function throwIfInvalidColorComponentValue($colorComponent) { diff --git a/src/Spout/Writer/Common/Entity/Style/Style.php b/src/Spout/Writer/Common/Entity/Style/Style.php index 16268b1..a8018e8 100644 --- a/src/Spout/Writer/Common/Entity/Style/Style.php +++ b/src/Spout/Writer/Common/Entity/Style/Style.php @@ -5,8 +5,6 @@ namespace Box\Spout\Writer\Common\Entity\Style; /** * Class Style * Represents a style to be applied to a cell - * - * @package Box\Spout\Writer\Common\Entity\Style */ class Style { @@ -16,7 +14,7 @@ class Style const DEFAULT_FONT_NAME = 'Arial'; /** @var int|null Style ID */ - private $id = null; + private $id; /** @var bool Whether the font should be bold */ private $fontBold = false; @@ -62,18 +60,17 @@ class Style private $hasSetWrapText = false; /** @var Border */ - private $border = null; + private $border; /** @var bool Whether border properties should be applied */ private $shouldApplyBorder = false; /** @var string Background color */ - private $backgroundColor = null; + private $backgroundColor; /** @var bool */ private $hasSetBackgroundColor = false; - /** * @return int|null */ @@ -89,6 +86,7 @@ class Style public function setId($id) { $this->id = $id; + return $this; } @@ -108,6 +106,7 @@ class Style { $this->shouldApplyBorder = true; $this->border = $border; + return $this; } @@ -135,6 +134,7 @@ class Style $this->fontBold = true; $this->hasSetFontBold = true; $this->shouldApplyFont = true; + return $this; } @@ -162,6 +162,7 @@ class Style $this->fontItalic = true; $this->hasSetFontItalic = true; $this->shouldApplyFont = true; + return $this; } @@ -189,6 +190,7 @@ class Style $this->fontUnderline = true; $this->hasSetFontUnderline = true; $this->shouldApplyFont = true; + return $this; } @@ -216,6 +218,7 @@ class Style $this->fontStrikethrough = true; $this->hasSetFontStrikethrough = true; $this->shouldApplyFont = true; + return $this; } @@ -244,6 +247,7 @@ class Style $this->fontSize = $fontSize; $this->hasSetFontSize = true; $this->shouldApplyFont = true; + return $this; } @@ -274,6 +278,7 @@ class Style $this->fontColor = $fontColor; $this->hasSetFontColor = true; $this->shouldApplyFont = true; + return $this; } @@ -302,6 +307,7 @@ class Style $this->fontName = $fontName; $this->hasSetFontName = true; $this->shouldApplyFont = true; + return $this; } @@ -322,13 +328,14 @@ class Style } /** - * @param bool|void $shouldWrap Should the text be wrapped + * @param bool $shouldWrap Should the text be wrapped * @return Style */ public function setShouldWrapText($shouldWrap = true) { $this->shouldWrapText = $shouldWrap; $this->hasSetWrapText = true; + return $this; } @@ -357,6 +364,7 @@ class Style { $this->hasSetBackgroundColor = true; $this->backgroundColor = $color; + return $this; } @@ -369,7 +377,6 @@ class Style } /** - * * @return bool Whether the background color should be applied */ public function shouldApplyBackgroundColor() diff --git a/src/Spout/Writer/Common/Entity/Workbook.php b/src/Spout/Writer/Common/Entity/Workbook.php index e10a419..782310b 100644 --- a/src/Spout/Writer/Common/Entity/Workbook.php +++ b/src/Spout/Writer/Common/Entity/Workbook.php @@ -5,8 +5,6 @@ namespace Box\Spout\Writer\Common\Entity; /** * Class Workbook * Entity describing a workbook - * - * @package Box\Spout\Writer\Common\Entity */ class Workbook { @@ -47,4 +45,4 @@ class Workbook { return $this->internalId; } -} \ No newline at end of file +} diff --git a/src/Spout/Writer/Common/Entity/Worksheet.php b/src/Spout/Writer/Common/Entity/Worksheet.php index 1783a5f..74c4976 100644 --- a/src/Spout/Writer/Common/Entity/Worksheet.php +++ b/src/Spout/Writer/Common/Entity/Worksheet.php @@ -5,15 +5,13 @@ namespace Box\Spout\Writer\Common\Entity; /** * Class Worksheet * Entity describing a Worksheet - * - * @package Box\Spout\Writer\Common\Entity */ class Worksheet { /** @var string Path to the XML file that will contain the sheet data */ private $filePath; - /** @var Resource Pointer to the sheet data file (e.g. xl/worksheets/sheet1.xml) */ + /** @var resource Pointer to the sheet data file (e.g. xl/worksheets/sheet1.xml) */ private $filePointer; /** @var Sheet The "external" sheet */ @@ -49,7 +47,7 @@ class Worksheet } /** - * @return Resource + * @return resource */ public function getFilePointer() { @@ -57,7 +55,7 @@ class Worksheet } /** - * @param Resource $filePointer + * @param resource $filePointer */ public function setFilePointer($filePointer) { @@ -112,4 +110,4 @@ class Worksheet // sheet index is zero-based, while ID is 1-based return $this->externalSheet->getIndex() + 1; } -} \ No newline at end of file +} diff --git a/src/Spout/Writer/Common/Helper/CellHelper.php b/src/Spout/Writer/Common/Helper/CellHelper.php index 50ead93..df935a0 100644 --- a/src/Spout/Writer/Common/Helper/CellHelper.php +++ b/src/Spout/Writer/Common/Helper/CellHelper.php @@ -5,8 +5,6 @@ namespace Box\Spout\Writer\Common\Helper; /** * Class CellHelper * This class provides helper functions when working with cells - * - * @package Box\Spout\Writer\Common\Helper */ class CellHelper { @@ -36,8 +34,7 @@ class CellHelper $cellIndex = chr($capitalAAsciiValue + $modulus) . $cellIndex; // substracting 1 because it's zero-based - $columnIndex = intval($columnIndex / 26) - 1; - + $columnIndex = (int) ($columnIndex / 26) - 1; } while ($columnIndex >= 0); self::$columnIndexToCellIndexCache[$originalColumnIndex] = $cellIndex; @@ -74,6 +71,7 @@ class CellHelper public static function isNumeric($value) { $valueType = gettype($value); + return ($valueType === 'integer' || $valueType === 'double'); } diff --git a/src/Spout/Writer/Common/Helper/FileSystemWithRootFolderHelperInterface.php b/src/Spout/Writer/Common/Helper/FileSystemWithRootFolderHelperInterface.php index 8e7a7a5..79cd440 100644 --- a/src/Spout/Writer/Common/Helper/FileSystemWithRootFolderHelperInterface.php +++ b/src/Spout/Writer/Common/Helper/FileSystemWithRootFolderHelperInterface.php @@ -2,22 +2,20 @@ namespace Box\Spout\Writer\Common\Helper; -use \Box\Spout\Common\Helper\FileSystemHelperInterface; +use Box\Spout\Common\Helper\FileSystemHelperInterface; /** * Class FileSystemHelperInterface * This interface describes helper functions to help with the file system operations * like files/folders creation & deletion - * - * @package Box\Spout\Writer\Common\Helper */ interface FileSystemWithRootFolderHelperInterface extends FileSystemHelperInterface { /** * Creates all the folders needed to create a spreadsheet, 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 + * @return void */ public function createBaseFilesAndFolders(); diff --git a/src/Spout/Writer/Common/Helper/ZipHelper.php b/src/Spout/Writer/Common/Helper/ZipHelper.php index f6fec55..e970571 100644 --- a/src/Spout/Writer/Common/Helper/ZipHelper.php +++ b/src/Spout/Writer/Common/Helper/ZipHelper.php @@ -2,11 +2,11 @@ namespace Box\Spout\Writer\Common\Helper; +use Box\Spout\Writer\Common\Creator\EntityFactory; + /** * Class ZipHelper * This class provides helper functions to create zip files - * - * @package Box\Spout\Writer\Common\Helper */ class ZipHelper { @@ -16,6 +16,17 @@ class ZipHelper const EXISTING_FILES_SKIP = 'skip'; const EXISTING_FILES_OVERWRITE = 'overwrite'; + /** @var EntityFactory Factory to create entities */ + private $entityFactory; + + /** + * @param EntityFactory $entityFactory Factory to create entities + */ + public function __construct($entityFactory) + { + $this->entityFactory = $entityFactory; + } + /** * Returns a new ZipArchive instance pointing at the given path. * @@ -24,10 +35,10 @@ class ZipHelper */ public function createZip($tmpFolderPath) { - $zip = new \ZipArchive(); + $zip = $this->entityFactory->createZipArchive(); $zipFilePath = $tmpFolderPath . self::ZIP_EXTENSION; - $zip->open($zipFilePath, \ZipArchive::CREATE|\ZipArchive::OVERWRITE); + $zip->open($zipFilePath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE); return $zip; } @@ -52,7 +63,7 @@ class ZipHelper * @param \ZipArchive $zip An opened zip archive object * @param string $rootFolderPath Path of the root folder that will be ignored in the archive tree. * @param string $localFilePath Path of the file to be added, under the root folder - * @param string|void $existingFileMode Controls what to do when trying to add an existing file + * @param string $existingFileMode Controls what to do when trying to add an existing file * @return void */ public function addFileToArchive($zip, $rootFolderPath, $localFilePath, $existingFileMode = self::EXISTING_FILES_OVERWRITE) @@ -77,7 +88,7 @@ class ZipHelper * @param \ZipArchive $zip An opened zip archive object * @param string $rootFolderPath Path of the root folder that will be ignored in the archive tree. * @param string $localFilePath Path of the file to be added, under the root folder - * @param string|void $existingFileMode Controls what to do when trying to add an existing file + * @param string $existingFileMode Controls what to do when trying to add an existing file * @return void */ public function addUncompressedFileToArchive($zip, $rootFolderPath, $localFilePath, $existingFileMode = self::EXISTING_FILES_OVERWRITE) @@ -130,7 +141,7 @@ class ZipHelper /** * @param \ZipArchive $zip An opened zip archive object * @param string $folderPath Path to the folder to be zipped - * @param string|void $existingFileMode Controls what to do when trying to add an existing file + * @param string $existingFileMode Controls what to do when trying to add an existing file * @return void */ public function addFolderToArchive($zip, $folderPath, $existingFileMode = self::EXISTING_FILES_OVERWRITE) @@ -171,6 +182,7 @@ class ZipHelper protected function getNormalizedRealPath($path) { $realPath = realpath($path); + return str_replace(DIRECTORY_SEPARATOR, '/', $realPath); } diff --git a/src/Spout/Writer/Common/Manager/SheetManager.php b/src/Spout/Writer/Common/Manager/SheetManager.php index 723cbe2..708137c 100644 --- a/src/Spout/Writer/Common/Manager/SheetManager.php +++ b/src/Spout/Writer/Common/Manager/SheetManager.php @@ -9,8 +9,6 @@ use Box\Spout\Writer\Exception\InvalidSheetNameException; /** * Class SheetManager * Sheet manager - * - * @package Box\Spout\Writer\Common\Manager */ class SheetManager { @@ -42,8 +40,8 @@ class SheetManager * * @param string $name * @param Sheet $sheet The sheet whose future name is checked - * @return void * @throws \Box\Spout\Writer\Exception\InvalidSheetNameException If the sheet's name is invalid. + * @return void */ public function throwIfNameIsInvalid($name, Sheet $sheet) { diff --git a/src/Spout/Writer/Common/Manager/Style/StyleManager.php b/src/Spout/Writer/Common/Manager/Style/StyleManager.php index ea6561e..647c214 100644 --- a/src/Spout/Writer/Common/Manager/Style/StyleManager.php +++ b/src/Spout/Writer/Common/Manager/Style/StyleManager.php @@ -8,8 +8,6 @@ use Box\Spout\Writer\Common\Entity\Style\Style; /** * Class StyleManager * Manages styles to be applied to a cell - * - * @package Box\Spout\Writer\Common\Manager\Style */ class StyleManager implements StyleManagerInterface { @@ -47,7 +45,6 @@ class StyleManager implements StyleManagerInterface return $this->styleRegistry->registerStyle($style); } - /** * Apply additional styles if the given row needs it. * Typically, set "wrap text" if a cell contains a new line. diff --git a/src/Spout/Writer/Common/Manager/Style/StyleManagerInterface.php b/src/Spout/Writer/Common/Manager/Style/StyleManagerInterface.php index d75506e..710a2ae 100644 --- a/src/Spout/Writer/Common/Manager/Style/StyleManagerInterface.php +++ b/src/Spout/Writer/Common/Manager/Style/StyleManagerInterface.php @@ -8,8 +8,6 @@ use Box\Spout\Writer\Common\Entity\Style\Style; /** * Interface StyleHManagernterface - * - * @package Box\Spout\Writer\Common\Manager\Style */ interface StyleManagerInterface { diff --git a/src/Spout/Writer/Common/Manager/Style/StyleMerger.php b/src/Spout/Writer/Common/Manager/Style/StyleMerger.php index b59e358..d254091 100644 --- a/src/Spout/Writer/Common/Manager/Style/StyleMerger.php +++ b/src/Spout/Writer/Common/Manager/Style/StyleMerger.php @@ -2,15 +2,11 @@ namespace Box\Spout\Writer\Common\Manager\Style; -use Box\Spout\Writer\Common\Entity\Style\Color; use Box\Spout\Writer\Common\Entity\Style\Style; -use Box\Spout\Writer\XLSX\Helper\BorderHelper; /** * Class StyleMerger * Takes care of merging styles together - * - * @package Box\Spout\Writer\Common\Manager\Style */ class StyleMerger { diff --git a/src/Spout/Writer/Common/Manager/Style/StyleRegistry.php b/src/Spout/Writer/Common/Manager/Style/StyleRegistry.php index 4a25cba..e817123 100644 --- a/src/Spout/Writer/Common/Manager/Style/StyleRegistry.php +++ b/src/Spout/Writer/Common/Manager/Style/StyleRegistry.php @@ -7,8 +7,6 @@ use Box\Spout\Writer\Common\Entity\Style\Style; /** * Class StyleRegistry * Registry for all used styles - * - * @package Box\Spout\Writer\Common\Manager\Style */ class StyleRegistry { @@ -72,6 +70,7 @@ class StyleRegistry protected function getStyleFromSerializedStyle($serializedStyle) { $styleId = $this->serializedStyleToStyleIdMappingTable[$serializedStyle]; + return $this->styleIdToStyleMappingTable[$styleId]; } diff --git a/src/Spout/Writer/Common/Manager/WorkbookManagerAbstract.php b/src/Spout/Writer/Common/Manager/WorkbookManagerAbstract.php index 2c8b57b..62d4572 100644 --- a/src/Spout/Writer/Common/Manager/WorkbookManagerAbstract.php +++ b/src/Spout/Writer/Common/Manager/WorkbookManagerAbstract.php @@ -3,13 +3,18 @@ namespace Box\Spout\Writer\Common\Manager; use Box\Spout\Common\Exception\IOException; -use Box\Spout\Writer\Common\Helper\FileSystemWithRootFolderHelperInterface; +use Box\Spout\Common\Manager\OptionsManagerInterface; +use Box\Spout\Writer\Common\Creator\EntityFactory; +use Box\Spout\Writer\Common\Creator\ManagerFactoryInterface; use Box\Spout\Writer\Common\Entity\Options; use Box\Spout\Writer\Common\Manager\Style\StyleManagerInterface; use Box\Spout\Writer\Common\Entity\Row; use Box\Spout\Writer\Common\Entity\Sheet; +use Box\Spout\Writer\Common\Entity\Style\Style; use Box\Spout\Writer\Common\Entity\Workbook; use Box\Spout\Writer\Common\Entity\Worksheet; +use Box\Spout\Writer\Common\Helper\FileSystemWithRootFolderHelperInterface; +use Box\Spout\Writer\Common\Manager\Style\StyleManagerInterface; use Box\Spout\Writer\Exception\SheetNotFoundException; use Box\Spout\Writer\Exception\WriterException; use Box\Spout\Writer\Common\Creator\EntityFactory; @@ -17,8 +22,6 @@ use Box\Spout\Writer\Common\Creator\EntityFactory; /** * Class WorkbookManagerAbstract * Abstract workbook manager, providing the generic interfaces to work with workbook. - * - * @package Box\Spout\Writer\Common\Manager */ abstract class WorkbookManagerAbstract implements WorkbookManagerInterface { @@ -40,10 +43,12 @@ abstract class WorkbookManagerAbstract implements WorkbookManagerInterface /** @var EntityFactory Factory to create entities */ protected $entityFactory; + /** @var ManagerFactoryInterface $managerFactory Factory to create managers */ + protected $managerFactory; + /** @var Worksheet The worksheet where data will be written to */ protected $currentWorksheet; - /** * @param Workbook $workbook * @param OptionsManagerInterface $optionsManager @@ -51,6 +56,7 @@ abstract class WorkbookManagerAbstract implements WorkbookManagerInterface * @param StyleManagerInterface $styleManager * @param FileSystemWithRootFolderHelperInterface $fileSystemHelper * @param EntityFactory $entityFactory + * @param ManagerFactoryInterface $managerFactory */ public function __construct( Workbook $workbook, @@ -58,14 +64,16 @@ abstract class WorkbookManagerAbstract implements WorkbookManagerInterface WorksheetManagerInterface $worksheetManager, StyleManagerInterface $styleManager, FileSystemWithRootFolderHelperInterface $fileSystemHelper, - EntityFactory $entityFactory) - { + EntityFactory $entityFactory, + ManagerFactoryInterface $managerFactory + ) { $this->workbook = $workbook; $this->optionManager = $optionsManager; $this->worksheetManager = $worksheetManager; $this->styleManager = $styleManager; $this->fileSystemHelper = $fileSystemHelper; $this->entityFactory = $entityFactory; + $this->managerFactory = $managerFactory; } /** @@ -91,8 +99,8 @@ abstract class WorkbookManagerAbstract implements WorkbookManagerInterface * 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 IOException If unable to open the sheet for writing + * @return Worksheet The created sheet */ public function addNewSheetAndMakeItCurrent() { @@ -105,15 +113,16 @@ abstract class WorkbookManagerAbstract implements WorkbookManagerInterface /** * 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 + * @return Worksheet The created sheet */ private function addNewSheet() { $worksheets = $this->getWorksheets(); $newSheetIndex = count($worksheets); - $sheet = $this->entityFactory->createSheet($newSheetIndex, $this->workbook->getInternalId()); + $sheetManager = $this->managerFactory->createSheetManager(); + $sheet = $this->entityFactory->createSheet($newSheetIndex, $this->workbook->getInternalId(), $sheetManager); $worksheetFilePath = $this->getWorksheetFilePath($sheet); $worksheet = $this->entityFactory->createWorksheet($worksheetFilePath, $sheet); @@ -149,8 +158,8 @@ abstract class WorkbookManagerAbstract implements WorkbookManagerInterface * The writing will resume where it stopped (i.e. data won't be truncated). * * @param Sheet $sheet The "external" sheet to set as current - * @return void * @throws SheetNotFoundException If the given sheet does not exist in the workbook + * @return void */ public function setCurrentSheet(Sheet $sheet) { @@ -200,6 +209,7 @@ abstract class WorkbookManagerAbstract implements WorkbookManagerInterface * @return void * @throws IOException If trying to create a new sheet and unable to open the sheet for writing * @throws WriterException If unable to write data + * @return void */ public function addRowToCurrentWorksheet(Row $row) { @@ -227,6 +237,7 @@ abstract class WorkbookManagerAbstract implements WorkbookManagerInterface private function hasCurrentWorksheetReachedMaxRows() { $currentWorksheet = $this->getCurrentWorksheet(); + return ($currentWorksheet->getLastWrittenRowIndex() >= $this->getMaxRowsPerWorksheet()); } @@ -237,6 +248,7 @@ abstract class WorkbookManagerAbstract implements WorkbookManagerInterface * @param Row $row The row to be added * @return void * @throws WriterException If unable to write data + * @return void */ private function addRowToWorksheet(Worksheet $worksheet, Row $row) { diff --git a/src/Spout/Writer/Common/Manager/WorkbookManagerInterface.php b/src/Spout/Writer/Common/Manager/WorkbookManagerInterface.php index ebfe922..ae21a0b 100644 --- a/src/Spout/Writer/Common/Manager/WorkbookManagerInterface.php +++ b/src/Spout/Writer/Common/Manager/WorkbookManagerInterface.php @@ -4,6 +4,7 @@ namespace Box\Spout\Writer\Common\Manager; use Box\Spout\Common\Exception\IOException; use Box\Spout\Writer\Common\Entity\Sheet; +use Box\Spout\Writer\Common\Entity\Style\Style; use Box\Spout\Writer\Common\Entity\Row; use Box\Spout\Writer\Common\Entity\Workbook; use Box\Spout\Writer\Common\Entity\Worksheet; @@ -13,8 +14,6 @@ use Box\Spout\Writer\Exception\WriterException; /** * Interface WorkbookManagerInterface * workbook manager interface, providing the generic interfaces to work with workbook. - * - * @package Box\Spout\Writer\Common\Manager */ interface WorkbookManagerInterface { @@ -27,8 +26,8 @@ interface WorkbookManagerInterface * 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 IOException If unable to open the sheet for writing + * @return Worksheet The created sheet */ public function addNewSheetAndMakeItCurrent(); @@ -49,8 +48,8 @@ interface WorkbookManagerInterface * The writing will resume where it stopped (i.e. data won't be truncated). * * @param Sheet $sheet The "external" sheet to set as current - * @return void * @throws SheetNotFoundException If the given sheet does not exist in the workbook + * @return void */ public function setCurrentSheet(Sheet $sheet); @@ -63,6 +62,7 @@ interface WorkbookManagerInterface * @return void * @throws IOException If trying to create a new sheet and unable to open the sheet for writing * @throws WriterException If unable to write data + * @return void */ public function addRowToCurrentWorksheet(Row $row); /** diff --git a/src/Spout/Writer/Common/Manager/WorksheetManagerInterface.php b/src/Spout/Writer/Common/Manager/WorksheetManagerInterface.php index 3382b6d..ab6362f 100644 --- a/src/Spout/Writer/Common/Manager/WorksheetManagerInterface.php +++ b/src/Spout/Writer/Common/Manager/WorksheetManagerInterface.php @@ -3,13 +3,12 @@ namespace Box\Spout\Writer\Common\Manager; use Box\Spout\Writer\Common\Entity\Row; +use Box\Spout\Writer\Common\Entity\Style\Style; use Box\Spout\Writer\Common\Entity\Worksheet; /** * Interface WorksheetManagerInterface * Inteface for worksheet managers, providing the generic interfaces to work with worksheets. - * - * @package Box\Spout\Writer\Common\Manager */ interface WorksheetManagerInterface { @@ -21,6 +20,7 @@ interface WorksheetManagerInterface * @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 + * @return void */ public function addRow(Worksheet $worksheet, Row $row); @@ -28,8 +28,8 @@ interface WorksheetManagerInterface * Prepares the worksheet to accept data * * @param Worksheet $worksheet The worksheet to start - * @return void * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing + * @return void */ public function startSheet(Worksheet $worksheet); diff --git a/src/Spout/Writer/Exception/Border/InvalidNameException.php b/src/Spout/Writer/Exception/Border/InvalidNameException.php index 329323a..0807298 100644 --- a/src/Spout/Writer/Exception/Border/InvalidNameException.php +++ b/src/Spout/Writer/Exception/Border/InvalidNameException.php @@ -2,8 +2,8 @@ namespace Box\Spout\Writer\Exception\Border; -use Box\Spout\Writer\Exception\WriterException; use Box\Spout\Writer\Common\Entity\Style\BorderPart; +use Box\Spout\Writer\Exception\WriterException; class InvalidNameException extends WriterException { diff --git a/src/Spout/Writer/Exception/Border/InvalidStyleException.php b/src/Spout/Writer/Exception/Border/InvalidStyleException.php index f3261f0..2efbded 100644 --- a/src/Spout/Writer/Exception/Border/InvalidStyleException.php +++ b/src/Spout/Writer/Exception/Border/InvalidStyleException.php @@ -2,8 +2,8 @@ namespace Box\Spout\Writer\Exception\Border; -use Box\Spout\Writer\Exception\WriterException; use Box\Spout\Writer\Common\Entity\Style\BorderPart; +use Box\Spout\Writer\Exception\WriterException; class InvalidStyleException extends WriterException { diff --git a/src/Spout/Writer/Exception/Border/InvalidWidthException.php b/src/Spout/Writer/Exception/Border/InvalidWidthException.php index 0f24faf..9fae1ea 100644 --- a/src/Spout/Writer/Exception/Border/InvalidWidthException.php +++ b/src/Spout/Writer/Exception/Border/InvalidWidthException.php @@ -2,8 +2,8 @@ namespace Box\Spout\Writer\Exception\Border; -use Box\Spout\Writer\Exception\WriterException; use Box\Spout\Writer\Common\Entity\Style\BorderPart; +use Box\Spout\Writer\Exception\WriterException; class InvalidWidthException extends WriterException { diff --git a/src/Spout/Writer/Exception/InvalidColorException.php b/src/Spout/Writer/Exception/InvalidColorException.php index 49b4a0d..b4428f2 100644 --- a/src/Spout/Writer/Exception/InvalidColorException.php +++ b/src/Spout/Writer/Exception/InvalidColorException.php @@ -6,7 +6,6 @@ namespace Box\Spout\Writer\Exception; * Class InvalidColorException * * @api - * @package Box\Spout\Writer\Exception */ class InvalidColorException extends WriterException { diff --git a/src/Spout/Writer/Exception/InvalidSheetNameException.php b/src/Spout/Writer/Exception/InvalidSheetNameException.php index ae0663e..6a5f934 100644 --- a/src/Spout/Writer/Exception/InvalidSheetNameException.php +++ b/src/Spout/Writer/Exception/InvalidSheetNameException.php @@ -6,7 +6,6 @@ namespace Box\Spout\Writer\Exception; * Class InvalidSheetNameException * * @api - * @package Box\Spout\Writer\Exception */ class InvalidSheetNameException extends WriterException { diff --git a/src/Spout/Writer/Exception/SheetNotFoundException.php b/src/Spout/Writer/Exception/SheetNotFoundException.php index c0ded5a..bc6aaa9 100644 --- a/src/Spout/Writer/Exception/SheetNotFoundException.php +++ b/src/Spout/Writer/Exception/SheetNotFoundException.php @@ -6,7 +6,6 @@ namespace Box\Spout\Writer\Exception; * Class SheetNotFoundException * * @api - * @package Box\Spout\Writer\Exception */ class SheetNotFoundException extends WriterException { diff --git a/src/Spout/Writer/Exception/WriterAlreadyOpenedException.php b/src/Spout/Writer/Exception/WriterAlreadyOpenedException.php index 657d611..8e049c8 100644 --- a/src/Spout/Writer/Exception/WriterAlreadyOpenedException.php +++ b/src/Spout/Writer/Exception/WriterAlreadyOpenedException.php @@ -6,7 +6,6 @@ namespace Box\Spout\Writer\Exception; * Class WriterAlreadyOpenedException * * @api - * @package Box\Spout\Writer\Exception */ class WriterAlreadyOpenedException extends WriterException { diff --git a/src/Spout/Writer/Exception/WriterException.php b/src/Spout/Writer/Exception/WriterException.php index 3d1fa60..72ab1bd 100644 --- a/src/Spout/Writer/Exception/WriterException.php +++ b/src/Spout/Writer/Exception/WriterException.php @@ -7,7 +7,6 @@ use Box\Spout\Common\Exception\SpoutException; /** * Class WriterException * - * @package Box\Spout\Writer\Exception * @abstract */ abstract class WriterException extends SpoutException diff --git a/src/Spout/Writer/Exception/WriterNotOpenedException.php b/src/Spout/Writer/Exception/WriterNotOpenedException.php index 5b08477..518cf2b 100644 --- a/src/Spout/Writer/Exception/WriterNotOpenedException.php +++ b/src/Spout/Writer/Exception/WriterNotOpenedException.php @@ -6,7 +6,6 @@ namespace Box\Spout\Writer\Exception; * Class WriterNotOpenedException * * @api - * @package Box\Spout\Writer\Exception */ class WriterNotOpenedException extends WriterException { diff --git a/src/Spout/Writer/ODS/Creator/HelperFactory.php b/src/Spout/Writer/ODS/Creator/HelperFactory.php new file mode 100644 index 0000000..bcb64b5 --- /dev/null +++ b/src/Spout/Writer/ODS/Creator/HelperFactory.php @@ -0,0 +1,56 @@ +getOption(Options::TEMP_FOLDER); + $zipHelper = $this->createZipHelper($entityFactory); + + return new FileSystemHelper($tempFolder, $zipHelper); + } + + /** + * @param $entityFactory + * @return ZipHelper + */ + private function createZipHelper($entityFactory) + { + return new ZipHelper($entityFactory); + } + + /** + * @return Escaper\ODS + */ + public function createStringsEscaper() + { + return new Escaper\ODS(); + } + + /** + * @return StringHelper + */ + public function createStringHelper() + { + return new StringHelper(); + } +} diff --git a/src/Spout/Writer/ODS/Creator/InternalFactory.php b/src/Spout/Writer/ODS/Creator/ManagerFactory.php similarity index 52% rename from src/Spout/Writer/ODS/Creator/InternalFactory.php rename to src/Spout/Writer/ODS/Creator/ManagerFactory.php index 24fc0d5..58d4941 100644 --- a/src/Spout/Writer/ODS/Creator/InternalFactory.php +++ b/src/Spout/Writer/ODS/Creator/ManagerFactory.php @@ -2,38 +2,36 @@ namespace Box\Spout\Writer\ODS\Creator; -use Box\Spout\Common\Helper\StringHelper; -use Box\Spout\Writer\Common\Helper\ZipHelper; -use Box\Spout\Writer\Common\Manager\OptionsManagerInterface; -use Box\Spout\Writer\Common\Entity\Options; +use Box\Spout\Common\Manager\OptionsManagerInterface; use Box\Spout\Writer\Common\Creator\EntityFactory; -use Box\Spout\Writer\Common\Creator\InternalFactoryInterface; -use Box\Spout\Writer\ODS\Helper\FileSystemHelper; +use Box\Spout\Writer\Common\Creator\ManagerFactoryInterface; +use Box\Spout\Writer\Common\Entity\Options; +use Box\Spout\Writer\Common\Manager\SheetManager; use Box\Spout\Writer\ODS\Manager\Style\StyleManager; use Box\Spout\Writer\ODS\Manager\Style\StyleRegistry; use Box\Spout\Writer\ODS\Manager\WorkbookManager; use Box\Spout\Writer\ODS\Manager\WorksheetManager; -use \Box\Spout\Common\Escaper; /** - * Class InternalFactory - * Factory for all useful types of objects needed by the ODS Writer - * - * @package Box\Spout\Writer\ODS\Creator + * Class ManagerFactory + * Factory for managers needed by the ODS Writer */ -class InternalFactory implements InternalFactoryInterface +class ManagerFactory implements ManagerFactoryInterface { /** @var EntityFactory */ - private $entityFactory; + protected $entityFactory; + + /** @var HelperFactory $helperFactory */ + protected $helperFactory; /** - * InternalFactory constructor. - * * @param EntityFactory $entityFactory + * @param HelperFactory $helperFactory */ - public function __construct(EntityFactory $entityFactory) + public function __construct(EntityFactory $entityFactory, HelperFactory $helperFactory) { $this->entityFactory = $entityFactory; + $this->helperFactory = $helperFactory; } /** @@ -44,13 +42,21 @@ class InternalFactory implements InternalFactoryInterface { $workbook = $this->entityFactory->createWorkbook(); - $fileSystemHelper = $this->createFileSystemHelper($optionsManager); + $fileSystemHelper = $this->helperFactory->createSpecificFileSystemHelper($optionsManager, $this->entityFactory); $fileSystemHelper->createBaseFilesAndFolders(); $styleManager = $this->createStyleManager($optionsManager); $worksheetManager = $this->createWorksheetManager($styleManager); - return new WorkbookManager($workbook, $optionsManager, $worksheetManager, $styleManager, $fileSystemHelper, $this->entityFactory); + return new WorkbookManager( + $workbook, + $optionsManager, + $worksheetManager, + $styleManager, + $fileSystemHelper, + $this->entityFactory, + $this + ); } /** @@ -59,11 +65,22 @@ class InternalFactory implements InternalFactoryInterface */ private function createWorksheetManager(StyleManager $styleManager) { - $stringsEscaper = $this->createStringsEscaper(); - $stringsHelper = $this->createStringHelper(); + $stringsEscaper = $this->helperFactory->createStringsEscaper(); + $stringsHelper = $this->helperFactory->createStringHelper(); return new WorksheetManager($styleManager, $stringsEscaper, $stringsHelper); + return new WorksheetManager($stringsEscaper, $stringsHelper, $this->entityFactory); + } + + /** + * @return SheetManager + */ + public function createSheetManager() + { + $stringHelper = $this->helperFactory->createStringHelper(); + + return new SheetManager($stringHelper); } /** @@ -73,6 +90,7 @@ class InternalFactory implements InternalFactoryInterface private function createStyleManager(OptionsManagerInterface $optionsManager) { $styleRegistry = $this->createStyleRegistry($optionsManager); + return new StyleManager($styleRegistry); } @@ -83,42 +101,7 @@ class InternalFactory implements InternalFactoryInterface private function createStyleRegistry(OptionsManagerInterface $optionsManager) { $defaultRowStyle = $optionsManager->getOption(Options::DEFAULT_ROW_STYLE); + return new StyleRegistry($defaultRowStyle); } - - /** - * @param OptionsManagerInterface $optionsManager - * @return FileSystemHelper - */ - public function createFileSystemHelper(OptionsManagerInterface $optionsManager) - { - $tempFolder = $optionsManager->getOption(Options::TEMP_FOLDER); - $zipHelper = $this->createZipHelper(); - - return new FileSystemHelper($tempFolder, $zipHelper); - } - - /** - * @return ZipHelper - */ - private function createZipHelper() - { - return new ZipHelper(); - } - - /** - * @return Escaper\ODS - */ - private function createStringsEscaper() - { - return Escaper\ODS::getInstance(); - } - - /** - * @return StringHelper - */ - private function createStringHelper() - { - return new StringHelper(); - } -} \ No newline at end of file +} diff --git a/src/Spout/Writer/ODS/Helper/BorderHelper.php b/src/Spout/Writer/ODS/Helper/BorderHelper.php index a619ffd..101bb4c 100644 --- a/src/Spout/Writer/ODS/Helper/BorderHelper.php +++ b/src/Spout/Writer/ODS/Helper/BorderHelper.php @@ -2,8 +2,8 @@ namespace Box\Spout\Writer\ODS\Helper; -use Box\Spout\Writer\Common\Entity\Style\BorderPart; use Box\Spout\Writer\Common\Entity\Style\Border; +use Box\Spout\Writer\Common\Entity\Style\BorderPart; /** * Class BorderHelper @@ -27,9 +27,9 @@ class BorderHelper * @var array */ protected static $widthMap = [ - Border::WIDTH_THIN => '0.75pt', + Border::WIDTH_THIN => '0.75pt', Border::WIDTH_MEDIUM => '1.75pt', - Border::WIDTH_THICK => '2.5pt', + Border::WIDTH_THICK => '2.5pt', ]; /** @@ -38,7 +38,7 @@ class BorderHelper * @var array */ protected static $styleMap = [ - Border::STYLE_SOLID => 'solid', + Border::STYLE_SOLID => 'solid', Border::STYLE_DASHED => 'dashed', Border::STYLE_DOTTED => 'dotted', Border::STYLE_DOUBLE => 'double', diff --git a/src/Spout/Writer/ODS/Helper/FileSystemHelper.php b/src/Spout/Writer/ODS/Helper/FileSystemHelper.php index 661a8ca..65ed815 100644 --- a/src/Spout/Writer/ODS/Helper/FileSystemHelper.php +++ b/src/Spout/Writer/ODS/Helper/FileSystemHelper.php @@ -2,9 +2,9 @@ namespace Box\Spout\Writer\ODS\Helper; +use Box\Spout\Writer\Common\Entity\Worksheet; use Box\Spout\Writer\Common\Helper\FileSystemWithRootFolderHelperInterface; use Box\Spout\Writer\Common\Helper\ZipHelper; -use Box\Spout\Writer\Common\Entity\Worksheet; use Box\Spout\Writer\ODS\Manager\Style\StyleManager; use Box\Spout\Writer\ODS\Manager\WorksheetManager; @@ -12,8 +12,6 @@ use Box\Spout\Writer\ODS\Manager\WorksheetManager; * 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 implements FileSystemWithRootFolderHelperInterface { @@ -70,8 +68,8 @@ class FileSystemHelper extends \Box\Spout\Common\Helper\FileSystemHelper impleme /** * 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 + * @return void */ public function createBaseFilesAndFolders() { @@ -86,20 +84,21 @@ class FileSystemHelper extends \Box\Spout\Common\Helper\FileSystemHelper impleme /** * Creates the folder that will be used as root * - * @return FileSystemHelper * @throws \Box\Spout\Common\Exception\IOException If unable to create the folder + * @return FileSystemHelper */ protected function createRootFolder() { $this->rootFolder = $this->createFolder($this->baseFolderRealPath, uniqid('ods')); + return $this; } /** * Creates the "META-INF" folder under the root folder as well as the "manifest.xml" file in it * - * @return FileSystemHelper * @throws \Box\Spout\Common\Exception\IOException If unable to create the folder or the "manifest.xml" file + * @return FileSystemHelper */ protected function createMetaInfoFolderAndFile() { @@ -113,12 +112,12 @@ class FileSystemHelper extends \Box\Spout\Common\Helper\FileSystemHelper impleme /** * 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 + * @return FileSystemHelper */ protected function createManifestFile() { - $manifestXmlFileContents = << @@ -137,20 +136,21 @@ EOD; * 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 + * @return FileSystemHelper */ 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 + * @return FileSystemHelper */ protected function createMetaFile() { @@ -176,12 +176,13 @@ EOD; /** * Creates the "mimetype" file under the root folder * - * @return FileSystemHelper * @throws \Box\Spout\Common\Exception\IOException If unable to create the file + * @return FileSystemHelper */ protected function createMimetypeFile() { $this->createFileWithContents($this->rootFolder, self::MIMETYPE_FILE_NAME, self::MIMETYPE); + return $this; } @@ -195,7 +196,7 @@ EOD; */ public function createContentFile($worksheetManager, $styleManager, $worksheets) { - $contentXmlFileContents = << EOD; @@ -253,10 +254,10 @@ EOD; public function deleteWorksheetTempFolder() { $this->deleteFolderRecursively($this->sheetsContentTempFolder); + return $this; } - /** * Creates the "styles.xml" file under the root folder * diff --git a/src/Spout/Writer/ODS/Manager/OptionsManager.php b/src/Spout/Writer/ODS/Manager/OptionsManager.php index 4a83428..4d29928 100644 --- a/src/Spout/Writer/ODS/Manager/OptionsManager.php +++ b/src/Spout/Writer/ODS/Manager/OptionsManager.php @@ -2,15 +2,13 @@ namespace Box\Spout\Writer\ODS\Manager; -use Box\Spout\Writer\Common\Entity\Options; -use Box\Spout\Writer\Common\Manager\OptionsManagerAbstract; +use Box\Spout\Common\Manager\OptionsManagerAbstract; use Box\Spout\Writer\Common\Creator\Style\StyleBuilder; +use Box\Spout\Writer\Common\Entity\Options; /** * Class OptionsManager * ODS Writer options manager - * - * @package Box\Spout\Writer\ODS\Manager */ class OptionsManager extends OptionsManagerAbstract { @@ -28,7 +26,7 @@ class OptionsManager extends OptionsManagerAbstract } /** - * @inheritdoc + * {@inheritdoc} */ protected function getSupportedOptions() { @@ -40,7 +38,7 @@ class OptionsManager extends OptionsManagerAbstract } /** - * @inheritdoc + * {@inheritdoc} */ protected function setDefaultOptions() { @@ -48,4 +46,4 @@ class OptionsManager extends OptionsManagerAbstract $this->setOption(Options::DEFAULT_ROW_STYLE, $this->styleBuilder->build()); $this->setOption(Options::SHOULD_CREATE_NEW_SHEETS_AUTOMATICALLY, true); } -} \ No newline at end of file +} diff --git a/src/Spout/Writer/ODS/Manager/Style/StyleManager.php b/src/Spout/Writer/ODS/Manager/Style/StyleManager.php index 0a9519e..c658b18 100644 --- a/src/Spout/Writer/ODS/Manager/Style/StyleManager.php +++ b/src/Spout/Writer/ODS/Manager/Style/StyleManager.php @@ -8,8 +8,6 @@ use Box\Spout\Writer\ODS\Helper\BorderHelper; /** * Class StyleManager * Manages styles to be applied to a cell - * - * @package Box\Spout\Writer\ODS\Manager\Style */ class StyleManager extends \Box\Spout\Writer\Common\Manager\Style\StyleManager { @@ -24,7 +22,7 @@ class StyleManager extends \Box\Spout\Writer\Common\Manager\Style\StyleManager */ public function getStylesXMLFileContent($numWorksheets) { - $content = << EOD; @@ -34,7 +32,7 @@ EOD; $content .= $this->getAutomaticStylesSectionContent($numWorksheets); $content .= $this->getMasterStylesSectionContent($numWorksheets); - $content .= << EOD; @@ -132,7 +130,6 @@ EOD; return $content; } - /** * Returns the contents of the "" section, inside "content.xml" file. * @@ -163,7 +160,7 @@ EOD; $content .= $this->getStyleSectionContent($style); } - $content .= << diff --git a/src/Spout/Writer/ODS/Manager/Style/StyleRegistry.php b/src/Spout/Writer/ODS/Manager/Style/StyleRegistry.php index 89c3af0..8d4f504 100644 --- a/src/Spout/Writer/ODS/Manager/Style/StyleRegistry.php +++ b/src/Spout/Writer/ODS/Manager/Style/StyleRegistry.php @@ -7,8 +7,6 @@ use Box\Spout\Writer\Common\Entity\Style\Style; /** * Class StyleRegistry * Registry for all used styles - * - * @package Box\Spout\Writer\ODS\Manager\Style */ class StyleRegistry extends \Box\Spout\Writer\Common\Manager\Style\StyleRegistry { diff --git a/src/Spout/Writer/ODS/Manager/WorkbookManager.php b/src/Spout/Writer/ODS/Manager/WorkbookManager.php index c95d90b..367c281 100644 --- a/src/Spout/Writer/ODS/Manager/WorkbookManager.php +++ b/src/Spout/Writer/ODS/Manager/WorkbookManager.php @@ -10,8 +10,6 @@ use Box\Spout\Writer\ODS\Manager\Style\StyleManager; /** * Class WorkbookManager * ODS workbook manager, providing the interfaces to work with workbook. - * - * @package Box\Spout\Writer\ODS\Manager */ class WorkbookManager extends WorkbookManagerAbstract { @@ -45,6 +43,7 @@ class WorkbookManager extends WorkbookManagerAbstract public function getWorksheetFilePath(Sheet $sheet) { $sheetsContentTempFolder = $this->fileSystemHelper->getSheetsContentTempFolder(); + return $sheetsContentTempFolder . '/sheet' . $sheet->getIndex() . '.xml'; } @@ -65,4 +64,4 @@ class WorkbookManager extends WorkbookManagerAbstract ->createStylesFile($this->styleManager, $numWorksheets) ->zipRootFolderAndCopyToStream($finalFilePointer); } -} \ No newline at end of file +} diff --git a/src/Spout/Writer/ODS/Manager/WorksheetManager.php b/src/Spout/Writer/ODS/Manager/WorksheetManager.php index 642899e..a9f096b 100644 --- a/src/Spout/Writer/ODS/Manager/WorksheetManager.php +++ b/src/Spout/Writer/ODS/Manager/WorksheetManager.php @@ -5,7 +5,9 @@ namespace Box\Spout\Writer\ODS\Manager; use Box\Spout\Common\Exception\InvalidArgumentException; use Box\Spout\Common\Exception\IOException; use Box\Spout\Common\Helper\StringHelper; +use Box\Spout\Writer\Common\Creator\EntityFactory; use Box\Spout\Writer\Common\Entity\Cell; +use Box\Spout\Writer\Common\Entity\Style\Style; use Box\Spout\Writer\Common\Entity\Row; use Box\Spout\Writer\Common\Entity\Worksheet; use Box\Spout\Writer\Common\Manager\WorksheetManagerInterface; @@ -14,42 +16,51 @@ use Box\Spout\Writer\ODS\Manager\Style\StyleManager; /** * Class WorksheetManager * ODS worksheet manager, providing the interfaces to work with ODS worksheets. - * - * @package Box\Spout\Writer\ODS\Manager */ class WorksheetManager implements WorksheetManagerInterface { - /** @var \Box\Spout\Common\Escaper\ODS Strings escaper */ + /** @var \Box\Spout\Common\Helper\Escaper\ODS Strings escaper */ private $stringsEscaper; /** @var StringHelper String helper */ private $stringHelper; + /** @var EntityFactory Factory to create entities */ + private $entityFactory; + /** @var StyleManager Manages styles */ private $styleManager; /** * WorksheetManager constructor. + * + * @param \Box\Spout\Common\Helper\Escaper\ODS $stringsEscaper * @param StyleManager $styleManager * @param \Box\Spout\Common\Escaper\ODS $stringsEscaper * @param StringHelper $stringHelper + * @param EntityFactory $entityFactory */ public function __construct( StyleManager $styleManager, \Box\Spout\Common\Escaper\ODS $stringsEscaper, StringHelper $stringHelper) { + \Box\Spout\Common\Helper\Escaper\ODS $stringsEscaper, + StringHelper $stringHelper, + EntityFactory $entityFactory + ) { $this->stringsEscaper = $stringsEscaper; $this->stringHelper = $stringHelper; $this->styleManager = $styleManager; + $this->entityFactory = $entityFactory; } /** * Prepares the worksheet to accept data * * @param Worksheet $worksheet The worksheet to start - * @return void * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing + * @return void */ public function startSheet(Worksheet $worksheet) { @@ -63,8 +74,8 @@ class WorksheetManager implements WorksheetManagerInterface * Checks if the sheet has been sucessfully created. Throws an exception if not. * * @param bool|resource $sheetFilePointer Pointer to the sheet data file or FALSE if unable to open the file - * @return void * @throws IOException If the sheet data file cannot be opened for writing + * @return void */ private function throwIfSheetFilePointerIsNotAvailable($sheetFilePointer) { @@ -100,6 +111,7 @@ class WorksheetManager implements WorksheetManagerInterface * * @throws IOException If the data cannot be written * @throws InvalidArgumentException If a cell value's type is not supported + * @return void */ public function addRow(Worksheet $worksheet, Row $row) { @@ -154,8 +166,8 @@ class WorksheetManager implements WorksheetManagerInterface * @param Cell $cell The cell 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 + * @return string The cell XML content */ protected function getCellXML(Cell $cell, $styleIndex, $numTimesValueRepeated) { @@ -174,15 +186,15 @@ class WorksheetManager implements WorksheetManagerInterface } $data .= ''; - } else if ($cell->isBoolean()) { + } elseif ($cell->isBoolean()) { $data .= ' office:value-type="boolean" calcext:value-type="boolean" office:boolean-value="' . $cell->getValue() . '">'; $data .= '' . $cell->getValue() . ''; $data .= ''; - } else if ($cell->isNumeric()) { + } elseif ($cell->isNumeric()) { $data .= ' office:value-type="float" calcext:value-type="float" office:value="' . $cell->getValue() . '">'; $data .= '' . $cell->getValue() . ''; $data .= ''; - } else if ($cell->isEmpty()) { + } elseif ($cell->isEmpty()) { $data .= '/>'; } else { throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cell->getValue())); @@ -207,4 +219,4 @@ class WorksheetManager implements WorksheetManagerInterface fclose($worksheetFilePointer); } -} \ No newline at end of file +} diff --git a/src/Spout/Writer/ODS/Writer.php b/src/Spout/Writer/ODS/Writer.php index e753c79..9a05cf9 100644 --- a/src/Spout/Writer/ODS/Writer.php +++ b/src/Spout/Writer/ODS/Writer.php @@ -8,8 +8,6 @@ use Box\Spout\Writer\WriterMultiSheetsAbstract; /** * Class Writer * This class provides base support to write data to ODS files - * - * @package Box\Spout\Writer\ODS */ class Writer extends WriterMultiSheetsAbstract { @@ -22,14 +20,15 @@ class Writer extends WriterMultiSheetsAbstract * * @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 + * @return Writer */ public function setTempFolder($tempFolder) { $this->throwIfWriterAlreadyOpened('Writer must be configured before opening it.'); $this->optionsManager->setOption(Options::TEMP_FOLDER, $tempFolder); + return $this; } } diff --git a/src/Spout/Writer/WriterAbstract.php b/src/Spout/Writer/WriterAbstract.php index b483997..52c18f7 100644 --- a/src/Spout/Writer/WriterAbstract.php +++ b/src/Spout/Writer/WriterAbstract.php @@ -2,16 +2,16 @@ namespace Box\Spout\Writer; +use Box\Spout\Common\Creator\HelperFactory; use Box\Spout\Common\Exception\InvalidArgumentException; use Box\Spout\Common\Exception\IOException; use Box\Spout\Common\Exception\SpoutException; -use Box\Spout\Common\Helper\FileSystemHelper; use Box\Spout\Common\Helper\GlobalFunctionsHelper; use Box\Spout\Writer\Common\Entity\Cell; +use Box\Spout\Common\Manager\OptionsManagerInterface; use Box\Spout\Writer\Common\Entity\Options; use Box\Spout\Writer\Common\Entity\Row; use Box\Spout\Writer\Common\Entity\Style\Style; -use Box\Spout\Writer\Common\Manager\OptionsManagerInterface; use Box\Spout\Writer\Common\Manager\Style\StyleMerger; use Box\Spout\Writer\Exception\WriterAlreadyOpenedException; use Box\Spout\Writer\Exception\WriterNotOpenedException; @@ -19,7 +19,6 @@ use Box\Spout\Writer\Exception\WriterNotOpenedException; /** * Class WriterAbstract * - * @package Box\Spout\Writer * @abstract */ abstract class WriterAbstract implements WriterInterface @@ -36,6 +35,9 @@ abstract class WriterAbstract implements WriterInterface /** @var GlobalFunctionsHelper Helper to work with global functions */ protected $globalFunctionsHelper; + /** @var HelperFactory $helperFactory */ + protected $helperFactory; + /** @var OptionsManagerInterface Writer options manager */ protected $optionsManager; @@ -49,23 +51,27 @@ abstract class WriterAbstract implements WriterInterface * @param OptionsManagerInterface $optionsManager * @param StyleMerger $styleMerger * @param GlobalFunctionsHelper $globalFunctionsHelper + * @param HelperFactory $helperFactory */ public function __construct( OptionsManagerInterface $optionsManager, StyleMerger $styleMerger, - GlobalFunctionsHelper $globalFunctionsHelper - ) - { + GlobalFunctionsHelper $globalFunctionsHelper, + HelperFactory $helperFactory + ) { $this->optionsManager = $optionsManager; $this->styleMerger = $styleMerger; $this->globalFunctionsHelper = $globalFunctionsHelper; + $this->helperFactory = $helperFactory; + + $this->resetRowStyleToDefault(); } /** * Opens the streamer and makes it ready to accept data. * - * @return void * @throws \Box\Spout\Common\Exception\IOException If the writer cannot be opened + * @return void */ abstract protected function openWriter(); @@ -150,8 +156,8 @@ abstract class WriterAbstract implements WriterInterface * Checks if the pointer to the file/stream to write to is available. * Will throw an exception if not available. * - * @return void * @throws \Box\Spout\Common\Exception\IOException If the pointer is not available + * @return void */ protected function throwIfFilePointerIsNotAvailable() { @@ -165,8 +171,8 @@ abstract class WriterAbstract implements WriterInterface * 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. + * @return void */ protected function throwIfWriterAlreadyOpened($message) { @@ -297,7 +303,7 @@ abstract class WriterAbstract implements WriterInterface // remove output file if it was created if ($this->globalFunctionsHelper->file_exists($this->outputFilePath)) { $outputFolderPath = dirname($this->outputFilePath); - $fileSystemHelper = new FileSystemHelper($outputFolderPath); + $fileSystemHelper = $this->helperFactory->createFileSystemHelper($outputFolderPath); $fileSystemHelper->deleteFile($this->outputFilePath); } } diff --git a/src/Spout/Writer/WriterFactory.php b/src/Spout/Writer/WriterFactory.php index b10db44..8395b29 100644 --- a/src/Spout/Writer/WriterFactory.php +++ b/src/Spout/Writer/WriterFactory.php @@ -2,11 +2,11 @@ namespace Box\Spout\Writer; +use Box\Spout\Common\Creator\HelperFactory; use Box\Spout\Common\Exception\UnsupportedTypeException; use Box\Spout\Common\Helper\GlobalFunctionsHelper; use Box\Spout\Common\Type; use Box\Spout\Writer\Common\Creator\EntityFactory; -use Box\Spout\Writer\Common\Creator\ManagerFactory; use Box\Spout\Writer\Common\Creator\Style\StyleBuilder; use Box\Spout\Writer\Common\Manager\Style\StyleMerger; @@ -14,8 +14,6 @@ use Box\Spout\Writer\Common\Manager\Style\StyleMerger; * Class WriterFactory * This factory is used to create writers, based on the type of the file to be read. * It supports CSV, XLSX and ODS formats. - * - * @package Box\Spout\Writer */ class WriterFactory { @@ -24,8 +22,8 @@ class WriterFactory * * @api * @param string $writerType Type of the writer to instantiate - * @return WriterInterface * @throws \Box\Spout\Common\Exception\UnsupportedTypeException + * @return WriterInterface */ public static function create($writerType) { @@ -47,7 +45,9 @@ class WriterFactory $styleMerger = new StyleMerger(); $globalFunctionsHelper = new GlobalFunctionsHelper(); - return new CSV\Writer($optionsManager, $styleMerger, $globalFunctionsHelper); + $helperFactory = new HelperFactory(); + + return new CSV\Writer($optionsManager, $styleMerger, $globalFunctionsHelper, $helperFactory); } /** @@ -60,10 +60,10 @@ class WriterFactory $styleMerger = new StyleMerger(); $globalFunctionsHelper = new GlobalFunctionsHelper(); - $entityFactory = new EntityFactory(new ManagerFactory()); - $internalFactory = new XLSX\Creator\InternalFactory($entityFactory); + $helperFactory = new XLSX\Creator\HelperFactory(); + $managerFactory = new XLSX\Creator\ManagerFactory(new EntityFactory(), $helperFactory); - return new XLSX\Writer($optionsManager, $styleMerger, $globalFunctionsHelper, $internalFactory); + return new XLSX\Writer($optionsManager, $styleMerger, $globalFunctionsHelper, $helperFactory, $managerFactory); } /** @@ -76,9 +76,9 @@ class WriterFactory $styleMerger = new StyleMerger(); $globalFunctionsHelper = new GlobalFunctionsHelper(); - $entityFactory = new EntityFactory(new ManagerFactory()); - $internalFactory = new ODS\Creator\InternalFactory($entityFactory); + $helperFactory = new ODS\Creator\HelperFactory(); + $managerFactory = new ODS\Creator\ManagerFactory(new EntityFactory(), $helperFactory); - return new ODS\Writer($optionsManager, $styleMerger, $globalFunctionsHelper, $internalFactory); + return new ODS\Writer($optionsManager, $styleMerger, $globalFunctionsHelper, $helperFactory, $managerFactory); } } diff --git a/src/Spout/Writer/WriterInterface.php b/src/Spout/Writer/WriterInterface.php index e1fdc3e..3b6890a 100644 --- a/src/Spout/Writer/WriterInterface.php +++ b/src/Spout/Writer/WriterInterface.php @@ -7,8 +7,6 @@ use Box\Spout\Writer\Common\Entity\Row; /** * Interface WriterInterface - * - * @package Box\Spout\Writer */ interface WriterInterface { @@ -17,8 +15,8 @@ interface WriterInterface * By using this method, the data will be written to a file. * * @param string $outputFilePath Path of the output file that will contain the data + * @throws \Box\Spout\Common\Exception\IOException If the writer cannot be opened or if the given path is not writable * @return WriterInterface - * @throws IOException If the writer cannot be opened or if the given path is not writable */ public function openToFile($outputFilePath); @@ -26,10 +24,9 @@ interface WriterInterface * Initializes the writer and opens it to accept data. * By using this method, the data will be outputted directly to the browser. * - * @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 + * @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 + * @throws \Box\Spout\Common\Exception\IOException If the writer cannot be opened * @return WriterInterface - * @throws IOException If the writer cannot be opened */ public function openToBrowser($outputFileName); @@ -57,6 +54,7 @@ interface WriterInterface * @throws \Box\Spout\Common\Exception\InvalidArgumentException If the input param is not valid * @throws \Box\Spout\Writer\Exception\WriterNotOpenedException If the writer has not been opened yet * @throws \Box\Spout\Common\Exception\IOException If unable to write data + * @return WriterInterface */ public function addRows(array $rows); diff --git a/src/Spout/Writer/WriterMultiSheetsAbstract.php b/src/Spout/Writer/WriterMultiSheetsAbstract.php index 67917db..8fd1c2e 100644 --- a/src/Spout/Writer/WriterMultiSheetsAbstract.php +++ b/src/Spout/Writer/WriterMultiSheetsAbstract.php @@ -3,28 +3,27 @@ namespace Box\Spout\Writer; use Box\Spout\Common\Helper\GlobalFunctionsHelper; -use Box\Spout\Writer\Common\Entity\Sheet; -use Box\Spout\Writer\Common\Manager\OptionsManagerInterface; +use Box\Spout\Common\Manager\OptionsManagerInterface; +use Box\Spout\Writer\Common\Creator\ManagerFactoryInterface; use Box\Spout\Writer\Common\Entity\Options; +use Box\Spout\Writer\Common\Entity\Sheet; use Box\Spout\Writer\Common\Entity\Row; use Box\Spout\Writer\Common\Entity\Worksheet; use Box\Spout\Writer\Common\Manager\Style\StyleMerger; -use Box\Spout\Writer\Exception\SheetNotFoundException; -use Box\Spout\Writer\Exception\WriterNotOpenedException; -use Box\Spout\Writer\Common\Creator\InternalFactoryInterface; use Box\Spout\Writer\Common\Manager\WorkbookManagerInterface; +use Box\Spout\Writer\Exception\SheetNotFoundException; +use Box\Spout\Writer\Exception\WriterAlreadyOpenedException; +use Box\Spout\Writer\Exception\WriterNotOpenedException; /** * Class WriterMultiSheetsAbstract * - * @package Box\Spout\Writer * @abstract */ abstract class WriterMultiSheetsAbstract extends WriterAbstract { - - /** @var InternalFactoryInterface */ - private $internalFactory; + /** @var ManagerFactoryInterface */ + private $managerFactory; /** @var WorkbookManagerInterface */ private $workbookManager; @@ -33,16 +32,18 @@ abstract class WriterMultiSheetsAbstract extends WriterAbstract * @param OptionsManagerInterface $optionsManager * @param StyleMerger $styleMerger * @param GlobalFunctionsHelper $globalFunctionsHelper - * @param InternalFactoryInterface $internalFactory + * @param HelperFactory $helperFactory + * @param ManagerFactoryInterface $managerFactory */ public function __construct( OptionsManagerInterface $optionsManager, StyleMerger $styleMerger, GlobalFunctionsHelper $globalFunctionsHelper, - InternalFactoryInterface $internalFactory) - { - parent::__construct($optionsManager, $styleMerger, $globalFunctionsHelper); - $this->internalFactory = $internalFactory; + HelperFactory $helperFactory, + ManagerFactoryInterface $managerFactory + ) { + parent::__construct($optionsManager, $styleMerger, $globalFunctionsHelper, $helperFactory); + $this->managerFactory = $managerFactory; } /** @@ -51,27 +52,28 @@ abstract class WriterMultiSheetsAbstract extends WriterAbstract * * @api * @param bool $shouldCreateNewSheetsAutomatically Whether new sheets should be automatically created when the max rows limit per sheet is reached - * @return WriterMultiSheetsAbstract * @throws WriterAlreadyOpenedException If the writer was already opened + * @return WriterMultiSheetsAbstract */ public function setShouldCreateNewSheetsAutomatically($shouldCreateNewSheetsAutomatically) { $this->throwIfWriterAlreadyOpened('Writer must be configured before opening it.'); $this->optionsManager->setOption(Options::SHOULD_CREATE_NEW_SHEETS_AUTOMATICALLY, $shouldCreateNewSheetsAutomatically); + 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 + * @return void */ protected function openWriter() { if (!$this->workbookManager) { - $this->workbookManager = $this->internalFactory->createWorkbookManager($this->optionsManager); + $this->workbookManager = $this->managerFactory->createWorkbookManager($this->optionsManager); $this->workbookManager->addNewSheetAndMakeItCurrent(); } } @@ -80,8 +82,8 @@ abstract class WriterMultiSheetsAbstract extends WriterAbstract * Returns all the workbook's sheets * * @api - * @return Sheet[] All the workbook's sheets * @throws WriterNotOpenedException If the writer has not been opened yet + * @return Sheet[] All the workbook's sheets */ public function getSheets() { @@ -102,8 +104,8 @@ abstract class WriterMultiSheetsAbstract extends WriterAbstract * Creates a new sheet and make it the current sheet. The data will now be written to this sheet. * * @api - * @return Sheet The created sheet * @throws WriterNotOpenedException If the writer has not been opened yet + * @return Sheet The created sheet */ public function addNewSheetAndMakeItCurrent() { @@ -117,12 +119,13 @@ abstract class WriterMultiSheetsAbstract extends WriterAbstract * Returns the current sheet * * @api - * @return Sheet The current sheet * @throws WriterNotOpenedException If the writer has not been opened yet + * @return Sheet The current sheet */ public function getCurrentSheet() { $this->throwIfWorkbookIsNotAvailable(); + return $this->workbookManager->getCurrentWorksheet()->getExternalSheet(); } @@ -132,9 +135,9 @@ abstract class WriterMultiSheetsAbstract extends WriterAbstract * * @api * @param Sheet $sheet The sheet to set as current - * @return void * @throws WriterNotOpenedException If the writer has not been opened yet * @throws SheetNotFoundException If the given sheet does not exist in the workbook + * @return void */ public function setCurrentSheet($sheet) { @@ -145,8 +148,8 @@ abstract class WriterMultiSheetsAbstract extends WriterAbstract /** * Checks if the workbook has been created. Throws an exception if not created yet. * - * @return void * @throws WriterNotOpenedException If the workbook is not created yet + * @return void */ protected function throwIfWorkbookIsNotAvailable() { @@ -164,6 +167,7 @@ abstract class WriterMultiSheetsAbstract extends WriterAbstract * @return void * @throws WriterNotOpenedException If the book is not created yet * @throws \Box\Spout\Common\Exception\IOException If unable to write data + * @return void */ protected function addRowToWriter(Row $row) { @@ -183,4 +187,3 @@ abstract class WriterMultiSheetsAbstract extends WriterAbstract } } } - diff --git a/src/Spout/Writer/XLSX/Creator/HelperFactory.php b/src/Spout/Writer/XLSX/Creator/HelperFactory.php new file mode 100644 index 0000000..8eea878 --- /dev/null +++ b/src/Spout/Writer/XLSX/Creator/HelperFactory.php @@ -0,0 +1,57 @@ +getOption(Options::TEMP_FOLDER); + $zipHelper = $this->createZipHelper($entityFactory); + $escaper = $this->createStringsEscaper(); + + return new FileSystemHelper($tempFolder, $zipHelper, $escaper); + } + + /** + * @param EntityFactory $entityFactory + * @return ZipHelper + */ + private function createZipHelper(EntityFactory $entityFactory) + { + return new ZipHelper($entityFactory); + } + + /** + * @return Escaper\XLSX + */ + public function createStringsEscaper() + { + return new Escaper\XLSX(); + } + + /** + * @return StringHelper + */ + public function createStringHelper() + { + return new StringHelper(); + } +} diff --git a/src/Spout/Writer/XLSX/Creator/InternalFactory.php b/src/Spout/Writer/XLSX/Creator/ManagerFactory.php similarity index 58% rename from src/Spout/Writer/XLSX/Creator/InternalFactory.php rename to src/Spout/Writer/XLSX/Creator/ManagerFactory.php index 9fd312a..b8d1f07 100644 --- a/src/Spout/Writer/XLSX/Creator/InternalFactory.php +++ b/src/Spout/Writer/XLSX/Creator/ManagerFactory.php @@ -2,14 +2,11 @@ namespace Box\Spout\Writer\XLSX\Creator; -use Box\Spout\Common\Escaper; -use Box\Spout\Common\Helper\StringHelper; +use Box\Spout\Common\Manager\OptionsManagerInterface; use Box\Spout\Writer\Common\Creator\EntityFactory; -use Box\Spout\Writer\Common\Creator\InternalFactoryInterface; +use Box\Spout\Writer\Common\Creator\ManagerFactoryInterface; use Box\Spout\Writer\Common\Entity\Options; -use Box\Spout\Writer\Common\Helper\ZipHelper; -use Box\Spout\Writer\Common\Manager\OptionsManagerInterface; -use Box\Spout\Writer\XLSX\Helper\FileSystemHelper; +use Box\Spout\Writer\Common\Manager\SheetManager; use Box\Spout\Writer\XLSX\Manager\SharedStringsManager; use Box\Spout\Writer\XLSX\Manager\Style\StyleManager; use Box\Spout\Writer\XLSX\Manager\Style\StyleRegistry; @@ -17,24 +14,25 @@ use Box\Spout\Writer\XLSX\Manager\WorkbookManager; use Box\Spout\Writer\XLSX\Manager\WorksheetManager; /** - * Class InternalFactory - * Factory for all useful types of objects needed by the XLSX Writer - * - * @package Box\Spout\Writer\XLSX\Creator + * Class ManagerFactory + * Factory for managers needed by the XLSX Writer */ -class InternalFactory implements InternalFactoryInterface +class ManagerFactory implements ManagerFactoryInterface { /** @var EntityFactory */ - private $entityFactory; + protected $entityFactory; + + /** @var HelperFactory $helperFactory */ + protected $helperFactory; /** - * InternalFactory constructor. - * * @param EntityFactory $entityFactory + * @param HelperFactory $helperFactory */ - public function __construct(EntityFactory $entityFactory) + public function __construct(EntityFactory $entityFactory, HelperFactory $helperFactory) { $this->entityFactory = $entityFactory; + $this->helperFactory = $helperFactory; } /** @@ -45,7 +43,7 @@ class InternalFactory implements InternalFactoryInterface { $workbook = $this->entityFactory->createWorkbook(); - $fileSystemHelper = $this->createFileSystemHelper($optionsManager); + $fileSystemHelper = $this->helperFactory->createSpecificFileSystemHelper($optionsManager, $this->entityFactory); $fileSystemHelper->createBaseFilesAndFolders(); $xlFolder = $fileSystemHelper->getXlFolder(); @@ -54,7 +52,15 @@ class InternalFactory implements InternalFactoryInterface $styleManager = $this->createStyleManager($optionsManager); $worksheetManager = $this->createWorksheetManager($optionsManager, $styleManager, $sharedStringsManager); - return new WorkbookManager($workbook, $optionsManager, $worksheetManager, $styleManager, $fileSystemHelper, $this->entityFactory); + return new WorkbookManager( + $workbook, + $optionsManager, + $worksheetManager, + $styleManager, + $fileSystemHelper, + $this->entityFactory, + $this + ); } /** @@ -67,12 +73,21 @@ class InternalFactory implements InternalFactoryInterface OptionsManagerInterface $optionsManager, StyleManager $styleManager, SharedStringsManager $sharedStringsManager - ) - { - $stringsEscaper = $this->createStringsEscaper(); - $stringsHelper = $this->createStringHelper(); + ) { + $stringsEscaper = $this->helperFactory->createStringsEscaper(); + $stringsHelper = $this->helperFactory->createStringHelper(); - return new WorksheetManager($optionsManager, $styleManager, $sharedStringsManager, $stringsEscaper, $stringsHelper); + return new WorksheetManager($optionsManager, $styleManager, $sharedStringsManager, $stringsEscaper, $stringsHelper, $this->entityFactory); + } + + /** + * @return SheetManager + */ + public function createSheetManager() + { + $stringHelper = $this->helperFactory->createStringHelper(); + + return new SheetManager($stringHelper); } /** @@ -82,6 +97,7 @@ class InternalFactory implements InternalFactoryInterface private function createStyleManager(OptionsManagerInterface $optionsManager) { $styleRegistry = $this->createStyleRegistry($optionsManager); + return new StyleManager($styleRegistry); } @@ -92,6 +108,7 @@ class InternalFactory implements InternalFactoryInterface private function createStyleRegistry(OptionsManagerInterface $optionsManager) { $defaultRowStyle = $optionsManager->getOption(Options::DEFAULT_ROW_STYLE); + return new StyleRegistry($defaultRowStyle); } @@ -101,43 +118,8 @@ class InternalFactory implements InternalFactoryInterface */ private function createSharedStringsManager($xlFolder) { - $stringEscaper = $this->createStringsEscaper(); + $stringEscaper = $this->helperFactory->createStringsEscaper(); + return new SharedStringsManager($xlFolder, $stringEscaper); } - - /** - * @param OptionsManagerInterface $optionsManager - * @return FileSystemHelper - */ - private function createFileSystemHelper(OptionsManagerInterface $optionsManager) - { - $tempFolder = $optionsManager->getOption(Options::TEMP_FOLDER); - $zipHelper = $this->createZipHelper(); - - return new FileSystemHelper($tempFolder, $zipHelper); - } - - /** - * @return ZipHelper - */ - private function createZipHelper() - { - return new ZipHelper(); - } - - /** - * @return Escaper\XLSX - */ - private function createStringsEscaper() - { - return Escaper\XLSX::getInstance(); - } - - /** - * @return StringHelper - */ - private function createStringHelper() - { - return new StringHelper(); - } -} \ No newline at end of file +} diff --git a/src/Spout/Writer/XLSX/Helper/BorderHelper.php b/src/Spout/Writer/XLSX/Helper/BorderHelper.php index 1b0183a..56c1d82 100644 --- a/src/Spout/Writer/XLSX/Helper/BorderHelper.php +++ b/src/Spout/Writer/XLSX/Helper/BorderHelper.php @@ -9,29 +9,29 @@ class BorderHelper { public static $xlsxStyleMap = [ Border::STYLE_SOLID => [ - Border::WIDTH_THIN => 'thin', + Border::WIDTH_THIN => 'thin', Border::WIDTH_MEDIUM => 'medium', - Border::WIDTH_THICK => 'thick' + Border::WIDTH_THICK => 'thick', ], Border::STYLE_DOTTED => [ - Border::WIDTH_THIN => 'dotted', + Border::WIDTH_THIN => 'dotted', Border::WIDTH_MEDIUM => 'dotted', - Border::WIDTH_THICK => 'dotted', + Border::WIDTH_THICK => 'dotted', ], Border::STYLE_DASHED => [ - Border::WIDTH_THIN => 'dashed', + Border::WIDTH_THIN => 'dashed', Border::WIDTH_MEDIUM => 'mediumDashed', - Border::WIDTH_THICK => 'mediumDashed', + Border::WIDTH_THICK => 'mediumDashed', ], Border::STYLE_DOUBLE => [ - Border::WIDTH_THIN => 'double', + Border::WIDTH_THIN => 'double', Border::WIDTH_MEDIUM => 'double', - Border::WIDTH_THICK => 'double', + Border::WIDTH_THICK => 'double', ], Border::STYLE_NONE => [ - Border::WIDTH_THIN => 'none', + Border::WIDTH_THIN => 'none', Border::WIDTH_MEDIUM => 'none', - Border::WIDTH_THICK => 'none', + Border::WIDTH_THICK => 'none', ], ]; diff --git a/src/Spout/Writer/XLSX/Helper/FileSystemHelper.php b/src/Spout/Writer/XLSX/Helper/FileSystemHelper.php index e640d09..8bba670 100644 --- a/src/Spout/Writer/XLSX/Helper/FileSystemHelper.php +++ b/src/Spout/Writer/XLSX/Helper/FileSystemHelper.php @@ -11,8 +11,6 @@ use Box\Spout\Writer\XLSX\Manager\Style\StyleManager; * Class FileSystemHelper * This class provides helper functions to help with the file system operations * like files/folders creation & deletion for XLSX files - * - * @package Box\Spout\Writer\XLSX\Helper */ class FileSystemHelper extends \Box\Spout\Common\Helper\FileSystemHelper implements FileSystemWithRootFolderHelperInterface { @@ -34,6 +32,9 @@ class FileSystemHelper extends \Box\Spout\Common\Helper\FileSystemHelper impleme /** @var ZipHelper Helper to perform tasks with Zip archive */ private $zipHelper; + /** @var \Box\Spout\Common\Helper\Escaper\XLSX Used to escape XML data */ + private $escaper; + /** @var string Path to the root folder inside the temp folder where the files to create the XLSX will be stored */ private $rootFolder; @@ -55,11 +56,13 @@ class FileSystemHelper extends \Box\Spout\Common\Helper\FileSystemHelper impleme /** * @param string $baseFolderPath The path of the base folder where all the I/O can occur * @param ZipHelper $zipHelper Helper to perform tasks with Zip archive + * @param \Box\Spout\Common\Helper\Escaper\XLSX $escaper Used to escape XML data */ - public function __construct($baseFolderPath, $zipHelper) + public function __construct($baseFolderPath, $zipHelper, $escaper) { parent::__construct($baseFolderPath); $this->zipHelper = $zipHelper; + $this->escaper = $escaper; } /** @@ -89,8 +92,8 @@ class FileSystemHelper extends \Box\Spout\Common\Helper\FileSystemHelper impleme /** * Creates all the folders needed to create a XLSX file, as well as the files that won't change. * - * @return void * @throws \Box\Spout\Common\Exception\IOException If unable to create at least one of the base folders + * @return void */ public function createBaseFilesAndFolders() { @@ -104,20 +107,21 @@ class FileSystemHelper extends \Box\Spout\Common\Helper\FileSystemHelper impleme /** * Creates the folder that will be used as root * - * @return FileSystemHelper * @throws \Box\Spout\Common\Exception\IOException If unable to create the folder + * @return FileSystemHelper */ private function createRootFolder() { $this->rootFolder = $this->createFolder($this->baseFolderRealPath, uniqid('xlsx', true)); + return $this; } /** * Creates the "_rels" folder under the root folder as well as the ".rels" file in it * - * @return FileSystemHelper * @throws \Box\Spout\Common\Exception\IOException If unable to create the folder or the ".rels" file + * @return FileSystemHelper */ private function createRelsFolderAndFile() { @@ -131,12 +135,12 @@ class FileSystemHelper extends \Box\Spout\Common\Helper\FileSystemHelper impleme /** * Creates the ".rels" file under the "_rels" folder (under root) * - * @return FileSystemHelper * @throws \Box\Spout\Common\Exception\IOException If unable to create the file + * @return FileSystemHelper */ private function createRelsFile() { - $relsFileContents = << @@ -153,8 +157,8 @@ EOD; /** * Creates the "docProps" folder under the root folder as well as the "app.xml" and "core.xml" files in it * - * @return FileSystemHelper * @throws \Box\Spout\Common\Exception\IOException If unable to create the folder or one of the files + * @return FileSystemHelper */ private function createDocPropsFolderAndFiles() { @@ -169,8 +173,8 @@ EOD; /** * Creates the "app.xml" file under the "docProps" folder * - * @return FileSystemHelper * @throws \Box\Spout\Common\Exception\IOException If unable to create the file + * @return FileSystemHelper */ private function createAppXmlFile() { @@ -191,8 +195,8 @@ EOD; /** * Creates the "core.xml" file under the "docProps" folder * - * @return FileSystemHelper * @throws \Box\Spout\Common\Exception\IOException If unable to create the file + * @return FileSystemHelper */ private function createCoreXmlFile() { @@ -214,8 +218,8 @@ EOD; /** * Creates the "xl" folder under the root folder as well as its subfolders * - * @return FileSystemHelper * @throws \Box\Spout\Common\Exception\IOException If unable to create at least one of the folders + * @return FileSystemHelper */ private function createXlFolderAndSubFolders() { @@ -229,24 +233,26 @@ EOD; /** * Creates the "_rels" folder under the "xl" folder * - * @return FileSystemHelper * @throws \Box\Spout\Common\Exception\IOException If unable to create the folder + * @return FileSystemHelper */ private function createXlRelsFolder() { $this->xlRelsFolder = $this->createFolder($this->xlFolder, self::RELS_FOLDER_NAME); + return $this; } /** * Creates the "worksheets" folder under the "xl" folder * - * @return FileSystemHelper * @throws \Box\Spout\Common\Exception\IOException If unable to create the folder + * @return FileSystemHelper */ private function createXlWorksheetsFolder() { $this->xlWorksheetsFolder = $this->createFolder($this->xlFolder, self::WORKSHEETS_FOLDER_NAME); + return $this; } @@ -258,7 +264,7 @@ EOD; */ public function createContentTypesFile($worksheets) { - $contentTypesXmlFileContents = << @@ -266,12 +272,12 @@ EOD; EOD; - /** @var Worksheet $worksheet */ - foreach ($worksheets as $worksheet) { - $contentTypesXmlFileContents .= ''; - } + /** @var Worksheet $worksheet */ + foreach ($worksheets as $worksheet) { + $contentTypesXmlFileContents .= ''; + } - $contentTypesXmlFileContents .= << @@ -292,23 +298,20 @@ EOD; */ public function createWorkbookFile($worksheets) { - $workbookXmlFileContents = << EOD; - /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */ - $escaper = \Box\Spout\Common\Escaper\XLSX::getInstance(); - /** @var Worksheet $worksheet */ foreach ($worksheets as $worksheet) { $worksheetName = $worksheet->getExternalSheet()->getName(); $worksheetId = $worksheet->getId(); - $workbookXmlFileContents .= ''; + $workbookXmlFileContents .= ''; } - $workbookXmlFileContents .= << EOD; @@ -326,7 +329,7 @@ EOD; */ public function createWorkbookRelsFile($worksheets) { - $workbookRelsXmlFileContents = << diff --git a/src/Spout/Writer/XLSX/Manager/OptionsManager.php b/src/Spout/Writer/XLSX/Manager/OptionsManager.php index 425f2f6..53718bc 100644 --- a/src/Spout/Writer/XLSX/Manager/OptionsManager.php +++ b/src/Spout/Writer/XLSX/Manager/OptionsManager.php @@ -2,15 +2,13 @@ namespace Box\Spout\Writer\XLSX\Manager; -use Box\Spout\Writer\Common\Entity\Options; -use Box\Spout\Writer\Common\Manager\OptionsManagerAbstract; +use Box\Spout\Common\Manager\OptionsManagerAbstract; use Box\Spout\Writer\Common\Creator\Style\StyleBuilder; +use Box\Spout\Writer\Common\Entity\Options; /** * Class OptionsManager * XLSX Writer options manager - * - * @package Box\Spout\Writer\XLSX\Manager */ class OptionsManager extends OptionsManagerAbstract { @@ -32,7 +30,7 @@ class OptionsManager extends OptionsManagerAbstract } /** - * @inheritdoc + * {@inheritdoc} */ protected function getSupportedOptions() { @@ -45,7 +43,7 @@ class OptionsManager extends OptionsManagerAbstract } /** - * @inheritdoc + * {@inheritdoc} */ protected function setDefaultOptions() { @@ -59,4 +57,4 @@ class OptionsManager extends OptionsManagerAbstract $this->setOption(Options::SHOULD_CREATE_NEW_SHEETS_AUTOMATICALLY, true); $this->setOption(Options::SHOULD_USE_INLINE_STRINGS, true); } -} \ No newline at end of file +} diff --git a/src/Spout/Writer/XLSX/Manager/SharedStringsManager.php b/src/Spout/Writer/XLSX/Manager/SharedStringsManager.php index 167063e..2a60c3c 100644 --- a/src/Spout/Writer/XLSX/Manager/SharedStringsManager.php +++ b/src/Spout/Writer/XLSX/Manager/SharedStringsManager.php @@ -3,19 +3,17 @@ namespace Box\Spout\Writer\XLSX\Manager; use Box\Spout\Common\Exception\IOException; -use Box\Spout\Common\Escaper; +use Box\Spout\Common\Helper\Escaper; /** * Class SharedStringsManager * This class provides functions to write shared strings - * - * @package Box\Spout\Writer\XLSX\Manager */ class SharedStringsManager { const SHARED_STRINGS_FILE_NAME = 'sharedStrings.xml'; - const SHARED_STRINGS_XML_FILE_FIRST_PART_HEADER = << EOD; @@ -58,7 +55,7 @@ EOD; $content .= $this->getCellXfsSectionContent(); $content .= $this->getCellStylesSectionContent(); - $content .= << EOD; @@ -187,7 +184,7 @@ EOD; */ protected function getCellStyleXfsSectionContent() { - return << @@ -239,7 +236,7 @@ EOD; */ protected function getCellStylesSectionContent() { - return << diff --git a/src/Spout/Writer/XLSX/Manager/Style/StyleRegistry.php b/src/Spout/Writer/XLSX/Manager/Style/StyleRegistry.php index f91484a..8039454 100644 --- a/src/Spout/Writer/XLSX/Manager/Style/StyleRegistry.php +++ b/src/Spout/Writer/XLSX/Manager/Style/StyleRegistry.php @@ -7,8 +7,6 @@ use Box\Spout\Writer\Common\Entity\Style\Style; /** * Class StyleRegistry * Registry for all used styles - * - * @package Box\Spout\Writer\XLSX\Manager\Style */ class StyleRegistry extends \Box\Spout\Writer\Common\Manager\Style\StyleRegistry { @@ -80,7 +78,6 @@ class StyleRegistry extends \Box\Spout\Writer\Common\Manager\Style\StyleRegistry $this->registeredFills[$backgroundColor] = $styleId; $this->styleIdToFillMappingTable[$styleId] = $this->fillIndex++; } - } else { // The fillId maps a style to a fill declaration // When there is no background color definition - we default to 0 @@ -122,7 +119,6 @@ class StyleRegistry extends \Box\Spout\Writer\Common\Manager\Style\StyleRegistry $this->registeredBorders[$serializedBorder] = $styleId; $this->styleIdToBorderMappingTable[$styleId] = count($this->registeredBorders); } - } else { // If no border should be applied - the mapping is the default border: 0 $this->styleIdToBorderMappingTable[$styleId] = 0; diff --git a/src/Spout/Writer/XLSX/Manager/WorkbookManager.php b/src/Spout/Writer/XLSX/Manager/WorkbookManager.php index 7adfd8c..944516b 100644 --- a/src/Spout/Writer/XLSX/Manager/WorkbookManager.php +++ b/src/Spout/Writer/XLSX/Manager/WorkbookManager.php @@ -10,8 +10,6 @@ use Box\Spout\Writer\XLSX\Manager\Style\StyleManager; /** * Class WorkbookManager * XLSX workbook manager, providing the interfaces to work with workbook. - * - * @package Box\Spout\Writer\XLSX\Manager */ class WorkbookManager extends WorkbookManagerAbstract { @@ -45,6 +43,7 @@ class WorkbookManager extends WorkbookManagerAbstract public function getWorksheetFilePath(Sheet $sheet) { $worksheetFilesFolder = $this->fileSystemHelper->getXlWorksheetsFolder(); + return $worksheetFilesFolder . '/' . strtolower($sheet->getName()) . '.xml'; } @@ -75,4 +74,4 @@ class WorkbookManager extends WorkbookManagerAbstract ->createStylesFile($this->styleManager) ->zipRootFolderAndCopyToStream($finalFilePointer); } -} \ No newline at end of file +} diff --git a/src/Spout/Writer/XLSX/Manager/WorksheetManager.php b/src/Spout/Writer/XLSX/Manager/WorksheetManager.php index 8eb2f76..0877286 100644 --- a/src/Spout/Writer/XLSX/Manager/WorksheetManager.php +++ b/src/Spout/Writer/XLSX/Manager/WorksheetManager.php @@ -5,20 +5,20 @@ namespace Box\Spout\Writer\XLSX\Manager; 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\Manager\OptionsManagerInterface; -use Box\Spout\Writer\Common\Entity\Options; +use Box\Spout\Common\Manager\OptionsManagerInterface; +use Box\Spout\Writer\Common\Creator\EntityFactory; use Box\Spout\Writer\Common\Entity\Cell; +use Box\Spout\Writer\Common\Entity\Options; +use Box\Spout\Writer\Common\Entity\Style\Style; use Box\Spout\Writer\Common\Entity\Row; use Box\Spout\Writer\Common\Entity\Worksheet; +use Box\Spout\Writer\Common\Helper\CellHelper; use Box\Spout\Writer\Common\Manager\WorksheetManagerInterface; use Box\Spout\Writer\XLSX\Manager\Style\StyleManager; /** * Class WorksheetManager * XLSX worksheet manager, providing the interfaces to work with XLSX worksheets. - * - * @package Box\Spout\Writer\XLSX\Manager */ class WorksheetManager implements WorksheetManagerInterface { @@ -30,7 +30,7 @@ class WorksheetManager implements WorksheetManagerInterface */ const MAX_CHARACTERS_PER_CELL = 32767; - const SHEET_XML_FILE_HEADER = << EOD; @@ -44,33 +44,39 @@ EOD; /** @var SharedStringsManager Helper to write shared strings */ private $sharedStringsManager; - /** @var \Box\Spout\Common\Escaper\XLSX Strings escaper */ + /** @var \Box\Spout\Common\Helper\Escaper\XLSX Strings escaper */ private $stringsEscaper; /** @var StringHelper String helper */ private $stringHelper; + /** @var EntityFactory Factory to create entities */ + private $entityFactory; + /** * WorksheetManager constructor. * * @param OptionsManagerInterface $optionsManager * @param StyleManager $styleManager * @param SharedStringsManager $sharedStringsManager - * @param \Box\Spout\Common\Escaper\XLSX $stringsEscaper + * @param \Box\Spout\Common\Helper\Escaper\XLSX $stringsEscaper * @param StringHelper $stringHelper + * @param EntityFactory $entityFactory */ public function __construct( OptionsManagerInterface $optionsManager, StyleManager $styleManager, SharedStringsManager $sharedStringsManager, - \Box\Spout\Common\Escaper\XLSX $stringsEscaper, - StringHelper $stringHelper) - { + \Box\Spout\Common\Helper\Escaper\XLSX $stringsEscaper, + StringHelper $stringHelper, + EntityFactory $entityFactory + ) { $this->shouldUseInlineStrings = $optionsManager->getOption(Options::SHOULD_USE_INLINE_STRINGS); $this->styleManager = $styleManager; $this->sharedStringsManager = $sharedStringsManager; $this->stringsEscaper = $stringsEscaper; $this->stringHelper = $stringHelper; + $this->entityFactory = $entityFactory; } /** @@ -81,13 +87,12 @@ EOD; return $this->sharedStringsManager; } - /** * Prepares the worksheet to accept data * * @param Worksheet $worksheet The worksheet to start - * @return void * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing + * @return void */ public function startSheet(Worksheet $worksheet) { @@ -104,8 +109,8 @@ EOD; * Checks if the sheet has been sucessfully created. Throws an exception if not. * * @param bool|resource $sheetFilePointer Pointer to the sheet data file or FALSE if unable to open the file - * @return void * @throws IOException If the sheet data file cannot be opened for writing + * @return void */ private function throwIfSheetFilePointerIsNotAvailable($sheetFilePointer) { @@ -122,6 +127,7 @@ EOD; * @return void * @throws IOException If the data cannot be written * @throws InvalidArgumentException If a cell value's type is not supported + * @return void */ public function addRow(Worksheet $worksheet, Row $row) { @@ -140,6 +146,7 @@ EOD; * * @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 + * @return void */ private function addNonEmptyRow(Worksheet $worksheet, Row $row) { @@ -175,8 +182,8 @@ EOD; * @param int $cellNumber * @param Cell $cell * @param int $styleId - * @return string * @throws InvalidArgumentException If the given value cannot be processed + * @return string */ private function getCellXML($rowIndex, $cellNumber, Cell $cell, $styleId) { @@ -186,11 +193,11 @@ EOD; if ($cell->isString()) { $cellXML .= $this->getCellXMLFragmentForNonEmptyString($cell->getValue()); - } else if ($cell->isBoolean()) { - $cellXML .= ' t="b">' . intval($cell->getValue()) . ''; - } else if ($cell->isNumeric()) { + } elseif ($cell->isBoolean()) { + $cellXML .= ' t="b">' . (int) ($cell->getValue()) . ''; + } elseif ($cell->isNumeric()) { $cellXML .= '>' . $cell->getValue() . ''; - } else if ($cell->isEmpty()) { + } elseif ($cell->isEmpty()) { if ($this->styleManager->shouldApplyStyleOnEmptyCell($styleId)) { $cellXML .= '/>'; } else { @@ -209,8 +216,8 @@ EOD; * Returns the XML fragment for a cell containing a non empty string * * @param string $cellValue The cell value - * @return string The XML fragment representing the cell * @throws InvalidArgumentException If the string exceeds the maximum number of characters allowed per cell + * @return string The XML fragment representing the cell */ private function getCellXMLFragmentForNonEmptyString($cellValue) { @@ -246,4 +253,4 @@ EOD; fwrite($worksheetFilePointer, ''); fclose($worksheetFilePointer); } -} \ No newline at end of file +} diff --git a/src/Spout/Writer/XLSX/Writer.php b/src/Spout/Writer/XLSX/Writer.php index f270921..9fd3143 100644 --- a/src/Spout/Writer/XLSX/Writer.php +++ b/src/Spout/Writer/XLSX/Writer.php @@ -8,8 +8,6 @@ use Box\Spout\Writer\WriterMultiSheetsAbstract; /** * Class Writer * This class provides base support to write data to XLSX files - * - * @package Box\Spout\Writer\XLSX */ class Writer extends WriterMultiSheetsAbstract { @@ -22,14 +20,15 @@ class Writer extends WriterMultiSheetsAbstract * * @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 + * @return Writer */ public function setTempFolder($tempFolder) { $this->throwIfWriterAlreadyOpened('Writer must be configured before opening it.'); $this->optionsManager->setOption(Options::TEMP_FOLDER, $tempFolder); + return $this; } @@ -39,14 +38,15 @@ class Writer extends WriterMultiSheetsAbstract * * @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 + * @return Writer */ public function setShouldUseInlineStrings($shouldUseInlineStrings) { $this->throwIfWriterAlreadyOpened('Writer must be configured before opening it.'); $this->optionsManager->setOption(Options::SHOULD_USE_INLINE_STRINGS, $shouldUseInlineStrings); + return $this; } } diff --git a/tests/Spout/Common/Helper/EncodingHelperTest.php b/tests/Spout/Common/Helper/EncodingHelperTest.php index d142d4e..ce48d8c 100644 --- a/tests/Spout/Common/Helper/EncodingHelperTest.php +++ b/tests/Spout/Common/Helper/EncodingHelperTest.php @@ -6,8 +6,6 @@ use Box\Spout\TestUsingResource; /** * Class EncodingHelperTest - * - * @package Box\Spout\Common\Helper */ class EncodingHelperTest extends \PHPUnit_Framework_TestCase { diff --git a/tests/Spout/Common/Escaper/ODSTest.php b/tests/Spout/Common/Helper/Escaper/ODSTest.php similarity index 80% rename from tests/Spout/Common/Escaper/ODSTest.php rename to tests/Spout/Common/Helper/Escaper/ODSTest.php index 77b4913..2702cc0 100644 --- a/tests/Spout/Common/Escaper/ODSTest.php +++ b/tests/Spout/Common/Helper/Escaper/ODSTest.php @@ -1,11 +1,11 @@ escape($stringToEscape); $this->assertEquals($expectedEscapedString, $escapedString, 'Incorrect escaped string'); diff --git a/tests/Spout/Common/Escaper/XLSXTest.php b/tests/Spout/Common/Helper/Escaper/XLSXTest.php similarity index 74% rename from tests/Spout/Common/Escaper/XLSXTest.php rename to tests/Spout/Common/Helper/Escaper/XLSXTest.php index 0f2098f..f657f71 100644 --- a/tests/Spout/Common/Escaper/XLSXTest.php +++ b/tests/Spout/Common/Helper/Escaper/XLSXTest.php @@ -1,11 +1,11 @@ escape($stringToEscape); $this->assertEquals($expectedEscapedString, $escapedString, 'Incorrect escaped string'); @@ -60,8 +59,8 @@ class XLSXTest extends \PHPUnit_Framework_TestCase ['_x0004_', chr(4)], ['_x005F_x0000_', '_x0000_'], ['_x0015_', chr(21)], - ['control _x0015_ character', 'control '.chr(21).' character'], - ['control's _x0015_ "character"', 'control's '.chr(21).' "character"'], + ['control _x0015_ character', 'control ' . chr(21) . ' character'], + ['control's _x0015_ "character"', 'control's ' . chr(21) . ' "character"'], ]; } @@ -74,8 +73,7 @@ class XLSXTest extends \PHPUnit_Framework_TestCase */ public function testUnescape($stringToUnescape, $expectedUnescapedString) { - /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */ - $escaper = \Box\Spout\Common\Escaper\XLSX::getInstance(); + $escaper = new Escaper\XLSX(); $unescapedString = $escaper->unescape($stringToUnescape); $this->assertEquals($expectedUnescapedString, $unescapedString, 'Incorrect escaped string'); diff --git a/tests/Spout/Common/Helper/FileSystemHelperTest.php b/tests/Spout/Common/Helper/FileSystemHelperTest.php index a73e7f2..52a3fdd 100644 --- a/tests/Spout/Common/Helper/FileSystemHelperTest.php +++ b/tests/Spout/Common/Helper/FileSystemHelperTest.php @@ -4,8 +4,6 @@ namespace Box\Spout\Common\Helper; /** * Class FileSystemHelperTest - * - * @package Box\Spout\Common\Helper */ class FileSystemHelperTest extends \PHPUnit_Framework_TestCase { diff --git a/tests/Spout/Writer/Common/Manager/OptionsManagerTest.php b/tests/Spout/Common/Manager/OptionsManagerTest.php similarity index 94% rename from tests/Spout/Writer/Common/Manager/OptionsManagerTest.php rename to tests/Spout/Common/Manager/OptionsManagerTest.php index 7598bcc..c3f25f7 100644 --- a/tests/Spout/Writer/Common/Manager/OptionsManagerTest.php +++ b/tests/Spout/Common/Manager/OptionsManagerTest.php @@ -1,11 +1,9 @@ setOption('foo', 'foo-val'); $this->setOption('bar', false); } -} \ No newline at end of file +} diff --git a/tests/Spout/Reader/CSV/ReaderTest.php b/tests/Spout/Reader/CSV/ReaderTest.php index 429ffa6..2a20b71 100644 --- a/tests/Spout/Reader/CSV/ReaderTest.php +++ b/tests/Spout/Reader/CSV/ReaderTest.php @@ -2,15 +2,16 @@ namespace Box\Spout\Reader\CSV; -use Box\Spout\Reader\ReaderFactory; -use Box\Spout\Common\Type; +use Box\Spout\Common\Creator\HelperFactory; use Box\Spout\Common\Helper\EncodingHelper; +use Box\Spout\Common\Helper\GlobalFunctionsHelper; +use Box\Spout\Reader\CSV\Creator\EntityFactory; +use Box\Spout\Reader\CSV\Manager\OptionsManager; +use Box\Spout\Reader\ReaderInterface; use Box\Spout\TestUsingResource; /** * Class ReaderTest - * - * @package Box\Spout\Reader\CSV */ class ReaderTest extends \PHPUnit_Framework_TestCase { @@ -23,7 +24,7 @@ class ReaderTest extends \PHPUnit_Framework_TestCase */ public function testOpenShouldThrowExceptionIfFileDoesNotExist() { - ReaderFactory::create(Type::CSV)->open('/path/to/fake/file.csv'); + $this->createCSVReader()->open('/path/to/fake/file.csv'); } /** @@ -33,7 +34,7 @@ class ReaderTest extends \PHPUnit_Framework_TestCase */ public function testOpenShouldThrowExceptionIfTryingToReadBeforeOpeningReader() { - ReaderFactory::create(Type::CSV)->getSheetIterator(); + $this->createCSVReader()->getSheetIterator(); } /** @@ -43,6 +44,7 @@ class ReaderTest extends \PHPUnit_Framework_TestCase */ public function testOpenShouldThrowExceptionIfFileNotReadable() { + /** @var \Box\Spout\Common\Helper\GlobalFunctionsHelper|\PHPUnit_Framework_MockObject_MockObject $helperStub */ $helperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\GlobalFunctionsHelper') ->setMethods(['is_readable']) ->getMock(); @@ -50,8 +52,7 @@ class ReaderTest extends \PHPUnit_Framework_TestCase $resourcePath = $this->getResourcePath('csv_standard.csv'); - $reader = ReaderFactory::create(Type::CSV); - $reader->setGlobalFunctionsHelper($helperStub); + $reader = $this->createCSVReader(null, $helperStub); $reader->open($resourcePath); } @@ -62,6 +63,7 @@ class ReaderTest extends \PHPUnit_Framework_TestCase */ public function testOpenShouldThrowExceptionIfCannotOpenFile() { + /** @var \Box\Spout\Common\Helper\GlobalFunctionsHelper|\PHPUnit_Framework_MockObject_MockObject $helperStub */ $helperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\GlobalFunctionsHelper') ->setMethods(['fopen']) ->getMock(); @@ -69,12 +71,10 @@ class ReaderTest extends \PHPUnit_Framework_TestCase $resourcePath = $this->getResourcePath('csv_standard.csv'); - $reader = ReaderFactory::create(Type::CSV); - $reader->setGlobalFunctionsHelper($helperStub); + $reader = $this->createCSVReader(null, $helperStub); $reader->open($resourcePath); } - /** * @return void */ @@ -139,7 +139,9 @@ class ReaderTest extends \PHPUnit_Framework_TestCase { $allRows = $this->getAllRowsForFile( 'csv_with_multiple_empty_lines.csv', - ',', '"', "\n", EncodingHelper::ENCODING_UTF8, + ',', + '"', + EncodingHelper::ENCODING_UTF8, $shouldPreserveEmptyRows = true ); @@ -215,21 +217,6 @@ class ReaderTest extends \PHPUnit_Framework_TestCase $this->assertEquals('This is, a comma', $allRows[0][0]); } - /** - * @return void - */ - public function testReadCustomEOLs() - { - $allRows = $this->getAllRowsForFile('csv_with_CR_EOL.csv', ',', '"', "\r"); - - $expectedRows = [ - ['csv--11', 'csv--12', 'csv--13'], - ['csv--21', 'csv--22', 'csv--23'], - ['csv--31', 'csv--32', 'csv--33'], - ]; - $this->assertEquals($expectedRows, $allRows); - } - /** * @return void */ @@ -262,7 +249,7 @@ class ReaderTest extends \PHPUnit_Framework_TestCase */ public function testReadShouldSkipBom($fileName, $fileEncoding) { - $allRows = $this->getAllRowsForFile($fileName, ',', '"', "\n", $fileEncoding); + $allRows = $this->getAllRowsForFile($fileName, ',', '"', $fileEncoding); $expectedRows = [ ['csv--11', 'csv--12', 'csv--13'], @@ -313,9 +300,8 @@ class ReaderTest extends \PHPUnit_Framework_TestCase $helperStub->method('function_exists')->will($this->returnValueMap($returnValueMap)); /** @var \Box\Spout\Reader\CSV\Reader $reader */ - $reader = ReaderFactory::create(Type::CSV); + $reader = $this->createCSVReader(null, $helperStub); $reader - ->setGlobalFunctionsHelper($helperStub) ->setEncoding($fileEncoding) ->open($resourcePath); @@ -343,7 +329,7 @@ class ReaderTest extends \PHPUnit_Framework_TestCase $allRows = []; $resourcePath = $this->getResourcePath('csv_standard.csv'); - $reader = ReaderFactory::create(Type::CSV); + $reader = $this->createCSVReader(); $reader->open($resourcePath); foreach ($reader->getSheetIterator() as $sheet) { @@ -390,7 +376,7 @@ class ReaderTest extends \PHPUnit_Framework_TestCase $expectedRows = [ ['A', 'B', 'C'], ['1', '2', '3'], - ['0', '0', '0'] + ['0', '0', '0'], ]; $this->assertEquals($expectedRows, $allRows, 'There should be only 3 rows, because zeros (0) are valid values'); } @@ -406,7 +392,7 @@ class ReaderTest extends \PHPUnit_Framework_TestCase $expectedRows = [ ['A', 'B', 'C'], ['0', '', ''], - ['1', '1', ''] + ['1', '1', ''], ]; $this->assertEquals($expectedRows, $allRows, 'There should be 3 rows, with equal length'); } @@ -428,47 +414,6 @@ class ReaderTest extends \PHPUnit_Framework_TestCase $this->assertEquals($expectedRows, $allRows, 'Cell values should not be trimmed'); } - /** - * @param string $fileName - * @param string|void $fieldDelimiter - * @param string|void $fieldEnclosure - * @param string|void $endOfLineCharacter - * @param string|void $encoding - * @param bool|void $shouldPreserveEmptyRows - * @return array All the read rows the given file - */ - private function getAllRowsForFile( - $fileName, - $fieldDelimiter = ',', - $fieldEnclosure = '"', - $endOfLineCharacter = "\n", - $encoding = EncodingHelper::ENCODING_UTF8, - $shouldPreserveEmptyRows = false) - { - $allRows = []; - $resourcePath = $this->getResourcePath($fileName); - - /** @var \Box\Spout\Reader\CSV\Reader $reader */ - $reader = ReaderFactory::create(Type::CSV); - $reader - ->setFieldDelimiter($fieldDelimiter) - ->setFieldEnclosure($fieldEnclosure) - ->setEndOfLineCharacter($endOfLineCharacter) - ->setEncoding($encoding) - ->setShouldPreserveEmptyRows($shouldPreserveEmptyRows) - ->open($resourcePath); - - foreach ($reader->getSheetIterator() as $sheetIndex => $sheet) { - foreach ($sheet->getRowIterator() as $rowIndex => $row) { - $allRows[] = $row; - } - } - - $reader->close(); - - return $allRows; - } - /** * @return void */ @@ -481,7 +426,7 @@ class ReaderTest extends \PHPUnit_Framework_TestCase stream_wrapper_register('spout', SpoutTestStream::CLASS_NAME); /** @var \Box\Spout\Reader\CSV\Reader $reader */ - $reader = ReaderFactory::create(Type::CSV); + $reader = $this->createCSVReader(); $reader->open($resourcePath); foreach ($reader->getSheetIterator() as $sheet) { @@ -511,8 +456,59 @@ class ReaderTest extends \PHPUnit_Framework_TestCase public function testReadWithUnsupportedCustomStreamWrapper() { /** @var \Box\Spout\Reader\CSV\Reader $reader */ - $reader = ReaderFactory::create(Type::CSV); + $reader = $this->createCSVReader(); $reader->open('unsupported://foobar'); } + /** + * @param \Box\Spout\Common\Helper\GlobalFunctionsHelper|null $optionsManager + * @param \Box\Spout\Common\Manager\OptionsManagerInterface|null $globalFunctionsHelper + * @return ReaderInterface + */ + private function createCSVReader($optionsManager = null, $globalFunctionsHelper = null) + { + $optionsManager = $optionsManager ?: new OptionsManager(); + $globalFunctionsHelper = $globalFunctionsHelper ?: new GlobalFunctionsHelper(); + $entityFactory = new EntityFactory(new HelperFactory()); + + return new Reader($optionsManager, $globalFunctionsHelper, $entityFactory); + } + + /** + * @param string $fileName + * @param string $fieldDelimiter + * @param string $fieldEnclosure + * @param string $encoding + * @param bool $shouldPreserveEmptyRows + * @return array All the read rows the given file + */ + private function getAllRowsForFile( + $fileName, + $fieldDelimiter = ',', + $fieldEnclosure = '"', + $encoding = EncodingHelper::ENCODING_UTF8, + $shouldPreserveEmptyRows = false + ) { + $allRows = []; + $resourcePath = $this->getResourcePath($fileName); + + /** @var \Box\Spout\Reader\CSV\Reader $reader */ + $reader = $this->createCSVReader(); + $reader + ->setFieldDelimiter($fieldDelimiter) + ->setFieldEnclosure($fieldEnclosure) + ->setEncoding($encoding) + ->setShouldPreserveEmptyRows($shouldPreserveEmptyRows) + ->open($resourcePath); + + foreach ($reader->getSheetIterator() as $sheetIndex => $sheet) { + foreach ($sheet->getRowIterator() as $rowIndex => $row) { + $allRows[] = $row; + } + } + + $reader->close(); + + return $allRows; + } } diff --git a/tests/Spout/Reader/CSV/SheetTest.php b/tests/Spout/Reader/CSV/SheetTest.php index ae18c2f..8812d89 100644 --- a/tests/Spout/Reader/CSV/SheetTest.php +++ b/tests/Spout/Reader/CSV/SheetTest.php @@ -8,8 +8,6 @@ use Box\Spout\TestUsingResource; /** * Class SheetTest - * - * @package Box\Spout\Reader\CSV */ class SheetTest extends \PHPUnit_Framework_TestCase { diff --git a/tests/Spout/Reader/CSV/SpoutTestStream.php b/tests/Spout/Reader/CSV/SpoutTestStream.php index fdaeb18..3bfd06e 100644 --- a/tests/Spout/Reader/CSV/SpoutTestStream.php +++ b/tests/Spout/Reader/CSV/SpoutTestStream.php @@ -6,8 +6,6 @@ namespace Box\Spout\Reader\CSV; * Class SpoutTestStream * Custom stream that reads CSV files located in the tests/resources/csv folder. * For example: spout://foobar will point to tests/resources/csv/foobar.csv - * - * @package Box\Spout\Reader\CSV */ class SpoutTestStream { @@ -30,6 +28,7 @@ class SpoutTestStream public function url_stat($path, $flag) { $filePath = $this->getFilePathFromStreamPath($path); + return stat($filePath); } @@ -40,6 +39,7 @@ class SpoutTestStream private function getFilePathFromStreamPath($streamPath) { $fileName = parse_url($streamPath, PHP_URL_HOST); + return self::PATH_TO_CSV_RESOURCES . $fileName . self::CSV_EXTENSION; } @@ -68,6 +68,7 @@ class SpoutTestStream public function stream_read($numBytes) { $this->position += $numBytes; + return fread($this->fileHandle, $numBytes); } @@ -81,7 +82,7 @@ class SpoutTestStream /** * @param int $offset - * @param int|void $whence + * @param int $whence * @return bool */ public function stream_seek($offset, $whence = SEEK_SET) @@ -93,7 +94,7 @@ class SpoutTestStream if ($whence === SEEK_SET) { $this->position = $offset; - } else if ($whence === SEEK_CUR) { + } elseif ($whence === SEEK_CUR) { $this->position += $offset; } else { // not implemented diff --git a/tests/Spout/Reader/ODS/ReaderTest.php b/tests/Spout/Reader/ODS/ReaderTest.php index f36348f..7c699f6 100644 --- a/tests/Spout/Reader/ODS/ReaderTest.php +++ b/tests/Spout/Reader/ODS/ReaderTest.php @@ -9,8 +9,6 @@ use Box\Spout\TestUsingResource; /** * Class ReaderTest - * - * @package Box\Spout\Reader\ODS */ class ReaderTest extends \PHPUnit_Framework_TestCase { @@ -134,9 +132,9 @@ class ReaderTest extends \PHPUnit_Framework_TestCase $allRows = $this->getAllRowsForFile($fileName); $expectedRows = [ - ['header1','header2','header3','header4'], - ['val11','val12','val13','val14'], - ['val21','','val23','val23'], + ['header1', 'header2', 'header3', 'header4'], + ['val11', 'val12', 'val13', 'val14'], + ['val21', '', 'val23', 'val23'], ['', 10.43, 29.11], ]; @@ -150,7 +148,6 @@ class ReaderTest extends \PHPUnit_Framework_TestCase $this->assertEquals($expectedRows, $allRows); } - /** * @return void */ @@ -278,7 +275,6 @@ class ReaderTest extends \PHPUnit_Framework_TestCase $this->assertEquals([$expectedRow], $allRows); } - /** * @NOTE: The LIBXML_NOENT is used to ACTUALLY substitute entities (and should therefore not be used) * @@ -450,7 +446,7 @@ class ReaderTest extends \PHPUnit_Framework_TestCase $expectedRows = [ ['A', 'B', 'C'], ['1', '2', '3'], - ['0', '0', '0'] + ['0', '0', '0'], ]; $this->assertEquals($expectedRows, $allRows, 'There should be only 3 rows, because zeros (0) are valid values'); } @@ -466,7 +462,7 @@ class ReaderTest extends \PHPUnit_Framework_TestCase $expectedRows = [ ['A', 'B', 'C'], ['0', '', ''], - ['1', '1', ''] + ['1', '1', ''], ]; $this->assertEquals($expectedRows, $allRows, 'There should be 3 rows, with equal length'); } @@ -513,7 +509,7 @@ class ReaderTest extends \PHPUnit_Framework_TestCase $allRows = $this->getAllRowsForFile('sheet_with_inline_font_formatting.ods'); $expectedRows = [ - ['I am a yellow bird'] + ['I am a yellow bird'], ]; $this->assertEquals($expectedRows, $allRows, 'Text formatted inline should be read'); @@ -521,8 +517,8 @@ class ReaderTest extends \PHPUnit_Framework_TestCase /** * @param string $fileName - * @param bool|void $shouldFormatDates - * @param bool|void $shouldPreserveEmptyRows + * @param bool $shouldFormatDates + * @param bool $shouldPreserveEmptyRows * @return array All the read rows the given file */ private function getAllRowsForFile($fileName, $shouldFormatDates = false, $shouldPreserveEmptyRows = false) diff --git a/tests/Spout/Reader/ODS/SheetTest.php b/tests/Spout/Reader/ODS/SheetTest.php index cc3bd03..e5dfdf8 100644 --- a/tests/Spout/Reader/ODS/SheetTest.php +++ b/tests/Spout/Reader/ODS/SheetTest.php @@ -8,8 +8,6 @@ use Box\Spout\TestUsingResource; /** * Class SheetTest - * - * @package Box\Spout\Reader\ODS */ class SheetTest extends \PHPUnit_Framework_TestCase { diff --git a/tests/Spout/Reader/ReaderFactoryTest.php b/tests/Spout/Reader/ReaderFactoryTest.php index 57a0b55..5bef063 100644 --- a/tests/Spout/Reader/ReaderFactoryTest.php +++ b/tests/Spout/Reader/ReaderFactoryTest.php @@ -4,8 +4,6 @@ namespace Box\Spout\Reader; /** * Class ReaderFactoryTest - * - * @package Box\Spout\Writer */ class ReaderFactoryTest extends \PHPUnit_Framework_TestCase { diff --git a/tests/Spout/Reader/Wrapper/XMLReaderTest.php b/tests/Spout/Reader/Wrapper/XMLReaderTest.php index 3b22378..3f76208 100644 --- a/tests/Spout/Reader/Wrapper/XMLReaderTest.php +++ b/tests/Spout/Reader/Wrapper/XMLReaderTest.php @@ -3,12 +3,9 @@ namespace Box\Spout\Reader\Wrapper; use Box\Spout\TestUsingResource; -use Box\Spout\Reader\Exception\XMLProcessingException; /** * Class XMLReaderTest - * - * @package Box\Spout\Reader\Wrapper */ class XMLReaderTest extends \PHPUnit_Framework_TestCase { diff --git a/tests/Spout/Reader/XLSX/Helper/CellHelperTest.php b/tests/Spout/Reader/XLSX/Helper/CellHelperTest.php index a410d9d..0f9ca9d 100644 --- a/tests/Spout/Reader/XLSX/Helper/CellHelperTest.php +++ b/tests/Spout/Reader/XLSX/Helper/CellHelperTest.php @@ -4,8 +4,6 @@ namespace Box\Spout\Reader\XLSX\Helper; /** * Class CellHelperTest - * - * @package Box\Spout\Reader\XLSX\Helper */ class CellHelperTest extends \PHPUnit_Framework_TestCase { @@ -15,9 +13,9 @@ class CellHelperTest extends \PHPUnit_Framework_TestCase public function dataProviderForTestFillMissingArrayIndexes() { return [ - [ null, [] ], - [ [], [] ], - [ [1 => 1, 3 => 3], ['FILL', 1, 'FILL', 3] ] + [null, []], + [[], []], + [[1 => 1, 3 => 3], ['FILL', 1, 'FILL', 3]], ]; } diff --git a/tests/Spout/Reader/XLSX/Helper/CellValueFormatterTest.php b/tests/Spout/Reader/XLSX/Helper/CellValueFormatterTest.php index 96c71a9..ef58574 100644 --- a/tests/Spout/Reader/XLSX/Helper/CellValueFormatterTest.php +++ b/tests/Spout/Reader/XLSX/Helper/CellValueFormatterTest.php @@ -2,10 +2,10 @@ namespace Box\Spout\Reader\XLSX\Helper; +use Box\Spout\Common\Helper\Escaper; + /** * Class CellValueFormatterTest - * - * @package Box\Spout\Reader\XLSX\Helper */ class CellValueFormatterTest extends \PHPUnit_Framework_TestCase { @@ -45,7 +45,7 @@ class CellValueFormatterTest extends \PHPUnit_Framework_TestCase ->expects($this->atLeastOnce()) ->method('item') ->with(0) - ->will($this->returnValue((object)['nodeValue' => $nodeValue])); + ->will($this->returnValue((object) ['nodeValue' => $nodeValue])); $nodeMock = $this->getMockBuilder('DOMElement')->disableOriginalConstructor()->getMock(); @@ -63,15 +63,16 @@ class CellValueFormatterTest extends \PHPUnit_Framework_TestCase ->with(CellValueFormatter::XML_NODE_VALUE) ->will($this->returnValue($nodeListMock)); - $styleHelperMock = $this->getMockBuilder('Box\Spout\Reader\XLSX\Helper\StyleHelper')->disableOriginalConstructor()->getMock(); + /** @var \Box\Spout\Reader\XLSX\Manager\StyleManager|\PHPUnit_Framework_MockObject_MockObject $styleManagerMock */ + $styleManagerMock = $this->getMockBuilder('Box\Spout\Reader\XLSX\Manager\StyleManager')->disableOriginalConstructor()->getMock(); - $styleHelperMock + $styleManagerMock ->expects($this->once()) ->method('shouldFormatNumericValueAsDate') ->with(123) ->will($this->returnValue(true)); - $formatter = new CellValueFormatter(null, $styleHelperMock, false); + $formatter = new CellValueFormatter(null, $styleManagerMock, false, new Escaper\XLSX()); $result = $formatter->extractAndFormatNodeValue($nodeMock); if ($expectedDateAsString === null) { @@ -118,13 +119,14 @@ class CellValueFormatterTest extends \PHPUnit_Framework_TestCase */ public function testFormatNumericCellValueWithNumbers($value, $expectedFormattedValue, $expectedType) { - $styleHelperMock = $this->getMockBuilder('Box\Spout\Reader\XLSX\Helper\StyleHelper')->disableOriginalConstructor()->getMock(); - $styleHelperMock + /** @var \Box\Spout\Reader\XLSX\Manager\StyleManager|\PHPUnit_Framework_MockObject_MockObject $styleManagerMock */ + $styleManagerMock = $this->getMockBuilder('Box\Spout\Reader\XLSX\Manager\StyleManager')->disableOriginalConstructor()->getMock(); + $styleManagerMock ->expects($this->once()) ->method('shouldFormatNumericValueAsDate') ->will($this->returnValue(false)); - $formatter = new CellValueFormatter(null, $styleHelperMock, false); + $formatter = new CellValueFormatter(null, $styleManagerMock, false, new Escaper\XLSX()); $formattedValue = \ReflectionHelper::callMethodOnObject($formatter, 'formatNumericCellValue', $value, 0); $this->assertEquals($expectedFormattedValue, $formattedValue); @@ -158,7 +160,7 @@ class CellValueFormatterTest extends \PHPUnit_Framework_TestCase ->expects($this->atLeastOnce()) ->method('item') ->with(0) - ->will($this->returnValue((object)['nodeValue' => $value])); + ->will($this->returnValue((object) ['nodeValue' => $value])); $nodeMock = $this->getMockBuilder('DOMElement')->disableOriginalConstructor()->getMock(); $nodeMock @@ -167,7 +169,7 @@ class CellValueFormatterTest extends \PHPUnit_Framework_TestCase ->with(CellValueFormatter::XML_NODE_INLINE_STRING_VALUE) ->will($this->returnValue($nodeListMock)); - $formatter = new CellValueFormatter(null, null, false); + $formatter = new CellValueFormatter(null, null, false, new Escaper\XLSX()); $formattedValue = \ReflectionHelper::callMethodOnObject($formatter, 'formatInlineStringCellValue', $nodeMock); $this->assertEquals($expectedFormattedValue, $formattedValue); diff --git a/tests/Spout/Reader/XLSX/Helper/DateFormatHelperTest.php b/tests/Spout/Reader/XLSX/Helper/DateFormatHelperTest.php index cca02a7..5d7eef2 100644 --- a/tests/Spout/Reader/XLSX/Helper/DateFormatHelperTest.php +++ b/tests/Spout/Reader/XLSX/Helper/DateFormatHelperTest.php @@ -4,8 +4,6 @@ namespace Box\Spout\Reader\XLSX\Helper; /** * Class DateFormatHelperTest - * - * @package Box\Spout\Reader\XLSX\Helper */ class DateFormatHelperTest extends \PHPUnit_Framework_TestCase { diff --git a/tests/Spout/Reader/XLSX/Helper/SharedStringsHelperTest.php b/tests/Spout/Reader/XLSX/Helper/SharedStringsHelperTest.php deleted file mode 100644 index 17d1b52..0000000 --- a/tests/Spout/Reader/XLSX/Helper/SharedStringsHelperTest.php +++ /dev/null @@ -1,144 +0,0 @@ -getResourcePath('one_sheet_with_shared_strings.xlsx'); - $this->sharedStringsHelper = new SharedStringsHelper($resourcePath); - } - - /** - * @return void - */ - public function tearDown() - { - $this->sharedStringsHelper->cleanup(); - } - - /** - * @expectedException \Box\Spout\Reader\Exception\SharedStringNotFoundException - * @return void - */ - public function testGetStringAtIndexShouldThrowExceptionIfStringNotFound() - { - $this->sharedStringsHelper->extractSharedStrings(); - $this->sharedStringsHelper->getStringAtIndex(PHP_INT_MAX); - } - - /** - * @return void - */ - public function testGetStringAtIndexShouldReturnTheCorrectStringIfFound() - { - $this->sharedStringsHelper->extractSharedStrings(); - - $sharedString = $this->sharedStringsHelper->getStringAtIndex(0); - $this->assertEquals('s1--A1', $sharedString); - - $sharedString = $this->sharedStringsHelper->getStringAtIndex(24); - $this->assertEquals('s1--E5', $sharedString); - - $usedCachingStrategy = \ReflectionHelper::getValueOnObject($this->sharedStringsHelper, 'cachingStrategy'); - $this->assertTrue($usedCachingStrategy instanceof InMemoryStrategy); - } - - /** - * @return void - */ - public function testGetStringAtIndexShouldWorkWithMultilineStrings() - { - $resourcePath = $this->getResourcePath('one_sheet_with_shared_multiline_strings.xlsx'); - $sharedStringsHelper = new SharedStringsHelper($resourcePath); - - $sharedStringsHelper->extractSharedStrings(); - - $sharedString = $sharedStringsHelper->getStringAtIndex(0); - $this->assertEquals("s1\nA1", $sharedString); - - $sharedString = $sharedStringsHelper->getStringAtIndex(24); - $this->assertEquals("s1\nE5", $sharedString); - - $sharedStringsHelper->cleanup(); - } - - /** - * @return void - */ - public function testGetStringAtIndexShouldWorkWithStringsContainingTextAndHyperlinkInSameCell() - { - $resourcePath = $this->getResourcePath('one_sheet_with_shared_strings_containing_text_and_hyperlink_in_same_cell.xlsx'); - $sharedStringsHelper = new SharedStringsHelper($resourcePath); - - $sharedStringsHelper->extractSharedStrings(); - - $sharedString = $sharedStringsHelper->getStringAtIndex(0); - $this->assertEquals('go to https://github.com please', $sharedString); - - $sharedStringsHelper->cleanup(); - } - - /** - * @return void - */ - public function testGetStringAtIndexShouldNotDoubleDecodeHTMLEntities() - { - $resourcePath = $this->getResourcePath('one_sheet_with_pre_encoded_html_entities.xlsx'); - $sharedStringsHelper = new SharedStringsHelper($resourcePath); - - $sharedStringsHelper->extractSharedStrings(); - - $sharedString = $sharedStringsHelper->getStringAtIndex(0); - $this->assertEquals('quote: " - ampersand: &', $sharedString); - - $sharedStringsHelper->cleanup(); - } - - /** - * @return void - */ - public function testGetStringAtIndexWithFileBasedStrategy() - { - // force the file-based strategy by setting no memory limit - $originalMemoryLimit = ini_get('memory_limit'); - ini_set('memory_limit', '-1'); - - $resourcePath = $this->getResourcePath('sheet_with_lots_of_shared_strings.xlsx'); - $sharedStringsHelper = new SharedStringsHelper($resourcePath); - - $sharedStringsHelper->extractSharedStrings(); - - $sharedString = $sharedStringsHelper->getStringAtIndex(0); - $this->assertEquals('str', $sharedString); - - $sharedString = $sharedStringsHelper->getStringAtIndex(CachingStrategyFactory::MAX_NUM_STRINGS_PER_TEMP_FILE + 1); - $this->assertEquals('str', $sharedString); - - $usedCachingStrategy = \ReflectionHelper::getValueOnObject($sharedStringsHelper, 'cachingStrategy'); - $this->assertTrue($usedCachingStrategy instanceof FileBasedStrategy); - - $sharedStringsHelper->cleanup(); - - ini_set('memory_limit', $originalMemoryLimit); - } -} diff --git a/tests/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyFactoryTest.php b/tests/Spout/Reader/XLSX/Manager/SharedStringsCaching/CachingStrategyFactoryTest.php similarity index 70% rename from tests/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyFactoryTest.php rename to tests/Spout/Reader/XLSX/Manager/SharedStringsCaching/CachingStrategyFactoryTest.php index e61760a..51db365 100644 --- a/tests/Spout/Reader/XLSX/Helper/SharedStringsCaching/CachingStrategyFactoryTest.php +++ b/tests/Spout/Reader/XLSX/Manager/SharedStringsCaching/CachingStrategyFactoryTest.php @@ -1,58 +1,57 @@ getMockBuilder('\Box\Spout\Reader\XLSX\Helper\SharedStringsCaching\CachingStrategyFactory') + ->getMockBuilder('\Box\Spout\Reader\XLSX\Manager\SharedStringsCaching\CachingStrategyFactory') ->disableOriginalConstructor() ->setMethods(['getMemoryLimitInKB']) ->getMock(); $factoryStub->method('getMemoryLimitInKB')->willReturn($memoryLimitInKB); - \ReflectionHelper::setStaticValue('\Box\Spout\Reader\XLSX\Helper\SharedStringsCaching\CachingStrategyFactory', 'instance', $factoryStub); + $tempFolder = sys_get_temp_dir(); + $helperFactory = new HelperFactory($factoryStub); + $strategy = $factoryStub->createBestCachingStrategy($sharedStringsUniqueCount, $tempFolder, $helperFactory); - $strategy = $factoryStub->getBestCachingStrategy($sharedStringsUniqueCount, null); - - $fullExpectedStrategyClassName = 'Box\Spout\Reader\XLSX\Helper\SharedStringsCaching\\' . $expectedStrategyClassName; + $fullExpectedStrategyClassName = 'Box\Spout\Reader\XLSX\Manager\SharedStringsCaching\\' . $expectedStrategyClassName; $this->assertEquals($fullExpectedStrategyClassName, get_class($strategy)); $strategy->clearCache(); - \ReflectionHelper::reset(); } /** @@ -86,7 +85,7 @@ class CachingStrategyFactoryTest extends \PHPUnit_Framework_TestCase { /** @var CachingStrategyFactory|\PHPUnit_Framework_MockObject_MockObject $factoryStub */ $factoryStub = $this - ->getMockBuilder('\Box\Spout\Reader\XLSX\Helper\SharedStringsCaching\CachingStrategyFactory') + ->getMockBuilder('\Box\Spout\Reader\XLSX\Manager\SharedStringsCaching\CachingStrategyFactory') ->disableOriginalConstructor() ->setMethods(['getMemoryLimitFromIni']) ->getMock(); diff --git a/tests/Spout/Reader/XLSX/Manager/SharedStringsManagerTest.php b/tests/Spout/Reader/XLSX/Manager/SharedStringsManagerTest.php new file mode 100644 index 0000000..8a46345 --- /dev/null +++ b/tests/Spout/Reader/XLSX/Manager/SharedStringsManagerTest.php @@ -0,0 +1,154 @@ +sharedStringsManager = null; + } + + /** + * @return void + */ + public function tearDown() + { + if ($this->sharedStringsManager !== null) { + $this->sharedStringsManager->cleanup(); + } + } + + /** + * @param string $resourceName + * @return SharedStringsManager + */ + private function createSharedStringsManager($resourceName = 'one_sheet_with_shared_strings.xlsx') + { + $resourcePath = $this->getResourcePath($resourceName); + $tempFolder = sys_get_temp_dir(); + $cachingStrategyFactory = new CachingStrategyFactory(); + $helperFactory = new HelperFactory(); + $managerFactory = new ManagerFactory($helperFactory, $cachingStrategyFactory); + $entityFactory = new EntityFactory($managerFactory, $helperFactory); + + $this->sharedStringsManager = new SharedStringsManager($resourcePath, $tempFolder, $entityFactory, $helperFactory, $cachingStrategyFactory); + + return $this->sharedStringsManager; + } + + /** + * @expectedException \Box\Spout\Reader\Exception\SharedStringNotFoundException + * @return void + */ + public function testGetStringAtIndexShouldThrowExceptionIfStringNotFound() + { + $sharedStringsManager = $this->createSharedStringsManager(); + $sharedStringsManager->extractSharedStrings(); + $sharedStringsManager->getStringAtIndex(PHP_INT_MAX); + } + + /** + * @return void + */ + public function testGetStringAtIndexShouldReturnTheCorrectStringIfFound() + { + $sharedStringsManager = $this->createSharedStringsManager(); + $sharedStringsManager->extractSharedStrings(); + + $sharedString = $sharedStringsManager->getStringAtIndex(0); + $this->assertEquals('s1--A1', $sharedString); + + $sharedString = $sharedStringsManager->getStringAtIndex(24); + $this->assertEquals('s1--E5', $sharedString); + + $usedCachingStrategy = \ReflectionHelper::getValueOnObject($sharedStringsManager, 'cachingStrategy'); + $this->assertTrue($usedCachingStrategy instanceof InMemoryStrategy); + } + + /** + * @return void + */ + public function testGetStringAtIndexShouldWorkWithMultilineStrings() + { + $sharedStringsManager = $this->createSharedStringsManager('one_sheet_with_shared_multiline_strings.xlsx'); + + $sharedStringsManager->extractSharedStrings(); + + $sharedString = $sharedStringsManager->getStringAtIndex(0); + $this->assertEquals("s1\nA1", $sharedString); + + $sharedString = $sharedStringsManager->getStringAtIndex(24); + $this->assertEquals("s1\nE5", $sharedString); + } + + /** + * @return void + */ + public function testGetStringAtIndexShouldWorkWithStringsContainingTextAndHyperlinkInSameCell() + { + $sharedStringsManager = $this->createSharedStringsManager('one_sheet_with_shared_strings_containing_text_and_hyperlink_in_same_cell.xlsx'); + + $sharedStringsManager->extractSharedStrings(); + + $sharedString = $sharedStringsManager->getStringAtIndex(0); + $this->assertEquals('go to https://github.com please', $sharedString); + } + + /** + * @return void + */ + public function testGetStringAtIndexShouldNotDoubleDecodeHTMLEntities() + { + $sharedStringsManager = $this->createSharedStringsManager('one_sheet_with_pre_encoded_html_entities.xlsx'); + + $sharedStringsManager->extractSharedStrings(); + + $sharedString = $sharedStringsManager->getStringAtIndex(0); + $this->assertEquals('quote: " - ampersand: &', $sharedString); + } + + /** + * @return void + */ + public function testGetStringAtIndexWithFileBasedStrategy() + { + // force the file-based strategy by setting no memory limit + $originalMemoryLimit = ini_get('memory_limit'); + ini_set('memory_limit', '-1'); + + $sharedStringsManager = $this->createSharedStringsManager('sheet_with_lots_of_shared_strings.xlsx'); + + $sharedStringsManager->extractSharedStrings(); + + $sharedString = $sharedStringsManager->getStringAtIndex(0); + $this->assertEquals('str', $sharedString); + + $sharedString = $sharedStringsManager->getStringAtIndex(CachingStrategyFactory::MAX_NUM_STRINGS_PER_TEMP_FILE + 1); + $this->assertEquals('str', $sharedString); + + $usedCachingStrategy = \ReflectionHelper::getValueOnObject($sharedStringsManager, 'cachingStrategy'); + $this->assertTrue($usedCachingStrategy instanceof FileBasedStrategy); + + ini_set('memory_limit', $originalMemoryLimit); + } +} diff --git a/tests/Spout/Reader/XLSX/Helper/StyleHelperTest.php b/tests/Spout/Reader/XLSX/Manager/StyleManagerTest.php similarity index 51% rename from tests/Spout/Reader/XLSX/Helper/StyleHelperTest.php rename to tests/Spout/Reader/XLSX/Manager/StyleManagerTest.php index 8d45fa5..4127795 100644 --- a/tests/Spout/Reader/XLSX/Helper/StyleHelperTest.php +++ b/tests/Spout/Reader/XLSX/Manager/StyleManagerTest.php @@ -1,32 +1,38 @@ getMockBuilder('\Box\Spout\Reader\XLSX\Helper\StyleHelper') - ->setConstructorArgs(['/path/to/file.xlsx']) - ->setMethods(['getCustomNumberFormats', 'getStylesAttributes']) - ->getMock(); + $helperFactory = new HelperFactory(); + $managerFactory = new ManagerFactory($helperFactory, new CachingStrategyFactory()); + $entityFactory = new EntityFactory($managerFactory, $helperFactory); - $styleHelper->method('getStylesAttributes')->willReturn($styleAttributes); - $styleHelper->method('getCustomNumberFormats')->willReturn($customNumberFormats); + /** @var StyleManager $styleManager */ + $styleManager = $this->getMockBuilder('\Box\Spout\Reader\XLSX\Manager\StyleManager') + ->setConstructorArgs(['/path/to/file.xlsx', $entityFactory]) + ->setMethods(['getCustomNumberFormats', 'getStylesAttributes']) + ->getMock(); - return $styleHelper; + $styleManager->method('getStylesAttributes')->willReturn($styleAttributes); + $styleManager->method('getCustomNumberFormats')->willReturn($customNumberFormats); + + return $styleManager; } /** @@ -34,8 +40,8 @@ class StyleHelperTest extends \PHPUnit_Framework_TestCase */ public function testShouldFormatNumericValueAsDateWithDefaultStyle() { - $styleHelper = $this->getStyleHelperMock(); - $shouldFormatAsDate = $styleHelper->shouldFormatNumericValueAsDate(0); + $styleManager = $this->getStyleManagerMock(); + $shouldFormatAsDate = $styleManager->shouldFormatNumericValueAsDate(0); $this->assertFalse($shouldFormatAsDate); } @@ -44,8 +50,8 @@ class StyleHelperTest extends \PHPUnit_Framework_TestCase */ public function testShouldFormatNumericValueAsDateWhenShouldNotApplyNumberFormat() { - $styleHelper = $this->getStyleHelperMock([[], ['applyNumberFormat' => false, 'numFmtId' => 14]]); - $shouldFormatAsDate = $styleHelper->shouldFormatNumericValueAsDate(1); + $styleManager = $this->getStyleManagerMock([[], ['applyNumberFormat' => false, 'numFmtId' => 14]]); + $shouldFormatAsDate = $styleManager->shouldFormatNumericValueAsDate(1); $this->assertFalse($shouldFormatAsDate); } @@ -54,8 +60,8 @@ class StyleHelperTest extends \PHPUnit_Framework_TestCase */ public function testShouldFormatNumericValueAsDateWithGeneralFormat() { - $styleHelper = $this->getStyleHelperMock([[], ['applyNumberFormat' => true, 'numFmtId' => 0]]); - $shouldFormatAsDate = $styleHelper->shouldFormatNumericValueAsDate(1); + $styleManager = $this->getStyleManagerMock([[], ['applyNumberFormat' => true, 'numFmtId' => 0]]); + $shouldFormatAsDate = $styleManager->shouldFormatNumericValueAsDate(1); $this->assertFalse($shouldFormatAsDate); } @@ -64,8 +70,8 @@ class StyleHelperTest extends \PHPUnit_Framework_TestCase */ public function testShouldFormatNumericValueAsDateWithNonDateBuiltinFormat() { - $styleHelper = $this->getStyleHelperMock([[], ['applyNumberFormat' => true, 'numFmtId' => 9]]); - $shouldFormatAsDate = $styleHelper->shouldFormatNumericValueAsDate(1); + $styleManager = $this->getStyleManagerMock([[], ['applyNumberFormat' => true, 'numFmtId' => 9]]); + $shouldFormatAsDate = $styleManager->shouldFormatNumericValueAsDate(1); $this->assertFalse($shouldFormatAsDate); } @@ -74,8 +80,8 @@ class StyleHelperTest extends \PHPUnit_Framework_TestCase */ public function testShouldFormatNumericValueAsDateWithNoNumFmtId() { - $styleHelper = $this->getStyleHelperMock([[], ['applyNumberFormat' => true, 'numFmtId' => null]]); - $shouldFormatAsDate = $styleHelper->shouldFormatNumericValueAsDate(1); + $styleManager = $this->getStyleManagerMock([[], ['applyNumberFormat' => true, 'numFmtId' => null]]); + $shouldFormatAsDate = $styleManager->shouldFormatNumericValueAsDate(1); $this->assertFalse($shouldFormatAsDate); } @@ -87,8 +93,8 @@ class StyleHelperTest extends \PHPUnit_Framework_TestCase $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); + $styleManager = $this->getStyleManagerMock([[], ['applyNumberFormat' => true, 'numFmtId' => $builtinNumFmtIdForDate]]); + $shouldFormatAsDate = $styleManager->shouldFormatNumericValueAsDate(1); $this->assertTrue($shouldFormatAsDate); } @@ -99,8 +105,8 @@ class StyleHelperTest extends \PHPUnit_Framework_TestCase */ public function testShouldFormatNumericValueAsDateWhenApplyNumberFormatNotSetAndUsingBuiltinDateFormat() { - $styleHelper = $this->getStyleHelperMock([[], ['applyNumberFormat' => null, 'numFmtId' => 14]]); - $shouldFormatAsDate = $styleHelper->shouldFormatNumericValueAsDate(1); + $styleManager = $this->getStyleManagerMock([[], ['applyNumberFormat' => null, 'numFmtId' => 14]]); + $shouldFormatAsDate = $styleManager->shouldFormatNumericValueAsDate(1); $this->assertTrue($shouldFormatAsDate); } @@ -110,8 +116,8 @@ class StyleHelperTest extends \PHPUnit_Framework_TestCase */ public function testShouldFormatNumericValueAsDateWhenApplyNumberFormatNotSetAndUsingBuiltinNonDateFormat() { - $styleHelper = $this->getStyleHelperMock([[], ['applyNumberFormat' => null, 'numFmtId' => 9]]); - $shouldFormatAsDate = $styleHelper->shouldFormatNumericValueAsDate(1); + $styleManager = $this->getStyleManagerMock([[], ['applyNumberFormat' => null, 'numFmtId' => 9]]); + $shouldFormatAsDate = $styleManager->shouldFormatNumericValueAsDate(1); $this->assertFalse($shouldFormatAsDate); } @@ -121,8 +127,8 @@ class StyleHelperTest extends \PHPUnit_Framework_TestCase */ public function testShouldFormatNumericValueAsDateWhenCustomNumberFormatNotFound() { - $styleHelper = $this->getStyleHelperMock([[], ['applyNumberFormat' => true, 'numFmtId' => 165]], [166 => []]); - $shouldFormatAsDate = $styleHelper->shouldFormatNumericValueAsDate(1); + $styleManager = $this->getStyleManagerMock([[], ['applyNumberFormat' => true, 'numFmtId' => 165]], [166 => []]); + $shouldFormatAsDate = $styleManager->shouldFormatNumericValueAsDate(1); $this->assertFalse($shouldFormatAsDate); } @@ -171,8 +177,8 @@ class StyleHelperTest extends \PHPUnit_Framework_TestCase public function testShouldFormatNumericValueAsDateWithCustomDateFormats($numberFormat, $expectedResult) { $numFmtId = 165; - $styleHelper = $this->getStyleHelperMock([[], ['applyNumberFormat' => true, 'numFmtId' => $numFmtId]], [$numFmtId => $numberFormat]); - $shouldFormatAsDate = $styleHelper->shouldFormatNumericValueAsDate(1); + $styleManager = $this->getStyleManagerMock([[], ['applyNumberFormat' => true, 'numFmtId' => $numFmtId]], [$numFmtId => $numberFormat]); + $shouldFormatAsDate = $styleManager->shouldFormatNumericValueAsDate(1); $this->assertEquals($expectedResult, $shouldFormatAsDate); } diff --git a/tests/Spout/Reader/XLSX/ReaderTest.php b/tests/Spout/Reader/XLSX/ReaderTest.php index b9e032e..e51f2df 100644 --- a/tests/Spout/Reader/XLSX/ReaderTest.php +++ b/tests/Spout/Reader/XLSX/ReaderTest.php @@ -9,8 +9,6 @@ use Box\Spout\TestUsingResource; /** * Class ReaderTest - * - * @package Box\Spout\Reader\XLSX */ class ReaderTest extends \PHPUnit_Framework_TestCase { @@ -51,7 +49,7 @@ class ReaderTest extends \PHPUnit_Framework_TestCase ['one_sheet_with_shared_strings.xlsx', 5, 5], ['one_sheet_with_inline_strings.xlsx', 5, 5], ['two_sheets_with_shared_strings.xlsx', 10, 5], - ['two_sheets_with_inline_strings.xlsx', 10, 5] + ['two_sheets_with_inline_strings.xlsx', 10, 5], ]; } @@ -236,7 +234,7 @@ class ReaderTest extends \PHPUnit_Framework_TestCase \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); } @@ -258,7 +256,7 @@ class ReaderTest extends \PHPUnit_Framework_TestCase \DateTime::createFromFormat('Y-m-d H:i:s', '1900-01-01 23:29:00'), \DateTime::createFromFormat('Y-m-d H:i:s', '1900-01-01 01:42:25'), \DateTime::createFromFormat('Y-m-d H:i:s', '1900-01-01 13:42:25'), - ] + ], ]; $this->assertEquals($expectedRows, $allRows); } @@ -579,7 +577,7 @@ class ReaderTest extends \PHPUnit_Framework_TestCase $expectedRows = [ ['A', 'B', 'C'], ['1', '2', '3'], - ['0', '0', '0'] + ['0', '0', '0'], ]; $this->assertEquals($expectedRows, $allRows, 'There should be only 3 rows, because zeros (0) are valid values'); } @@ -595,12 +593,11 @@ class ReaderTest extends \PHPUnit_Framework_TestCase $expectedRows = [ ['A', 'B', 'C'], ['0', '', ''], - ['1', '1', ''] + ['1', '1', ''], ]; $this->assertEquals($expectedRows, $allRows, 'There should be 3 rows, with equal length'); } - /** * https://github.com/box/spout/issues/195 * @return void @@ -618,11 +615,10 @@ class ReaderTest extends \PHPUnit_Framework_TestCase $this->assertEquals($expectedRows, $allRows, 'Cell values should not be trimmed'); } - /** * @param string $fileName - * @param bool|void $shouldFormatDates - * @param bool|void $shouldPreserveEmptyRows + * @param bool $shouldFormatDates + * @param bool $shouldPreserveEmptyRows * @return array All the read rows the given file */ private function getAllRowsForFile($fileName, $shouldFormatDates = false, $shouldPreserveEmptyRows = false) diff --git a/tests/Spout/Reader/XLSX/SheetTest.php b/tests/Spout/Reader/XLSX/SheetTest.php index b8c332b..b4291fb 100644 --- a/tests/Spout/Reader/XLSX/SheetTest.php +++ b/tests/Spout/Reader/XLSX/SheetTest.php @@ -8,8 +8,6 @@ use Box\Spout\TestUsingResource; /** * Class SheetTest - * - * @package Box\Spout\Reader\XLSX */ class SheetTest extends \PHPUnit_Framework_TestCase { diff --git a/tests/Spout/ReflectionHelper.php b/tests/Spout/ReflectionHelper.php index df02de8..c078f3b 100644 --- a/tests/Spout/ReflectionHelper.php +++ b/tests/Spout/ReflectionHelper.php @@ -5,7 +5,7 @@ */ class ReflectionHelper { - private static $privateVarsToReset = array(); + private static $privateVarsToReset = []; /** * Resets any static vars that were set to their @@ -20,7 +20,7 @@ class ReflectionHelper self::setStaticValue($class, $valueName, $originalValue, $saveOriginalValue = false); } } - self::$privateVarsToReset = array(); + self::$privateVarsToReset = []; } /** @@ -51,7 +51,7 @@ class ReflectionHelper * @param string $class * @param string $valueName * @param mixed|null $value - * @param bool|void $saveOriginalValue + * @param bool $saveOriginalValue * @return void */ public static function setStaticValue($class, $valueName, $value, $saveOriginalValue = true) diff --git a/tests/Spout/TestUsingResource.php b/tests/Spout/TestUsingResource.php index 2b200d9..551f86b 100644 --- a/tests/Spout/TestUsingResource.php +++ b/tests/Spout/TestUsingResource.php @@ -4,8 +4,6 @@ namespace Box\Spout; /** * Trait TestUsingResource - * - * @package Box\Spout */ trait TestUsingResource { diff --git a/tests/Spout/Writer/CSV/WriterTest.php b/tests/Spout/Writer/CSV/WriterTest.php index 0d07144..d5041e9 100644 --- a/tests/Spout/Writer/CSV/WriterTest.php +++ b/tests/Spout/Writer/CSV/WriterTest.php @@ -2,9 +2,9 @@ namespace Box\Spout\Writer\CSV; -use Box\Spout\TestUsingResource; -use Box\Spout\Common\Type; use Box\Spout\Common\Helper\EncodingHelper; +use Box\Spout\Common\Type; +use Box\Spout\TestUsingResource; use Box\Spout\Writer\Common\Creator\EntityFactory; use Box\Spout\Writer\Common\Creator\ManagerFactory; use Box\Spout\Writer\Common\Entity\Cell; @@ -12,8 +12,6 @@ use Box\Spout\Writer\WriterFactory; /** * Class WriterTest - * - * @package Box\Spout\Writer\CSV */ class WriterTest extends \PHPUnit_Framework_TestCase { @@ -210,7 +208,7 @@ class WriterTest extends \PHPUnit_Framework_TestCase public function testWriteShouldAcceptCellObjects() { $allRows = [ - [new Cell('String Value'), new Cell(1)] + [new Cell('String Value'), new Cell(1)], ]; $writtenContent = $this->writeToCsvFileAndReturnWrittenContent($allRows, 'csv_with_cell_objects.csv'); $writtenContent = $this->trimWrittenContent($writtenContent); @@ -222,8 +220,8 @@ class WriterTest extends \PHPUnit_Framework_TestCase * @param string $fileName * @param string $fieldDelimiter * @param string $fieldEnclosure - * @param bool $shouldAddBOM - * @return null|string + * @param bool $shouldAddBOM + * @return string|null */ private function writeToCsvFileAndReturnWrittenContent($allRows, $fileName, $fieldDelimiter = ',', $fieldEnclosure = '"', $shouldAddBOM = true) { diff --git a/tests/Spout/Writer/Common/Creator/StyleBuilderTest.php b/tests/Spout/Writer/Common/Creator/StyleBuilderTest.php index f250e8e..36e94d4 100644 --- a/tests/Spout/Writer/Common/Creator/StyleBuilderTest.php +++ b/tests/Spout/Writer/Common/Creator/StyleBuilderTest.php @@ -8,8 +8,6 @@ use Box\Spout\Writer\Common\Manager\Style\StyleMerger; /** * Class StyleManagerTest - * - * @package Box\Spout\Writer\Common\Creator\Style */ class StyleBuilderTest extends \PHPUnit_Framework_TestCase { diff --git a/tests/Spout/Writer/Common/Entity/SheetTest.php b/tests/Spout/Writer/Common/Entity/SheetTest.php index 37ddabf..678449e 100644 --- a/tests/Spout/Writer/Common/Entity/SheetTest.php +++ b/tests/Spout/Writer/Common/Entity/SheetTest.php @@ -7,8 +7,6 @@ use Box\Spout\Writer\Common\Manager\SheetManager; /** * Class SheetTest - * - * @package Box\Spout\Writer\Common\Entity */ class SheetTest extends \PHPUnit_Framework_TestCase { diff --git a/tests/Spout/Writer/Common/Entity/Style/BorderTest.php b/tests/Spout/Writer/Common/Entity/Style/BorderTest.php index e9cd1d2..4117c91 100644 --- a/tests/Spout/Writer/Common/Entity/Style/BorderTest.php +++ b/tests/Spout/Writer/Common/Entity/Style/BorderTest.php @@ -9,8 +9,6 @@ use Box\Spout\Writer\Common\Entity\Style\Color; /** * Class BorderTest - * - * @package Box\Spout\Writer\Common\EntityStyle */ class BorderTest extends \PHPUnit_Framework_TestCase { @@ -21,7 +19,7 @@ class BorderTest extends \PHPUnit_Framework_TestCase { $noConstructorParams = new Border(); $withConstructorParams = new Border([ - new BorderPart(Border::LEFT) + new BorderPart(Border::LEFT), ]); } @@ -72,7 +70,7 @@ class BorderTest extends \PHPUnit_Framework_TestCase { $border = new Border(); $border->setParts([ - new BorderPart(Border::LEFT) + new BorderPart(Border::LEFT), ]); $this->assertEquals(1, count($border->getParts()), 'It should be possible to set the border parts'); diff --git a/tests/Spout/Writer/Common/Entity/Style/ColorTest.php b/tests/Spout/Writer/Common/Entity/Style/ColorTest.php index 34ffe24..15ad990 100644 --- a/tests/Spout/Writer/Common/Entity/Style/ColorTest.php +++ b/tests/Spout/Writer/Common/Entity/Style/ColorTest.php @@ -4,8 +4,6 @@ namespace Box\Spout\Writer\Common\Entity\Style; /** * Class ColorTest - * - * @package Box\Spout\Writer\Common\Entity\Style */ class ColorTest extends \PHPUnit_Framework_TestCase { @@ -14,7 +12,6 @@ class ColorTest extends \PHPUnit_Framework_TestCase */ public function dataProviderForTestRGB() { - return [ [0, 0, 0, Color::BLACK], [255, 255, 255, Color::WHITE], diff --git a/tests/Spout/Writer/Common/Helper/CellHelperTest.php b/tests/Spout/Writer/Common/Helper/CellHelperTest.php index a07046f..1468bfa 100644 --- a/tests/Spout/Writer/Common/Helper/CellHelperTest.php +++ b/tests/Spout/Writer/Common/Helper/CellHelperTest.php @@ -4,8 +4,6 @@ namespace Box\Spout\Writer\Common\Helper; /** * Class CellHelperTest - * - * @package Box\Spout\Writer\Common\Helper */ class CellHelperTest extends \PHPUnit_Framework_TestCase { @@ -41,14 +39,14 @@ class CellHelperTest extends \PHPUnit_Framework_TestCase public function testIsEmpty() { $this->assertTrue(CellHelper::isEmpty(null)); - $this->assertTrue(CellHelper::isEmpty("")); + $this->assertTrue(CellHelper::isEmpty('')); - $this->assertFalse(CellHelper::isEmpty("string")); + $this->assertFalse(CellHelper::isEmpty('string')); $this->assertFalse(CellHelper::isEmpty(0)); $this->assertFalse(CellHelper::isEmpty(1)); $this->assertFalse(CellHelper::isEmpty(true)); $this->assertFalse(CellHelper::isEmpty(false)); - $this->assertFalse(CellHelper::isEmpty(["string"])); + $this->assertFalse(CellHelper::isEmpty(['string'])); $this->assertFalse(CellHelper::isEmpty(new \stdClass())); } @@ -57,14 +55,14 @@ class CellHelperTest extends \PHPUnit_Framework_TestCase */ public function testIsNonEmptyString() { - $this->assertTrue(CellHelper::isNonEmptyString("string")); + $this->assertTrue(CellHelper::isNonEmptyString('string')); - $this->assertFalse(CellHelper::isNonEmptyString("")); + $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(['string'])); $this->assertFalse(CellHelper::isNonEmptyString(new \stdClass())); $this->assertFalse(CellHelper::isNonEmptyString(null)); } @@ -83,8 +81,8 @@ class CellHelperTest extends \PHPUnit_Framework_TestCase $this->assertTrue(CellHelper::isNumeric(0b10100111001)); $this->assertTrue(CellHelper::isNumeric(1337e0)); - $this->assertFalse(CellHelper::isNumeric("0")); - $this->assertFalse(CellHelper::isNumeric("42")); + $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())); @@ -101,10 +99,10 @@ class CellHelperTest extends \PHPUnit_Framework_TestCase $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('0')); + $this->assertFalse(CellHelper::isBoolean('1')); + $this->assertFalse(CellHelper::isBoolean('true')); + $this->assertFalse(CellHelper::isBoolean('false')); $this->assertFalse(CellHelper::isBoolean([true])); $this->assertFalse(CellHelper::isBoolean(new \stdClass())); $this->assertFalse(CellHelper::isBoolean(null)); diff --git a/tests/Spout/Writer/Common/Manager/Style/StyleManagerTest.php b/tests/Spout/Writer/Common/Manager/Style/StyleManagerTest.php index 2978087..4f4341e 100644 --- a/tests/Spout/Writer/Common/Manager/Style/StyleManagerTest.php +++ b/tests/Spout/Writer/Common/Manager/Style/StyleManagerTest.php @@ -7,8 +7,6 @@ use Box\Spout\Writer\Common\Entity\Cell; /** * Class StyleManagerTest - * - * @package Box\Spout\Writer\Common\Manager\Style */ class StyleManagerTest extends \PHPUnit_Framework_TestCase { diff --git a/tests/Spout/Writer/Common/Manager/Style/StyleMergerTest.php b/tests/Spout/Writer/Common/Manager/Style/StyleMergerTest.php index d3b7d2d..ed87af4 100644 --- a/tests/Spout/Writer/Common/Manager/Style/StyleMergerTest.php +++ b/tests/Spout/Writer/Common/Manager/Style/StyleMergerTest.php @@ -8,8 +8,6 @@ use Box\Spout\Writer\Common\Entity\Style\Style; /** * Class StyleMergerTest - * - * @package Box\Spout\Writer\Common\Manager\Style */ class StyleMergerTest extends \PHPUnit_Framework_TestCase { diff --git a/tests/Spout/Writer/Common/Manager/Style/StyleRegistryTest.php b/tests/Spout/Writer/Common/Manager/Style/StyleRegistryTest.php index b11b2ed..52a2d36 100644 --- a/tests/Spout/Writer/Common/Manager/Style/StyleRegistryTest.php +++ b/tests/Spout/Writer/Common/Manager/Style/StyleRegistryTest.php @@ -2,16 +2,11 @@ namespace Box\Spout\Writer\Common\Manager\Style; -use Box\Spout\Writer\Common\Creator\Style\BorderBuilder; use Box\Spout\Writer\Common\Creator\Style\StyleBuilder; -use Box\Spout\Writer\Common\Entity\Style\Border; -use Box\Spout\Writer\Common\Entity\Style\Color; use Box\Spout\Writer\Common\Entity\Style\Style; /** * Class StyleRegistryTest - * - * @package Box\Spout\Writer\Common\Manager\Style */ class StyleRegistryTest extends \PHPUnit_Framework_TestCase { diff --git a/tests/Spout/Writer/ODS/Manager/Style/StyleRegistryTest.php b/tests/Spout/Writer/ODS/Manager/Style/StyleRegistryTest.php index ef5a9e5..ae3ecf4 100644 --- a/tests/Spout/Writer/ODS/Manager/Style/StyleRegistryTest.php +++ b/tests/Spout/Writer/ODS/Manager/Style/StyleRegistryTest.php @@ -6,8 +6,6 @@ use Box\Spout\Writer\Common\Creator\Style\StyleBuilder; /** * Class StyleRegistryTest - * - * @package Box\Spout\Writer\ODS\Manager\Style */ class StyleRegistryTest extends \PHPUnit_Framework_TestCase { @@ -17,6 +15,7 @@ class StyleRegistryTest extends \PHPUnit_Framework_TestCase private function getStyleRegistry() { $defaultStyle = (new StyleBuilder())->build(); + return new StyleRegistry($defaultStyle); } @@ -29,10 +28,10 @@ class StyleRegistryTest extends \PHPUnit_Framework_TestCase $this->assertEquals(1, count($styleRegistry->getUsedFonts()), 'There should only be the default font name'); - $style1 = (new StyleBuilder())->setFontName("MyFont1")->build(); + $style1 = (new StyleBuilder())->setFontName('MyFont1')->build(); $styleRegistry->registerStyle($style1); - $style2 = (new StyleBuilder())->setFontName("MyFont2")->build(); + $style2 = (new StyleBuilder())->setFontName('MyFont2')->build(); $styleRegistry->registerStyle($style2); $this->assertEquals(3, count($styleRegistry->getUsedFonts()), 'There should be 3 fonts registered'); diff --git a/tests/Spout/Writer/ODS/SheetTest.php b/tests/Spout/Writer/ODS/SheetTest.php index f6dc73a..d8163dd 100644 --- a/tests/Spout/Writer/ODS/SheetTest.php +++ b/tests/Spout/Writer/ODS/SheetTest.php @@ -12,8 +12,6 @@ use Box\Spout\Writer\WriterFactory; /** * Class SheetTest - * - * @package Box\Spout\Writer\ODS */ class SheetTest extends \PHPUnit_Framework_TestCase { diff --git a/tests/Spout/Writer/ODS/WriterTest.php b/tests/Spout/Writer/ODS/WriterTest.php index c0bcfc0..86e204e 100644 --- a/tests/Spout/Writer/ODS/WriterTest.php +++ b/tests/Spout/Writer/ODS/WriterTest.php @@ -10,12 +10,11 @@ use Box\Spout\Writer\Common\Creator\EntityFactory; use Box\Spout\Writer\Common\Creator\ManagerFactory; use Box\Spout\Writer\Common\Helper\ZipHelper; use Box\Spout\Writer\Common\Entity\Cell; +use Box\Spout\Writer\Common\Helper\ZipHelper; use Box\Spout\Writer\WriterFactory; /** * Class WriterTest - * - * @package Box\Spout\Writer\ODS */ class WriterTest extends \PHPUnit_Framework_TestCase { @@ -306,6 +305,7 @@ class WriterTest extends \PHPUnit_Framework_TestCase [['foo', 'bar'], 2, 0], ]; } + /** * @dataProvider dataProviderForTestAddRowShouldUseNumberColumnsRepeatedForRepeatedValues * @@ -326,7 +326,7 @@ class WriterTest extends \PHPUnit_Framework_TestCase if ($expectedNumTableCells === 1) { $tableCellNode = $tableCellNodes->item(0); - $numColumnsRepeated = intval($tableCellNode->getAttribute('table:number-columns-repeated')); + $numColumnsRepeated = (int) ($tableCellNode->getAttribute('table:number-columns-repeated')); $this->assertEquals($expectedNumColumnsRepeated, $numColumnsRepeated); } else { foreach ($tableCellNodes as $tableCellNode) { @@ -536,7 +536,7 @@ class WriterTest extends \PHPUnit_Framework_TestCase foreach ($dataRows as $dataRow) { /** @var Cell $cell */ foreach ($dataRow as $cell) { - $this->assertValueWasWritten($fileName, (string)$cell->getValue(), ''); + $this->assertValueWasWritten($fileName, (string) $cell->getValue(), ''); } } } @@ -624,7 +624,6 @@ class WriterTest extends \PHPUnit_Framework_TestCase $xmlContents = file_get_contents('zip://' . $pathToContentFile); $this->assertContains($value, $xmlContents, $message); - } /** @@ -665,6 +664,7 @@ class WriterTest extends \PHPUnit_Framework_TestCase private function getSheetXmlNode($fileName, $sheetIndex) { $xmlReader = $this->moveReaderToCorrectTableNode($fileName, $sheetIndex); + return $xmlReader->expand(); } @@ -676,6 +676,7 @@ class WriterTest extends \PHPUnit_Framework_TestCase private function getSheetXmlNodeAsString($fileName, $sheetIndex) { $xmlReader = $this->moveReaderToCorrectTableNode($fileName, $sheetIndex); + return $xmlReader->readOuterXml(); } diff --git a/tests/Spout/Writer/ODS/WriterWithStyleTest.php b/tests/Spout/Writer/ODS/WriterWithStyleTest.php index 6eb9972..84b55be 100644 --- a/tests/Spout/Writer/ODS/WriterWithStyleTest.php +++ b/tests/Spout/Writer/ODS/WriterWithStyleTest.php @@ -11,15 +11,14 @@ use Box\Spout\Writer\Common\Entity\Cell; use Box\Spout\Writer\ODS\Helper\BorderHelper; use Box\Spout\Writer\Common\Entity\Style\Border; use Box\Spout\Writer\Common\Creator\Style\BorderBuilder; +use Box\Spout\Writer\Common\Creator\Style\StyleBuilder; +use Box\Spout\Writer\Common\Entity\Style\Border; use Box\Spout\Writer\Common\Entity\Style\Color; use Box\Spout\Writer\Common\Entity\Style\Style; -use Box\Spout\Writer\Common\Creator\Style\StyleBuilder; use Box\Spout\Writer\WriterFactory; /** * Class WriterWithStyleTest - * - * @package Box\Spout\Writer\ODS */ class WriterWithStyleTest extends \PHPUnit_Framework_TestCase { @@ -312,7 +311,6 @@ class WriterWithStyleTest extends \PHPUnit_Framework_TestCase $borderBottomGreenThickSolid = (new BorderBuilder()) ->setBorderBottom(Color::GREEN, Border::WIDTH_THICK, Border::STYLE_SOLID)->build(); - $borderTopRedThinDashed = (new BorderBuilder()) ->setBorderTop(Color::RED, Border::WIDTH_THIN, Border::STYLE_DASHED)->build(); diff --git a/tests/Spout/Writer/WriterFactoryTest.php b/tests/Spout/Writer/WriterFactoryTest.php index 528eff3..f972549 100644 --- a/tests/Spout/Writer/WriterFactoryTest.php +++ b/tests/Spout/Writer/WriterFactoryTest.php @@ -4,8 +4,6 @@ namespace Box\Spout\Writer; /** * Class WriterFactoryTest - * - * @package Box\Spout\Writer */ class WriterFactoryTest extends \PHPUnit_Framework_TestCase { diff --git a/tests/Spout/Writer/XLSX/Manager/Style/StyleManagerTest.php b/tests/Spout/Writer/XLSX/Manager/Style/StyleManagerTest.php index 867fbf7..733e4a2 100644 --- a/tests/Spout/Writer/XLSX/Manager/Style/StyleManagerTest.php +++ b/tests/Spout/Writer/XLSX/Manager/Style/StyleManagerTest.php @@ -4,8 +4,6 @@ namespace Box\Spout\Writer\XLSX\Manager\Style; /** * Class StyleManagerTest - * - * @package Box\Spout\Writer\XLSX\Manager\Style */ class StyleManagerTest extends \PHPUnit_Framework_TestCase { diff --git a/tests/Spout/Writer/XLSX/Manager/Style/StyleRegistryTest.php b/tests/Spout/Writer/XLSX/Manager/Style/StyleRegistryTest.php index 0cbd5e3..3b77d0b 100644 --- a/tests/Spout/Writer/XLSX/Manager/Style/StyleRegistryTest.php +++ b/tests/Spout/Writer/XLSX/Manager/Style/StyleRegistryTest.php @@ -8,8 +8,6 @@ use Box\Spout\Writer\Common\Entity\Style\Color; /** * Class StyleRegistryTest - * - * @package Box\Spout\Writer\XLSX\Manager\Style */ class StyleRegistryTest extends \PHPUnit_Framework_TestCase { @@ -19,6 +17,7 @@ class StyleRegistryTest extends \PHPUnit_Framework_TestCase private function getStyleRegistry() { $defaultStyle = (new StyleBuilder())->build(); + return new StyleRegistry($defaultStyle); } @@ -53,7 +52,7 @@ class StyleRegistryTest extends \PHPUnit_Framework_TestCase public function testRegisterStyleAlsoRegistersBorders() { $styleRegistry = $this->getStyleRegistry(); - + $borderLeft = (new BorderBuilder())->setBorderLeft()->build(); $borderRight = (new BorderBuilder())->setBorderRight()->build(); diff --git a/tests/Spout/Writer/XLSX/SheetTest.php b/tests/Spout/Writer/XLSX/SheetTest.php index 3240c2b..20e56a7 100644 --- a/tests/Spout/Writer/XLSX/SheetTest.php +++ b/tests/Spout/Writer/XLSX/SheetTest.php @@ -12,8 +12,6 @@ use Box\Spout\Writer\WriterFactory; /** * Class SheetTest - * - * @package Box\Spout\Writer\XLSX */ class SheetTest extends \PHPUnit_Framework_TestCase { diff --git a/tests/Spout/Writer/XLSX/WriterTest.php b/tests/Spout/Writer/XLSX/WriterTest.php index 7c50560..be5539e 100644 --- a/tests/Spout/Writer/XLSX/WriterTest.php +++ b/tests/Spout/Writer/XLSX/WriterTest.php @@ -13,8 +13,6 @@ use Box\Spout\Writer\XLSX\Manager\WorksheetManager; /** * Class WriterTest - * - * @package Box\Spout\Writer\XLSX */ class WriterTest extends \PHPUnit_Framework_TestCase { @@ -521,7 +519,7 @@ class WriterTest extends \PHPUnit_Framework_TestCase { $fileName = 'test_add_row_should_escape_control_characters.xlsx'; $dataRows = [ - ['control '.chr(21).' character'], + ['control ' . chr(21) . ' character'], ]; $this->writeToXLSXFile($dataRows, $fileName); @@ -576,7 +574,7 @@ class WriterTest extends \PHPUnit_Framework_TestCase [new Cell('i am a string')], ]; $dataRowsInline = [ - [new Cell(51465), new Cell(true), new Cell(51465.5)] + [new Cell(51465), new Cell(true), new Cell(51465.5)], ]; $dataRows = array_merge($dataRowsShared, $dataRowsInline); @@ -586,7 +584,7 @@ class WriterTest extends \PHPUnit_Framework_TestCase foreach ($dataRowsShared as $dataRow) { /** @var Cell $cell */ foreach ($dataRow as $cell) { - $this->assertSharedStringWasWritten($fileName, (string)$cell->getValue()); + $this->assertSharedStringWasWritten($fileName, (string) $cell->getValue()); } } @@ -685,7 +683,7 @@ class WriterTest extends \PHPUnit_Framework_TestCase $pathToSheetFile = $resourcePath . '#xl/worksheets/sheet' . $sheetIndex . '.xml'; $xmlContents = file_get_contents('zip://' . $pathToSheetFile); - $this->assertContains((string)$inlineData, $xmlContents, $message); + $this->assertContains((string) $inlineData, $xmlContents, $message); } /** @@ -701,7 +699,7 @@ class WriterTest extends \PHPUnit_Framework_TestCase $pathToSheetFile = $resourcePath . '#xl/worksheets/sheet' . $sheetIndex . '.xml'; $xmlContents = file_get_contents('zip://' . $pathToSheetFile); - $this->assertNotContains((string)$inlineData, $xmlContents, $message); + $this->assertNotContains((string) $inlineData, $xmlContents, $message); } /** diff --git a/tests/Spout/Writer/XLSX/WriterWithStyleTest.php b/tests/Spout/Writer/XLSX/WriterWithStyleTest.php index 5d6318b..159a8bb 100644 --- a/tests/Spout/Writer/XLSX/WriterWithStyleTest.php +++ b/tests/Spout/Writer/XLSX/WriterWithStyleTest.php @@ -10,17 +10,16 @@ use Box\Spout\Writer\Common\Creator\ManagerFactory; use Box\Spout\Writer\Common\Entity\Cell; use Box\Spout\Writer\Common\Entity\Style\Border; use Box\Spout\Writer\Common\Creator\Style\BorderBuilder; +use Box\Spout\Writer\Common\Creator\Style\StyleBuilder; +use Box\Spout\Writer\Common\Entity\Style\Border; use Box\Spout\Writer\Common\Entity\Style\Color; use Box\Spout\Writer\Common\Entity\Style\Style; -use Box\Spout\Writer\Common\Creator\Style\StyleBuilder; use Box\Spout\Writer\Common\Manager\Style\StyleMerger; use Box\Spout\Writer\WriterFactory; use Box\Spout\Writer\XLSX\Manager\OptionsManager; /** * Class WriterWithStyleTest - * - * @package Box\Spout\Writer\XLSX */ class WriterWithStyleTest extends \PHPUnit_Framework_TestCase { @@ -323,7 +322,7 @@ class WriterWithStyleTest extends \PHPUnit_Framework_TestCase { $fileName = 'test_add_background_color.xlsx'; $dataRows = [ - ["BgColor"], + ['BgColor'], ]; $style = (new StyleBuilder())->setBackgroundColor(Color::WHITE)->build(); $this->writeToXLSXFile($dataRows, $fileName, $style); @@ -341,7 +340,7 @@ class WriterWithStyleTest extends \PHPUnit_Framework_TestCase $this->assertEquals(2, $styleXfsElements->getAttribute('count'), '2 cell xfs present - a default one and a custom one'); $customFillId = $styleXfsElements->lastChild->getAttribute('fillId'); - $this->assertEquals(2, (int)$customFillId, 'The custom fill id should have the index 2'); + $this->assertEquals(2, (int) $customFillId, 'The custom fill id should have the index 2'); } /** @@ -351,13 +350,13 @@ class WriterWithStyleTest extends \PHPUnit_Framework_TestCase { $fileName = 'test_add_background_color_shared_definition.xlsx'; $dataRows = [ - ["row-bold-background-red"], - ["row-background-red"], + ['row-bold-background-red'], + ['row-background-red'], ]; $styles = [ (new StyleBuilder())->setBackgroundColor(Color::RED)->setFontBold()->build(), - (new StyleBuilder())->setBackgroundColor(Color::RED)->build() + (new StyleBuilder())->setBackgroundColor(Color::RED)->build(), ]; $this->writeToXLSXFileWithMultipleStyles($dataRows, $fileName, $styles); @@ -377,10 +376,10 @@ class WriterWithStyleTest extends \PHPUnit_Framework_TestCase ); $firstCustomId = $styleXfsElements->childNodes->item(1)->getAttribute('fillId'); - $this->assertEquals(2, (int)$firstCustomId, 'The first custom fill id should have the index 2'); + $this->assertEquals(2, (int) $firstCustomId, 'The first custom fill id should have the index 2'); $secondCustomId = $styleXfsElements->childNodes->item(2)->getAttribute('fillId'); - $this->assertEquals(2, (int)$secondCustomId, 'The second custom fill id should have the index 2'); + $this->assertEquals(2, (int) $secondCustomId, 'The second custom fill id should have the index 2'); } /** @@ -399,7 +398,6 @@ class WriterWithStyleTest extends \PHPUnit_Framework_TestCase $borderBottomGreenThickSolid = (new BorderBuilder()) ->setBorderBottom(Color::GREEN, Border::WIDTH_THICK, Border::STYLE_SOLID)->build(); - $borderTopRedThinDashed = (new BorderBuilder()) ->setBorderTop(Color::RED, Border::WIDTH_THIN, Border::STYLE_DASHED)->build(); @@ -441,15 +439,15 @@ class WriterWithStyleTest extends \PHPUnit_Framework_TestCase $borderElements = $this->getXmlSectionFromStylesXmlFile($fileName, 'borders'); $correctOrdering = [ - 'left', 'right', 'top', 'bottom' + 'left', 'right', 'top', 'bottom', ]; - /** @var $borderNode \DOMElement */ + /** @var \DOMElement $borderNode */ foreach ($borderElements->childNodes as $borderNode) { $borderParts = $borderNode->childNodes; $ordering = []; - /** @var $part \DOMText */ + /** @var \DOMText $part */ foreach ($borderParts as $part) { if ($part instanceof \DOMElement) { $ordering[] = $part->nodeName; @@ -457,7 +455,7 @@ class WriterWithStyleTest extends \PHPUnit_Framework_TestCase } $this->assertEquals($correctOrdering, $ordering, 'The border parts are in correct ordering'); - }; + } } /** @@ -516,7 +514,7 @@ class WriterWithStyleTest extends \PHPUnit_Framework_TestCase $emptyStyle, $fontStyle, $borderRightStyle, - $borderRightFontBoldStyle + $borderRightFontBoldStyle, ]; $this->writeToXLSXFileWithMultipleStyles($dataRows, $fileName, $styles); @@ -542,11 +540,12 @@ class WriterWithStyleTest extends \PHPUnit_Framework_TestCase $bordersApplied = 0; /** @var \DOMElement $node */ foreach ($styleXfsElements->childNodes as $node) { - if ($node->getAttribute('applyBorder') == 1) { + $shouldApplyBorder = ((int) $node->getAttribute('applyBorder') === 1); + if ($shouldApplyBorder) { $bordersApplied++; - $this->assertTrue((int)$node->getAttribute('borderId') > 0, 'BorderId is greater than 0'); + $this->assertTrue((int) $node->getAttribute('borderId') > 0, 'BorderId is greater than 0'); } else { - $this->assertTrue((int)$node->getAttribute('borderId') === 0, 'BorderId is 0'); + $this->assertTrue((int) $node->getAttribute('borderId') === 0, 'BorderId is 0'); } } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 902b4e9..df50f53 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -1,9 +1,10 @@