Merge efcf35be50ad669a575ee152bce51ba69c1d7ce0 into 9533accd73edc020072bc7a4f0c0ddb28a5b701f

This commit is contained in:
Antoine Lamirault 2021-09-18 07:58:56 -07:00 committed by GitHub
commit 66bddcdefe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
113 changed files with 574 additions and 317 deletions

View File

@ -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

View File

@ -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.

View File

@ -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"

5
phpstan.neon Normal file
View File

@ -0,0 +1,5 @@
parameters:
level: 7
paths:
- src
- tests

View File

@ -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<string, array>
*/
protected $prefixes = [];

View File

@ -77,7 +77,7 @@ class Cell
/**
* @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 @@ class Cell
/**
* @param Style|null $style
*/
public function setStyle($style)
public function setStyle($style) : void
{
$this->style = $style ?: new Style();
}
@ -126,7 +126,7 @@ class Cell
/**
* @param int $type
*/
public function setType($type)
public function setType($type) : void
{
$this->type = $type;
}

View File

@ -95,7 +95,10 @@ class Row
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 @@ class Row
}
/**
* @return array The row values, as array
* @return array<mixed> The row values, as array
*/
public function toArray()
{

View File

@ -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<BorderPart> A list of BorderPart objects for this border. */
private $parts = [];
/**
* @param array $borderParts
* @param array<BorderPart> $borderParts
*/
public function __construct(array $borderParts = [])
{
@ -52,7 +52,7 @@ class Border
}
/**
* @return array
* @return array<BorderPart>
*/
public function getParts()
{
@ -61,7 +61,7 @@ class Border
/**
* Set BorderParts
* @param array $parts
* @param array<BorderPart> $parts
* @return void
*/
public function setParts($parts)

View File

@ -32,7 +32,7 @@ class BorderPart
protected $width;
/**
* @var array Allowed style constants for parts.
* @var array<string> 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<string> 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<string> Allowed width constants for border parts.
*/
protected static $allowedWidths = [
'thin',
@ -159,7 +159,7 @@ class BorderPart
}
/**
* @return array
* @return array<string>
*/
public static function getAllowedStyles()
{
@ -167,7 +167,7 @@ class BorderPart
}
/**
* @return array
* @return array<string>
*/
public static function getAllowedNames()
{
@ -175,7 +175,7 @@ class BorderPart
}
/**
* @return array
* @return array<string>
*/
public static function getAllowedWidths()
{

View File

@ -13,6 +13,9 @@ abstract class CellAlignment
const CENTER = 'center';
const JUSTIFY = 'justify';
/**
* @var array<string, int>
*/
private static $VALID_ALIGNMENTS = [
self::LEFT => 1,
self::RIGHT => 1,

View File

@ -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 @@ class Style
}
/**
* @return Border
* @return Border|null
*/
public function getBorder()
{

View File

@ -9,7 +9,7 @@ namespace Box\Spout\Common\Helper;
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 @@ class CellTypeHelper
}
/**
* @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 @@ class CellTypeHelper
* 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 @@ class CellTypeHelper
* 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 @@ class CellTypeHelper
/**
* 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)

View File

@ -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<string, string> Map representing the encodings supporting BOMs (key) and their associated BOM (value) */
protected $supportedEncodingsWithBom;
/**
@ -143,7 +143,7 @@ class EncodingHelper
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.");
}

View File

@ -22,6 +22,7 @@ class XLSX implements EscaperInterface
/**
* Initializes the control characters if not already done
* @return void
*/
protected function initIfNeeded()
{

View File

@ -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 @@ class FileSystemHelper implements FileSystemHelperInterface
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}");

View File

@ -33,7 +33,10 @@ class GlobalFunctionsHelper
*/
public function fgets($handle, $length = null)
{
return \fgets($handle, $length);
/** @var string $fgets */
$fgets = \fgets($handle, $length);
return $fgets;
}
/**
@ -46,7 +49,10 @@ class GlobalFunctionsHelper
*/
public function fputs($handle, $string)
{
return \fputs($handle, $string);
/** @var int $fputs */
$fputs = \fputs($handle, $string);
return $fputs;
}
/**
@ -82,7 +88,7 @@ class GlobalFunctionsHelper
* @param int|null $length
* @param string|null $delimiter
* @param string|null $enclosure
* @return array
* @return array<mixed>|false
*/
public function fgetcsv($handle, $length = null, $delimiter = null, $enclosure = null)
{
@ -100,10 +106,10 @@ class GlobalFunctionsHelper
* @see fputcsv()
*
* @param resource $handle
* @param array $fields
* @param array<mixed> $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 @@ class GlobalFunctionsHelper
*/
public function fwrite($handle, $string)
{
return \fwrite($handle, $string);
/** @var int $fwrite */
$fwrite = \fwrite($handle, $string);
return $fwrite;
}
/**
@ -176,7 +185,10 @@ class GlobalFunctionsHelper
{
$realFilePath = $this->convertToUseRealPath($filePath);
return \file_get_contents($realFilePath);
/** @var string $content */
$content = \file_get_contents($realFilePath);
return $content;
}
/**
@ -197,7 +209,9 @@ class GlobalFunctionsHelper
$realFilePath = 'zip://' . \realpath($documentPath) . '#' . $documentInsideZipPath;
}
} else {
$realFilePath = \realpath($filePath);
/** @var string $realPath */
$realPath = \realpath($filePath);
$realFilePath = $realPath;
}
return $realFilePath;
@ -308,7 +322,7 @@ class GlobalFunctionsHelper
* Wrapper around global function stream_get_wrappers()
* @see stream_get_wrappers()
*
* @return array
* @return array<int, string>
*/
public function stream_get_wrappers()
{

View File

@ -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<string, mixed> Locale info, used for number formatting */
private $localeInfo;
/**
@ -93,13 +93,16 @@ class StringHelper
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;
}
}

View File

@ -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<string, mixed> Associative array [OPTION_NAME => OPTION_VALUE] */
private $options = [];
/**
@ -25,7 +25,7 @@ abstract class OptionsManagerAbstract implements OptionsManagerInterface
}
/**
* @return array List of supported options
* @return array<string> List of supported options
*/
abstract protected function getSupportedOptions();

View File

@ -84,7 +84,7 @@ class InternalEntityFactory implements InternalEntityFactoryInterface
}
/**
* @param array $cellValues
* @param array<mixed> $cellValues
* @return Row
*/
public function createRowFromArray(array $cellValues = [])

View File

@ -13,7 +13,7 @@ use Box\Spout\Reader\ReaderAbstract;
*/
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 @@ class Reader extends ReaderAbstract
*/
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;

View File

@ -13,6 +13,7 @@ use Box\Spout\Reader\IteratorInterface;
/**
* Class RowIterator
* Iterate over CSV rows.
* @implements IteratorInterface<Row>
*/
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 @@ class RowIterator implements IteratorInterface
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 @@ class RowIterator implements IteratorInterface
}
/**
* @param array|bool $currentRowData
* @param array<int, string>|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 @@ class RowIterator implements IteratorInterface
* 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<int, string>|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 @@ class RowIterator implements IteratorInterface
}
/**
* @param array|bool $lineData Array containing the cells value for the line
* @param array<mixed>|bool $lineData Array containing the cells value for the line
* @return bool Whether the given line is empty
*/
protected function isEmptyLine($lineData)

View File

@ -7,6 +7,7 @@ use Box\Spout\Reader\IteratorInterface;
/**
* Class SheetIterator
* Iterate over CSV unique "sheet".
* @implements IteratorInterface<Sheet>
*/
class SheetIterator implements IteratorInterface
{

View File

@ -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 @@ class ReaderEntityFactory
*/
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 @@ class ReaderEntityFactory
*/
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 @@ class ReaderEntityFactory
*/
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;
}
}

