diff --git a/.travis.yml b/.travis.yml index 365ee595f..abc92c474 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,14 +7,14 @@ matrix: include: - php: 7.2 env: WITH_PHPUNIT=true + - php: 7.2 + env: WITH_PHPSTAN=true - php: 7.3 env: WITH_PHPUNIT=true - php: 7.3 env: WITH_PHPUNIT=true WITH_COVERAGE=true - php: 7.4 env: WITH_PHPUNIT=true - - php: 8.0 - env: WITH_PHPUNIT=true cache: @@ -30,6 +30,9 @@ before_install: if [[ "$WITH_CS" != "true" ]]; then composer remove friendsofphp/php-cs-fixer --dev --no-update fi + if [[ "$WITH_PHPSTAN" != "true" ]]; then + composer remove phpstan/phpstan --dev --no-update + fi - composer validate install: @@ -44,6 +47,10 @@ script: if [[ "$WITH_CS" == "true" ]]; then vendor/bin/php-cs-fixer fix --config=.php_cs.dist --verbose --diff --dry-run --diff-format=udiff fi + - | + if [[ "$WITH_PHPSTAN" == "true" ]]; then + vendor/bin/phpstan + fi - | if [[ "$WITH_PHPUNIT" == "true" ]]; then if [[ "$WITH_COVERAGE" == "true" ]]; then diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5db0f6e75..b9f14400a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -82,7 +82,28 @@ This will print a diff of proposed code style changes. To apply these suggestion vendor/bin/php-cs-fixer fix --config=.php_cs.dist ``` -### Step 9: Send the pull request +You can also use + +``` +composer phpcs +``` + +### Step 9: Fix phpstan + +Run the following command to analyse source code. +Make sure to fix all errors before submitting a pull request. + +``` +vendor/bin/phpstan analyse +``` + +You can also use + +``` +composer phpstan +``` + +### Step 10: Send the pull request Send the pull request from your feature branch to us. Be sure to include a description that lets us know what work you did. diff --git a/composer.json b/composer.json index 912349de9..62e4e0ef1 100644 --- a/composer.json +++ b/composer.json @@ -19,7 +19,8 @@ }, "require-dev": { "phpunit/phpunit": "^8", - "friendsofphp/php-cs-fixer": "^2" + "friendsofphp/php-cs-fixer": "^2", + "phpstan/phpstan": "^0.12.98" }, "suggest": { "ext-iconv": "To handle non UTF-8 CSV files (if \"php-intl\" is not already installed or is too limited)", @@ -30,6 +31,11 @@ "Box\\Spout\\": "src/Spout" } }, + "scripts": { + "phpunit": "vendor/bin/phpunit", + "phpstan": "vendor/bin/phpstan analyse", + "phpcs": "vendor/bin/php-cs-fixer fix --config=.php_cs.dist" + }, "extra": { "branch-alias": { "dev-master": "3.1.x-dev" diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 000000000..7c877801d --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,5 @@ +parameters: + level: 7 + paths: + - src + - tests diff --git a/src/Spout/Autoloader/Psr4Autoloader.php b/src/Spout/Autoloader/Psr4Autoloader.php index 37b6d4ac1..5c30ed784 100644 --- a/src/Spout/Autoloader/Psr4Autoloader.php +++ b/src/Spout/Autoloader/Psr4Autoloader.php @@ -12,7 +12,7 @@ class Psr4Autoloader * An associative array where the key is a namespace prefix and the value * is an array of base directories for classes in that namespace. * - * @var array + * @var array */ protected $prefixes = []; diff --git a/src/Spout/Common/Entity/Cell.php b/src/Spout/Common/Entity/Cell.php index 174831c29..660a9a0e6 100644 --- a/src/Spout/Common/Entity/Cell.php +++ b/src/Spout/Common/Entity/Cell.php @@ -77,7 +77,7 @@ public function __construct($value, Style $style = null) /** * @param mixed|null $value */ - public function setValue($value) + public function setValue($value) : void { $this->value = $value; $this->type = $this->detectType($value); @@ -102,7 +102,7 @@ public function getValueEvenIfError() /** * @param Style|null $style */ - public function setStyle($style) + public function setStyle($style) : void { $this->style = $style ?: new Style(); } @@ -126,7 +126,7 @@ public function getType() /** * @param int $type */ - public function setType($type) + public function setType($type) : void { $this->type = $type; } diff --git a/src/Spout/Common/Entity/Row.php b/src/Spout/Common/Entity/Row.php index 0cc49c730..bf55bed9b 100644 --- a/src/Spout/Common/Entity/Row.php +++ b/src/Spout/Common/Entity/Row.php @@ -95,7 +95,10 @@ public function getNumCells() return 0; } - return \max(\array_keys($this->cells)) + 1; + /** @var int $highest */ + $highest = \max(\array_keys($this->cells)); + + return $highest + 1; } /** @@ -118,7 +121,7 @@ public function setStyle($style) } /** - * @return array The row values, as array + * @return array The row values, as array */ public function toArray() { diff --git a/src/Spout/Common/Entity/Style/Border.php b/src/Spout/Common/Entity/Style/Border.php index bbf43ad30..3ab6e208a 100644 --- a/src/Spout/Common/Entity/Style/Border.php +++ b/src/Spout/Common/Entity/Style/Border.php @@ -22,11 +22,11 @@ class Border const WIDTH_MEDIUM = 'medium'; const WIDTH_THICK = 'thick'; - /** @var array A list of BorderPart objects for this border. */ + /** @var array A list of BorderPart objects for this border. */ private $parts = []; /** - * @param array $borderParts + * @param array $borderParts */ public function __construct(array $borderParts = []) { @@ -52,7 +52,7 @@ public function hasPart($name) } /** - * @return array + * @return array */ public function getParts() { @@ -61,7 +61,7 @@ public function getParts() /** * Set BorderParts - * @param array $parts + * @param array $parts * @return void */ public function setParts($parts) diff --git a/src/Spout/Common/Entity/Style/BorderPart.php b/src/Spout/Common/Entity/Style/BorderPart.php index c0874847e..be433fc03 100644 --- a/src/Spout/Common/Entity/Style/BorderPart.php +++ b/src/Spout/Common/Entity/Style/BorderPart.php @@ -32,7 +32,7 @@ class BorderPart protected $width; /** - * @var array Allowed style constants for parts. + * @var array Allowed style constants for parts. */ protected static $allowedStyles = [ 'none', @@ -43,7 +43,7 @@ class BorderPart ]; /** - * @var array Allowed names constants for border parts. + * @var array Allowed names constants for border parts. */ protected static $allowedNames = [ 'left', @@ -53,7 +53,7 @@ class BorderPart ]; /** - * @var array Allowed width constants for border parts. + * @var array Allowed width constants for border parts. */ protected static $allowedWidths = [ 'thin', @@ -159,7 +159,7 @@ public function setWidth($width) } /** - * @return array + * @return array */ public static function getAllowedStyles() { @@ -167,7 +167,7 @@ public static function getAllowedStyles() } /** - * @return array + * @return array */ public static function getAllowedNames() { @@ -175,7 +175,7 @@ public static function getAllowedNames() } /** - * @return array + * @return array */ public static function getAllowedWidths() { diff --git a/src/Spout/Common/Entity/Style/CellAlignment.php b/src/Spout/Common/Entity/Style/CellAlignment.php index 60fe83309..ed47f8470 100644 --- a/src/Spout/Common/Entity/Style/CellAlignment.php +++ b/src/Spout/Common/Entity/Style/CellAlignment.php @@ -13,6 +13,9 @@ abstract class CellAlignment const CENTER = 'center'; const JUSTIFY = 'justify'; + /** + * @var array + */ private static $VALID_ALIGNMENTS = [ self::LEFT => 1, self::RIGHT => 1, diff --git a/src/Spout/Common/Entity/Style/Style.php b/src/Spout/Common/Entity/Style/Style.php index 2bacc7afa..3fc020dea 100644 --- a/src/Spout/Common/Entity/Style/Style.php +++ b/src/Spout/Common/Entity/Style/Style.php @@ -66,7 +66,7 @@ class Style /** @var bool Whether the wrap text property was set */ private $hasSetWrapText = false; - /** @var Border */ + /** @var Border|null */ private $border; /** @var bool Whether border properties should be applied */ @@ -110,7 +110,7 @@ public function setId($id) } /** - * @return Border + * @return Border|null */ public function getBorder() { diff --git a/src/Spout/Common/Helper/CellTypeHelper.php b/src/Spout/Common/Helper/CellTypeHelper.php index 97d2e8dda..74e18f330 100644 --- a/src/Spout/Common/Helper/CellTypeHelper.php +++ b/src/Spout/Common/Helper/CellTypeHelper.php @@ -9,7 +9,7 @@ class CellTypeHelper { /** - * @param $value + * @param mixed $value * @return bool Whether the given value is considered "empty" */ public static function isEmpty($value) @@ -18,7 +18,7 @@ public static function isEmpty($value) } /** - * @param $value + * @param mixed $value * @return bool Whether the given value is a non empty string */ public static function isNonEmptyString($value) @@ -30,7 +30,7 @@ public static function isNonEmptyString($value) * Returns whether the given value is numeric. * A numeric value is from type "integer" or "double" ("float" is not returned by gettype). * - * @param $value + * @param mixed $value * @return bool Whether the given value is numeric */ public static function isNumeric($value) @@ -44,7 +44,7 @@ public static function isNumeric($value) * Returns whether the given value is boolean. * "true"/"false" and 0/1 are not booleans. * - * @param $value + * @param mixed $value * @return bool Whether the given value is boolean */ public static function isBoolean($value) @@ -55,7 +55,7 @@ public static function isBoolean($value) /** * Returns whether the given value is a DateTime or DateInterval object. * - * @param $value + * @param mixed $value * @return bool Whether the given value is a DateTime or DateInterval object */ public static function isDateTimeOrDateInterval($value) diff --git a/src/Spout/Common/Helper/EncodingHelper.php b/src/Spout/Common/Helper/EncodingHelper.php index 62ddf60bd..8ace6d3f2 100644 --- a/src/Spout/Common/Helper/EncodingHelper.php +++ b/src/Spout/Common/Helper/EncodingHelper.php @@ -27,7 +27,7 @@ class EncodingHelper /** @var \Box\Spout\Common\Helper\GlobalFunctionsHelper Helper to work with global functions */ protected $globalFunctionsHelper; - /** @var array Map representing the encodings supporting BOMs (key) and their associated BOM (value) */ + /** @var array Map representing the encodings supporting BOMs (key) and their associated BOM (value) */ protected $supportedEncodingsWithBom; /** @@ -143,7 +143,7 @@ protected function attemptConversion($string, $sourceEncoding, $targetEncoding) throw new EncodingConversionException("The conversion from $sourceEncoding to $targetEncoding is not supported. Please install \"iconv\" or \"PHP Intl\"."); } - if ($convertedString === false) { + if (!is_string($convertedString)) { throw new EncodingConversionException("The conversion from $sourceEncoding to $targetEncoding failed."); } diff --git a/src/Spout/Common/Helper/Escaper/XLSX.php b/src/Spout/Common/Helper/Escaper/XLSX.php index daef46e4d..6fef6c778 100644 --- a/src/Spout/Common/Helper/Escaper/XLSX.php +++ b/src/Spout/Common/Helper/Escaper/XLSX.php @@ -22,6 +22,7 @@ class XLSX implements EscaperInterface /** * Initializes the control characters if not already done + * @return void */ protected function initIfNeeded() { diff --git a/src/Spout/Common/Helper/FileSystemHelper.php b/src/Spout/Common/Helper/FileSystemHelper.php index 4d21fd38c..fed9bb838 100644 --- a/src/Spout/Common/Helper/FileSystemHelper.php +++ b/src/Spout/Common/Helper/FileSystemHelper.php @@ -19,7 +19,10 @@ class FileSystemHelper implements FileSystemHelperInterface */ public function __construct(string $baseFolderPath) { - $this->baseFolderRealPath = \realpath($baseFolderPath); + /** @var string $realPath */ + $realPath = \realpath($baseFolderPath); + + $this->baseFolderRealPath = $realPath; } /** @@ -127,6 +130,7 @@ protected function throwIfOperationNotInBaseFolder(string $operationFolderPath) if (!$this->baseFolderRealPath) { throw new IOException("The base folder path is invalid: {$this->baseFolderRealPath}"); } + /** @var string $operationFolderRealPath */ $isInBaseFolder = (\strpos($operationFolderRealPath, $this->baseFolderRealPath) === 0); if (!$isInBaseFolder) { throw new IOException("Cannot perform I/O operation outside of the base folder: {$this->baseFolderRealPath}"); diff --git a/src/Spout/Common/Helper/GlobalFunctionsHelper.php b/src/Spout/Common/Helper/GlobalFunctionsHelper.php index 5deb8d93f..ea4300019 100644 --- a/src/Spout/Common/Helper/GlobalFunctionsHelper.php +++ b/src/Spout/Common/Helper/GlobalFunctionsHelper.php @@ -33,7 +33,10 @@ public function fopen($fileName, $mode) */ public function fgets($handle, $length = null) { - return \fgets($handle, $length); + /** @var string $fgets */ + $fgets = \fgets($handle, $length); + + return $fgets; } /** @@ -46,7 +49,10 @@ public function fgets($handle, $length = null) */ public function fputs($handle, $string) { - return \fputs($handle, $string); + /** @var int $fputs */ + $fputs = \fputs($handle, $string); + + return $fputs; } /** @@ -82,7 +88,7 @@ public function fseek($handle, $offset) * @param int|null $length * @param string|null $delimiter * @param string|null $enclosure - * @return array + * @return array|false */ public function fgetcsv($handle, $length = null, $delimiter = null, $enclosure = null) { @@ -100,10 +106,10 @@ public function fgetcsv($handle, $length = null, $delimiter = null, $enclosure = * @see fputcsv() * * @param resource $handle - * @param array $fields + * @param array $fields * @param string|null $delimiter * @param string|null $enclosure - * @return int + * @return int|false */ public function fputcsv($handle, array $fields, $delimiter = null, $enclosure = null) { @@ -126,7 +132,10 @@ public function fputcsv($handle, array $fields, $delimiter = null, $enclosure = */ public function fwrite($handle, $string) { - return \fwrite($handle, $string); + /** @var int $fwrite */ + $fwrite = \fwrite($handle, $string); + + return $fwrite; } /** @@ -176,7 +185,10 @@ public function file_get_contents($filePath) { $realFilePath = $this->convertToUseRealPath($filePath); - return \file_get_contents($realFilePath); + /** @var string $content */ + $content = \file_get_contents($realFilePath); + + return $content; } /** @@ -197,7 +209,9 @@ protected function convertToUseRealPath($filePath) $realFilePath = 'zip://' . \realpath($documentPath) . '#' . $documentInsideZipPath; } } else { - $realFilePath = \realpath($filePath); + /** @var string $realPath */ + $realPath = \realpath($filePath); + $realFilePath = $realPath; } return $realFilePath; @@ -308,7 +322,7 @@ public function mb_convert_encoding($string, $sourceEncoding, $targetEncoding) * Wrapper around global function stream_get_wrappers() * @see stream_get_wrappers() * - * @return array + * @return array */ public function stream_get_wrappers() { diff --git a/src/Spout/Common/Helper/StringHelper.php b/src/Spout/Common/Helper/StringHelper.php index 6256b1e5f..84996df37 100644 --- a/src/Spout/Common/Helper/StringHelper.php +++ b/src/Spout/Common/Helper/StringHelper.php @@ -16,7 +16,7 @@ class StringHelper /** @var bool Whether the code is running with PHP7 or older versions */ private $isRunningPhp7OrOlder; - /** @var array Locale info, used for number formatting */ + /** @var array Locale info, used for number formatting */ private $localeInfo; /** @@ -93,13 +93,16 @@ public function getCharLastOccurrencePosition($char, $string) public function formatNumericValue($numericValue) { if ($this->isRunningPhp7OrOlder && is_float($numericValue)) { - return str_replace( + /** @var string $replaced */ + $replaced = str_replace( [$this->localeInfo['thousands_sep'], $this->localeInfo['decimal_point']], ['', '.'], - $numericValue + (string) $numericValue ); + + return $replaced; } - return $numericValue; + return (string) $numericValue; } } diff --git a/src/Spout/Common/Manager/OptionsManagerAbstract.php b/src/Spout/Common/Manager/OptionsManagerAbstract.php index 5670b95be..d8a853eb6 100644 --- a/src/Spout/Common/Manager/OptionsManagerAbstract.php +++ b/src/Spout/Common/Manager/OptionsManagerAbstract.php @@ -12,7 +12,7 @@ abstract class OptionsManagerAbstract implements OptionsManagerInterface /** @var string[] List of all supported option names */ private $supportedOptions = []; - /** @var array Associative array [OPTION_NAME => OPTION_VALUE] */ + /** @var array Associative array [OPTION_NAME => OPTION_VALUE] */ private $options = []; /** @@ -25,7 +25,7 @@ public function __construct() } /** - * @return array List of supported options + * @return array List of supported options */ abstract protected function getSupportedOptions(); diff --git a/src/Spout/Reader/CSV/Creator/InternalEntityFactory.php b/src/Spout/Reader/CSV/Creator/InternalEntityFactory.php index 65cf3eb7e..57291da47 100644 --- a/src/Spout/Reader/CSV/Creator/InternalEntityFactory.php +++ b/src/Spout/Reader/CSV/Creator/InternalEntityFactory.php @@ -84,7 +84,7 @@ public function createCell($cellValue) } /** - * @param array $cellValues + * @param array $cellValues * @return Row */ public function createRowFromArray(array $cellValues = []) diff --git a/src/Spout/Reader/CSV/Reader.php b/src/Spout/Reader/CSV/Reader.php index ca61ef2e2..1dc0b4f38 100644 --- a/src/Spout/Reader/CSV/Reader.php +++ b/src/Spout/Reader/CSV/Reader.php @@ -13,7 +13,7 @@ */ class Reader extends ReaderAbstract { - /** @var resource Pointer to the file to be written */ + /** @var resource|null Pointer to the file to be written */ protected $filePointer; /** @var SheetIterator To iterator over the CSV unique "sheet" */ @@ -84,13 +84,16 @@ protected function doesSupportStreamWrapper() */ protected function openReader($filePath) { - $this->originalAutoDetectLineEndings = \ini_get('auto_detect_line_endings'); + /** @var string $autoDetectLineEndings */ + $autoDetectLineEndings = \ini_get('auto_detect_line_endings'); + $this->originalAutoDetectLineEndings = $autoDetectLineEndings; \ini_set('auto_detect_line_endings', '1'); - $this->filePointer = $this->globalFunctionsHelper->fopen($filePath, 'r'); - if (!$this->filePointer) { + $filePointer = $this->globalFunctionsHelper->fopen($filePath, 'r'); + if (!is_resource($filePointer)) { throw new IOException("Could not open file $filePath for reading."); } + $this->filePointer = $filePointer; /** @var InternalEntityFactory $entityFactory */ $entityFactory = $this->entityFactory; diff --git a/src/Spout/Reader/CSV/RowIterator.php b/src/Spout/Reader/CSV/RowIterator.php index 78e665013..c022e6458 100644 --- a/src/Spout/Reader/CSV/RowIterator.php +++ b/src/Spout/Reader/CSV/RowIterator.php @@ -13,6 +13,7 @@ /** * Class RowIterator * Iterate over CSV rows. + * @implements IteratorInterface */ class RowIterator implements IteratorInterface { @@ -21,7 +22,7 @@ class RowIterator implements IteratorInterface */ const MAX_READ_BYTES_PER_LINE = 0; - /** @var resource Pointer to the CSV file to read */ + /** @var resource|null Pointer to the CSV file to read */ protected $filePointer; /** @var int Number of read rows */ @@ -147,6 +148,7 @@ protected function readDataForNextRow() if ($rowData !== false) { // str_replace will replace NULL values by empty strings + /** @phpstan-ignore-next-line */ $rowDataBufferAsArray = \str_replace(null, null, $rowData); $this->rowBuffer = $this->entityFactory->createRowFromArray($rowDataBufferAsArray); $this->numReadRows++; @@ -158,7 +160,7 @@ protected function readDataForNextRow() } /** - * @param array|bool $currentRowData + * @param array|bool $currentRowData * @return bool Whether the data for the current row can be returned or if we need to keep reading */ protected function shouldReadNextRow($currentRowData) @@ -179,7 +181,7 @@ protected function shouldReadNextRow($currentRowData) * we remove manually whitespace with ltrim or rtrim (depending on the order of the bytes) * * @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 + * @return array|false The row for the current file pointer, encoded in UTF-8 or FALSE if nothing to read */ protected function getNextUTF8EncodedRow() { @@ -210,7 +212,7 @@ protected function getNextUTF8EncodedRow() } /** - * @param array|bool $lineData Array containing the cells value for the line + * @param array|bool $lineData Array containing the cells value for the line * @return bool Whether the given line is empty */ protected function isEmptyLine($lineData) diff --git a/src/Spout/Reader/CSV/SheetIterator.php b/src/Spout/Reader/CSV/SheetIterator.php index 69eb58a0b..dcf96d342 100644 --- a/src/Spout/Reader/CSV/SheetIterator.php +++ b/src/Spout/Reader/CSV/SheetIterator.php @@ -7,6 +7,7 @@ /** * Class SheetIterator * Iterate over CSV unique "sheet". + * @implements IteratorInterface */ class SheetIterator implements IteratorInterface { diff --git a/src/Spout/Reader/Common/Creator/ReaderEntityFactory.php b/src/Spout/Reader/Common/Creator/ReaderEntityFactory.php index 06a9d9fbe..2c5d74ada 100644 --- a/src/Spout/Reader/Common/Creator/ReaderEntityFactory.php +++ b/src/Spout/Reader/Common/Creator/ReaderEntityFactory.php @@ -2,7 +2,6 @@ namespace Box\Spout\Reader\Common\Creator; -use Box\Spout\Common\Exception\UnsupportedTypeException; use Box\Spout\Common\Type; use Box\Spout\Reader\ReaderInterface; @@ -31,11 +30,10 @@ public static function createReaderFromFile(string $path) */ public static function createCSVReader() { - try { - return ReaderFactory::createFromType(Type::CSV); - } catch (UnsupportedTypeException $e) { - // should never happen - } + /** @var \Box\Spout\Reader\CSV\Reader $csvReader */ + $csvReader = ReaderFactory::createFromType(Type::CSV); + + return $csvReader; } /** @@ -45,11 +43,10 @@ public static function createCSVReader() */ public static function createXLSXReader() { - try { - return ReaderFactory::createFromType(Type::XLSX); - } catch (UnsupportedTypeException $e) { - // should never happen - } + /** @var \Box\Spout\Reader\XLSX\Reader $xlsxReader */ + $xlsxReader = ReaderFactory::createFromType(Type::XLSX); + + return $xlsxReader; } /** @@ -59,10 +56,9 @@ public static function createXLSXReader() */ public static function createODSReader() { - try { - return ReaderFactory::createFromType(Type::ODS); - } catch (UnsupportedTypeException $e) { - // should never happen - } + /** @var \Box\Spout\Reader\ODS\Reader $odsReader */ + $odsReader = ReaderFactory::createFromType(Type::ODS); + + return $odsReader; } } diff --git a/src/Spout/Reader/Common/XMLProcessor.php b/src/Spout/Reader/Common/XMLProcessor.php index 05ee970b5..2ac3f96a6 100644 --- a/src/Spout/Reader/Common/XMLProcessor.php +++ b/src/Spout/Reader/Common/XMLProcessor.php @@ -25,7 +25,7 @@ class XMLProcessor /** @var \Box\Spout\Reader\Wrapper\XMLReader The XMLReader object that will help read sheet's XML data */ protected $xmlReader; - /** @var array Registered callbacks */ + /** @var array Registered callbacks */ private $callbacks = []; /** @@ -39,7 +39,7 @@ public function __construct($xmlReader) /** * @param string $nodeName A callback may be triggered when a node with this name is read * @param int $nodeType Type of the node [NODE_TYPE_START || NODE_TYPE_END] - * @param callable $callback Callback to execute when the read node has the given name and type + * @param array{object, string} $callback Callback to execute when the read node has the given name and type * @return XMLProcessor */ public function registerCallback($nodeName, $nodeType, $callback) @@ -66,8 +66,8 @@ private function getCallbackKey($nodeName, $nodeType) * Since some functions can be called a lot, we pre-process the callback to only return the elements that * will be needed to invoke the callback later. * - * @param callable $callback Array reference to a callback: [OBJECT, METHOD_NAME] - * @return array Associative array containing the elements needed to invoke the callback using Reflection + * @param array{object, string} $callback Array reference to a callback: [OBJECT, METHOD_NAME] + * @return array Associative array containing the elements needed to invoke the callback using Reflection */ private function getInvokableCallbackData($callback) { @@ -113,7 +113,7 @@ public function readUntilStopped() * @param string $nodeNamePossiblyWithPrefix Name of the node, possibly prefixed * @param string $nodeNameWithoutPrefix Name of the same node, un-prefixed * @param int $nodeType Type of the node [NODE_TYPE_START || NODE_TYPE_END] - * @return array|null Callback data to be used for execution when a node of the given name/type is read or NULL if none found + * @return array|null Callback data to be used for execution when a node of the given name/type is read or NULL if none found */ private function getRegisteredCallbackData($nodeNamePossiblyWithPrefix, $nodeNameWithoutPrefix, $nodeType) { @@ -134,8 +134,8 @@ private function getRegisteredCallbackData($nodeNamePossiblyWithPrefix, $nodeNam } /** - * @param array $callbackData Associative array containing data to invoke the callback using Reflection - * @param array $args Arguments to pass to the callback + * @param array $callbackData Associative array containing data to invoke the callback using Reflection + * @param array $args Arguments to pass to the callback * @return int Callback response */ private function invokeCallback($callbackData, $args) diff --git a/src/Spout/Reader/IteratorInterface.php b/src/Spout/Reader/IteratorInterface.php index 4a9305d98..48ce233dd 100644 --- a/src/Spout/Reader/IteratorInterface.php +++ b/src/Spout/Reader/IteratorInterface.php @@ -4,6 +4,8 @@ /** * Interface IteratorInterface + * @template TValue + * @extends \Iterator */ interface IteratorInterface extends \Iterator { diff --git a/src/Spout/Reader/ODS/Creator/InternalEntityFactory.php b/src/Spout/Reader/ODS/Creator/InternalEntityFactory.php index cb06ce207..a9d96d6ee 100644 --- a/src/Spout/Reader/ODS/Creator/InternalEntityFactory.php +++ b/src/Spout/Reader/ODS/Creator/InternalEntityFactory.php @@ -105,7 +105,7 @@ public function createXMLReader() } /** - * @param $xmlReader + * @param XMLReader $xmlReader * @return XMLProcessor */ private function createXMLProcessor($xmlReader) diff --git a/src/Spout/Reader/ODS/Helper/CellValueFormatter.php b/src/Spout/Reader/ODS/Helper/CellValueFormatter.php index 168770f10..ba2edc9b1 100644 --- a/src/Spout/Reader/ODS/Helper/CellValueFormatter.php +++ b/src/Spout/Reader/ODS/Helper/CellValueFormatter.php @@ -43,7 +43,7 @@ class CellValueFormatter /** @var \Box\Spout\Common\Helper\Escaper\ODS Used to unescape XML data */ protected $escaper; - /** @var array List of XML nodes representing whitespaces and their corresponding value */ + /** @var array List of XML nodes representing whitespaces and their corresponding value */ private static $WHITESPACE_XML_NODES = [ self::XML_NODE_TEXT_S => ' ', self::XML_NODE_TEXT_TAB => "\t", @@ -64,7 +64,7 @@ public function __construct($shouldFormatDates, $escaper) * Returns the (unescaped) correctly marshalled, cell value associated to the given XML node. * @see http://docs.oasis-open.org/office/v1.2/os/OpenDocument-v1.2-os-part1.html#refTable13 * - * @param \DOMNode $node + * @param \DOMElement $node * @throws InvalidValueException If the node value is not valid * @return string|int|float|bool|\DateTime|\DateInterval The value associated with the cell, empty string if cell's type is void/undefined */ @@ -96,7 +96,7 @@ public function extractAndFormatNodeValue($node) /** * Returns the cell String value. * - * @param \DOMNode $node + * @param \DOMElement $node * @return string The value associated with the cell */ protected function formatStringCellValue($node) @@ -115,7 +115,7 @@ protected function formatStringCellValue($node) } /** - * @param $pNode + * @param \DOMNode $pNode * @return string */ private function extractTextValueFromNode($pNode) @@ -159,7 +159,7 @@ private function isWhitespaceNode($nodeName) * * @see https://docs.oasis-open.org/office/v1.2/os/OpenDocument-v1.2-os-part1.html#__RefHeading__1415200_253892949 * - * @param \DOMNode $node The XML node representing a whitespace + * @param \DOMElement $node The XML node representing a whitespace * @return string The corresponding whitespace value */ private function transformWhitespaceNode($node) @@ -173,7 +173,7 @@ private function transformWhitespaceNode($node) /** * Returns the cell Numeric value from the given node. * - * @param \DOMNode $node + * @param \DOMElement $node * @return int|float The value associated with the cell */ protected function formatFloatCellValue($node) @@ -190,7 +190,7 @@ protected function formatFloatCellValue($node) /** * Returns the cell Boolean value from the given node. * - * @param \DOMNode $node + * @param \DOMElement $node * @return bool The value associated with the cell */ protected function formatBooleanCellValue($node) @@ -203,7 +203,7 @@ protected function formatBooleanCellValue($node) /** * Returns the cell Date value from the given node. * - * @param \DOMNode $node + * @param \DOMElement $node * @throws InvalidValueException If the value is not a valid date * @return \DateTime|string The value associated with the cell */ @@ -234,7 +234,7 @@ protected function formatDateCellValue($node) /** * Returns the cell Time value from the given node. * - * @param \DOMNode $node + * @param \DOMElement $node * @throws InvalidValueException If the value is not a valid time * @return \DateInterval|string The value associated with the cell */ @@ -265,7 +265,7 @@ protected function formatTimeCellValue($node) /** * Returns the cell Currency value from the given node. * - * @param \DOMNode $node + * @param \DOMElement $node * @return string The value associated with the cell (e.g. "100 USD" or "9.99 EUR") */ protected function formatCurrencyCellValue($node) @@ -279,7 +279,7 @@ protected function formatCurrencyCellValue($node) /** * Returns the cell Percentage value from the given node. * - * @param \DOMNode $node + * @param \DOMElement $node * @return int|float The value associated with the cell */ protected function formatPercentageCellValue($node) diff --git a/src/Spout/Reader/ODS/Reader.php b/src/Spout/Reader/ODS/Reader.php index d07dbb43c..9e3f4d1d2 100644 --- a/src/Spout/Reader/ODS/Reader.php +++ b/src/Spout/Reader/ODS/Reader.php @@ -12,7 +12,7 @@ */ class Reader extends ReaderAbstract { - /** @var \ZipArchive */ + /** @var \ZipArchive|null */ protected $zip; /** @var SheetIterator To iterator over the ODS sheets */ diff --git a/src/Spout/Reader/ODS/RowIterator.php b/src/Spout/Reader/ODS/RowIterator.php index 81f0953d8..a0c348f85 100644 --- a/src/Spout/Reader/ODS/RowIterator.php +++ b/src/Spout/Reader/ODS/RowIterator.php @@ -19,6 +19,7 @@ /** * Class RowIterator + * @implements IteratorInterface */ class RowIterator implements IteratorInterface { @@ -56,7 +57,7 @@ class RowIterator implements IteratorInterface /** @var Row The currently processed row */ protected $currentlyProcessedRow; - /** @var Row Buffer used to store the current row, while checking if there are more rows to read */ + /** @var Row|null Buffer used to store the current row, while checking if there are more rows to read */ protected $rowBuffer; /** @var bool Indicates whether all rows have been read */ @@ -68,7 +69,7 @@ class RowIterator implements IteratorInterface /** @var int Row index to be processed next (one-based) */ protected $nextRowIndexToBeProcessed = 1; - /** @var Cell Last processed cell (because when reading cell at column N+1, cell N is processed) */ + /** @var Cell|null Last processed cell (because when reading cell at column N+1, cell N is processed) */ protected $lastProcessedCell; /** @var int Number of times the last processed row should be repeated */ @@ -225,6 +226,7 @@ protected function processCellStartingNode($xmlReader) $currentNumColumnsRepeated = $this->getNumColumnsRepeatedForCurrentNode($xmlReader); // NOTE: expand() will automatically decode all XML entities of the child nodes + /** @var \DOMElement $node */ $node = $xmlReader->expand(); $currentCell = $this->getCell($node); @@ -316,7 +318,7 @@ protected function getNumColumnsRepeatedForCurrentNode($xmlReader) /** * Returns the cell with (unescaped) correctly marshalled, cell value associated to the given XML node. * - * @param \DOMNode $node + * @param \DOMElement $node * @return Cell The cell set with the associated with the cell */ protected function getCell($node) @@ -339,7 +341,7 @@ protected function getCell($node) * row data yet (as we still need to apply the "num-columns-repeated" attribute). * * @param Row $currentRow - * @param Cell $lastReadCell The last read cell + * @param Cell|null $lastReadCell The last read cell * @return bool Whether the row is empty */ protected function isEmptyRow($currentRow, $lastReadCell) diff --git a/src/Spout/Reader/ODS/SheetIterator.php b/src/Spout/Reader/ODS/SheetIterator.php index c7b8cd9dc..7f9a45344 100644 --- a/src/Spout/Reader/ODS/SheetIterator.php +++ b/src/Spout/Reader/ODS/SheetIterator.php @@ -12,6 +12,7 @@ /** * Class SheetIterator * Iterate over ODS sheet. + * @implements IteratorInterface */ class SheetIterator implements IteratorInterface { @@ -52,7 +53,7 @@ class SheetIterator implements IteratorInterface /** @var string The name of the sheet that was defined as active */ protected $activeSheetName; - /** @var array Associative array [STYLE_NAME] => [IS_SHEET_VISIBLE] */ + /** @var array Associative array [STYLE_NAME] => [IS_SHEET_VISIBLE] */ protected $sheetsVisibility; /** @@ -101,13 +102,14 @@ public function rewind() /** * Extracts the visibility of the sheets * - * @return array Associative array [STYLE_NAME] => [IS_SHEET_VISIBLE] + * @return array Associative array [STYLE_NAME] => [IS_SHEET_VISIBLE] */ private function readSheetsVisibility() { $sheetsVisibility = []; $this->xmlReader->readUntilNodeFound(self::XML_NODE_AUTOMATIC_STYLES); + /** @var \DOMElement $automaticStylesNode */ $automaticStylesNode = $this->xmlReader->expand(); $tableStyleNodes = $automaticStylesNode->getElementsByTagNameNS(self::XML_STYLE_NAMESPACE, self::XML_NODE_STYLE_TABLE_PROPERTIES); diff --git a/src/Spout/Reader/ReaderAbstract.php b/src/Spout/Reader/ReaderAbstract.php index 39b333d4c..4156f457b 100644 --- a/src/Spout/Reader/ReaderAbstract.php +++ b/src/Spout/Reader/ReaderAbstract.php @@ -45,15 +45,15 @@ abstract protected function openReader($filePath); /** * Returns an iterator to iterate over sheets. - * - * @return IteratorInterface To iterate over sheets + * @template T + * @return IteratorInterface|null To iterate over sheets */ abstract protected function getConcreteSheetIterator(); /** * Closes the reader. To be used after reading the file. * - * @return ReaderAbstract + * @return void */ abstract protected function closeReader(); @@ -145,7 +145,10 @@ protected function getFileRealPath($filePath) } // Need to use realpath to fix "Can't open file" on some Windows setup - return \realpath($filePath); + /** @var string $path */ + $path = \realpath($filePath); + + return $path; } /** @@ -211,7 +214,8 @@ protected function isPhpStream($filePath) * Returns an iterator to iterate over sheets. * * @throws \Box\Spout\Reader\Exception\ReaderNotOpenedException If called before opening the reader - * @return \Iterator To iterate over sheets + * @template T + * @return IteratorInterface To iterate over sheets */ public function getSheetIterator() { diff --git a/src/Spout/Reader/ReaderInterface.php b/src/Spout/Reader/ReaderInterface.php index 74bcc4a99..bbd9f4aee 100644 --- a/src/Spout/Reader/ReaderInterface.php +++ b/src/Spout/Reader/ReaderInterface.php @@ -21,7 +21,7 @@ public function open($filePath); * Returns an iterator to iterate over sheets. * * @throws \Box\Spout\Reader\Exception\ReaderNotOpenedException If called before opening the reader - * @return \Iterator To iterate over sheets + * @return \Iterator To iterate over sheets */ public function getSheetIterator(); diff --git a/src/Spout/Reader/SheetInterface.php b/src/Spout/Reader/SheetInterface.php index f77ecdf5e..99a1c8563 100644 --- a/src/Spout/Reader/SheetInterface.php +++ b/src/Spout/Reader/SheetInterface.php @@ -2,13 +2,15 @@ namespace Box\Spout\Reader; +use Box\Spout\Common\Entity\Row; + /** * Interface SheetInterface */ interface SheetInterface { /** - * @return IteratorInterface Iterator to iterate over the sheet's rows. + * @return IteratorInterface Iterator to iterate over the sheet's rows. */ public function getRowIterator(); diff --git a/src/Spout/Reader/XLSX/Creator/InternalEntityFactory.php b/src/Spout/Reader/XLSX/Creator/InternalEntityFactory.php index 4dc2dc7d9..d5ab4c98c 100644 --- a/src/Spout/Reader/XLSX/Creator/InternalEntityFactory.php +++ b/src/Spout/Reader/XLSX/Creator/InternalEntityFactory.php @@ -152,7 +152,7 @@ public function createXMLReader() } /** - * @param $xmlReader + * @param XMLReader $xmlReader * @return XMLProcessor */ public function createXMLProcessor($xmlReader) diff --git a/src/Spout/Reader/XLSX/Helper/CellHelper.php b/src/Spout/Reader/XLSX/Helper/CellHelper.php index d970189e6..01c3faf73 100644 --- a/src/Spout/Reader/XLSX/Helper/CellHelper.php +++ b/src/Spout/Reader/XLSX/Helper/CellHelper.php @@ -10,7 +10,10 @@ */ class CellHelper { - // Using ord() is super slow... Using a pre-computed hash table instead. + /** + * Using ord() is super slow... Using a pre-computed hash table instead. + * @var array + */ private static $columnLetterToIndexMapping = [ 'A' => 0, 'B' => 1, 'C' => 2, 'D' => 3, 'E' => 4, 'F' => 5, 'G' => 6, 'H' => 7, 'I' => 8, 'J' => 9, 'K' => 10, 'L' => 11, 'M' => 12, 'N' => 13, diff --git a/src/Spout/Reader/XLSX/Helper/CellValueFormatter.php b/src/Spout/Reader/XLSX/Helper/CellValueFormatter.php index ec8368170..49bc72c1f 100644 --- a/src/Spout/Reader/XLSX/Helper/CellValueFormatter.php +++ b/src/Spout/Reader/XLSX/Helper/CellValueFormatter.php @@ -66,7 +66,7 @@ public function __construct($sharedStringsManager, $styleManager, $shouldFormatD /** * Returns the (unescaped) correctly marshalled, cell value associated to the given XML node. * - * @param \DOMNode $node + * @param \DOMElement $node * @throws InvalidValueException If the value is not valid * @return string|int|float|bool|\DateTime The value associated with the cell */ @@ -102,7 +102,7 @@ public function extractAndFormatNodeValue($node) /** * Returns the cell's string value from a node's nested value node * - * @param \DOMNode $node + * @param \DOMElement $node * @return string The value associated with the cell */ protected function getVNodeValue($node) @@ -117,7 +117,7 @@ protected function getVNodeValue($node) /** * Returns the cell String value where string is inline. * - * @param \DOMNode $node + * @param \DOMElement $node * @return string The value associated with the cell */ protected function formatInlineStringCellValue($node) @@ -207,6 +207,7 @@ protected function formatNumericCellValue($nodeValue, $cellStyleId) protected function formatExcelTimestampValue($nodeValue, $cellStyleId) { if ($this->isValidTimestampValue($nodeValue)) { + /** @var \DateTime $cellValue */ $cellValue = $this->formatExcelTimestampValueAsDateTimeValue($nodeValue, $cellStyleId); } else { throw new InvalidValueException($nodeValue); @@ -248,6 +249,7 @@ protected function formatExcelTimestampValueAsDateTimeValue($nodeValue, $cellSty $timeRemainder = \fmod($nodeValue, 1); $secondsRemainder = \round($timeRemainder * self::NUM_SECONDS_IN_ONE_DAY, 0); + /** @var \DateTime $dateObj */ $dateObj = \DateTime::createFromFormat('|Y-m-d', $baseDate); $dateObj->modify('+' . $daysSinceBaseDate . 'days'); $dateObj->modify('+' . $secondsRemainder . 'seconds'); diff --git a/src/Spout/Reader/XLSX/Helper/DateFormatHelper.php b/src/Spout/Reader/XLSX/Helper/DateFormatHelper.php index 443578819..0140f6546 100644 --- a/src/Spout/Reader/XLSX/Helper/DateFormatHelper.php +++ b/src/Spout/Reader/XLSX/Helper/DateFormatHelper.php @@ -16,7 +16,7 @@ class DateFormatHelper * This map is used to replace Excel format characters by their PHP equivalent. * Keys should be ordered from longest to smallest. * - * @var array Mapping between Excel format characters and PHP format characters + * @var array Mapping between Excel format characters and PHP format characters */ private static $excelDateFormatToPHPDateFormatMapping = [ self::KEY_GENERAL => [ @@ -104,6 +104,7 @@ public static function toPHPDateFormat($excelDateFormat) // For instance, ["Day " dd] should become [\D\a\y\ dd] $phpDateFormat = \preg_replace_callback('/"(.+?)"/', function ($matches) { $stringToEscape = $matches[1]; + /** @var string[] $letters */ $letters = \preg_split('//u', $stringToEscape, -1, PREG_SPLIT_NO_EMPTY); return '\\' . \implode('\\', $letters); diff --git a/src/Spout/Reader/XLSX/Manager/SharedStringsCaching/CachingStrategyFactory.php b/src/Spout/Reader/XLSX/Manager/SharedStringsCaching/CachingStrategyFactory.php index 1c00a52d6..95bb33cd1 100644 --- a/src/Spout/Reader/XLSX/Manager/SharedStringsCaching/CachingStrategyFactory.php +++ b/src/Spout/Reader/XLSX/Manager/SharedStringsCaching/CachingStrategyFactory.php @@ -98,7 +98,7 @@ protected function isInMemoryStrategyUsageSafe($sharedStringsUniqueCount) /** * Returns the PHP "memory_limit" in Kilobytes * - * @return float + * @return int */ protected function getMemoryLimitInKB() { @@ -133,6 +133,9 @@ protected function getMemoryLimitInKB() */ protected function getMemoryLimitFromIni() { - return \ini_get('memory_limit'); + /** @var string $memoryLimit */ + $memoryLimit = \ini_get('memory_limit'); + + return $memoryLimit; } } diff --git a/src/Spout/Reader/XLSX/Manager/SharedStringsCaching/FileBasedStrategy.php b/src/Spout/Reader/XLSX/Manager/SharedStringsCaching/FileBasedStrategy.php index 0e743b492..d209d4045 100644 --- a/src/Spout/Reader/XLSX/Manager/SharedStringsCaching/FileBasedStrategy.php +++ b/src/Spout/Reader/XLSX/Manager/SharedStringsCaching/FileBasedStrategy.php @@ -32,7 +32,7 @@ class FileBasedStrategy implements CachingStrategyInterface */ protected $maxNumStringsPerTempFile; - /** @var resource Pointer to the last temp file a shared string was written to */ + /** @var resource|null Pointer to the last temp file a shared string was written to */ protected $tempFilePointer; /** @@ -42,7 +42,7 @@ class FileBasedStrategy implements CachingStrategyInterface protected $inMemoryTempFilePath; /** - * @var array Contents of the temporary file that was last read + * @var array Contents of the temporary file that was last read * @see CachingStrategyFactory::MAX_NUM_STRINGS_PER_TEMP_FILE */ protected $inMemoryTempFileContents; @@ -78,7 +78,9 @@ public function addStringForIndex($sharedString, $sharedStringIndex) if ($this->tempFilePointer) { $this->globalFunctionsHelper->fclose($this->tempFilePointer); } - $this->tempFilePointer = $this->globalFunctionsHelper->fopen($tempFilePath, 'w'); + /** @var resource $tempFilePointer */ + $tempFilePointer = $this->globalFunctionsHelper->fopen($tempFilePath, 'w'); + $this->tempFilePointer = $tempFilePointer; } // The shared string retrieval logic expects each cell data to be on one line only diff --git a/src/Spout/Reader/XLSX/Manager/SharedStringsCaching/InMemoryStrategy.php b/src/Spout/Reader/XLSX/Manager/SharedStringsCaching/InMemoryStrategy.php index a16d4de50..59d0d8020 100644 --- a/src/Spout/Reader/XLSX/Manager/SharedStringsCaching/InMemoryStrategy.php +++ b/src/Spout/Reader/XLSX/Manager/SharedStringsCaching/InMemoryStrategy.php @@ -12,7 +12,7 @@ */ class InMemoryStrategy implements CachingStrategyInterface { - /** @var \SplFixedArray Array used to cache the shared strings */ + /** @var \SplFixedArray Array used to cache the shared strings */ protected $inMemoryCache; /** @var bool Whether the cache has been closed */ diff --git a/src/Spout/Reader/XLSX/Manager/SharedStringsManager.php b/src/Spout/Reader/XLSX/Manager/SharedStringsManager.php index 81b4ba299..0da6e54e4 100644 --- a/src/Spout/Reader/XLSX/Manager/SharedStringsManager.php +++ b/src/Spout/Reader/XLSX/Manager/SharedStringsManager.php @@ -46,7 +46,7 @@ class SharedStringsManager /** @var CachingStrategyFactory Factory to create shared strings caching strategies */ protected $cachingStrategyFactory; - /** @var CachingStrategyInterface The best caching strategy for storing shared strings */ + /** @var CachingStrategyInterface|null The best caching strategy for storing shared strings */ protected $cachingStrategy; /** @@ -179,6 +179,7 @@ protected function processSharedStringsItem($xmlReader, $sharedStringIndex) $sharedStringValue = ''; // NOTE: expand() will automatically decode all XML entities of the child nodes + /** @var \DOMElement $siNode */ $siNode = $xmlReader->expand(); $textNodes = $siNode->getElementsByTagName(self::XML_NODE_T); diff --git a/src/Spout/Reader/XLSX/Manager/SheetManager.php b/src/Spout/Reader/XLSX/Manager/SheetManager.php index e7b41e010..d6b5126b2 100644 --- a/src/Spout/Reader/XLSX/Manager/SheetManager.php +++ b/src/Spout/Reader/XLSX/Manager/SheetManager.php @@ -54,7 +54,7 @@ class SheetManager /** @var \Box\Spout\Common\Helper\Escaper\XLSX Used to unescape XML data */ protected $escaper; - /** @var array List of sheets */ + /** @var array List of sheets */ protected $sheets; /** @var int Index of the sheet currently read */ diff --git a/src/Spout/Reader/XLSX/Manager/StyleManager.php b/src/Spout/Reader/XLSX/Manager/StyleManager.php index d5db0d588..f51771f97 100644 --- a/src/Spout/Reader/XLSX/Manager/StyleManager.php +++ b/src/Spout/Reader/XLSX/Manager/StyleManager.php @@ -28,7 +28,7 @@ class StyleManager /** * @see https://msdn.microsoft.com/en-us/library/ff529597(v=office.12).aspx - * @var array Mapping between built-in numFmtId and the associated format - for dates only + * @var array Mapping between built-in numFmtId and the associated format - for dates only */ protected static $builtinNumFmtIdToNumFormatMapping = [ 14 => 'm/d/yyyy', // @NOTE: ECMA spec is 'mm-dd-yy' @@ -57,16 +57,16 @@ class StyleManager /** @var InternalEntityFactory Factory to create entities */ protected $entityFactory; - /** @var array Array containing the IDs of built-in number formats indicating a date */ + /** @var int[]|string[] Array containing the IDs of built-in number formats indicating a date */ protected $builtinNumFmtIdIndicatingDates; - /** @var array Array containing a mapping NUM_FMT_ID => FORMAT_CODE */ + /** @var array Array containing a mapping NUM_FMT_ID => FORMAT_CODE */ protected $customNumberFormats; - /** @var array Array containing a mapping STYLE_ID => [STYLE_ATTRIBUTES] */ + /** @var array Array containing a mapping STYLE_ID => [STYLE_ATTRIBUTES] */ protected $stylesAttributes; - /** @var array Cache containing a mapping NUM_FMT_ID => IS_DATE_FORMAT. Used to avoid lots of recalculations */ + /** @var array Cache containing a mapping NUM_FMT_ID => IS_DATE_FORMAT. Used to avoid lots of recalculations */ protected $numFmtIdToIsDateFormatCache = []; /** @@ -189,7 +189,7 @@ protected function extractStyleAttributes($xmlReader) } /** - * @return array The custom number formats + * @return array The custom number formats */ protected function getCustomNumberFormats() { @@ -201,7 +201,7 @@ protected function getCustomNumberFormats() } /** - * @return array The styles attributes + * @return array The styles attributes */ protected function getStylesAttributes() { @@ -213,7 +213,7 @@ protected function getStylesAttributes() } /** - * @param array $styleAttributes Array containing the style attributes (2 keys: "applyNumberFormat" and "numFmtId") + * @param array $styleAttributes Array containing the style attributes (2 keys: "applyNumberFormat" and "numFmtId") * @return bool Whether the style with the given attributes indicates that the number is a date */ protected function doesStyleIndicateDate($styleAttributes) diff --git a/src/Spout/Reader/XLSX/Manager/WorkbookRelationshipsManager.php b/src/Spout/Reader/XLSX/Manager/WorkbookRelationshipsManager.php index 0a9f6f51a..f9fb82ca8 100644 --- a/src/Spout/Reader/XLSX/Manager/WorkbookRelationshipsManager.php +++ b/src/Spout/Reader/XLSX/Manager/WorkbookRelationshipsManager.php @@ -34,7 +34,7 @@ class WorkbookRelationshipsManager /** @var InternalEntityFactory Factory to create entities */ private $entityFactory; - /** @var array Cache of the already read workbook relationships: [TYPE] => [FILE_NAME] */ + /** @var array Cache of the already read workbook relationships: [TYPE] => [FILE_NAME] */ private $cachedWorkbookRelationships; /** @@ -112,7 +112,7 @@ public function getStylesXMLFilePath() * It caches the result so that the file is read only once. * * @throws \Box\Spout\Common\Exception\IOException If workbook.xml.rels can't be read - * @return array + * @return array */ private function getWorkbookRelationships() { diff --git a/src/Spout/Reader/XLSX/Reader.php b/src/Spout/Reader/XLSX/Reader.php index 689f6e2f1..c64f550af 100644 --- a/src/Spout/Reader/XLSX/Reader.php +++ b/src/Spout/Reader/XLSX/Reader.php @@ -20,10 +20,10 @@ class Reader extends ReaderAbstract /** @var ManagerFactory */ protected $managerFactory; - /** @var \ZipArchive */ + /** @var \ZipArchive|null */ protected $zip; - /** @var \Box\Spout\Reader\XLSX\Manager\SharedStringsManager Manages shared strings */ + /** @var \Box\Spout\Reader\XLSX\Manager\SharedStringsManager|null Manages shared strings */ protected $sharedStringsManager; /** @var SheetIterator To iterator over the XLSX sheets */ diff --git a/src/Spout/Reader/XLSX/RowIterator.php b/src/Spout/Reader/XLSX/RowIterator.php index a54b8b192..b543c1865 100644 --- a/src/Spout/Reader/XLSX/RowIterator.php +++ b/src/Spout/Reader/XLSX/RowIterator.php @@ -17,6 +17,7 @@ /** * Class RowIterator + * @implements IteratorInterface */ class RowIterator implements IteratorInterface { @@ -276,6 +277,7 @@ protected function processCellStartingNode($xmlReader) $currentColumnIndex = $this->getColumnIndex($xmlReader); // NOTE: expand() will automatically decode all XML entities of the child nodes + /** @var \DOMElement $node */ $node = $xmlReader->expand(); $cell = $this->getCell($node); @@ -352,7 +354,7 @@ protected function getColumnIndex($xmlReader) /** * Returns the cell with (unescaped) correctly marshalled, cell value associated to the given XML node. * - * @param \DOMNode $node + * @param \DOMElement $node * @return Cell The cell set with the associated with the cell */ protected function getCell($node) diff --git a/src/Spout/Reader/XLSX/SheetIterator.php b/src/Spout/Reader/XLSX/SheetIterator.php index 81f481c3c..fdd393343 100644 --- a/src/Spout/Reader/XLSX/SheetIterator.php +++ b/src/Spout/Reader/XLSX/SheetIterator.php @@ -9,6 +9,7 @@ /** * Class SheetIterator * Iterate over XLSX sheet. + * @implements IteratorInterface */ class SheetIterator implements IteratorInterface { diff --git a/src/Spout/Writer/Common/Creator/WriterEntityFactory.php b/src/Spout/Writer/Common/Creator/WriterEntityFactory.php index 8e43c31e3..cc1b0fab4 100644 --- a/src/Spout/Writer/Common/Creator/WriterEntityFactory.php +++ b/src/Spout/Writer/Common/Creator/WriterEntityFactory.php @@ -5,7 +5,6 @@ use Box\Spout\Common\Entity\Cell; use Box\Spout\Common\Entity\Row; use Box\Spout\Common\Entity\Style\Style; -use Box\Spout\Common\Exception\UnsupportedTypeException; use Box\Spout\Common\Type; use Box\Spout\Writer\WriterInterface; @@ -46,11 +45,10 @@ public static function createWriterFromFile(string $path) */ public static function createCSVWriter() { - try { - return WriterFactory::createFromType(Type::CSV); - } catch (UnsupportedTypeException $e) { - // should never happen - } + /** @var \Box\Spout\Writer\CSV\Writer $csvWriter */ + $csvWriter = WriterFactory::createFromType(Type::CSV); + + return $csvWriter; } /** @@ -60,11 +58,10 @@ public static function createCSVWriter() */ public static function createXLSXWriter() { - try { - return WriterFactory::createFromType(Type::XLSX); - } catch (UnsupportedTypeException $e) { - // should never happen - } + /** @var \Box\Spout\Writer\XLSX\Writer $xlsxWriter */ + $xlsxWriter = WriterFactory::createFromType(Type::XLSX); + + return $xlsxWriter; } /** @@ -74,11 +71,10 @@ public static function createXLSXWriter() */ public static function createODSWriter() { - try { - return WriterFactory::createFromType(Type::ODS); - } catch (UnsupportedTypeException $e) { - // should never happen - } + /** @var \Box\Spout\Writer\ODS\Writer $odsWriter */ + $odsWriter = WriterFactory::createFromType(Type::ODS); + + return $odsWriter; } /** @@ -92,7 +88,7 @@ public static function createRow(array $cells = [], Style $rowStyle = null) } /** - * @param array $cellValues + * @param array $cellValues * @param Style|null $rowStyle * @return Row */ diff --git a/src/Spout/Writer/Common/Entity/Workbook.php b/src/Spout/Writer/Common/Entity/Workbook.php index dd182199d..1a803b388 100644 --- a/src/Spout/Writer/Common/Entity/Workbook.php +++ b/src/Spout/Writer/Common/Entity/Workbook.php @@ -33,7 +33,7 @@ public function getWorksheets() /** * @param Worksheet[] $worksheets */ - public function setWorksheets($worksheets) + public function setWorksheets($worksheets) : void { $this->worksheets = $worksheets; } diff --git a/src/Spout/Writer/Common/Entity/Worksheet.php b/src/Spout/Writer/Common/Entity/Worksheet.php index 74c4976f0..9506d00a4 100644 --- a/src/Spout/Writer/Common/Entity/Worksheet.php +++ b/src/Spout/Writer/Common/Entity/Worksheet.php @@ -11,10 +11,10 @@ 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|null Pointer to the sheet data file (e.g. xl/worksheets/sheet1.xml) */ private $filePointer; - /** @var Sheet The "external" sheet */ + /** @var Sheet|null The "external" sheet */ private $externalSheet; /** @var int Maximum number of columns among all the written rows */ @@ -57,7 +57,7 @@ public function getFilePointer() /** * @param resource $filePointer */ - public function setFilePointer($filePointer) + public function setFilePointer($filePointer) : void { $this->filePointer = $filePointer; } @@ -81,7 +81,7 @@ public function getMaxNumColumns() /** * @param int $maxNumColumns */ - public function setMaxNumColumns($maxNumColumns) + public function setMaxNumColumns($maxNumColumns) : void { $this->maxNumColumns = $maxNumColumns; } @@ -97,7 +97,7 @@ public function getLastWrittenRowIndex() /** * @param int $lastWrittenRowIndex */ - public function setLastWrittenRowIndex($lastWrittenRowIndex) + public function setLastWrittenRowIndex($lastWrittenRowIndex) : void { $this->lastWrittenRowIndex = $lastWrittenRowIndex; } diff --git a/src/Spout/Writer/Common/Helper/CellHelper.php b/src/Spout/Writer/Common/Helper/CellHelper.php index afe3c7126..9032b7df9 100644 --- a/src/Spout/Writer/Common/Helper/CellHelper.php +++ b/src/Spout/Writer/Common/Helper/CellHelper.php @@ -8,7 +8,7 @@ */ class CellHelper { - /** @var array Cache containing the mapping column index => column letters */ + /** @var array Cache containing the mapping column index => column letters */ private static $columnIndexToColumnLettersCache = []; /** diff --git a/src/Spout/Writer/Common/Helper/ZipHelper.php b/src/Spout/Writer/Common/Helper/ZipHelper.php index 7a250c86a..566b92738 100644 --- a/src/Spout/Writer/Common/Helper/ZipHelper.php +++ b/src/Spout/Writer/Common/Helper/ZipHelper.php @@ -181,9 +181,13 @@ protected function shouldSkipFile($zip, $itemLocalPath, $existingFileMode) */ protected function getNormalizedRealPath($path) { + /** @var string $realPath */ $realPath = \realpath($path); - return \str_replace(DIRECTORY_SEPARATOR, '/', $realPath); + /** @var string $normalized */ + $normalized = \str_replace(DIRECTORY_SEPARATOR, '/', $realPath); + + return $normalized; } /** @@ -210,6 +214,7 @@ public function closeArchiveAndCopyToStream($zip, $streamPointer) */ protected function copyZipToStream($zipFilePath, $pointer) { + /** @var resource $zipFilePointer */ $zipFilePointer = \fopen($zipFilePath, 'r'); \stream_copy_to_stream($zipFilePointer, $pointer); \fclose($zipFilePointer); diff --git a/src/Spout/Writer/Common/Manager/SheetManager.php b/src/Spout/Writer/Common/Manager/SheetManager.php index d1d4e6a04..249292a9e 100644 --- a/src/Spout/Writer/Common/Manager/SheetManager.php +++ b/src/Spout/Writer/Common/Manager/SheetManager.php @@ -15,10 +15,10 @@ class SheetManager /** Sheet name should not exceed 31 characters */ const MAX_LENGTH_SHEET_NAME = 31; - /** @var array Invalid characters that cannot be contained in the sheet name */ + /** @var array Invalid characters that cannot be contained in the sheet name */ private static $INVALID_CHARACTERS_IN_SHEET_NAME = ['\\', '/', '?', '*', ':', '[', ']']; - /** @var array Associative array [WORKBOOK_ID] => [[SHEET_INDEX] => [SHEET_NAME]] keeping track of sheets' name to enforce uniqueness per workbook */ + /** @var array Associative array [WORKBOOK_ID] => [[SHEET_INDEX] => [SHEET_NAME]] keeping track of sheets' name to enforce uniqueness per workbook */ private static $SHEETS_NAME_USED = []; /** @var StringHelper */ @@ -126,7 +126,7 @@ private function isNameUnique($name, Sheet $sheet) } /** - * @param int $workbookId Workbook ID associated to a Sheet + * @param string $workbookId Workbook ID associated to a Sheet * @return void */ public function markWorkbookIdAsUsed($workbookId) diff --git a/src/Spout/Writer/Common/Manager/Style/PossiblyUpdatedStyle.php b/src/Spout/Writer/Common/Manager/Style/PossiblyUpdatedStyle.php index 6ccaa29d9..b8087183f 100644 --- a/src/Spout/Writer/Common/Manager/Style/PossiblyUpdatedStyle.php +++ b/src/Spout/Writer/Common/Manager/Style/PossiblyUpdatedStyle.php @@ -11,7 +11,14 @@ */ class PossiblyUpdatedStyle { + /** + * @var Style + */ private $style; + + /** + * @var bool + */ private $isUpdated; public function __construct(Style $style, bool $isUpdated) diff --git a/src/Spout/Writer/Common/Manager/Style/StyleRegistry.php b/src/Spout/Writer/Common/Manager/Style/StyleRegistry.php index 6b439a75d..5a7e5c1ef 100644 --- a/src/Spout/Writer/Common/Manager/Style/StyleRegistry.php +++ b/src/Spout/Writer/Common/Manager/Style/StyleRegistry.php @@ -10,10 +10,10 @@ */ class StyleRegistry { - /** @var array [SERIALIZED_STYLE] => [STYLE_ID] mapping table, keeping track of the registered styles */ + /** @var array [SERIALIZED_STYLE] => [STYLE_ID] mapping table, keeping track of the registered styles */ protected $serializedStyleToStyleIdMappingTable = []; - /** @var array [STYLE_ID] => [STYLE] mapping table, keeping track of the registered styles */ + /** @var array [STYLE_ID] => [STYLE] mapping table, keeping track of the registered styles */ protected $styleIdToStyleMappingTable = []; /** diff --git a/src/Spout/Writer/Common/Manager/WorkbookManagerAbstract.php b/src/Spout/Writer/Common/Manager/WorkbookManagerAbstract.php index 653778c70..07f01877d 100644 --- a/src/Spout/Writer/Common/Manager/WorkbookManagerAbstract.php +++ b/src/Spout/Writer/Common/Manager/WorkbookManagerAbstract.php @@ -265,6 +265,7 @@ private function addRowToWorksheet(Worksheet $worksheet, Row $row) /** * @param Row $row + * @return void */ private function applyDefaultRowStyle(Row $row) { diff --git a/src/Spout/Writer/Exception/Border/InvalidNameException.php b/src/Spout/Writer/Exception/Border/InvalidNameException.php index c975d4fc4..93514c37f 100644 --- a/src/Spout/Writer/Exception/Border/InvalidNameException.php +++ b/src/Spout/Writer/Exception/Border/InvalidNameException.php @@ -7,6 +7,9 @@ class InvalidNameException extends WriterException { + /** + * @param string $name + */ public function __construct($name) { $msg = '%s is not a valid name identifier for a border. Valid identifiers are: %s.'; diff --git a/src/Spout/Writer/Exception/Border/InvalidStyleException.php b/src/Spout/Writer/Exception/Border/InvalidStyleException.php index 2d1d78c86..ed02bb826 100644 --- a/src/Spout/Writer/Exception/Border/InvalidStyleException.php +++ b/src/Spout/Writer/Exception/Border/InvalidStyleException.php @@ -7,6 +7,9 @@ class InvalidStyleException extends WriterException { + /** + * @param string $name + */ public function __construct($name) { $msg = '%s is not a valid style identifier for a border. Valid identifiers are: %s.'; diff --git a/src/Spout/Writer/Exception/Border/InvalidWidthException.php b/src/Spout/Writer/Exception/Border/InvalidWidthException.php index 790ddc2cb..b61257c54 100644 --- a/src/Spout/Writer/Exception/Border/InvalidWidthException.php +++ b/src/Spout/Writer/Exception/Border/InvalidWidthException.php @@ -7,6 +7,9 @@ class InvalidWidthException extends WriterException { + /** + * @param string $name + */ public function __construct($name) { $msg = '%s is not a valid width identifier for a border. Valid identifiers are: %s.'; diff --git a/src/Spout/Writer/ODS/Creator/HelperFactory.php b/src/Spout/Writer/ODS/Creator/HelperFactory.php index e6aa64539..cdc5a6ab9 100644 --- a/src/Spout/Writer/ODS/Creator/HelperFactory.php +++ b/src/Spout/Writer/ODS/Creator/HelperFactory.php @@ -30,7 +30,7 @@ public function createSpecificFileSystemHelper(OptionsManagerInterface $optionsM } /** - * @param $entityFactory + * @param InternalEntityFactory $entityFactory * @return ZipHelper */ private function createZipHelper($entityFactory) diff --git a/src/Spout/Writer/ODS/Helper/BorderHelper.php b/src/Spout/Writer/ODS/Helper/BorderHelper.php index 34886acf4..1fe124a14 100644 --- a/src/Spout/Writer/ODS/Helper/BorderHelper.php +++ b/src/Spout/Writer/ODS/Helper/BorderHelper.php @@ -24,7 +24,7 @@ class BorderHelper /** * Width mappings * - * @var array + * @var array */ protected static $widthMap = [ Border::WIDTH_THIN => '0.75pt', @@ -35,7 +35,7 @@ class BorderHelper /** * Style mapping * - * @var array + * @var array */ protected static $styleMap = [ Border::STYLE_SOLID => 'solid', diff --git a/src/Spout/Writer/ODS/Helper/FileSystemHelper.php b/src/Spout/Writer/ODS/Helper/FileSystemHelper.php index 5598bb4a5..172ce19ce 100644 --- a/src/Spout/Writer/ODS/Helper/FileSystemHelper.php +++ b/src/Spout/Writer/ODS/Helper/FileSystemHelper.php @@ -210,6 +210,7 @@ public function createContentFile($worksheetManager, $styleManager, $worksheets) // Append sheets content to "content.xml" $contentXmlFilePath = $this->rootFolder . '/' . self::CONTENT_XML_FILE_NAME; + /** @var resource $contentXmlHandle */ $contentXmlHandle = \fopen($contentXmlFilePath, 'a'); foreach ($worksheets as $worksheet) { @@ -241,6 +242,7 @@ public function createContentFile($worksheetManager, $styleManager, $worksheets) */ protected function copyFileContentsToTarget($sourceFilePath, $targetResource) { + /** @var resource $sourceHandle */ $sourceHandle = \fopen($sourceFilePath, 'r'); \stream_copy_to_stream($sourceHandle, $targetResource); \fclose($sourceHandle); diff --git a/src/Spout/Writer/ODS/Manager/Style/StyleRegistry.php b/src/Spout/Writer/ODS/Manager/Style/StyleRegistry.php index 42484f292..47ca61cb2 100644 --- a/src/Spout/Writer/ODS/Manager/Style/StyleRegistry.php +++ b/src/Spout/Writer/ODS/Manager/Style/StyleRegistry.php @@ -10,7 +10,7 @@ */ class StyleRegistry extends \Box\Spout\Writer\Common\Manager\Style\StyleRegistry { - /** @var array [FONT_NAME] => [] Map whose keys contain all the fonts used */ + /** @var array [FONT_NAME] => [] Map whose keys contain all the fonts used */ protected $usedFontsSet = []; /** diff --git a/src/Spout/Writer/ODS/Manager/WorkbookManager.php b/src/Spout/Writer/ODS/Manager/WorkbookManager.php index 77c5f9037..bda1b16c1 100644 --- a/src/Spout/Writer/ODS/Manager/WorkbookManager.php +++ b/src/Spout/Writer/ODS/Manager/WorkbookManager.php @@ -16,6 +16,7 @@ class WorkbookManager extends WorkbookManagerAbstract /** * Maximum number of rows a ODS sheet can contain * @see https://ask.libreoffice.org/en/question/8631/upper-limit-to-number-of-rows-in-calc/ + * @var int */ protected static $maxRowsPerWorksheet = 1048576; diff --git a/src/Spout/Writer/ODS/Manager/WorksheetManager.php b/src/Spout/Writer/ODS/Manager/WorksheetManager.php index 7d7cb0ebb..11b396e8b 100644 --- a/src/Spout/Writer/ODS/Manager/WorksheetManager.php +++ b/src/Spout/Writer/ODS/Manager/WorksheetManager.php @@ -62,6 +62,7 @@ public function __construct( */ public function startSheet(Worksheet $worksheet) { + /** @var resource $sheetFilePointer */ $sheetFilePointer = \fopen($worksheet->getFilePath(), 'w'); $this->throwIfSheetFilePointerIsNotAvailable($sheetFilePointer); @@ -86,7 +87,7 @@ private function throwIfSheetFilePointerIsNotAvailable($sheetFilePointer) * Returns the table XML root node as string. * * @param Worksheet $worksheet - * @return string node as string + * @return string "
node as string" */ public function getTableElementStartAsString(Worksheet $worksheet) { diff --git a/src/Spout/Writer/WriterAbstract.php b/src/Spout/Writer/WriterAbstract.php index 36a583fe6..104539fd1 100644 --- a/src/Spout/Writer/WriterAbstract.php +++ b/src/Spout/Writer/WriterAbstract.php @@ -24,7 +24,7 @@ abstract class WriterAbstract implements WriterInterface /** @var string Path to the output file */ protected $outputFilePath; - /** @var resource Pointer to the file/stream we will write to */ + /** @var resource|null Pointer to the file/stream we will write to */ protected $filePointer; /** @var bool Indicates whether the writer has been opened or not */ @@ -99,7 +99,10 @@ public function openToFile($outputFilePath) { $this->outputFilePath = $outputFilePath; - $this->filePointer = $this->globalFunctionsHelper->fopen($this->outputFilePath, 'wb+'); + /** @var resource $filePointer */ + $filePointer = $this->globalFunctionsHelper->fopen($this->outputFilePath, 'wb+'); + + $this->filePointer = $filePointer; $this->throwIfFilePointerIsNotAvailable(); $this->openWriter(); @@ -115,8 +118,10 @@ public function openToFile($outputFilePath) public function openToBrowser($outputFileName) { $this->outputFilePath = $this->globalFunctionsHelper->basename($outputFileName); + /** @var resource $filePointer */ + $filePointer = $this->globalFunctionsHelper->fopen('php://output', 'w'); - $this->filePointer = $this->globalFunctionsHelper->fopen('php://output', 'w'); + $this->filePointer = $filePointer; $this->throwIfFilePointerIsNotAvailable(); // Clear any previous output (otherwise the generated file will be corrupted) diff --git a/src/Spout/Writer/WriterMultiSheetsAbstract.php b/src/Spout/Writer/WriterMultiSheetsAbstract.php index 8170b679c..6128ec374 100644 --- a/src/Spout/Writer/WriterMultiSheetsAbstract.php +++ b/src/Spout/Writer/WriterMultiSheetsAbstract.php @@ -25,7 +25,7 @@ abstract class WriterMultiSheetsAbstract extends WriterAbstract /** @var ManagerFactoryInterface */ private $managerFactory; - /** @var WorkbookManagerInterface */ + /** @var WorkbookManagerInterface|null */ private $workbookManager; /** @@ -143,7 +143,7 @@ public function setCurrentSheet($sheet) */ protected function throwIfWorkbookIsNotAvailable() { - if (!$this->workbookManager->getWorkbook()) { + if ($this->workbookManager === null) { throw new WriterNotOpenedException('The writer must be opened before performing this action.'); } } diff --git a/src/Spout/Writer/XLSX/Helper/BorderHelper.php b/src/Spout/Writer/XLSX/Helper/BorderHelper.php index ed202cb63..59d738604 100644 --- a/src/Spout/Writer/XLSX/Helper/BorderHelper.php +++ b/src/Spout/Writer/XLSX/Helper/BorderHelper.php @@ -7,6 +7,9 @@ class BorderHelper { + /** + * @var array + */ public static $xlsxStyleMap = [ Border::STYLE_SOLID => [ Border::WIDTH_THIN => 'thin', diff --git a/src/Spout/Writer/XLSX/Manager/SharedStringsManager.php b/src/Spout/Writer/XLSX/Manager/SharedStringsManager.php index b0a5b48d6..76703fb8e 100644 --- a/src/Spout/Writer/XLSX/Manager/SharedStringsManager.php +++ b/src/Spout/Writer/XLSX/Manager/SharedStringsManager.php @@ -24,7 +24,7 @@ class SharedStringsManager */ const DEFAULT_STRINGS_COUNT_PART = 'count="9999999999999" uniqueCount="9999999999999"'; - /** @var resource Pointer to the sharedStrings.xml file */ + /** @var resource|false Pointer to the sharedStrings.xml file */ protected $sharedStringsFilePointer; /** @var int Number of shared strings already written */ @@ -40,13 +40,17 @@ class SharedStringsManager public function __construct($xlFolder, $stringsEscaper) { $sharedStringsFilePath = $xlFolder . '/' . self::SHARED_STRINGS_FILE_NAME; - $this->sharedStringsFilePointer = \fopen($sharedStringsFilePath, 'w'); + + /** @var resource $sharedStringsFilePointer */ + $sharedStringsFilePointer =\fopen($sharedStringsFilePath, 'w'); + + $this->sharedStringsFilePointer = $sharedStringsFilePointer; $this->throwIfSharedStringsFilePointerIsNotAvailable(); // the headers is split into different parts so that we can fseek and put in the correct count and uniqueCount later $header = self::SHARED_STRINGS_XML_FILE_FIRST_PART_HEADER . ' ' . self::DEFAULT_STRINGS_COUNT_PART . '>'; - \fwrite($this->sharedStringsFilePointer, $header); + \fwrite($sharedStringsFilePointer, $header); $this->stringsEscaper = $stringsEscaper; } @@ -59,7 +63,7 @@ public function __construct($xlFolder, $stringsEscaper) */ protected function throwIfSharedStringsFilePointerIsNotAvailable() { - if (!$this->sharedStringsFilePointer) { + if ($this->sharedStringsFilePointer === false) { throw new IOException('Unable to open shared strings file for writing.'); } } @@ -73,7 +77,10 @@ protected function throwIfSharedStringsFilePointerIsNotAvailable() */ public function writeString($string) { - \fwrite($this->sharedStringsFilePointer, '' . $this->stringsEscaper->escape($string) . ''); + /** @var resource $sharedStringsFilePointer */ + $sharedStringsFilePointer = $this->sharedStringsFilePointer; + + \fwrite($sharedStringsFilePointer, '' . $this->stringsEscaper->escape($string) . ''); $this->numSharedStrings++; // Shared string ID is zero-based diff --git a/src/Spout/Writer/XLSX/Manager/Style/StyleManager.php b/src/Spout/Writer/XLSX/Manager/Style/StyleManager.php index f0ca9d9e6..66059c05f 100644 --- a/src/Spout/Writer/XLSX/Manager/Style/StyleManager.php +++ b/src/Spout/Writer/XLSX/Manager/Style/StyleManager.php @@ -2,6 +2,7 @@ namespace Box\Spout\Writer\XLSX\Manager\Style; +use Box\Spout\Common\Entity\Style\BorderPart; use Box\Spout\Common\Entity\Style\Color; use Box\Spout\Common\Entity\Style\Style; use Box\Spout\Writer\XLSX\Helper\BorderHelper; @@ -196,7 +197,7 @@ protected function getBordersSectionContent() foreach ($sortOrder as $partName) { if ($border->hasPart($partName)) { - /** @var $part \Box\Spout\Common\Entity\Style\BorderPart */ + /** @var BorderPart $part */ $part = $border->getPart($partName); $content .= BorderHelper::serializeBorderPart($part); } diff --git a/src/Spout/Writer/XLSX/Manager/Style/StyleRegistry.php b/src/Spout/Writer/XLSX/Manager/Style/StyleRegistry.php index 14eb98623..d18d8fd1c 100644 --- a/src/Spout/Writer/XLSX/Manager/Style/StyleRegistry.php +++ b/src/Spout/Writer/XLSX/Manager/Style/StyleRegistry.php @@ -12,7 +12,7 @@ class StyleRegistry extends \Box\Spout\Writer\Common\Manager\Style\StyleRegistry { /** * @see https://msdn.microsoft.com/en-us/library/ff529597(v=office.12).aspx - * @var array Mapping between built-in format and the associated numFmtId + * @var array Mapping between built-in format and the associated numFmtId */ protected static $builtinNumFormatToIdMapping = [ 'General' => 0, @@ -65,12 +65,12 @@ class StyleRegistry extends \Box\Spout\Writer\Common\Manager\Style\StyleRegistry ]; /** - * @var array + * @var array */ protected $registeredFormats = []; /** - * @var array [STYLE_ID] => [FORMAT_ID] maps a style to a format declaration + * @var array [STYLE_ID] => [FORMAT_ID] maps a style to a format declaration */ protected $styleIdToFormatsMappingTable = []; @@ -84,12 +84,12 @@ class StyleRegistry extends \Box\Spout\Writer\Common\Manager\Style\StyleRegistry protected $formatIndex = 164; /** - * @var array + * @var array */ protected $registeredFills = []; /** - * @var array [STYLE_ID] => [FILL_ID] maps a style to a fill declaration + * @var array [STYLE_ID] => [FILL_ID] maps a style to a fill declaration */ protected $styleIdToFillMappingTable = []; @@ -102,12 +102,12 @@ class StyleRegistry extends \Box\Spout\Writer\Common\Manager\Style\StyleRegistry protected $fillIndex = 2; /** - * @var array + * @var array */ protected $registeredBorders = []; /** - * @var array [STYLE_ID] => [BORDER_ID] maps a style to a border declaration + * @var array [STYLE_ID] => [BORDER_ID] maps a style to a border declaration */ protected $styleIdToBorderMappingTable = []; @@ -136,8 +136,9 @@ public function registerStyle(Style $style) * * @param Style $style */ - protected function registerFormat(Style $style) + protected function registerFormat(Style $style) : void { + /** @var int $styleId */ $styleId = $style->getId(); $format = $style->getFormat(); @@ -176,8 +177,9 @@ public function getFormatIdForStyleId($styleId) * * @param Style $style */ - private function registerFill(Style $style) + private function registerFill(Style $style) : void { + /** @var int $styleId */ $styleId = $style->getId(); // Currently - only solid backgrounds are supported @@ -219,8 +221,9 @@ public function getFillIdForStyleId($styleId) * * @param Style $style */ - private function registerBorder(Style $style) + private function registerBorder(Style $style) : void { + /** @var int $styleId */ $styleId = $style->getId(); if ($style->shouldApplyBorder()) { @@ -255,7 +258,7 @@ public function getBorderIdForStyleId($styleId) } /** - * @return array + * @return array */ public function getRegisteredFills() { @@ -263,7 +266,7 @@ public function getRegisteredFills() } /** - * @return array + * @return array */ public function getRegisteredBorders() { @@ -271,7 +274,7 @@ public function getRegisteredBorders() } /** - * @return array + * @return array */ public function getRegisteredFormats() { diff --git a/src/Spout/Writer/XLSX/Manager/WorkbookManager.php b/src/Spout/Writer/XLSX/Manager/WorkbookManager.php index 708208bd5..1b16f9fd3 100644 --- a/src/Spout/Writer/XLSX/Manager/WorkbookManager.php +++ b/src/Spout/Writer/XLSX/Manager/WorkbookManager.php @@ -14,6 +14,7 @@ class WorkbookManager extends WorkbookManagerAbstract { /** + * @var int * Maximum number of rows a XLSX sheet can contain * @see http://office.microsoft.com/en-us/excel-help/excel-specifications-and-limits-HP010073849.aspx */ diff --git a/src/Spout/Writer/XLSX/Manager/WorksheetManager.php b/src/Spout/Writer/XLSX/Manager/WorksheetManager.php index 61b93a176..14ffecb03 100644 --- a/src/Spout/Writer/XLSX/Manager/WorksheetManager.php +++ b/src/Spout/Writer/XLSX/Manager/WorksheetManager.php @@ -108,6 +108,7 @@ public function getSharedStringsManager() */ public function startSheet(Worksheet $worksheet) { + /** @var resource $sheetFilePointer */ $sheetFilePointer = \fopen($worksheet->getFilePath(), 'w'); $this->throwIfSheetFilePointerIsNotAvailable($sheetFilePointer); diff --git a/tests/Spout/Common/Entity/RowTest.php b/tests/Spout/Common/Entity/RowTest.php index 9aa12f607..d734bcae8 100644 --- a/tests/Spout/Common/Entity/RowTest.php +++ b/tests/Spout/Common/Entity/RowTest.php @@ -3,23 +3,30 @@ namespace Box\Spout\Common\Entity; use Box\Spout\Common\Entity\Style\Style; +use PHPUnit\Framework\MockObject\MockObject; class RowTest extends \PHPUnit\Framework\TestCase { /** - * @return \PHPUnit_Framework_MockObject_MockObject|Style + * @return Style&MockObject */ private function getStyleMock() { - return $this->createMock(Style::class); + /** @var Style&MockObject $styleMock */ + $styleMock = $this->createMock(Style::class); + + return $styleMock; } /** - * @return \PHPUnit_Framework_MockObject_MockObject|Cell + * @return Cell&MockObject */ private function getCellMock() { - return $this->createMock(Cell::class); + /** @var Cell&MockObject $cellMock */ + $cellMock = $this->createMock(Cell::class); + + return $cellMock; } /** diff --git a/tests/Spout/Common/Entity/Style/BorderTest.php b/tests/Spout/Common/Entity/Style/BorderTest.php index fa1e7ef42..bb89af756 100644 --- a/tests/Spout/Common/Entity/Style/BorderTest.php +++ b/tests/Spout/Common/Entity/Style/BorderTest.php @@ -113,7 +113,7 @@ public function testAnyCombinationOfAllowedBorderPartsParams() $border->addPart($borderPart); $this->assertCount(1, $border->getParts()); - /** @var $part BorderPart */ + /** @var BorderPart $part */ $part = $border->getParts()[$allowedName]; $this->assertEquals($allowedStyle, $part->getStyle()); diff --git a/tests/Spout/Common/Entity/Style/ColorTest.php b/tests/Spout/Common/Entity/Style/ColorTest.php index 3d27a1c5e..deee80311 100644 --- a/tests/Spout/Common/Entity/Style/ColorTest.php +++ b/tests/Spout/Common/Entity/Style/ColorTest.php @@ -11,7 +11,7 @@ class ColorTest extends TestCase { /** - * @return array + * @return array */ public function dataProviderForTestRGB() { @@ -54,7 +54,7 @@ public function testRGB($red, $green, $blue, $expectedColor) } /** - * @return array + * @return array */ public function dataProviderForTestRGBAInvalidColorComponents() { diff --git a/tests/Spout/Common/Helper/CellTypeHelperTest.php b/tests/Spout/Common/Helper/CellTypeHelperTest.php index b5a47503e..701a406df 100644 --- a/tests/Spout/Common/Helper/CellTypeHelperTest.php +++ b/tests/Spout/Common/Helper/CellTypeHelperTest.php @@ -10,7 +10,7 @@ class CellTypeHelperTest extends TestCase { /** - * @return array + * @return void */ public function testIsEmpty() { @@ -27,7 +27,7 @@ public function testIsEmpty() } /** - * @return array + * @return void */ public function testIsNonEmptyString() { @@ -44,7 +44,7 @@ public function testIsNonEmptyString() } /** - * @return array + * @return void */ public function testIsNumeric() { @@ -66,7 +66,7 @@ public function testIsNumeric() } /** - * @return array + * @return void */ public function testIsBoolean() { diff --git a/tests/Spout/Common/Helper/EncodingHelperTest.php b/tests/Spout/Common/Helper/EncodingHelperTest.php index 8d3c158b3..9bb0e832f 100644 --- a/tests/Spout/Common/Helper/EncodingHelperTest.php +++ b/tests/Spout/Common/Helper/EncodingHelperTest.php @@ -4,6 +4,7 @@ use Box\Spout\Common\Exception\EncodingConversionException; use Box\Spout\TestUsingResource; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -14,7 +15,7 @@ class EncodingHelperTest extends TestCase use TestUsingResource; /** - * @return array + * @return array */ public function dataProviderForTestGetBytesOffsetToSkipBOM() { @@ -38,6 +39,7 @@ public function dataProviderForTestGetBytesOffsetToSkipBOM() public function testGetBytesOffsetToSkipBOM($fileName, $encoding, $expectedBytesOffset) { $resourcePath = $this->getResourcePath($fileName); + /** @var resource $filePointer */ $filePointer = fopen($resourcePath, 'r'); $encodingHelper = new EncodingHelper(new GlobalFunctionsHelper()); @@ -47,7 +49,7 @@ public function testGetBytesOffsetToSkipBOM($fileName, $encoding, $expectedBytes } /** - * @return array + * @return array */ public function dataProviderForIconvOrMbstringUsage() { @@ -73,7 +75,7 @@ public function testAttemptConversionToUTF8ShouldThrowIfConversionFailed($should $helperStub->method('iconv')->willReturn(false); $helperStub->method('mb_convert_encoding')->willReturn(false); - /** @var EncodingHelper $encodingHelperStub */ + /** @var EncodingHelper&MockObject $encodingHelperStub */ $encodingHelperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\EncodingHelper') ->setConstructorArgs([$helperStub]) ->setMethods(['canUseIconv', 'canUseMbString']) @@ -91,7 +93,7 @@ public function testAttemptConversionToUTF8ShouldThrowIfConversionNotSupported() { $this->expectException(EncodingConversionException::class); - /** @var EncodingHelper $encodingHelperStub */ + /** @var EncodingHelper&MockObject $encodingHelperStub */ $encodingHelperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\EncodingHelper') ->disableOriginalConstructor() ->setMethods(['canUseIconv', 'canUseMbString']) @@ -110,7 +112,7 @@ public function testAttemptConversionToUTF8ShouldThrowIfConversionNotSupported() */ public function testAttemptConversionToUTF8ShouldReturnReencodedString($shouldUseIconv) { - /** @var EncodingHelper $encodingHelperStub */ + /** @var EncodingHelper&MockObject $encodingHelperStub */ $encodingHelperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\EncodingHelper') ->setConstructorArgs([new GlobalFunctionsHelper()]) ->setMethods(['canUseIconv', 'canUseMbString']) @@ -118,6 +120,7 @@ public function testAttemptConversionToUTF8ShouldReturnReencodedString($shouldUs $encodingHelperStub->method('canUseIconv')->willReturn($shouldUseIconv); $encodingHelperStub->method('canUseMbString')->willReturn(true); + /** @var string $encodedString */ $encodedString = iconv(EncodingHelper::ENCODING_UTF8, EncodingHelper::ENCODING_UTF16_LE, 'input'); $decodedString = $encodingHelperStub->attemptConversionToUTF8($encodedString, EncodingHelper::ENCODING_UTF16_LE); @@ -129,7 +132,7 @@ public function testAttemptConversionToUTF8ShouldReturnReencodedString($shouldUs */ public function testAttemptConversionToUTF8ShouldBeNoopWhenTargetIsUTF8() { - /** @var EncodingHelper $encodingHelperStub */ + /** @var EncodingHelper&MockObject $encodingHelperStub */ $encodingHelperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\EncodingHelper') ->disableOriginalConstructor() ->setMethods(['canUseIconv']) @@ -156,7 +159,7 @@ public function testAttemptConversionFromUTF8ShouldThrowIfConversionFailed($shou $helperStub->method('iconv')->willReturn(false); $helperStub->method('mb_convert_encoding')->willReturn(false); - /** @var EncodingHelper $encodingHelperStub */ + /** @var EncodingHelper&MockObject $encodingHelperStub */ $encodingHelperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\EncodingHelper') ->setConstructorArgs([$helperStub]) ->setMethods(['canUseIconv', 'canUseMbString']) @@ -174,7 +177,7 @@ public function testAttemptConversionFromUTF8ShouldThrowIfConversionNotSupported { $this->expectException(EncodingConversionException::class); - /** @var EncodingHelper $encodingHelperStub */ + /** @var EncodingHelper&MockObject $encodingHelperStub */ $encodingHelperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\EncodingHelper') ->disableOriginalConstructor() ->setMethods(['canUseIconv', 'canUseMbString']) @@ -193,7 +196,7 @@ public function testAttemptConversionFromUTF8ShouldThrowIfConversionNotSupported */ public function testAttemptConversionFromUTF8ShouldReturnReencodedString($shouldUseIconv) { - /** @var EncodingHelper $encodingHelperStub */ + /** @var EncodingHelper&MockObject $encodingHelperStub */ $encodingHelperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\EncodingHelper') ->setConstructorArgs([new GlobalFunctionsHelper()]) ->setMethods(['canUseIconv', 'canUseMbString']) @@ -212,7 +215,7 @@ public function testAttemptConversionFromUTF8ShouldReturnReencodedString($should */ public function testAttemptConversionFromUTF8ShouldBeNoopWhenTargetIsUTF8() { - /** @var EncodingHelper $encodingHelperStub */ + /** @var EncodingHelper&MockObject $encodingHelperStub */ $encodingHelperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\EncodingHelper') ->disableOriginalConstructor() ->setMethods(['canUseIconv']) diff --git a/tests/Spout/Common/Helper/Escaper/ODSTest.php b/tests/Spout/Common/Helper/Escaper/ODSTest.php index 858eb6882..c88a09464 100644 --- a/tests/Spout/Common/Helper/Escaper/ODSTest.php +++ b/tests/Spout/Common/Helper/Escaper/ODSTest.php @@ -11,7 +11,7 @@ class ODSTest extends TestCase { /** - * @return array + * @return array */ public function dataProviderForTestEscape() { diff --git a/tests/Spout/Common/Helper/Escaper/XLSXTest.php b/tests/Spout/Common/Helper/Escaper/XLSXTest.php index 3efe0e716..aeb8afdd2 100644 --- a/tests/Spout/Common/Helper/Escaper/XLSXTest.php +++ b/tests/Spout/Common/Helper/Escaper/XLSXTest.php @@ -11,7 +11,7 @@ class XLSXTest extends TestCase { /** - * @return array + * @return array */ public function dataProviderForTestEscape() { @@ -46,7 +46,7 @@ public function testEscape($stringToEscape, $expectedEscapedString) } /** - * @return array + * @return array */ public function dataProviderForTestUnescape() { diff --git a/tests/Spout/Common/Helper/FileSystemHelperTest.php b/tests/Spout/Common/Helper/FileSystemHelperTest.php index 7eb018365..0eb314e9e 100644 --- a/tests/Spout/Common/Helper/FileSystemHelperTest.php +++ b/tests/Spout/Common/Helper/FileSystemHelperTest.php @@ -10,7 +10,7 @@ */ class FileSystemHelperTest extends TestCase { - /** @var \Box\Spout\Writer\XLSX\Helper\FileSystemHelper */ + /** @var FileSystemHelper */ protected $fileSystemHelper; /** diff --git a/tests/Spout/Common/Manager/OptionsManagerTest.php b/tests/Spout/Common/Manager/OptionsManagerTest.php index d5fe5d8e1..32fa1e571 100644 --- a/tests/Spout/Common/Manager/OptionsManagerTest.php +++ b/tests/Spout/Common/Manager/OptionsManagerTest.php @@ -17,7 +17,10 @@ class OptionsManagerTest extends TestCase protected function setUp() : void { $this->optionsManager = new class() extends OptionsManagerAbstract { - protected function getSupportedOptions() + /** + * @return string[] + */ + protected function getSupportedOptions() : array { return [ 'foo', diff --git a/tests/Spout/Reader/CSV/ReaderTest.php b/tests/Spout/Reader/CSV/ReaderTest.php index 684b04542..9d88f0b94 100644 --- a/tests/Spout/Reader/CSV/ReaderTest.php +++ b/tests/Spout/Reader/CSV/ReaderTest.php @@ -6,11 +6,13 @@ use Box\Spout\Common\Exception\IOException; use Box\Spout\Common\Helper\EncodingHelper; use Box\Spout\Common\Helper\GlobalFunctionsHelper; +use Box\Spout\Common\Manager\OptionsManagerInterface; use Box\Spout\Reader\CSV\Creator\InternalEntityFactory; use Box\Spout\Reader\CSV\Manager\OptionsManager; use Box\Spout\Reader\Exception\ReaderNotOpenedException; use Box\Spout\Reader\ReaderInterface; use Box\Spout\TestUsingResource; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -47,7 +49,7 @@ public function testOpenShouldThrowExceptionIfFileNotReadable() { $this->expectException(IOException::class); - /** @var \Box\Spout\Common\Helper\GlobalFunctionsHelper|\PHPUnit_Framework_MockObject_MockObject $helperStub */ + /** @var \Box\Spout\Common\Helper\GlobalFunctionsHelper&MockObject $helperStub */ $helperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\GlobalFunctionsHelper') ->setMethods(['is_readable']) ->getMock(); @@ -66,7 +68,7 @@ public function testOpenShouldThrowExceptionIfCannotOpenFile() { $this->expectException(IOException::class); - /** @var \Box\Spout\Common\Helper\GlobalFunctionsHelper|\PHPUnit_Framework_MockObject_MockObject $helperStub */ + /** @var \Box\Spout\Common\Helper\GlobalFunctionsHelper&MockObject $helperStub */ $helperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\GlobalFunctionsHelper') ->setMethods(['fopen']) ->getMock(); @@ -159,7 +161,7 @@ public function testReadShouldReturnEmptyLinesIfShouldPreserveEmptyRowsSet() } /** - * @return array + * @return array */ public function dataProviderForTestReadShouldReadEmptyFile() { @@ -241,7 +243,7 @@ public function testReadShouldNotTruncateLineBreak() } /** - * @return array + * @return array */ public function dataProviderForTestReadShouldSkipBom() { @@ -274,7 +276,7 @@ public function testReadShouldSkipBom($fileName, $fileEncoding) } /** - * @return array + * @return array */ public function dataProviderForTestReadShouldSupportNonUTF8FilesWithoutBOMs() { @@ -302,7 +304,7 @@ public function testReadShouldSupportNonUTF8FilesWithoutBOMs($fileName, $fileEnc $allRows = []; $resourcePath = $this->getResourcePath($fileName); - /** @var \Box\Spout\Common\Helper\GlobalFunctionsHelper|\PHPUnit_Framework_MockObject_MockObject $helperStub */ + /** @var \Box\Spout\Common\Helper\GlobalFunctionsHelper&MockObject $helperStub */ $helperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\GlobalFunctionsHelper') ->setMethods(['function_exists']) ->getMock(); @@ -475,8 +477,8 @@ public function testReadWithUnsupportedCustomStreamWrapper() } /** - * @param \Box\Spout\Common\Helper\GlobalFunctionsHelper|null $optionsManager - * @param \Box\Spout\Common\Manager\OptionsManagerInterface|null $globalFunctionsHelper + * @param OptionsManagerInterface|null $optionsManager + * @param GlobalFunctionsHelper|null $globalFunctionsHelper * @return ReaderInterface */ private function createCSVReader($optionsManager = null, $globalFunctionsHelper = null) @@ -494,7 +496,7 @@ private function createCSVReader($optionsManager = null, $globalFunctionsHelper * @param string $fieldEnclosure * @param string $encoding * @param bool $shouldPreserveEmptyRows - * @return array All the read rows the given file + * @return array All the read rows the given file */ private function getAllRowsForFile( $fileName, diff --git a/tests/Spout/Reader/CSV/SheetTest.php b/tests/Spout/Reader/CSV/SheetTest.php index d910d3216..82ae593a3 100644 --- a/tests/Spout/Reader/CSV/SheetTest.php +++ b/tests/Spout/Reader/CSV/SheetTest.php @@ -3,6 +3,7 @@ namespace Box\Spout\Reader\CSV; use Box\Spout\Reader\Common\Creator\ReaderEntityFactory; +use Box\Spout\Reader\SheetInterface; use Box\Spout\TestUsingResource; use PHPUnit\Framework\TestCase; @@ -27,7 +28,7 @@ public function testReaderShouldReturnCorrectSheetInfos() /** * @param string $fileName - * @return Sheet + * @return SheetInterface */ private function openFileAndReturnSheet($fileName) { diff --git a/tests/Spout/Reader/CSV/SpoutTestStream.php b/tests/Spout/Reader/CSV/SpoutTestStream.php index d66e8117c..77823c769 100644 --- a/tests/Spout/Reader/CSV/SpoutTestStream.php +++ b/tests/Spout/Reader/CSV/SpoutTestStream.php @@ -23,13 +23,16 @@ class SpoutTestStream /** * @param string $path * @param int $flag - * @return array + * @return array */ public function url_stat($path, $flag) { $filePath = $this->getFilePathFromStreamPath($path); - return stat($filePath); + /** @var array $stat */ + $stat = stat($filePath); + + return $stat; } /** @@ -56,7 +59,11 @@ public function stream_open($path, $mode, $options, &$opened_path) // the path is like "spout://csv_name" so the actual file name correspond the name of the host. $filePath = $this->getFilePathFromStreamPath($path); - $this->fileHandle = fopen($filePath, $mode); + + /** @var resource $fileHandle */ + $fileHandle = fopen($filePath, $mode); + + $this->fileHandle = $fileHandle; return true; } @@ -69,7 +76,10 @@ public function stream_read($numBytes) { $this->position += $numBytes; - return fread($this->fileHandle, $numBytes); + /** @var string $read */ + $read = fread($this->fileHandle, $numBytes); + + return $read; } /** diff --git a/tests/Spout/Reader/Common/Manager/RowManagerTest.php b/tests/Spout/Reader/Common/Manager/RowManagerTest.php index b67684830..2bb5fc802 100644 --- a/tests/Spout/Reader/Common/Manager/RowManagerTest.php +++ b/tests/Spout/Reader/Common/Manager/RowManagerTest.php @@ -15,7 +15,7 @@ class RowManagerTest extends TestCase { /** - * @return array + * @return array */ public function dataProviderForTestFillMissingIndexesWithEmptyCells() { @@ -34,7 +34,7 @@ public function dataProviderForTestFillMissingIndexesWithEmptyCells() * @param Cell[]|null $rowCells * @param Cell[] $expectedFilledCells */ - public function testFillMissingIndexesWithEmptyCells($rowCells, $expectedFilledCells) + public function testFillMissingIndexesWithEmptyCells($rowCells, $expectedFilledCells) : void { $rowManager = $this->createRowManager(); @@ -48,7 +48,7 @@ public function testFillMissingIndexesWithEmptyCells($rowCells, $expectedFilledC } /** - * @return array + * @return array */ public function dataProviderForTestIsEmptyRow() { @@ -64,7 +64,7 @@ public function dataProviderForTestIsEmptyRow() /** * @dataProvider dataProviderForTestIsEmptyRow * - * @param array $cells + * @param array $cells * @param bool $expectedIsEmpty * @return void */ @@ -81,10 +81,13 @@ public function testIsEmptyRow(array $cells, $expectedIsEmpty) */ private function createRowManager() { - $entityFactory = new InternalEntityFactory( - $this->createMock(ManagerFactory::class), - $this->createMock(HelperFactory::class) - ); + /** @var ManagerFactory $managerFactory */ + $managerFactory = $this->createMock(ManagerFactory::class); + + /** @var HelperFactory $helperFactory */ + $helperFactory = $this->createMock(HelperFactory::class); + + $entityFactory = new InternalEntityFactory($managerFactory, $helperFactory); return new RowManager($entityFactory); } diff --git a/tests/Spout/Reader/ODS/ReaderTest.php b/tests/Spout/Reader/ODS/ReaderTest.php index cd30ae54b..3bdf70dbf 100644 --- a/tests/Spout/Reader/ODS/ReaderTest.php +++ b/tests/Spout/Reader/ODS/ReaderTest.php @@ -16,7 +16,7 @@ class ReaderTest extends TestCase use TestUsingResource; /** - * @return array + * @return array */ public function dataProviderForTestReadShouldThrowException() { @@ -41,7 +41,7 @@ public function testReadShouldThrowException($filePath) } /** - * @return array + * @return array */ public function dataProviderForTestReadForAllWorksheets() { @@ -109,7 +109,7 @@ public function testReadShouldSupportNumberColumnsRepeated() } /** - * @return array + * @return array */ public function dataProviderForTestReadWithFilesGeneratedByExternalSoftwares() { @@ -538,7 +538,7 @@ public function testReaderShouldReadInlineFontFormattingAsText() * @param string $fileName * @param bool $shouldFormatDates * @param bool $shouldPreserveEmptyRows - * @return array All the read rows the given file + * @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 530e6c74a..cfd95c197 100644 --- a/tests/Spout/Reader/ODS/SheetTest.php +++ b/tests/Spout/Reader/ODS/SheetTest.php @@ -3,6 +3,7 @@ namespace Box\Spout\Reader\ODS; use Box\Spout\Reader\Common\Creator\ReaderEntityFactory; +use Box\Spout\Reader\SheetInterface; use Box\Spout\TestUsingResource; use PHPUnit\Framework\TestCase; @@ -55,7 +56,7 @@ public function testReaderShouldReturnCorrectSheetVisibility() /** * @param string $fileName - * @return Sheet[] + * @return SheetInterface[] */ private function openFileAndReturnSheets($fileName) { diff --git a/tests/Spout/Reader/Wrapper/XMLReaderTest.php b/tests/Spout/Reader/Wrapper/XMLReaderTest.php index 61aa7e7f1..0c6e4afcf 100644 --- a/tests/Spout/Reader/Wrapper/XMLReaderTest.php +++ b/tests/Spout/Reader/Wrapper/XMLReaderTest.php @@ -102,7 +102,7 @@ public function testNextShouldThrowExceptionOnError() } /** - * @return array + * @return array */ public function dataProviderForTestFileExistsWithinZip() { @@ -134,10 +134,11 @@ public function testFileExistsWithinZip($innerFilePath, $expectedResult) } /** - * @return array + * @return array */ public function dataProviderForTestGetRealPathURIForFileInZip() { + /** @var string $tempFolder */ $tempFolder = realpath(sys_get_temp_dir()); $tempFolderName = basename($tempFolder); $expectedRealPathURI = 'zip://' . $tempFolder . '/test.xlsx#test.xml'; @@ -174,7 +175,7 @@ public function testGetRealPathURIForFileInZip($tempFolder, $zipFilePath, $fileI } /** - * @return array + * @return array */ public function dataProviderForTestIsPositionedOnStartingAndEndingNode() { diff --git a/tests/Spout/Reader/XLSX/Helper/CellHelperTest.php b/tests/Spout/Reader/XLSX/Helper/CellHelperTest.php index 87a65a669..9bdf7c9d9 100644 --- a/tests/Spout/Reader/XLSX/Helper/CellHelperTest.php +++ b/tests/Spout/Reader/XLSX/Helper/CellHelperTest.php @@ -11,7 +11,7 @@ class CellHelperTest extends TestCase { /** - * @return array + * @return array */ public function dataProviderForTestGetColumnIndexFromCellIndex() { diff --git a/tests/Spout/Reader/XLSX/Helper/CellValueFormatterTest.php b/tests/Spout/Reader/XLSX/Helper/CellValueFormatterTest.php index f981a63f9..1e044d43f 100644 --- a/tests/Spout/Reader/XLSX/Helper/CellValueFormatterTest.php +++ b/tests/Spout/Reader/XLSX/Helper/CellValueFormatterTest.php @@ -4,7 +4,9 @@ use Box\Spout\Common\Helper\Escaper; use Box\Spout\Reader\Exception\InvalidValueException; +use Box\Spout\Reader\XLSX\Manager\SharedStringsManager; use Box\Spout\Reader\XLSX\Manager\StyleManager; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -13,7 +15,7 @@ class CellValueFormatterTest extends TestCase { /** - * @return array + * @return array */ public function dataProviderForTestExcelDate() { @@ -72,6 +74,7 @@ public function testExcelDate($shouldUse1904Dates, $nodeValue, $expectedDateAsSt ->with(0) ->will($this->returnValue((object) ['nodeValue' => $nodeValue])); + /** @var \DOMElement&MockObject $nodeMock */ $nodeMock = $this->createMock(\DOMElement::class); $nodeMock @@ -88,7 +91,7 @@ public function testExcelDate($shouldUse1904Dates, $nodeValue, $expectedDateAsSt ->with(CellValueFormatter::XML_NODE_VALUE) ->will($this->returnValue($nodeListMock)); - /** @var StyleManager|\PHPUnit_Framework_MockObject_MockObject $styleManagerMock */ + /** @var StyleManager&MockObject $styleManagerMock */ $styleManagerMock = $this->createMock(StyleManager::class); $styleManagerMock @@ -97,7 +100,10 @@ public function testExcelDate($shouldUse1904Dates, $nodeValue, $expectedDateAsSt ->with(123) ->will($this->returnValue(true)); - $formatter = new CellValueFormatter(null, $styleManagerMock, false, $shouldUse1904Dates, new Escaper\XLSX()); + /** @var SharedStringsManager $sharedStringManager */ + $sharedStringManager = $this->createMock(SharedStringsManager::class); + + $formatter = new CellValueFormatter($sharedStringManager, $styleManagerMock, false, $shouldUse1904Dates, new Escaper\XLSX()); try { $result = $formatter->extractAndFormatNodeValue($nodeMock); @@ -106,7 +112,9 @@ public function testExcelDate($shouldUse1904Dates, $nodeValue, $expectedDateAsSt $this->fail('An exception should have been thrown'); } else { $this->assertInstanceOf(\DateTime::class, $result); - $this->assertSame($expectedDateAsString, $result->format('Y-m-d H:i:s')); + /** @var \DateTime $datetime */ + $datetime = $result; + $this->assertSame($expectedDateAsString, $datetime->format('Y-m-d H:i:s')); } } catch (InvalidValueException $exception) { // do nothing @@ -114,7 +122,7 @@ public function testExcelDate($shouldUse1904Dates, $nodeValue, $expectedDateAsSt } /** - * @return array + * @return array */ public function dataProviderForTestFormatNumericCellValueWithNumbers() { @@ -149,14 +157,17 @@ public function dataProviderForTestFormatNumericCellValueWithNumbers() */ public function testFormatNumericCellValueWithNumbers($value, $expectedFormattedValue, $expectedType) { - /** @var StyleManager|\PHPUnit_Framework_MockObject_MockObject $styleManagerMock */ + /** @var StyleManager&MockObject $styleManagerMock */ $styleManagerMock = $this->createMock(StyleManager::class); $styleManagerMock ->expects($this->once()) ->method('shouldFormatNumericValueAsDate') ->will($this->returnValue(false)); - $formatter = new CellValueFormatter(null, $styleManagerMock, false, false, new Escaper\XLSX()); + /** @var SharedStringsManager $sharedStringManager */ + $sharedStringManager = $this->createMock(SharedStringsManager::class); + + $formatter = new CellValueFormatter($sharedStringManager, $styleManagerMock, false, false, new Escaper\XLSX()); $formattedValue = \ReflectionHelper::callMethodOnObject($formatter, 'formatNumericCellValue', $value, 0); $this->assertEquals($expectedFormattedValue, $formattedValue); @@ -164,7 +175,7 @@ public function testFormatNumericCellValueWithNumbers($value, $expectedFormatted } /** - * @return array + * @return array */ public function dataProviderForTestFormatStringCellValue() { @@ -203,7 +214,13 @@ public function testFormatInlineStringCellValue($value, $expectedFormattedValue) ->with(CellValueFormatter::XML_NODE_INLINE_STRING_VALUE) ->willReturn($nodeListMock); - $formatter = new CellValueFormatter(null, null, false, false, new Escaper\XLSX()); + /** @var SharedStringsManager $sharedStringManager */ + $sharedStringManager = $this->createMock(SharedStringsManager::class); + + /** @var StyleManager $styleManager */ + $styleManager = $this->createMock(StyleManager::class); + + $formatter = new CellValueFormatter($sharedStringManager, $styleManager, false, 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 b2aea227a..92403cb8a 100644 --- a/tests/Spout/Reader/XLSX/Helper/DateFormatHelperTest.php +++ b/tests/Spout/Reader/XLSX/Helper/DateFormatHelperTest.php @@ -10,7 +10,7 @@ class DateFormatHelperTest extends TestCase { /** - * @return array + * @return array */ public function dataProviderForTestToPHPDateFormat() { diff --git a/tests/Spout/Reader/XLSX/Manager/SharedStringsCaching/CachingStrategyFactoryTest.php b/tests/Spout/Reader/XLSX/Manager/SharedStringsCaching/CachingStrategyFactoryTest.php index 807daf78a..01cccc0ba 100644 --- a/tests/Spout/Reader/XLSX/Manager/SharedStringsCaching/CachingStrategyFactoryTest.php +++ b/tests/Spout/Reader/XLSX/Manager/SharedStringsCaching/CachingStrategyFactoryTest.php @@ -3,6 +3,7 @@ namespace Box\Spout\Reader\XLSX\Manager\SharedStringsCaching; use Box\Spout\Reader\XLSX\Creator\HelperFactory; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -11,7 +12,7 @@ class CachingStrategyFactoryTest extends TestCase { /** - * @return array + * @return array */ public function dataProviderForTestCreateBestCachingStrategy() { @@ -36,7 +37,7 @@ public function dataProviderForTestCreateBestCachingStrategy() */ public function testCreateBestCachingStrategy($sharedStringsUniqueCount, $memoryLimitInKB, $expectedStrategyClassName) { - /** @var CachingStrategyFactory|\PHPUnit_Framework_MockObject_MockObject $factoryStub */ + /** @var CachingStrategyFactory&MockObject $factoryStub */ $factoryStub = $this ->getMockBuilder('\Box\Spout\Reader\XLSX\Manager\SharedStringsCaching\CachingStrategyFactory') ->disableOriginalConstructor() @@ -46,7 +47,7 @@ public function testCreateBestCachingStrategy($sharedStringsUniqueCount, $memory $factoryStub->method('getMemoryLimitInKB')->willReturn($memoryLimitInKB); $tempFolder = sys_get_temp_dir(); - $helperFactory = new HelperFactory($factoryStub); + $helperFactory = new HelperFactory(); $strategy = $factoryStub->createBestCachingStrategy($sharedStringsUniqueCount, $tempFolder, $helperFactory); $fullExpectedStrategyClassName = 'Box\Spout\Reader\XLSX\Manager\SharedStringsCaching\\' . $expectedStrategyClassName; @@ -56,7 +57,7 @@ public function testCreateBestCachingStrategy($sharedStringsUniqueCount, $memory } /** - * @return array + * @return array */ public function dataProviderForTestGetMemoryLimitInKB() { @@ -84,7 +85,7 @@ public function dataProviderForTestGetMemoryLimitInKB() */ public function testGetMemoryLimitInKB($memoryLimitFormatted, $expectedMemoryLimitInKB) { - /** @var CachingStrategyFactory|\PHPUnit_Framework_MockObject_MockObject $factoryStub */ + /** @var CachingStrategyFactory&MockObject $factoryStub */ $factoryStub = $this ->getMockBuilder('\Box\Spout\Reader\XLSX\Manager\SharedStringsCaching\CachingStrategyFactory') ->disableOriginalConstructor() diff --git a/tests/Spout/Reader/XLSX/Manager/SharedStringsManagerTest.php b/tests/Spout/Reader/XLSX/Manager/SharedStringsManagerTest.php index f344b3541..727490440 100644 --- a/tests/Spout/Reader/XLSX/Manager/SharedStringsManagerTest.php +++ b/tests/Spout/Reader/XLSX/Manager/SharedStringsManagerTest.php @@ -19,7 +19,7 @@ class SharedStringsManagerTest extends TestCase { use TestUsingResource; - /** @var SharedStringsManager */ + /** @var SharedStringsManager|null */ private $sharedStringsManager; /** @@ -144,6 +144,7 @@ public function testGetStringAtIndexShouldNotDoubleDecodeHTMLEntities() public function testGetStringAtIndexWithFileBasedStrategy() { // force the file-based strategy by setting no memory limit + /** @var string $originalMemoryLimit */ $originalMemoryLimit = ini_get('memory_limit'); ini_set('memory_limit', '-1'); diff --git a/tests/Spout/Reader/XLSX/Manager/StyleManagerTest.php b/tests/Spout/Reader/XLSX/Manager/StyleManagerTest.php index 794f4bc3e..7e35c5051 100644 --- a/tests/Spout/Reader/XLSX/Manager/StyleManagerTest.php +++ b/tests/Spout/Reader/XLSX/Manager/StyleManagerTest.php @@ -3,6 +3,7 @@ namespace Box\Spout\Reader\XLSX\Manager; use Box\Spout\Reader\XLSX\Creator\InternalEntityFactory; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -11,8 +12,8 @@ class StyleManagerTest extends TestCase { /** - * @param array $styleAttributes - * @param array $customNumberFormats + * @param array $styleAttributes + * @param array $customNumberFormats * @return StyleManager */ private function getStyleManagerMock($styleAttributes = [], $customNumberFormats = []) @@ -21,7 +22,7 @@ private function getStyleManagerMock($styleAttributes = [], $customNumberFormats $workbookRelationshipsManager = $this->createMock(WorkbookRelationshipsManager::class); $workbookRelationshipsManager->method('hasStylesXMLFile')->willReturn(true); - /** @var StyleManager $styleManager */ + /** @var StyleManager&MockObject $styleManager */ $styleManager = $this->getMockBuilder('\Box\Spout\Reader\XLSX\Manager\StyleManager') ->setConstructorArgs(['/path/to/file.xlsx', $workbookRelationshipsManager, $entityFactory]) ->setMethods(['getCustomNumberFormats', 'getStylesAttributes']) @@ -132,7 +133,7 @@ public function testShouldFormatNumericValueAsDateWhenCustomNumberFormatNotFound } /** - * @return array + * @return array */ public function dataProviderForCustomDateFormats() { diff --git a/tests/Spout/Reader/XLSX/ReaderPerfTest.php b/tests/Spout/Reader/XLSX/ReaderPerfTest.php index 3cb97725a..bc3ff6c3f 100644 --- a/tests/Spout/Reader/XLSX/ReaderPerfTest.php +++ b/tests/Spout/Reader/XLSX/ReaderPerfTest.php @@ -15,7 +15,7 @@ class ReaderPerfTest extends TestCase use TestUsingResource; /** - * @return array + * @return array */ public function dataProviderForTestPerfWhenReading300kRowsXLSX() { diff --git a/tests/Spout/Reader/XLSX/ReaderTest.php b/tests/Spout/Reader/XLSX/ReaderTest.php index 5b155b48a..8cda9de3d 100644 --- a/tests/Spout/Reader/XLSX/ReaderTest.php +++ b/tests/Spout/Reader/XLSX/ReaderTest.php @@ -15,7 +15,7 @@ class ReaderTest extends TestCase use TestUsingResource; /** - * @return array + * @return array */ public function dataProviderForTestReadShouldThrowException() { @@ -42,7 +42,7 @@ public function testReadShouldThrowException($filePath) } /** - * @return array + * @return array */ public function dataProviderForTestReadForAllWorksheets() { @@ -748,7 +748,7 @@ public function testReaderShouldSupportStrictOOXML() * @param string $fileName * @param bool $shouldFormatDates * @param bool $shouldPreserveEmptyRows - * @return array All the read rows the given file + * @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 a5389421b..25b16c0c3 100644 --- a/tests/Spout/Reader/XLSX/SheetTest.php +++ b/tests/Spout/Reader/XLSX/SheetTest.php @@ -3,6 +3,7 @@ namespace Box\Spout\Reader\XLSX; use Box\Spout\Reader\Common\Creator\ReaderEntityFactory; +use Box\Spout\Reader\SheetInterface; use Box\Spout\TestUsingResource; use PHPUnit\Framework\TestCase; @@ -43,7 +44,7 @@ public function testReaderShouldReturnCorrectSheetVisibility() /** * @param string $fileName - * @return Sheet[] + * @return SheetInterface[] */ private function openFileAndReturnSheets($fileName) { diff --git a/tests/Spout/ReflectionHelper.php b/tests/Spout/ReflectionHelper.php index c078f3bd0..4796afc4a 100644 --- a/tests/Spout/ReflectionHelper.php +++ b/tests/Spout/ReflectionHelper.php @@ -5,6 +5,9 @@ */ class ReflectionHelper { + /** + * @var array + */ private static $privateVarsToReset = []; /** @@ -27,7 +30,7 @@ public static function reset() * Get the value of a static private or public class property. * Used to test internals of class without having to make the property public * - * @param string $class + * @param class-string $class * @param string $valueName * @return mixed|null */ @@ -48,7 +51,7 @@ public static function getStaticValue($class, $valueName) * Set the value of a static private or public class property. * Used to test internals of class without having to make the property public * - * @param string $class + * @param class-string $class * @param string $valueName * @param mixed|null $value * @param bool $saveOriginalValue @@ -62,7 +65,7 @@ public static function setStaticValue($class, $valueName, $value, $saveOriginalV // to prevent side-effects in later tests, we need to remember the original value and reset it on tear down // @NOTE: we need to check isset in case the original value was null or array() - if ($saveOriginalValue && (!isset(self::$privateVarsToReset[$class]) || !isset(self::$privateVarsToReset[$class][$name]))) { + if ($saveOriginalValue && (!isset(self::$privateVarsToReset[$class]))) { self::$privateVarsToReset[$class][$valueName] = $reflectionProperty->getValue(); } $reflectionProperty->setValue($value); @@ -95,7 +98,6 @@ public static function getValueOnObject($object, $valueName) * * @param object $object * @param string $methodName - * @param *mixed|null $params * * @return mixed|null */ diff --git a/tests/Spout/TestUsingResource.php b/tests/Spout/TestUsingResource.php index 551f86b61..d4c96f7fe 100644 --- a/tests/Spout/TestUsingResource.php +++ b/tests/Spout/TestUsingResource.php @@ -92,7 +92,13 @@ protected function createUnwritableFolderIfNeeded() */ protected function getTempFolderPath() { - return realpath($this->tempFolderPath); + $path = realpath($this->tempFolderPath); + + if ($path === false) { + throw new \RuntimeException(sprintf("Realpath of '%s' failed.", $path)); + } + + return $path; } /** diff --git a/tests/Spout/Writer/CSV/WriterTest.php b/tests/Spout/Writer/CSV/WriterTest.php index deb3f22b6..405208ffc 100644 --- a/tests/Spout/Writer/CSV/WriterTest.php +++ b/tests/Spout/Writer/CSV/WriterTest.php @@ -69,6 +69,7 @@ public function testAddRowsShouldThrowExceptionIfRowsAreNotArrayOfArrays() $this->expectException(InvalidArgumentException::class); $writer = WriterEntityFactory::createCSVWriter(); + /* @phpstan-ignore-next-line */ $writer->addRows([['csv--11', 'csv--12']]); $writer->close(); } @@ -176,7 +177,7 @@ public function testWriteShouldSupportCustomFieldEnclosure() $this->assertEquals('#This is, a comma#,csv--12,csv--13', $writtenContent, 'The fields should be enclosed with #'); } - public function testWriteShouldSupportedEscapedCharacters() + public function testWriteShouldSupportedEscapedCharacters() : void { $allRows = $this->createRowsFromValues([ ['"csv--11"', 'csv--12\\', 'csv--13\\\\', 'csv--14\\\\\\'], @@ -193,7 +194,7 @@ public function testWriteShouldSupportedEscapedCharacters() * @param string $fieldDelimiter * @param string $fieldEnclosure * @param bool $shouldAddBOM - * @return string|null + * @return string */ private function writeToCsvFileAndReturnWrittenContent($allRows, $fileName, $fieldDelimiter = ',', $fieldEnclosure = '"', $shouldAddBOM = true) { @@ -209,7 +210,10 @@ private function writeToCsvFileAndReturnWrittenContent($allRows, $fileName, $fie $writer->addRows($allRows); $writer->close(); - return file_get_contents($resourcePath); + /** @var string $content */ + $content = file_get_contents($resourcePath); + + return $content; } /** diff --git a/tests/Spout/Writer/Common/Entity/SheetTest.php b/tests/Spout/Writer/Common/Entity/SheetTest.php index e0cf8eeb2..2326cb791 100644 --- a/tests/Spout/Writer/Common/Entity/SheetTest.php +++ b/tests/Spout/Writer/Common/Entity/SheetTest.php @@ -25,7 +25,7 @@ public function setUp() : void /** * @param int $sheetIndex - * @param int $associatedWorkbookId + * @param string $associatedWorkbookId * @return Sheet */ private function createSheet($sheetIndex, $associatedWorkbookId) @@ -57,7 +57,7 @@ public function testSetSheetNameShouldCreateSheetWithCustomName() } /** - * @return array + * @return array */ public function dataProviderForInvalidSheetNames() { diff --git a/tests/Spout/Writer/Common/Helper/CellHelperTest.php b/tests/Spout/Writer/Common/Helper/CellHelperTest.php index 3ab9a795a..33815d28d 100644 --- a/tests/Spout/Writer/Common/Helper/CellHelperTest.php +++ b/tests/Spout/Writer/Common/Helper/CellHelperTest.php @@ -10,7 +10,7 @@ class CellHelperTest extends TestCase { /** - * @return array + * @return array */ public function dataProviderForTestGetColumnLettersFromColumnIndex() { diff --git a/tests/Spout/Writer/Common/Manager/RowManagerTest.php b/tests/Spout/Writer/Common/Manager/RowManagerTest.php index 91ae37805..75b7553da 100644 --- a/tests/Spout/Writer/Common/Manager/RowManagerTest.php +++ b/tests/Spout/Writer/Common/Manager/RowManagerTest.php @@ -10,7 +10,7 @@ class RowManagerTest extends TestCase { /** - * @return array + * @return array */ public function dataProviderForTestIsEmptyRow() { @@ -26,7 +26,7 @@ public function dataProviderForTestIsEmptyRow() /** * @dataProvider dataProviderForTestIsEmptyRow * - * @param array $cells + * @param array $cells * @param bool $expectedIsEmpty * @return void */ diff --git a/tests/Spout/Writer/ODS/SheetTest.php b/tests/Spout/Writer/ODS/SheetTest.php index 3bd219366..64b99b178 100644 --- a/tests/Spout/Writer/ODS/SheetTest.php +++ b/tests/Spout/Writer/ODS/SheetTest.php @@ -87,6 +87,7 @@ public function testSetSheetVisibilityShouldCreateSheetHidden() $resourcePath = $this->getGeneratedResourcePath($fileName); $pathToContentFile = $resourcePath . '#content.xml'; + /** @var string $xmlContents */ $xmlContents = file_get_contents('zip://' . $pathToContentFile); $this->assertStringContainsString(' table:display="false"', $xmlContents, 'The sheet visibility should have been changed to "hidden"'); @@ -95,7 +96,7 @@ public function testSetSheetVisibilityShouldCreateSheetHidden() /** * @param string $fileName * @param string $sheetName - * @return Sheet + * @return void */ private function writeDataAndReturnSheetWithCustomName($fileName, $sheetName) { @@ -162,6 +163,7 @@ private function assertSheetNameEquals($expectedName, $fileName, $message = '') { $resourcePath = $this->getGeneratedResourcePath($fileName); $pathToWorkbookFile = $resourcePath . '#content.xml'; + /** @var string $xmlContents */ $xmlContents = file_get_contents('zip://' . $pathToWorkbookFile); $this->assertStringContainsString("table:name=\"$expectedName\"", $xmlContents, $message); diff --git a/tests/Spout/Writer/ODS/WriterTest.php b/tests/Spout/Writer/ODS/WriterTest.php index a9aaa0e39..6ad0288c2 100644 --- a/tests/Spout/Writer/ODS/WriterTest.php +++ b/tests/Spout/Writer/ODS/WriterTest.php @@ -284,19 +284,28 @@ public function testAddRowShouldSupportMultipleTypesOfData() */ public function testAddRowShouldSupportFloatValuesInDifferentLocale() { - $previousLocale = \setlocale(LC_ALL, 0); + /** @var string[] $previousLocale */ + $previousLocale = \setlocale(LC_ALL, '0'); try { // Pick a supported locale whose decimal point is a comma. // Installed locales differ from one system to another, so we can't pick // a given locale. $supportedLocales = explode("\n", shell_exec('locale -a')); + + $commaDecimalPointSupported = false; foreach ($supportedLocales as $supportedLocale) { \setlocale(LC_ALL, $supportedLocale); if (\localeconv()['decimal_point'] === ',') { + $commaDecimalPointSupported = true; break; } } + + if ($commaDecimalPointSupported === false) { + $this->markTestSkipped('System has no local which support comma decimal point'); + } + $this->assertEquals(',', \localeconv()['decimal_point']); $fileName = 'test_add_row_should_support_float_values_in_different_locale.xlsx'; @@ -306,8 +315,8 @@ public function testAddRowShouldSupportFloatValuesInDifferentLocale() $this->writeToODSFile($dataRows, $fileName); - $this->assertValueWasNotWrittenToSheet($fileName, 1, "1234,5"); - $this->assertValueWasWrittenToSheet($fileName, 1, "1234.5"); + $this->assertValueWasNotWrittenToSheet($fileName, 1, '1234,5'); + $this->assertValueWasWrittenToSheet($fileName, 1, '1234.5'); } finally { // reset locale \setlocale(LC_ALL, $previousLocale); @@ -315,7 +324,7 @@ public function testAddRowShouldSupportFloatValuesInDifferentLocale() } /** - * @return array + * @return array */ public function dataProviderForTestAddRowShouldUseNumberColumnsRepeatedForRepeatedValues() { @@ -331,7 +340,7 @@ public function dataProviderForTestAddRowShouldUseNumberColumnsRepeatedForRepeat /** * @dataProvider dataProviderForTestAddRowShouldUseNumberColumnsRepeatedForRepeatedValues * - * @param array $dataRow + * @param array $dataRow * @param int $expectedNumTableCells * @param int $expectedNumColumnsRepeated * @return void @@ -341,6 +350,7 @@ public function testAddRowShouldUseNumberColumnsRepeatedForRepeatedValues($dataR $fileName = 'test_add_row_should_use_number_columns_repeated.ods'; $this->writeToODSFile($this->createRowsFromValues([$dataRow]), $fileName); + /** @var \DOMElement $sheetXmlNode */ $sheetXmlNode = $this->getSheetXmlNode($fileName, 1); $tableCellNodes = $sheetXmlNode->getElementsByTagName('table-cell'); @@ -580,6 +590,7 @@ private function assertValueWasWritten($fileName, $value, $message = '') { $resourcePath = $this->getGeneratedResourcePath($fileName); $pathToContentFile = $resourcePath . '#content.xml'; + /** @var string $xmlContents */ $xmlContents = file_get_contents('zip://' . $pathToContentFile); $this->assertStringContainsString($value, $xmlContents, $message); @@ -624,7 +635,10 @@ private function getSheetXmlNode($fileName, $sheetIndex) { $xmlReader = $this->moveReaderToCorrectTableNode($fileName, $sheetIndex); - return $xmlReader->expand(); + /** @var \DOMNode $node */ + $node = $xmlReader->expand(); + + return $node; } /** diff --git a/tests/Spout/Writer/ODS/WriterWithStyleTest.php b/tests/Spout/Writer/ODS/WriterWithStyleTest.php index 75177da2e..07e15e1a7 100644 --- a/tests/Spout/Writer/ODS/WriterWithStyleTest.php +++ b/tests/Spout/Writer/ODS/WriterWithStyleTest.php @@ -112,6 +112,7 @@ public function testAddRowShouldWriteDefaultStyleSettings() $this->writeToODSFile([$dataRow], $fileName); + /** @var \DOMElement $textPropertiesElement */ $textPropertiesElement = $this->getXmlSectionFromStylesXmlFile($fileName, 'style:text-properties'); $this->assertEquals(Style::DEFAULT_FONT_SIZE . 'pt', $textPropertiesElement->getAttribute('fo:font-size')); $this->assertEquals('#' . Style::DEFAULT_FONT_COLOR, $textPropertiesElement->getAttribute('fo:color')); @@ -351,6 +352,7 @@ public function testSetDefaultRowStyle() $this->writeToODSFileWithDefaultStyle($dataRows, $fileName, $defaultStyle); + /** @var \DOMElement $textPropertiesElement */ $textPropertiesElement = $this->getXmlSectionFromStylesXmlFile($fileName, 'style:text-properties'); $this->assertEquals($defaultFontSize . 'pt', $textPropertiesElement->getAttribute('fo:font-size')); } @@ -397,7 +399,7 @@ private function writeToODSFileWithDefaultStyle($allRows, $fileName, $defaultSty /** * @param string $fileName - * @return \DOMNode[] + * @return \DOMElement[] */ private function getCellElementsFromContentXmlFile($fileName) { @@ -410,7 +412,9 @@ private function getCellElementsFromContentXmlFile($fileName) while ($xmlReader->read()) { if ($xmlReader->isPositionedOnStartingNode('table:table-cell') && $xmlReader->getAttribute('office:value-type') !== null) { - $cellElements[] = $xmlReader->expand(); + /** @var \DOMElement $element */ + $element = $xmlReader->expand(); + $cellElements[] = $element; } } @@ -421,7 +425,7 @@ private function getCellElementsFromContentXmlFile($fileName) /** * @param string $fileName - * @return \DOMNode[] + * @return \DOMElement[] */ private function getCellStyleElementsFromContentXmlFile($fileName) { @@ -434,7 +438,10 @@ private function getCellStyleElementsFromContentXmlFile($fileName) while ($xmlReader->read()) { if ($xmlReader->isPositionedOnStartingNode('style:style') && $xmlReader->getAttribute('style:family') === 'table-cell') { - $cellStyleElements[] = $xmlReader->expand(); + /** @var \DOMElement $element */ + $element = $xmlReader->expand(); + + $cellStyleElements[] = $element; } } @@ -456,18 +463,23 @@ private function getXmlSectionFromStylesXmlFile($fileName, $section) $xmlReader->openFileInZip($resourcePath, 'styles.xml'); $xmlReader->readUntilNodeFound($section); - return $xmlReader->expand(); + /** @var \DOMNode $node */ + $node = $xmlReader->expand(); + + return $node; } /** * @param string $expectedValue - * @param \DOMNode $parentElement + * @param \DOMElement $parentElement * @param string $childTagName * @param string $attributeName * @return void */ private function assertFirstChildHasAttributeEquals($expectedValue, $parentElement, $childTagName, $attributeName) { - $this->assertEquals($expectedValue, $parentElement->getElementsByTagName($childTagName)->item(0)->getAttribute($attributeName)); + /** @var \DOMElement $child */ + $child = $parentElement->getElementsByTagName($childTagName)->item(0); + $this->assertEquals($expectedValue, $child->getAttribute($attributeName)); } } diff --git a/tests/Spout/Writer/RowCreationHelper.php b/tests/Spout/Writer/RowCreationHelper.php index 0f3c6bbe0..db9f2374f 100644 --- a/tests/Spout/Writer/RowCreationHelper.php +++ b/tests/Spout/Writer/RowCreationHelper.php @@ -12,7 +12,7 @@ trait RowCreationHelper { /** - * @param array $cellValues + * @param array $cellValues * @return Row */ protected function createRowFromValues(array $cellValues) @@ -21,7 +21,7 @@ protected function createRowFromValues(array $cellValues) } /** - * @param array $cellValues + * @param array $cellValues * @param Style|null $rowStyle * @return Row */ @@ -31,7 +31,7 @@ protected function createStyledRowFromValues(array $cellValues, Style $rowStyle } /** - * @param array $rowValues + * @param array $rowValues * @return Row[] */ protected function createRowsFromValues(array $rowValues) @@ -40,7 +40,7 @@ protected function createRowsFromValues(array $rowValues) } /** - * @param array $rowValues + * @param array $rowValues * @param Style|null $rowsStyle * @return Row[] */ diff --git a/tests/Spout/Writer/XLSX/Manager/Style/StyleManagerTest.php b/tests/Spout/Writer/XLSX/Manager/Style/StyleManagerTest.php index 3bb0f42e2..76808ef6f 100644 --- a/tests/Spout/Writer/XLSX/Manager/Style/StyleManagerTest.php +++ b/tests/Spout/Writer/XLSX/Manager/Style/StyleManagerTest.php @@ -2,6 +2,7 @@ namespace Box\Spout\Writer\XLSX\Manager\Style; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** @@ -10,7 +11,7 @@ class StyleManagerTest extends TestCase { /** - * @return array + * @return array */ public function dataProviderForTestShouldApplyStyleOnEmptyCell() { @@ -38,6 +39,7 @@ public function dataProviderForTestShouldApplyStyleOnEmptyCell() */ public function testShouldApplyStyleOnEmptyCell($fillId, $borderId, $expectedResult) { + /** @var \Box\Spout\Writer\Common\Manager\Style\StyleRegistry&MockObject $styleRegistryMock */ $styleRegistryMock = $this->getMockBuilder(StyleRegistry::class) ->disableOriginalConstructor() ->setMethods(['getFillIdForStyleId', 'getBorderIdForStyleId']) diff --git a/tests/Spout/Writer/XLSX/SheetTest.php b/tests/Spout/Writer/XLSX/SheetTest.php index a2431619c..53a3fbeec 100644 --- a/tests/Spout/Writer/XLSX/SheetTest.php +++ b/tests/Spout/Writer/XLSX/SheetTest.php @@ -87,6 +87,7 @@ public function testSetSheetVisibilityShouldCreateSheetHidden() $resourcePath = $this->getGeneratedResourcePath($fileName); $pathToWorkbookFile = $resourcePath . '#xl/workbook.xml'; + /** @var string $xmlContents */ $xmlContents = file_get_contents('zip://' . $pathToWorkbookFile); $this->assertStringContainsString(' state="hidden"', $xmlContents, 'The sheet visibility should have been changed to "hidden"'); @@ -164,6 +165,7 @@ private function assertSheetNameEquals($expectedName, $fileName, $message = '') { $resourcePath = $this->getGeneratedResourcePath($fileName); $pathToWorkbookFile = $resourcePath . '#xl/workbook.xml'; + /** @var string $xmlContents */ $xmlContents = file_get_contents('zip://' . $pathToWorkbookFile); $this->assertStringContainsString(" */ public function dataProviderForTestPerfWhenWritingOneMillionRowsXLSX() { @@ -102,7 +102,7 @@ private function getNumWrittenRowsUsingSharedStrings($resourcePath) /** * @param string $filePath - * @return string + * @return int */ private function getLasRowNumberForFile($filePath) { diff --git a/tests/Spout/Writer/XLSX/WriterTest.php b/tests/Spout/Writer/XLSX/WriterTest.php index 26b379257..6126a896c 100644 --- a/tests/Spout/Writer/XLSX/WriterTest.php +++ b/tests/Spout/Writer/XLSX/WriterTest.php @@ -120,6 +120,7 @@ public function testAddRowShouldThrowExceptionIfUnsupportedDataTypePassedIn() [str_repeat('a', WorksheetManager::MAX_CHARACTERS_PER_CELL + 1)], ]; + /* @phpstan-ignore-next-line */ $this->writeToXLSXFile($dataRows, $fileName); } @@ -398,7 +399,8 @@ public function testAddRowShouldSupportCellInError() */ public function testAddRowShouldSupportFloatValuesInDifferentLocale() { - $previousLocale = \setlocale(LC_ALL, 0); + /** @var string[] $previousLocale */ + $previousLocale = \setlocale(LC_ALL, '0'); $valueToWrite = 1234.5; // needs to be defined before changing the locale as PHP8 would expect 1234,5 try { @@ -406,12 +408,19 @@ public function testAddRowShouldSupportFloatValuesInDifferentLocale() // Installed locales differ from one system to another, so we can't pick // a given locale. $supportedLocales = explode("\n", shell_exec('locale -a')); + + $commaDecimalPointSupported = false; foreach ($supportedLocales as $supportedLocale) { \setlocale(LC_ALL, $supportedLocale); if (\localeconv()['decimal_point'] === ',') { + $commaDecimalPointSupported = true; break; } } + if ($commaDecimalPointSupported === false) { + $this->markTestSkipped('System has no local which support comma decimal point'); + } + $this->assertEquals(',', \localeconv()['decimal_point']); $fileName = 'test_add_row_should_support_float_values_in_different_locale.xlsx'; @@ -421,8 +430,8 @@ public function testAddRowShouldSupportFloatValuesInDifferentLocale() $this->writeToXLSXFile($dataRows, $fileName, $shouldUseInlineStrings = false); - $this->assertInlineDataWasNotWrittenToSheet($fileName, 1, "1234,5"); - $this->assertInlineDataWasWrittenToSheet($fileName, 1, "1234.5"); + $this->assertInlineDataWasNotWrittenToSheet($fileName, 1, '1234,5'); + $this->assertInlineDataWasWrittenToSheet($fileName, 1, '1234.5'); } finally { // reset locale \setlocale(LC_ALL, $previousLocale); @@ -642,6 +651,7 @@ private function assertInlineDataWasWrittenToSheet($fileName, $sheetIndex, $inli { $resourcePath = $this->getGeneratedResourcePath($fileName); $pathToSheetFile = $resourcePath . '#xl/worksheets/sheet' . $sheetIndex . '.xml'; + /** @var string $xmlContents */ $xmlContents = file_get_contents('zip://' . $pathToSheetFile); $this->assertStringContainsString((string) $inlineData, $xmlContents, $message); @@ -658,6 +668,7 @@ private function assertInlineDataWasNotWrittenToSheet($fileName, $sheetIndex, $i { $resourcePath = $this->getGeneratedResourcePath($fileName); $pathToSheetFile = $resourcePath . '#xl/worksheets/sheet' . $sheetIndex . '.xml'; + /** @var string $xmlContents */ $xmlContents = file_get_contents('zip://' . $pathToSheetFile); $this->assertStringNotContainsString((string) $inlineData, $xmlContents, $message); @@ -673,6 +684,7 @@ private function assertSharedStringWasWritten($fileName, $sharedString, $message { $resourcePath = $this->getGeneratedResourcePath($fileName); $pathToSharedStringsFile = $resourcePath . '#xl/sharedStrings.xml'; + /** @var string $xmlContents */ $xmlContents = file_get_contents('zip://' . $pathToSharedStringsFile); $this->assertStringContainsString($sharedString, $xmlContents, $message); diff --git a/tests/Spout/Writer/XLSX/WriterWithStyleTest.php b/tests/Spout/Writer/XLSX/WriterWithStyleTest.php index 2571df416..c174151c9 100644 --- a/tests/Spout/Writer/XLSX/WriterWithStyleTest.php +++ b/tests/Spout/Writer/XLSX/WriterWithStyleTest.php @@ -394,10 +394,16 @@ public function testReuseBackgroundColorSharedDefinition() '3 cell xfs present - a default one and two custom ones' ); - $firstCustomId = $styleXfsElements->childNodes->item(1)->getAttribute('fillId'); + /** @var \DOMElement $firstItem */ + $firstItem = $styleXfsElements->childNodes->item(1); + + $firstCustomId = $firstItem->getAttribute('fillId'); $this->assertEquals(2, (int) $firstCustomId, 'The first custom fill id should have the index 2'); - $secondCustomId = $styleXfsElements->childNodes->item(2)->getAttribute('fillId'); + /** @var \DOMElement $secondItem */ + $secondItem = $styleXfsElements->childNodes->item(2); + + $secondCustomId = $secondItem->getAttribute('fillId'); $this->assertEquals(2, (int) $secondCustomId, 'The second custom fill id should have the index 2'); } @@ -468,7 +474,6 @@ public function testBordersCorrectOrder() $borderParts = $borderNode->childNodes; $ordering = []; - /** @var \DOMText $part */ foreach ($borderParts as $part) { if ($part instanceof \DOMElement) { $ordering[] = $part->nodeName; @@ -617,6 +622,7 @@ private function getXmlSectionFromStylesXmlFile($fileName, $section) $xmlReader->openFileInZip($resourcePath, 'xl/styles.xml'); $xmlReader->readUntilNodeFound($section); + /** @var \DOMElement $xmlSection */ $xmlSection = $xmlReader->expand(); $xmlReader->close(); @@ -626,7 +632,7 @@ private function getXmlSectionFromStylesXmlFile($fileName, $section) /** * @param string $fileName - * @return \DOMNode[] + * @return \DOMElement[] */ private function getCellElementsFromSheetXmlFile($fileName) { @@ -639,7 +645,9 @@ private function getCellElementsFromSheetXmlFile($fileName) while ($xmlReader->read()) { if ($xmlReader->isPositionedOnStartingNode('c')) { - $cellElements[] = $xmlReader->expand(); + /** @var \DOMElement $element */ + $element = $xmlReader->expand(); + $cellElements[] = $element; } } @@ -650,19 +658,21 @@ private function getCellElementsFromSheetXmlFile($fileName) /** * @param string $expectedValue - * @param \DOMNode $parentElement + * @param \DOMElement $parentElement * @param string $childTagName * @param string $attributeName * @return void */ private function assertFirstChildHasAttributeEquals($expectedValue, $parentElement, $childTagName, $attributeName) { - $this->assertEquals($expectedValue, $parentElement->getElementsByTagName($childTagName)->item(0)->getAttribute($attributeName)); + /** @var \DOMElement $child */ + $child = $parentElement->getElementsByTagName($childTagName)->item(0); + $this->assertEquals($expectedValue, $child->getAttribute($attributeName)); } /** * @param int $expectedNumber - * @param \DOMNode $parentElement + * @param \DOMElement $parentElement * @param string $message * @return void */ @@ -672,7 +682,7 @@ private function assertChildrenNumEquals($expectedNumber, $parentElement, $messa } /** - * @param \DOMNode $parentElement + * @param \DOMElement $parentElement * @param string $childTagName * @return void */