View File

@ -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<string, array> Registered callbacks */
private $callbacks = [];
/**
@ -39,7 +39,7 @@ class XMLProcessor
/**
* @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 @@ class XMLProcessor
* 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<string, mixed> Associative array containing the elements needed to invoke the callback using Reflection
*/
private function getInvokableCallbackData($callback)
{
@ -113,7 +113,7 @@ class XMLProcessor
* @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<mixed>|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 @@ class XMLProcessor
}
/**
* @param array $callbackData Associative array containing data to invoke the callback using Reflection
* @param array $args Arguments to pass to the callback
* @param array<string, mixed> $callbackData Associative array containing data to invoke the callback using Reflection
* @param array<mixed> $args Arguments to pass to the callback
* @return int Callback response
*/
private function invokeCallback($callbackData, $args)

View File

@ -4,6 +4,8 @@ namespace Box\Spout\Reader;
/**
* Interface IteratorInterface
* @template TValue
* @extends \Iterator<int, TValue>
*/
interface IteratorInterface extends \Iterator
{

View File

@ -105,7 +105,7 @@ class InternalEntityFactory implements InternalEntityFactoryInterface
}
/**
* @param $xmlReader
* @param XMLReader $xmlReader
* @return XMLProcessor
*/
private function createXMLProcessor($xmlReader)

View File

@ -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<string, string> 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 @@ class CellValueFormatter
* 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 @@ class CellValueFormatter
/**
* 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 @@ class CellValueFormatter
}
/**
* @param $pNode
* @param \DOMNode $pNode
* @return string
*/
private function extractTextValueFromNode($pNode)
@ -159,7 +159,7 @@ class CellValueFormatter
*
* @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 @@ class CellValueFormatter
/**
* 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 @@ class CellValueFormatter
/**
* 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 @@ class CellValueFormatter
/**
* 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 @@ class CellValueFormatter
/**
* 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 @@ class CellValueFormatter
/**
* 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 @@ class CellValueFormatter
/**
* 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)

View File

@ -12,7 +12,7 @@ use Box\Spout\Reader\ReaderAbstract;
*/
class Reader extends ReaderAbstract
{
/** @var \ZipArchive */
/** @var \ZipArchive|null */
protected $zip;
/** @var SheetIterator To iterator over the ODS sheets */

View File

@ -19,6 +19,7 @@ use Box\Spout\Reader\Wrapper\XMLReader;
/**
* Class RowIterator
* @implements IteratorInterface<Row>
*/
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 @@ class RowIterator implements IteratorInterface
$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 @@ class RowIterator implements IteratorInterface
/**
* 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 @@ class RowIterator implements IteratorInterface
* 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)

View File

@ -12,6 +12,7 @@ use Box\Spout\Reader\Wrapper\XMLReader;
/**
* Class SheetIterator
* Iterate over ODS sheet.
* @implements IteratorInterface<Sheet>
*/
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<string, bool> Associative array [STYLE_NAME] => [IS_SHEET_VISIBLE] */
protected $sheetsVisibility;
/**
@ -101,13 +102,14 @@ class SheetIterator implements IteratorInterface
/**
* Extracts the visibility of the sheets
*
* @return array Associative array [STYLE_NAME] => [IS_SHEET_VISIBLE]
* @return array<string, bool> 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);

View File

@ -45,15 +45,15 @@ abstract class ReaderAbstract implements ReaderInterface
/**
* Returns an iterator to iterate over sheets.
*
* @return IteratorInterface To iterate over sheets
* @template T
* @return IteratorInterface<T>|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 @@ abstract class ReaderAbstract implements ReaderInterface
}
// 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 @@ abstract class ReaderAbstract implements ReaderInterface
* 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<T> To iterate over sheets
*/
public function getSheetIterator()
{

View File

@ -21,7 +21,7 @@ interface ReaderInterface
* 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<SheetInterface> To iterate over sheets
*/
public function getSheetIterator();

View File

@ -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<Row> Iterator to iterate over the sheet's rows.
*/
public function getRowIterator();

View File

@ -152,7 +152,7 @@ class InternalEntityFactory implements InternalEntityFactoryInterface
}
/**
* @param $xmlReader
* @param XMLReader $xmlReader
* @return XMLProcessor
*/
public function createXMLProcessor($xmlReader)

View File

@ -10,7 +10,10 @@ use Box\Spout\Common\Exception\InvalidArgumentException;
*/
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<string, int>
*/
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,

View File

@ -66,7 +66,7 @@ class CellValueFormatter
/**
* 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 @@ class CellValueFormatter
/**
* 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 @@ class CellValueFormatter
/**
* 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 @@ class CellValueFormatter
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 @@ class CellValueFormatter
$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');

View File

@ -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<string, array> Mapping between Excel format characters and PHP format characters
*/
private static $excelDateFormatToPHPDateFormatMapping = [
self::KEY_GENERAL => [
@ -104,6 +104,7 @@ class DateFormatHelper
// 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);

View File

@ -98,7 +98,7 @@ class CachingStrategyFactory
/**
* Returns the PHP "memory_limit" in Kilobytes
*
* @return float
* @return int
*/
protected function getMemoryLimitInKB()
{
@ -133,6 +133,9 @@ class CachingStrategyFactory
*/
protected function getMemoryLimitFromIni()
{
return \ini_get('memory_limit');
/** @var string $memoryLimit */
$memoryLimit = \ini_get('memory_limit');
return $memoryLimit;
}
}

View File

@ -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<string> Contents of the temporary file that was last read
* @see CachingStrategyFactory::MAX_NUM_STRINGS_PER_TEMP_FILE
*/
protected $inMemoryTempFileContents;
@ -78,7 +78,9 @@ class FileBasedStrategy implements CachingStrategyInterface
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

View File

@ -12,7 +12,7 @@ use Box\Spout\Reader\Exception\SharedStringNotFoundException;
*/
class InMemoryStrategy implements CachingStrategyInterface
{
/** @var \SplFixedArray Array used to cache the shared strings */
/** @var \SplFixedArray<string> Array used to cache the shared strings */
protected $inMemoryCache;
/** @var bool Whether the cache has been closed */

View File

@ -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 @@ class SharedStringsManager
$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);

View File

@ -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<Sheet> List of sheets */
protected $sheets;
/** @var int Index of the sheet currently read */

View File

@ -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<int, string> 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<int,string> Array containing a mapping NUM_FMT_ID => FORMAT_CODE */
protected $customNumberFormats;
/** @var array Array containing a mapping STYLE_ID => [STYLE_ATTRIBUTES] */
/** @var array<mixed> 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<int, bool> Cache containing a mapping NUM_FMT_ID => IS_DATE_FORMAT. Used to avoid lots of recalculations */
protected $numFmtIdToIsDateFormatCache = [];
/**
@ -189,7 +189,7 @@ class StyleManager
}
/**
* @return array The custom number formats
* @return array<int,string> The custom number formats
*/
protected function getCustomNumberFormats()
{
@ -201,7 +201,7 @@ class StyleManager
}
/**
* @return array The styles attributes
* @return array<mixed> The styles attributes
*/
protected function getStylesAttributes()
{
@ -213,7 +213,7 @@ class StyleManager
}
/**
* @param array $styleAttributes Array containing the style attributes (2 keys: "applyNumberFormat" and "numFmtId")
* @param array<string, mixed> $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)

View File

@ -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<string, string> Cache of the already read workbook relationships: [TYPE] => [FILE_NAME] */
private $cachedWorkbookRelationships;
/**
@ -112,7 +112,7 @@ class WorkbookRelationshipsManager
* 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<string, string>
*/
private function getWorkbookRelationships()
{

View File

@ -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 */

View File

@ -17,6 +17,7 @@ use Box\Spout\Reader\XLSX\Helper\CellValueFormatter;
/**
* Class RowIterator
* @implements IteratorInterface<Row>
*/
class RowIterator implements IteratorInterface
{
@ -276,6 +277,7 @@ class RowIterator implements IteratorInterface
$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 @@ class RowIterator implements IteratorInterface
/**
* 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)

View File

@ -9,6 +9,7 @@ use Box\Spout\Reader\XLSX\Manager\SheetManager;
/**
* Class SheetIterator
* Iterate over XLSX sheet.
* @implements IteratorInterface<Sheet>
*/
class SheetIterator implements IteratorInterface
{

View File

@ -5,7 +5,6 @@ namespace Box\Spout\Writer\Common\Creator;
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 @@ class WriterEntityFactory
*/
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 @@ class WriterEntityFactory
*/
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 @@ class WriterEntityFactory
*/
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 @@ class WriterEntityFactory
}
/**
* @param array $cellValues
* @param array<mixed> $cellValues
* @param Style|null $rowStyle
* @return Row
*/

View File

@ -33,7 +33,7 @@ class Workbook
/**
* @param Worksheet[] $worksheets
*/
public function setWorksheets($worksheets)
public function setWorksheets($worksheets) : void
{
$this->worksheets = $worksheets;
}

View File

@ -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 @@ class Worksheet
/**
* @param resource $filePointer
*/
public function setFilePointer($filePointer)
public function setFilePointer($filePointer) : void
{
$this->filePointer = $filePointer;
}
@ -81,7 +81,7 @@ class Worksheet
/**
* @param int $maxNumColumns
*/
public function setMaxNumColumns($maxNumColumns)
public function setMaxNumColumns($maxNumColumns) : void
{
$this->maxNumColumns = $maxNumColumns;
}
@ -97,7 +97,7 @@ class Worksheet
/**
* @param int $lastWrittenRowIndex
*/
public function setLastWrittenRowIndex($lastWrittenRowIndex)
public function setLastWrittenRowIndex($lastWrittenRowIndex) : void
{
$this->lastWrittenRowIndex = $lastWrittenRowIndex;
}

View File

@ -8,7 +8,7 @@ namespace Box\Spout\Writer\Common\Helper;
*/
class CellHelper
{
/** @var array Cache containing the mapping column index => column letters */
/** @var array<int, string> Cache containing the mapping column index => column letters */
private static $columnIndexToColumnLettersCache = [];
/**

View File

@ -181,9 +181,13 @@ class ZipHelper
*/
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 @@ class ZipHelper
*/
protected function copyZipToStream($zipFilePath, $pointer)
{
/** @var resource $zipFilePointer */
$zipFilePointer = \fopen($zipFilePath, 'r');
\stream_copy_to_stream($zipFilePointer, $pointer);
\fclose($zipFilePointer);

View File

@ -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<string> 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<string, 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 @@ class SheetManager
}
/**
* @param int $workbookId Workbook ID associated to a Sheet
* @param string $workbookId Workbook ID associated to a Sheet
* @return void
*/
public function markWorkbookIdAsUsed($workbookId)

View File

@ -11,7 +11,14 @@ use Box\Spout\Common\Entity\Style\Style;
*/
class PossiblyUpdatedStyle
{
/**
* @var Style
*/
private $style;
/**
* @var bool
*/
private $isUpdated;
public function __construct(Style $style, bool $isUpdated)

View File

@ -10,10 +10,10 @@ use Box\Spout\Common\Entity\Style\Style;
*/
class StyleRegistry
{
/** @var array [SERIALIZED_STYLE] => [STYLE_ID] mapping table, keeping track of the registered styles */
/** @var array<string, int> [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<int, Style> [STYLE_ID] => [STYLE] mapping table, keeping track of the registered styles */
protected $styleIdToStyleMappingTable = [];
/**

View File

@ -265,6 +265,7 @@ abstract class WorkbookManagerAbstract implements WorkbookManagerInterface
/**
* @param Row $row
* @return void
*/
private function applyDefaultRowStyle(Row $row)
{

View File

@ -7,6 +7,9 @@ use Box\Spout\Writer\Exception\WriterException;
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.';

View File

@ -7,6 +7,9 @@ use Box\Spout\Writer\Exception\WriterException;
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.';

View File

@ -7,6 +7,9 @@ use Box\Spout\Writer\Exception\WriterException;
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.';

View File

@ -30,7 +30,7 @@ class HelperFactory extends \Box\Spout\Common\Creator\HelperFactory
}
/**
* @param $entityFactory
* @param InternalEntityFactory $entityFactory
* @return ZipHelper
*/
private function createZipHelper($entityFactory)

View File

@ -24,7 +24,7 @@ class BorderHelper
/**
* Width mappings
*
* @var array
* @var array<string, string>
*/
protected static $widthMap = [
Border::WIDTH_THIN => '0.75pt',
@ -35,7 +35,7 @@ class BorderHelper
/**
* Style mapping
*
* @var array
* @var array<string, string>
*/
protected static $styleMap = [
Border::STYLE_SOLID => 'solid',

View File

@ -210,6 +210,7 @@ EOD;
// 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 @@ EOD;
*/
protected function copyFileContentsToTarget($sourceFilePath, $targetResource)
{
/** @var resource $sourceHandle */
$sourceHandle = \fopen($sourceFilePath, 'r');
\stream_copy_to_stream($sourceHandle, $targetResource);
\fclose($sourceHandle);

View File

@ -10,7 +10,7 @@ use Box\Spout\Common\Entity\Style\Style;
*/
class StyleRegistry extends \Box\Spout\Writer\Common\Manager\Style\StyleRegistry
{
/** @var array [FONT_NAME] => [] Map whose keys contain all the fonts used */
/** @var array<string, bool> [FONT_NAME] => [] Map whose keys contain all the fonts used */
protected $usedFontsSet = [];
/**

View File

@ -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;

View File

@ -62,6 +62,7 @@ class WorksheetManager implements WorksheetManagerInterface
*/
public function startSheet(Worksheet $worksheet)
{
/** @var resource $sheetFilePointer */
$sheetFilePointer = \fopen($worksheet->getFilePath(), 'w');
$this->throwIfSheetFilePointerIsNotAvailable($sheetFilePointer);
@ -86,7 +87,7 @@ class WorksheetManager implements WorksheetManagerInterface
* Returns the table XML root node as string.
*
* @param Worksheet $worksheet
* @return string <table> node as string
* @return string "<table> node as string"
*/
public function getTableElementStartAsString(Worksheet $worksheet)
{

View File

@ -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 @@ abstract class WriterAbstract implements WriterInterface
{
$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 @@ abstract class WriterAbstract implements WriterInterface
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)

View File

@ -25,7 +25,7 @@ abstract class WriterMultiSheetsAbstract extends WriterAbstract
/** @var ManagerFactoryInterface */
private $managerFactory;
/** @var WorkbookManagerInterface */
/** @var WorkbookManagerInterface|null */
private $workbookManager;
/**
@ -143,7 +143,7 @@ abstract class WriterMultiSheetsAbstract extends WriterAbstract
*/
protected function throwIfWorkbookIsNotAvailable()
{
if (!$this->workbookManager->getWorkbook()) {
if ($this->workbookManager === null) {
throw new WriterNotOpenedException('The writer must be opened before performing this action.');
}
}

View File

@ -7,6 +7,9 @@ use Box\Spout\Common\Entity\Style\BorderPart;
class BorderHelper
{
/**
* @var array<string, array>
*/
public static $xlsxStyleMap = [
Border::STYLE_SOLID => [
Border::WIDTH_THIN => 'thin',

View File

@ -24,7 +24,7 @@ EOD;
*/
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 @@ EOD;
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 @@ EOD;
*/
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 @@ EOD;
*/
public function writeString($string)
{
\fwrite($this->sharedStringsFilePointer, '<si><t xml:space="preserve">' . $this->stringsEscaper->escape($string) . '</t></si>');
/** @var resource $sharedStringsFilePointer */
$sharedStringsFilePointer = $this->sharedStringsFilePointer;
\fwrite($sharedStringsFilePointer, '<si><t xml:space="preserve">' . $this->stringsEscaper->escape($string) . '</t></si>');
$this->numSharedStrings++;
// Shared string ID is zero-based

View File

@ -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 @@ EOD;
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);
}

View File

@ -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<int|string, int> 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<string, int>
*/
protected $registeredFormats = [];
/**
* @var array [STYLE_ID] => [FORMAT_ID] maps a style to a format declaration
* @var array <int, int> [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<string, int>
*/
protected $registeredFills = [];
/**
* @var array [STYLE_ID] => [FILL_ID] maps a style to a fill declaration
* @var array<int, int> [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<string, int>
*/
protected $registeredBorders = [];
/**
* @var array [STYLE_ID] => [BORDER_ID] maps a style to a border declaration
* @var array<int, int> [STYLE_ID] => [BORDER_ID] maps a style to a border declaration
*/
protected $styleIdToBorderMappingTable = [];
@ -136,8 +136,9 @@ class StyleRegistry extends \Box\Spout\Writer\Common\Manager\Style\StyleRegistry
*
* @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 @@ class StyleRegistry extends \Box\Spout\Writer\Common\Manager\Style\StyleRegistry
*
* @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 @@ class StyleRegistry extends \Box\Spout\Writer\Common\Manager\Style\StyleRegistry
*
* @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 @@ class StyleRegistry extends \Box\Spout\Writer\Common\Manager\Style\StyleRegistry
}
/**
* @return array
* @return array<string, int>
*/
public function getRegisteredFills()
{
@ -263,7 +266,7 @@ class StyleRegistry extends \Box\Spout\Writer\Common\Manager\Style\StyleRegistry
}
/**
* @return array
* @return array<string, int>
*/
public function getRegisteredBorders()
{
@ -271,7 +274,7 @@ class StyleRegistry extends \Box\Spout\Writer\Common\Manager\Style\StyleRegistry
}
/**
* @return array
* @return array<string, int>
*/
public function getRegisteredFormats()
{

View File

@ -14,6 +14,7 @@ use Box\Spout\Writer\XLSX\Manager\Style\StyleManager;
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
*/

View File

@ -108,6 +108,7 @@ EOD;
*/
public function startSheet(Worksheet $worksheet)
{
/** @var resource $sheetFilePointer */
$sheetFilePointer = \fopen($worksheet->getFilePath(), 'w');
$this->throwIfSheetFilePointerIsNotAvailable($sheetFilePointer);

View File

@ -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;
}
/**

View File

@ -113,7 +113,7 @@ class BorderTest extends TestCase
$border->addPart($borderPart);
$this->assertCount(1, $border->getParts());
/** @var $part BorderPart */
/** @var BorderPart $part */
$part = $border->getParts()[$allowedName];
$this->assertEquals($allowedStyle, $part->getStyle());

View File

@ -11,7 +11,7 @@ use PHPUnit\Framework\TestCase;
class ColorTest extends TestCase
{
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestRGB()
{
@ -54,7 +54,7 @@ class ColorTest extends TestCase
}
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestRGBAInvalidColorComponents()
{

View File

@ -10,7 +10,7 @@ use PHPUnit\Framework\TestCase;
class CellTypeHelperTest extends TestCase
{
/**
* @return array
* @return void
*/
public function testIsEmpty()
{
@ -27,7 +27,7 @@ class CellTypeHelperTest extends TestCase
}
/**
* @return array
* @return void
*/
public function testIsNonEmptyString()
{
@ -44,7 +44,7 @@ class CellTypeHelperTest extends TestCase
}
/**
* @return array
* @return void
*/
public function testIsNumeric()
{
@ -66,7 +66,7 @@ class CellTypeHelperTest extends TestCase
}
/**
* @return array
* @return void
*/
public function testIsBoolean()
{

View File

@ -4,6 +4,7 @@ namespace Box\Spout\Common\Helper;
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<array>
*/
public function dataProviderForTestGetBytesOffsetToSkipBOM()
{
@ -38,6 +39,7 @@ class EncodingHelperTest extends TestCase
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 @@ class EncodingHelperTest extends TestCase
}
/**
* @return array
* @return array<array>
*/
public function dataProviderForIconvOrMbstringUsage()
{
@ -73,7 +75,7 @@ class EncodingHelperTest extends TestCase
$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 @@ class EncodingHelperTest extends TestCase
{
$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 @@ class EncodingHelperTest extends TestCase
*/
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 @@ class EncodingHelperTest extends TestCase
$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 @@ class EncodingHelperTest extends TestCase
*/
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 @@ class EncodingHelperTest extends TestCase
$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 @@ class EncodingHelperTest extends TestCase
{
$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 @@ class EncodingHelperTest extends TestCase
*/
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 @@ class EncodingHelperTest extends TestCase
*/
public function testAttemptConversionFromUTF8ShouldBeNoopWhenTargetIsUTF8()
{
/** @var EncodingHelper $encodingHelperStub */
/** @var EncodingHelper&MockObject $encodingHelperStub */
$encodingHelperStub = $this->getMockBuilder('\Box\Spout\Common\Helper\EncodingHelper')
->disableOriginalConstructor()
->setMethods(['canUseIconv'])

View File

@ -11,7 +11,7 @@ use PHPUnit\Framework\TestCase;
class ODSTest extends TestCase
{
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestEscape()
{

View File

@ -11,7 +11,7 @@ use PHPUnit\Framework\TestCase;
class XLSXTest extends TestCase
{
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestEscape()
{
@ -46,7 +46,7 @@ class XLSXTest extends TestCase
}
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestUnescape()
{

View File

@ -10,7 +10,7 @@ use PHPUnit\Framework\TestCase;
*/
class FileSystemHelperTest extends TestCase
{
/** @var \Box\Spout\Writer\XLSX\Helper\FileSystemHelper */
/** @var FileSystemHelper */
protected $fileSystemHelper;
/**

View File

@ -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',

View File

@ -6,11 +6,13 @@ use Box\Spout\Common\Creator\HelperFactory;
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 @@ class ReaderTest extends TestCase
{
$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 @@ class ReaderTest extends TestCase
{
$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 @@ class ReaderTest extends TestCase
}
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestReadShouldReadEmptyFile()
{
@ -241,7 +243,7 @@ class ReaderTest extends TestCase
}
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestReadShouldSkipBom()
{
@ -274,7 +276,7 @@ class ReaderTest extends TestCase
}
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestReadShouldSupportNonUTF8FilesWithoutBOMs()
{
@ -302,7 +304,7 @@ class ReaderTest extends TestCase
$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 @@ class ReaderTest extends TestCase
}
/**
* @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 @@ class ReaderTest extends TestCase
* @param string $fieldEnclosure
* @param string $encoding
* @param bool $shouldPreserveEmptyRows
* @return array All the read rows the given file
* @return array<array> All the read rows the given file
*/
private function getAllRowsForFile(
$fileName,

View File

@ -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 @@ class SheetTest extends TestCase
/**
* @param string $fileName
* @return Sheet
* @return SheetInterface
*/
private function openFileAndReturnSheet($fileName)
{

View File

@ -23,13 +23,16 @@ class SpoutTestStream
/**
* @param string $path
* @param int $flag
* @return array
* @return array<mixed>
*/
public function url_stat($path, $flag)
{
$filePath = $this->getFilePathFromStreamPath($path);
return stat($filePath);
/** @var array<mixed> $stat */
$stat = stat($filePath);
return $stat;
}
/**
@ -56,7 +59,11 @@ class SpoutTestStream
// 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 @@ class SpoutTestStream
{
$this->position += $numBytes;
return fread($this->fileHandle, $numBytes);
/** @var string $read */
$read = fread($this->fileHandle, $numBytes);
return $read;
}
/**

View File

@ -15,7 +15,7 @@ use PHPUnit\Framework\TestCase;
class RowManagerTest extends TestCase
{
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestFillMissingIndexesWithEmptyCells()
{
@ -34,7 +34,7 @@ class RowManagerTest extends TestCase
* @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 @@ class RowManagerTest extends TestCase
}
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestIsEmptyRow()
{
@ -64,7 +64,7 @@ class RowManagerTest extends TestCase
/**
* @dataProvider dataProviderForTestIsEmptyRow
*
* @param array $cells
* @param array<Cell> $cells
* @param bool $expectedIsEmpty
* @return void
*/
@ -81,10 +81,13 @@ class RowManagerTest extends TestCase
*/
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);
}

View File

@ -16,7 +16,7 @@ class ReaderTest extends TestCase
use TestUsingResource;
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestReadShouldThrowException()
{
@ -41,7 +41,7 @@ class ReaderTest extends TestCase
}
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestReadForAllWorksheets()
{
@ -109,7 +109,7 @@ class ReaderTest extends TestCase
}
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestReadWithFilesGeneratedByExternalSoftwares()
{
@ -538,7 +538,7 @@ class ReaderTest extends TestCase
* @param string $fileName
* @param bool $shouldFormatDates
* @param bool $shouldPreserveEmptyRows
* @return array All the read rows the given file
* @return array<array> All the read rows the given file
*/
private function getAllRowsForFile($fileName, $shouldFormatDates = false, $shouldPreserveEmptyRows = false)
{

View File

@ -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 @@ class SheetTest extends TestCase
/**
* @param string $fileName
* @return Sheet[]
* @return SheetInterface[]
*/
private function openFileAndReturnSheets($fileName)
{

View File

@ -102,7 +102,7 @@ class XMLReaderTest extends TestCase
}
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestFileExistsWithinZip()
{
@ -134,10 +134,11 @@ class XMLReaderTest extends TestCase
}
/**
* @return array
* @return array<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 @@ class XMLReaderTest extends TestCase
}
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestIsPositionedOnStartingAndEndingNode()
{

View File

@ -11,7 +11,7 @@ use PHPUnit\Framework\TestCase;
class CellHelperTest extends TestCase
{
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestGetColumnIndexFromCellIndex()
{

View File

@ -4,7 +4,9 @@ namespace Box\Spout\Reader\XLSX\Helper;
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 @@ use PHPUnit\Framework\TestCase;
class CellValueFormatterTest extends TestCase
{
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestExcelDate()
{
@ -72,6 +74,7 @@ class CellValueFormatterTest extends TestCase
->with(0)
->will($this->returnValue((object) ['nodeValue' => $nodeValue]));
/** @var \DOMElement&MockObject $nodeMock */
$nodeMock = $this->createMock(\DOMElement::class);
$nodeMock
@ -88,7 +91,7 @@ class CellValueFormatterTest extends TestCase
->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 @@ class CellValueFormatterTest extends TestCase
->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 @@ class CellValueFormatterTest extends TestCase
$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 @@ class CellValueFormatterTest extends TestCase
}
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestFormatNumericCellValueWithNumbers()
{
@ -149,14 +157,17 @@ class CellValueFormatterTest extends TestCase
*/
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 @@ class CellValueFormatterTest extends TestCase
}
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestFormatStringCellValue()
{
@ -203,7 +214,13 @@ class CellValueFormatterTest extends TestCase
->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);

View File

@ -10,7 +10,7 @@ use PHPUnit\Framework\TestCase;
class DateFormatHelperTest extends TestCase
{
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestToPHPDateFormat()
{

View File

@ -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 @@ use PHPUnit\Framework\TestCase;
class CachingStrategyFactoryTest extends TestCase
{
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestCreateBestCachingStrategy()
{
@ -36,7 +37,7 @@ class CachingStrategyFactoryTest extends TestCase
*/
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 @@ class CachingStrategyFactoryTest extends TestCase
$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 @@ class CachingStrategyFactoryTest extends TestCase
}
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestGetMemoryLimitInKB()
{
@ -84,7 +85,7 @@ class CachingStrategyFactoryTest extends TestCase
*/
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()

View File

@ -19,7 +19,7 @@ class SharedStringsManagerTest extends TestCase
{
use TestUsingResource;
/** @var SharedStringsManager */
/** @var SharedStringsManager|null */
private $sharedStringsManager;
/**
@ -144,6 +144,7 @@ class SharedStringsManagerTest extends TestCase
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');

View File

@ -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 @@ use PHPUnit\Framework\TestCase;
class StyleManagerTest extends TestCase
{
/**
* @param array $styleAttributes
* @param array $customNumberFormats
* @param array<mixed> $styleAttributes
* @param array<mixed> $customNumberFormats
* @return StyleManager
*/
private function getStyleManagerMock($styleAttributes = [], $customNumberFormats = [])
@ -21,7 +22,7 @@ class StyleManagerTest extends TestCase
$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 @@ class StyleManagerTest extends TestCase
}
/**
* @return array
* @return array<array>
*/
public function dataProviderForCustomDateFormats()
{

View File

@ -15,7 +15,7 @@ class ReaderPerfTest extends TestCase
use TestUsingResource;
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestPerfWhenReading300kRowsXLSX()
{

View File

@ -15,7 +15,7 @@ class ReaderTest extends TestCase
use TestUsingResource;
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestReadShouldThrowException()
{
@ -42,7 +42,7 @@ class ReaderTest extends TestCase
}
/**
* @return array
* @return array<array>
*/
public function dataProviderForTestReadForAllWorksheets()
{
@ -748,7 +748,7 @@ class ReaderTest extends TestCase
* @param string $fileName
* @param bool $shouldFormatDates
* @param bool $shouldPreserveEmptyRows
* @return array All the read rows the given file
* @return array<array> All the read rows the given file
*/
private function getAllRowsForFile($fileName, $shouldFormatDates = false, $shouldPreserveEmptyRows = false)
{

View File

@ -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 @@ class SheetTest extends TestCase
/**
* @param string $fileName
* @return Sheet[]
* @return SheetInterface[]
*/
private function openFileAndReturnSheets($fileName)
{

View File

@ -5,6 +5,9 @@
*/
class ReflectionHelper
{
/**
* @var array<class-string, array>
*/
private static $privateVarsToReset = [];
/**
@ -27,7 +30,7 @@ class ReflectionHelper
* 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 @@ class ReflectionHelper
* 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 @@ class ReflectionHelper
// 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 @@ class ReflectionHelper
*
* @param object $object
* @param string $methodName
* @param *mixed|null $params
*
* @return mixed|null
*/

View File

@ -92,7 +92,13 @@ trait TestUsingResource
*/
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;
}
/**

Some files were not shown because too many files have changed in this diff Show More