diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..abb4f50 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,31 @@ +name: CI-coverage + +on: [ push ] + +jobs: + build-test: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + + - name: Cache Composer dependencies + uses: actions/cache@v2 + with: + path: /tmp/composer-cache + key: ${{ runner.os }}-${{ hashFiles('**/composer.lock') }} + + - uses: php-actions/composer@v6 + with: + php_version: "8.0" + php_extensions: fileinfo gd xml zip + version: 2 + + - name: PHPUnit Tests + uses: php-actions/phpunit@v3 + with: + version: 9 + php_version: 8.0 + configuration: phpunit.xml.dist + php_extensions: fileinfo gd xml zip + args: -c phpunit.coverage.xml.dist --coverage-clover var/coverage/coverage.xml diff --git a/.gitignore b/.gitignore index 496b505..3ea3fe2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,8 @@ /var/ /vendor/ /.php_cs -/.php_cs.cache +/.php-cs-fixer.cache /composer.lock /phpunit.coverage.xml /phpunit.xml +/.phpunit.result.cache diff --git a/.php_cs.dist b/.php-cs-fixer.dist.php similarity index 69% rename from .php_cs.dist rename to .php-cs-fixer.dist.php index 428d96e..031f8f2 100644 --- a/.php_cs.dist +++ b/.php-cs-fixer.dist.php @@ -1,6 +1,6 @@ setRiskyAllowed(true) ->setRules([ '@Symfony' => true, @@ -8,10 +8,10 @@ 'array_syntax' => ['syntax' => 'short'], 'combine_consecutive_unsets' => true, // one should use PHPUnit methods to set up expected exception instead of annotations - 'general_phpdoc_annotation_remove' => ['expectedException', 'expectedExceptionMessage', 'expectedExceptionMessageRegExp'], + 'general_phpdoc_annotation_remove' => ['annotations' => ['expectedException', 'expectedExceptionMessage', 'expectedExceptionMessageRegExp']], 'heredoc_to_nowdoc' => true, - 'no_extra_consecutive_blank_lines' => ['break', 'continue', 'extra', 'return', 'throw', 'use', 'parenthesis_brace_block', 'square_brace_block', 'curly_brace_block'], - 'no_short_echo_tag' => true, + 'no_extra_blank_lines' => ['tokens' => ['break', 'continue', 'extra', 'return', 'throw', 'use', 'parenthesis_brace_block', 'square_brace_block', 'curly_brace_block']], + 'echo_tag_syntax' => ['format' => 'long'], 'no_unreachable_default_argument_value' => true, 'no_useless_else' => true, 'no_useless_return' => true, diff --git a/.php-version b/.php-version new file mode 100644 index 0000000..cc40bca --- /dev/null +++ b/.php-version @@ -0,0 +1 @@ +8.0 diff --git a/.scrutinizer.yml b/.scrutinizer.yml index e45890c..aaf5ed6 100644 --- a/.scrutinizer.yml +++ b/.scrutinizer.yml @@ -1,18 +1,17 @@ build: - environment: - php: - version: '7.0' - tests: - override: - - - command: vendor/bin/simple-phpunit -c phpunit.coverage.xml.dist - coverage: - file: var/coverage/coverage.xml - format: clover + environment: + php: + version: '8.0' + tests: + override: + - command: vendor/bin/phpunit -c phpunit.coverage.xml.dist + coverage: + file: var/coverage/coverage.xml + format: clover checks: - php: true + php: true filter: - excluded_paths: - - tests/* + excluded_paths: + - tests/* diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 6c02786..0000000 --- a/.travis.yml +++ /dev/null @@ -1,35 +0,0 @@ -language: php - -dist: trusty -sudo: false - -matrix: - fast_finish: true - include: - - php: '7.0' - env: SYMFONY_VERSION='3.2.*' - - php: '7.0' - env: SYMFONY_VERSION='3.3.*' - - php: '7.0' - env: SYMFONY_VERSION='3.4.*' - - php: '7.1' - env: SYMFONY_VERSION='3.4.*' - - php: '7.2' - env: SYMFONY_VERSION='3.4.*' - - php: '7.1.3' - env: SYMFONY_VERSION='4.0.*' - - php: '7.2' - env: SYMFONY_VERSION='4.0.*' - - php: '7.1.3' - env: SYMFONY_VERSION='4.1.*' - - php: '7.2' - env: SYMFONY_VERSION='4.1.*' - -before_install: - - if [ "$SYMFONY_VERSION" != "" ]; then composer require --dev --no-update symfony/symfony=$SYMFONY_VERSION; fi - -install: - - composer update $COMPOSER_FLAGS --prefer-dist --prefer-stable - -script: - - vendor/bin/simple-phpunit diff --git a/README.md b/README.md index 9cbec36..2b362fe 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# TwigSpreadsheetBundle +# TwigSpreadsheetBundle (PHP 8.0, Symfony 6.0 & Twig 3.0) [![Teavis CI: Build Status](https://travis-ci.org/MewesK/TwigSpreadsheetBundle.png?branch=master)](https://travis-ci.org/MewesK/TwigSpreadsheetBundle) [![Scrutinizer: Code Quality](https://scrutinizer-ci.com/g/MewesK/TwigSpreadsheetBundle/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/MewesK/TwigSpreadsheetBundle/?branch=master) @@ -7,6 +7,13 @@ This Symfony bundle integrates PhpSpreadsheet into Symfony using Twig. +This repository is a continuation of the original TwigSpreadsheetBundle. + +A list of differences from the original TwigSpreadsheetBundle: +- added support for Symfony 6 and Twig 3 +- removed RequestListener.php +- removed functional tests for controller functionality + ## Features * Easy to use Twig integration including ``macro`` and ``include`` support @@ -29,8 +36,9 @@ The following software is required to use PhpSpreadsheet/TwigSpreadsheetBundle. **Required by this bundle:** - * PHP 7.0 or newer - * Symfony 3.2 or newer + * PHP 8.0 or newer + * Symfony 6.0 or newer + * Twig 3.0 or newer **Required by PhpSpreadsheet:** diff --git a/composer.json b/composer.json index a6fe728..31e9eac 100644 --- a/composer.json +++ b/composer.json @@ -1,9 +1,9 @@ { - "name": "technetium/twig-spreadsheet-bundle", + "name": "subugoe/twig-spreadsheet-bundle", "type": "symfony-bundle", - "description": "This Symfony bundle integrates PhpSpreadsheet into Symfony using Twig. Forked by technetium to get bugfixes in", - "keywords": ["excel","phpexcel","spreadsheet","phpspreadsheet","twig","symfony"], - "homepage": "https://github.com/technetium/TwigSpreadsheetBundle", + "description": "This Symfony bundle integrates PhpSpreadsheet into Symfony using Twig.", + "keywords": ["excel","phpexcel","spreadsheet","phpspreadsheet","twig","twig3","symfony","symfony6"], + "homepage": "https://github.com/subugoe/TwigSpreadsheetBundle", "license": "MIT", "authors": [ { @@ -12,21 +12,26 @@ }, { "name": "Community Contributors", - "homepage": "https://github.com/technetium/TwigSpreadsheetBundle/graphs/contributors" + "homepage": "https://github.com/MewesK/TwigSpreadsheetBundle/graphs/contributors" } ], "require": { - "php": ">=7.0", - "symfony/framework-bundle": "~3.2|~4.0", - "twig/twig": "~2.0", - "phpoffice/phpspreadsheet": "~1.8.0" + "php": "^8.0", + "ext-fileinfo": "*", + "ext-gd": "*", + "ext-xml": "*", + "ext-zip": "*", + "symfony/framework-bundle": "^6.0", + "twig/twig": "^3.0", + "phpoffice/phpspreadsheet": "^1.3" }, "require-dev": { - "symfony/symfony": "~3.2|~4.0", - "sensio/framework-extra-bundle": "~3.2|~4.0", - "symfony/phpunit-bridge": "~4.0", - "phpunit/phpunit": "^6.5", - "mpdf/mpdf": "~7.0" + "sensio/framework-extra-bundle": "^6.0", + "phpunit/phpunit": "^9.5", + "mpdf/mpdf": "~8.0", + "friendsofphp/php-cs-fixer": "^3", + "rector/rector": "^0.14.0", + "symfony/twig-bridge": "^6.0" }, "suggest": { "mpdf/mpdf": "Add support for PDF rendering, requires ~7.0" diff --git a/phpunit.coverage.xml.dist b/phpunit.coverage.xml.dist index 2235e9b..8ce8f04 100644 --- a/phpunit.coverage.xml.dist +++ b/phpunit.coverage.xml.dist @@ -1,27 +1,22 @@ - - - - ./tests - - - - - - ./src - - ./src/Resources - - - - - - - - + + + + ./src + + + ./src/Resources + ./src/DependencyInjection + + + + + + + + + ./tests + + + diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 4b18c27..d455f74 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,26 +1,19 @@ - - - - - - - - ./tests - - - - - - ./src - - ./src/Resources - - - + + + + ./src + + + ./src/Resources + + + + + + + + ./tests + + diff --git a/rector.php b/rector.php new file mode 100644 index 0000000..1acb73b --- /dev/null +++ b/rector.php @@ -0,0 +1,24 @@ +paths([ + __DIR__.'/src', + __DIR__.'/tests', + ]); + + // register a single rule + $rectorConfig->rule(InlineConstructorDefaultToPropertyRector::class); + $rectorConfig->importShortClasses(false); + $rectorConfig->sets([ + LevelSetList::UP_TO_PHP_80, + SetList::CODING_STYLE, + SetList::CODE_QUALITY, + ]); +}; diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php index e2343eb..95d2b86 100644 --- a/src/DependencyInjection/Configuration.php +++ b/src/DependencyInjection/Configuration.php @@ -5,9 +5,6 @@ use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; -/** - * Class Configuration. - */ class Configuration implements ConfigurationInterface { /** @@ -17,14 +14,14 @@ class Configuration implements ConfigurationInterface */ public function getConfigTreeBuilder() { - $treeBuilder = new TreeBuilder(); - $rootNode = $treeBuilder->root('mewes_k_twig_spreadsheet'); + $treeBuilder = new TreeBuilder('mewes_k_twig_spreadsheet'); + $rootNode = $treeBuilder->getRootNode(); $rootNode ->children() ->booleanNode('pre_calculate_formulas') ->defaultTrue() - ->info('Disabling formula calculations can improve the performance but the resulting documents won\'t immediately show formula results in external programs.') + ->info("Disabling formula calculations can improve the performance but the resulting documents won't immediately show formula results in external programs.") ->end() ->arrayNode('cache') ->addDefaultsIfNotSet() @@ -41,6 +38,33 @@ public function getConfigTreeBuilder() ->end() ->end() ->end() + ->arrayNode('csv_writer') + ->addDefaultsIfNotSet() + ->info('See PhpOffice\PhpSpreadsheet\Writer\Csv.php for more information.') + ->children() + ->scalarNode('delimiter') + ->defaultValue(',') + ->end() + ->scalarNode('enclosure') + ->defaultValue('"') + ->end() + ->booleanNode('excel_compatibility') + ->defaultFalse() + ->end() + ->booleanNode('include_separator_line') + ->defaultFalse() + ->end() + ->scalarNode('line_ending') + ->defaultValue(\PHP_EOL) + ->end() + ->integerNode('sheet_index') + ->defaultValue(0) + ->end() + ->booleanNode('use_bom') + ->defaultFalse() + ->end() + ->end() + ->end() ->end(); return $treeBuilder; diff --git a/src/DependencyInjection/MewesKTwigSpreadsheetExtension.php b/src/DependencyInjection/MewesKTwigSpreadsheetExtension.php index 0a1ec06..bc25be1 100644 --- a/src/DependencyInjection/MewesKTwigSpreadsheetExtension.php +++ b/src/DependencyInjection/MewesKTwigSpreadsheetExtension.php @@ -7,9 +7,6 @@ use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\HttpKernel\DependencyInjection\ConfigurableExtension; -/** - * Class MewesKTwigSpreadsheetExtension. - */ class MewesKTwigSpreadsheetExtension extends ConfigurableExtension { /** diff --git a/src/EventListener/AddRequestFormatsListener.php b/src/EventListener/AddRequestFormatsListener.php index d56fc83..bbb62a4 100644 --- a/src/EventListener/AddRequestFormatsListener.php +++ b/src/EventListener/AddRequestFormatsListener.php @@ -3,7 +3,7 @@ namespace MewesK\TwigSpreadsheetBundle\EventListener; use Symfony\Component\EventDispatcher\EventSubscriberInterface; -use Symfony\Component\HttpKernel\Event\GetResponseEvent; +use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\KernelEvents; /** @@ -11,10 +11,7 @@ */ class AddRequestFormatsListener implements EventSubscriberInterface { - /** - * @param GetResponseEvent $event - */ - public function onKernelRequest(GetResponseEvent $event) + public function onKernelRequest(RequestEvent $event): void { $event->getRequest()->setFormat('csv', 'text/csv'); $event->getRequest()->setFormat('ods', 'application/vnd.oasis.opendocument.spreadsheet'); @@ -26,7 +23,7 @@ public function onKernelRequest(GetResponseEvent $event) /** * {@inheritdoc} */ - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return [ KernelEvents::REQUEST => ['onKernelRequest', 1], diff --git a/src/Helper/Arrays.php b/src/Helper/Arrays.php new file mode 100644 index 0000000..2160bf2 --- /dev/null +++ b/src/Helper/Arrays.php @@ -0,0 +1,21 @@ + &$value) { + $array1[$key] = \is_array($value) && isset($array1[$key]) && \is_array($array1[$key]) ? + self::mergeRecursive($array1[$key], $value) : + $value; + } + + return $array1; + } +} diff --git a/src/Helper/Filesystem.php b/src/Helper/Filesystem.php index 36087b1..5ccf888 100644 --- a/src/Helper/Filesystem.php +++ b/src/Helper/Filesystem.php @@ -5,25 +5,16 @@ use Symfony\Component\Filesystem\Exception\IOException; use Symfony\Component\Filesystem\Filesystem as BaseFilesystem; -/** - * Class Filesystem. - */ class Filesystem { - /** - * @var BaseFilesystem - */ - private static $delegate; + private static ?BaseFilesystem $delegate = null; /** * Creates a directory recursively. * - * @param string|array|\Traversable $dirs The directory path - * @param int $mode The directory mode - * * @throws IOException On any directory creation failure */ - public static function mkdir($dirs, int $mode = 0777) + public static function mkdir(string|iterable $dirs, int $mode = 0777): void { self::getDelegate()->mkdir($dirs, $mode); } @@ -31,11 +22,9 @@ public static function mkdir($dirs, int $mode = 0777) /** * Checks the existence of files or directories. * - * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to check - * - * @return bool true if the file exists, false otherwise + * @param string|iterable $files A filename, an array of files, or a \Traversable instance to check */ - public static function exists($files): bool + public static function exists(string|iterable $files): bool { return self::getDelegate()->exists($files); } @@ -43,11 +32,11 @@ public static function exists($files): bool /** * Removes files or directories. * - * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to remove + * @param string|iterable $files A filename, an array of files, or a \Traversable instance to remove * * @throws IOException When removal fails */ - public static function remove($files) + public static function remove(string|iterable $files): void { self::getDelegate()->remove($files); } @@ -60,17 +49,14 @@ public static function remove($files) * * @throws IOException If the file cannot be written to */ - public static function dumpFile(string $filename, string $content) + public static function dumpFile(string $filename, string $content): void { self::getDelegate()->dumpFile($filename, $content); } - /** - * @return BaseFilesystem - */ public static function getDelegate(): BaseFilesystem { - if (!self::$delegate) { + if (null === self::$delegate) { self::$delegate = new BaseFilesystem(); } diff --git a/src/MewesKTwigSpreadsheetBundle.php b/src/MewesKTwigSpreadsheetBundle.php index 871ac75..18d1221 100644 --- a/src/MewesKTwigSpreadsheetBundle.php +++ b/src/MewesKTwigSpreadsheetBundle.php @@ -4,9 +4,6 @@ use Symfony\Component\HttpKernel\Bundle\Bundle; -/** - * Class MewesKTwigSpreadsheetBundle. - */ class MewesKTwigSpreadsheetBundle extends Bundle { } diff --git a/src/Resources/config/services.yml b/src/Resources/config/services.yml index d957295..9d2ccf4 100644 --- a/src/Resources/config/services.yml +++ b/src/Resources/config/services.yml @@ -1,12 +1,12 @@ services: - mewes_k_twig_spreadsheet.add_request_formats_listener: - class: MewesK\TwigSpreadsheetBundle\EventListener\AddRequestFormatsListener - tags: - - { name: kernel.event_subscriber } + mewes_k_twig_spreadsheet.add_request_formats_listener: + class: MewesK\TwigSpreadsheetBundle\EventListener\AddRequestFormatsListener + tags: + - { name: kernel.event_subscriber } - mewes_k_twig_spreadsheet.twig_spreadsheet_extension: - class: MewesK\TwigSpreadsheetBundle\Twig\TwigSpreadsheetExtension - public: true - arguments: [ null ] # config placeholder - tags: - - { name: twig.extension } + mewes_k_twig_spreadsheet.twig_spreadsheet_extension: + class: MewesK\TwigSpreadsheetBundle\Twig\TwigSpreadsheetExtension + public: true + arguments: [ null ] # config placeholder + tags: + - { name: twig.extension } diff --git a/src/Resources/doc/installation.rst b/src/Resources/doc/installation.rst index 9fcc9cd..cec913a 100644 --- a/src/Resources/doc/installation.rst +++ b/src/Resources/doc/installation.rst @@ -9,7 +9,7 @@ following command to download the latest stable version of this bundle: .. code-block:: terminal - $ composer require mewesk/twig-spreadsheet-bundle + $ composer require subugoe/twig-spreadsheet-bundle This command requires you to have Composer installed globally, as explained in the `installation chapter`_ of the Composer documentation. diff --git a/src/Twig/Node/AlignmentNode.php b/src/Twig/Node/AlignmentNode.php index 28eb97e..de7678c 100644 --- a/src/Twig/Node/AlignmentNode.php +++ b/src/Twig/Node/AlignmentNode.php @@ -3,26 +3,13 @@ namespace MewesK\TwigSpreadsheetBundle\Twig\Node; use MewesK\TwigSpreadsheetBundle\Wrapper\HeaderFooterWrapper; +use Twig\Compiler; -/** - * Class AlignmentNode. - */ class AlignmentNode extends BaseNode { - /** - * @var string - */ - private $alignment; + private string $alignment; /** - * AlignmentNode constructor. - * - * @param array $nodes - * @param array $attributes - * @param int $lineNo - * @param string|null $tag - * @param string $alignment - * * @throws \InvalidArgumentException */ public function __construct(array $nodes = [], array $attributes = [], int $lineNo = 0, string $tag = null, string $alignment = HeaderFooterWrapper::ALIGNMENT_CENTER) @@ -32,21 +19,18 @@ public function __construct(array $nodes = [], array $attributes = [], int $line $this->alignment = HeaderFooterWrapper::validateAlignment(strtolower($alignment)); } - /** - * @param \Twig_Compiler $compiler - */ - public function compile(\Twig_Compiler $compiler) + public function compile(Compiler $compiler) { $compiler->addDebugInfo($this) ->write(self::CODE_FIX_CONTEXT) ->write(self::CODE_INSTANCE.'->startAlignment(') ->repr($this->alignment) - ->raw(');'.PHP_EOL) + ->raw(');'.\PHP_EOL) ->write("ob_start();\n") ->subcompile($this->getNode('body')) - ->write('$alignmentValue = trim(ob_get_clean());'.PHP_EOL) - ->write(self::CODE_INSTANCE.'->endAlignment($alignmentValue);'.PHP_EOL) - ->write('unset($alignmentValue);'.PHP_EOL); + ->write('$alignmentValue = trim(ob_get_clean());'.\PHP_EOL) + ->write(self::CODE_INSTANCE.'->endAlignment($alignmentValue);'.\PHP_EOL) + ->write('unset($alignmentValue);'.\PHP_EOL); } /** diff --git a/src/Twig/Node/BaseNode.php b/src/Twig/Node/BaseNode.php index 1d0590e..98deefe 100644 --- a/src/Twig/Node/BaseNode.php +++ b/src/Twig/Node/BaseNode.php @@ -3,21 +3,19 @@ namespace MewesK\TwigSpreadsheetBundle\Twig\Node; use MewesK\TwigSpreadsheetBundle\Wrapper\PhpSpreadsheetWrapper; +use Twig\Node\Node; -/** - * Class BaseNode. - */ -abstract class BaseNode extends \Twig_Node +abstract class BaseNode extends Node { /** * @var string */ - const CODE_FIX_CONTEXT = '$context = '.PhpSpreadsheetWrapper::class.'::fixContext($context);'.PHP_EOL; + public const CODE_FIX_CONTEXT = '$context = '.PhpSpreadsheetWrapper::class.'::fixContext($context);'.\PHP_EOL; /** * @var string */ - const CODE_INSTANCE = '$context[\''.PhpSpreadsheetWrapper::INSTANCE_KEY.'\']'; + public const CODE_INSTANCE = '$context[\''.PhpSpreadsheetWrapper::INSTANCE_KEY."']"; /** * @return string[] diff --git a/src/Twig/Node/CellNode.php b/src/Twig/Node/CellNode.php index 39050fd..f771994 100644 --- a/src/Twig/Node/CellNode.php +++ b/src/Twig/Node/CellNode.php @@ -2,29 +2,26 @@ namespace MewesK\TwigSpreadsheetBundle\Twig\Node; +use Twig\Compiler; + /** * Class CellNode. */ class CellNode extends BaseNode { - /** - * @param \Twig_Compiler $compiler - */ - public function compile(\Twig_Compiler $compiler) + public function compile(Compiler $compiler) { $compiler->addDebugInfo($this) ->write(self::CODE_FIX_CONTEXT) - ->write(self::CODE_INSTANCE.'->setCellIndex(') + ->write(self::CODE_INSTANCE.'->startCell(') ->subcompile($this->getNode('index')) - ->raw(');'.PHP_EOL) + ->raw(', ') + ->subcompile($this->getNode('properties')) + ->raw(');'.\PHP_EOL) ->write("ob_start();\n") ->subcompile($this->getNode('body')) - ->write('$cellValue = trim(ob_get_clean());'.PHP_EOL) - ->write(self::CODE_INSTANCE.'->startCell($cellValue, ') - ->subcompile($this->getNode('properties')) - ->raw(');'.PHP_EOL) - ->write(self::CODE_INSTANCE.'->endCell();'.PHP_EOL) - ->write('unset($cellValue);'.PHP_EOL); + ->write(self::CODE_INSTANCE.'->setCellValue(trim(ob_get_clean()));'.\PHP_EOL) + ->write(self::CODE_INSTANCE.'->endCell();'.\PHP_EOL); } /** diff --git a/src/Twig/Node/DocumentNode.php b/src/Twig/Node/DocumentNode.php index 726a418..4d2e352 100644 --- a/src/Twig/Node/DocumentNode.php +++ b/src/Twig/Node/DocumentNode.php @@ -4,29 +4,23 @@ use MewesK\TwigSpreadsheetBundle\Wrapper\PhpSpreadsheetWrapper; -/** - * Class DocumentNode. - */ class DocumentNode extends BaseNode { - /** - * @param \Twig_Compiler $compiler - */ - public function compile(\Twig_Compiler $compiler) + public function compile(\Twig\Compiler $compiler) { $compiler->addDebugInfo($this) ->write("ob_start();\n") ->write(self::CODE_INSTANCE.' = new '.PhpSpreadsheetWrapper::class.'($context, $this->env, ') ->repr($this->attributes) - ->raw(');'.PHP_EOL) + ->raw(');'.\PHP_EOL) ->write(self::CODE_INSTANCE.'->startDocument(') ->subcompile($this->getNode('properties')) - ->raw(');'.PHP_EOL) + ->raw(');'.\PHP_EOL) ->subcompile($this->getNode('body')) ->addDebugInfo($this) ->write("ob_end_clean();\n") - ->write(self::CODE_INSTANCE.'->endDocument();'.PHP_EOL) - ->write('unset('.self::CODE_INSTANCE.');'.PHP_EOL); + ->write(self::CODE_INSTANCE.'->endDocument();'.\PHP_EOL) + ->write('unset('.self::CODE_INSTANCE.');'.\PHP_EOL); } /** diff --git a/src/Twig/Node/DrawingNode.php b/src/Twig/Node/DrawingNode.php index c3906e0..96f680b 100644 --- a/src/Twig/Node/DrawingNode.php +++ b/src/Twig/Node/DrawingNode.php @@ -2,23 +2,19 @@ namespace MewesK\TwigSpreadsheetBundle\Twig\Node; -/** - * Class DrawingNode. - */ +use Twig\Compiler; + class DrawingNode extends BaseNode { - /** - * @param \Twig_Compiler $compiler - */ - public function compile(\Twig_Compiler $compiler) + public function compile(Compiler $compiler) { $compiler->addDebugInfo($this) ->write(self::CODE_FIX_CONTEXT) ->write(self::CODE_INSTANCE.'->startDrawing(') ->subcompile($this->getNode('path'))->raw(', ') ->subcompile($this->getNode('properties')) - ->raw(');'.PHP_EOL) - ->write(self::CODE_INSTANCE.'->endDrawing();'.PHP_EOL); + ->raw(');'.\PHP_EOL) + ->write(self::CODE_INSTANCE.'->endDrawing();'.\PHP_EOL); } /** diff --git a/src/Twig/Node/HeaderFooterNode.php b/src/Twig/Node/HeaderFooterNode.php index 72bca1b..6f48527 100644 --- a/src/Twig/Node/HeaderFooterNode.php +++ b/src/Twig/Node/HeaderFooterNode.php @@ -3,26 +3,13 @@ namespace MewesK\TwigSpreadsheetBundle\Twig\Node; use MewesK\TwigSpreadsheetBundle\Wrapper\HeaderFooterWrapper; +use Twig\Compiler; -/** - * Class HeaderFooterNode. - */ class HeaderFooterNode extends BaseNode { - /** - * @var string - */ - private $baseType; + private string $baseType; /** - * HeaderFooterNode constructor. - * - * @param array $nodes - * @param array $attributes - * @param int $lineNo - * @param string|null $tag - * @param string $baseType - * * @throws \InvalidArgumentException */ public function __construct(array $nodes = [], array $attributes = [], int $lineNo = 0, string $tag = null, string $baseType = HeaderFooterWrapper::BASETYPE_HEADER) @@ -32,10 +19,7 @@ public function __construct(array $nodes = [], array $attributes = [], int $line $this->baseType = HeaderFooterWrapper::validateBaseType(strtolower($baseType)); } - /** - * @param \Twig_Compiler $compiler - */ - public function compile(\Twig_Compiler $compiler) + public function compile(Compiler $compiler) { $compiler->addDebugInfo($this) ->write(self::CODE_FIX_CONTEXT) @@ -43,10 +27,10 @@ public function compile(\Twig_Compiler $compiler) ->repr($this->baseType)->raw(', ') ->subcompile($this->getNode('type'))->raw(', ') ->subcompile($this->getNode('properties')) - ->raw(');'.PHP_EOL) + ->raw(');'.\PHP_EOL) ->subcompile($this->getNode('body')) ->addDebugInfo($this) - ->write(self::CODE_INSTANCE.'->endHeaderFooter();'.PHP_EOL); + ->write(self::CODE_INSTANCE.'->endHeaderFooter();'.\PHP_EOL); } /** diff --git a/src/Twig/Node/RowNode.php b/src/Twig/Node/RowNode.php index 15ab0e2..e66b1d7 100644 --- a/src/Twig/Node/RowNode.php +++ b/src/Twig/Node/RowNode.php @@ -2,25 +2,20 @@ namespace MewesK\TwigSpreadsheetBundle\Twig\Node; -/** - * Class RowNode. - */ +use Twig\Compiler; + class RowNode extends BaseNode { - /** - * @param \Twig_Compiler $compiler - */ - public function compile(\Twig_Compiler $compiler) + public function compile(Compiler $compiler) { $compiler->addDebugInfo($this) ->write(self::CODE_FIX_CONTEXT) - ->write(self::CODE_INSTANCE.'->setRowIndex(') + ->write(self::CODE_INSTANCE.'->startRow(') ->subcompile($this->getNode('index')) - ->raw(');'.PHP_EOL) - ->write(self::CODE_INSTANCE.'->startRow('.self::CODE_INSTANCE.'->getRowIndex());'.PHP_EOL) + ->raw(');'.\PHP_EOL) ->subcompile($this->getNode('body')) ->addDebugInfo($this) - ->write(self::CODE_INSTANCE.'->endRow();'.PHP_EOL); + ->write(self::CODE_INSTANCE.'->endRow();'.\PHP_EOL); } /** diff --git a/src/Twig/Node/SheetNode.php b/src/Twig/Node/SheetNode.php index fef6a44..c918722 100644 --- a/src/Twig/Node/SheetNode.php +++ b/src/Twig/Node/SheetNode.php @@ -2,25 +2,19 @@ namespace MewesK\TwigSpreadsheetBundle\Twig\Node; -/** - * Class SheetNode. - */ class SheetNode extends BaseNode { - /** - * @param \Twig_Compiler $compiler - */ - public function compile(\Twig_Compiler $compiler) + public function compile(\Twig\Compiler $compiler) { $compiler->addDebugInfo($this) ->write(self::CODE_FIX_CONTEXT) ->write(self::CODE_INSTANCE.'->startSheet(') ->subcompile($this->getNode('index'))->raw(', ') ->subcompile($this->getNode('properties')) - ->raw(');'.PHP_EOL) + ->raw(');'.\PHP_EOL) ->subcompile($this->getNode('body')) ->addDebugInfo($this) - ->write(self::CODE_INSTANCE.'->endSheet();'.PHP_EOL); + ->write(self::CODE_INSTANCE.'->endSheet();'.\PHP_EOL); } /** diff --git a/src/Twig/NodeVisitor/MacroContextNodeVisitor.php b/src/Twig/NodeVisitor/MacroContextNodeVisitor.php index 44509ba..6e83d45 100644 --- a/src/Twig/NodeVisitor/MacroContextNodeVisitor.php +++ b/src/Twig/NodeVisitor/MacroContextNodeVisitor.php @@ -3,16 +3,20 @@ namespace MewesK\TwigSpreadsheetBundle\Twig\NodeVisitor; use MewesK\TwigSpreadsheetBundle\Wrapper\PhpSpreadsheetWrapper; - -/** - * Class MacroContextNodeVisitor. - */ -class MacroContextNodeVisitor extends \Twig_BaseNodeVisitor +use Twig\Environment; +use Twig\Node\Expression\ArrayExpression; +use Twig\Node\Expression\ConstantExpression; +use Twig\Node\Expression\MethodCallExpression; +use Twig\Node\Expression\NameExpression; +use Twig\Node\Node; +use Twig\NodeVisitor\AbstractNodeVisitor; + +class MacroContextNodeVisitor extends AbstractNodeVisitor { /** * {@inheritdoc} */ - public function getPriority() + public function getPriority(): int { return 0; } @@ -20,18 +24,18 @@ public function getPriority() /** * {@inheritdoc} */ - protected function doEnterNode(\Twig_Node $node, \Twig_Environment $env) + protected function doEnterNode(Node $node, Environment $env) { // add wrapper instance as argument on all method calls - if ($node instanceof \Twig_Node_Expression_MethodCall) { - $keyNode = new \Twig_Node_Expression_Constant(PhpSpreadsheetWrapper::INSTANCE_KEY, $node->getTemplateLine()); + if ($node instanceof MethodCallExpression) { + $keyNode = new ConstantExpression(PhpSpreadsheetWrapper::INSTANCE_KEY, $node->getTemplateLine()); // add wrapper even if it not exists, we fix that later - $valueNode = new \Twig_Node_Expression_Name(PhpSpreadsheetWrapper::INSTANCE_KEY, $node->getTemplateLine()); + $valueNode = new NameExpression(PhpSpreadsheetWrapper::INSTANCE_KEY, $node->getTemplateLine()); $valueNode->setAttribute('ignore_strict_check', true); /** - * @var \Twig_Node_Expression_Array $argumentsNode + * @var ArrayExpression $argumentsNode */ $argumentsNode = $node->getNode('arguments'); $argumentsNode->addElement($valueNode, $keyNode); @@ -43,7 +47,7 @@ protected function doEnterNode(\Twig_Node $node, \Twig_Environment $env) /** * {@inheritdoc} */ - protected function doLeaveNode(\Twig_Node $node, \Twig_Environment $env) + protected function doLeaveNode(Node $node, Environment $env): ?Node { return $node; } diff --git a/src/Twig/NodeVisitor/SyntaxCheckNodeVisitor.php b/src/Twig/NodeVisitor/SyntaxCheckNodeVisitor.php index aefed7d..201192c 100644 --- a/src/Twig/NodeVisitor/SyntaxCheckNodeVisitor.php +++ b/src/Twig/NodeVisitor/SyntaxCheckNodeVisitor.php @@ -4,21 +4,20 @@ use MewesK\TwigSpreadsheetBundle\Twig\Node\BaseNode; use MewesK\TwigSpreadsheetBundle\Twig\Node\DocumentNode; +use Twig\Environment; +use Twig\Error\SyntaxError; +use Twig\Node\Node; +use Twig\Node\TextNode; +use Twig\NodeVisitor\AbstractNodeVisitor; -/** - * Class SyntaxCheckNodeVisitor. - */ -class SyntaxCheckNodeVisitor extends \Twig_BaseNodeVisitor +class SyntaxCheckNodeVisitor extends AbstractNodeVisitor { - /** - * @var array - */ - protected $path = []; + protected array $path = []; /** * {@inheritdoc} */ - public function getPriority() + public function getPriority(): int { return 0; } @@ -26,9 +25,9 @@ public function getPriority() /** * {@inheritdoc} * - * @throws \Twig_Error_Syntax + * @throws SyntaxError */ - protected function doEnterNode(\Twig_Node $node, \Twig_Environment $env) + protected function doEnterNode(Node $node, Environment $env): Node { try { if ($node instanceof BaseNode) { @@ -36,13 +35,13 @@ protected function doEnterNode(\Twig_Node $node, \Twig_Environment $env) } else { $this->checkAllowedChildren($node); } - } catch (\Twig_Error_Syntax $e) { + } catch (SyntaxError $syntaxError) { // reset path since throwing an error prevents doLeaveNode to be called $this->path = []; - throw $e; + throw $syntaxError; } - $this->path[] = $node !== null ? \get_class($node) : null; + $this->path[] = null !== $node ? $node::class : null; return $node; } @@ -50,7 +49,7 @@ protected function doEnterNode(\Twig_Node $node, \Twig_Environment $env) /** * {@inheritdoc} */ - protected function doLeaveNode(\Twig_Node $node, \ Twig_Environment $env) + protected function doLeaveNode(Node $node, Environment $env): ?Node { array_pop($this->path); @@ -58,52 +57,51 @@ protected function doLeaveNode(\Twig_Node $node, \ Twig_Environment $env) } /** - * @param \Twig_Node $node - * - * @throws \Twig_Error_Syntax + * @throws SyntaxError + * @throws \Exception */ - private function checkAllowedChildren(\Twig_Node $node) + private function checkAllowedChildren(Node $node): void { $hasDocumentNode = false; $hasTextNode = false; /** - * @var \Twig_Node $currentNode + * @var Node $currentNode */ foreach ($node->getIterator() as $currentNode) { - if ($currentNode instanceof \Twig_Node_Text) { + if ($currentNode instanceof TextNode) { if ($hasDocumentNode) { - throw new \Twig_Error_Syntax(sprintf('Node "%s" is not allowed after Node "%s".', \Twig_Node_Text::class, DocumentNode::class)); + throw new SyntaxError(sprintf('Node "%s" is not allowed after Node "%s".', TextNode::class, DocumentNode::class)); } + $hasTextNode = true; } elseif ($currentNode instanceof DocumentNode) { if ($hasTextNode) { - throw new \Twig_Error_Syntax(sprintf('Node "%s" is not allowed before Node "%s".', \Twig_Node_Text::class, DocumentNode::class)); + throw new SyntaxError(sprintf('Node "%s" is not allowed before Node "%s".', TextNode::class, DocumentNode::class)); } + $hasDocumentNode = true; } } } /** - * @param BaseNode $node - * - * @throws \Twig_Error_Syntax + * @throws SyntaxError */ - private function checkAllowedParents(BaseNode $node) + private function checkAllowedParents(BaseNode $node): void { $parentName = null; // find first parent from this bundle foreach (array_reverse($this->path) as $className) { - if (strpos($className, 'MewesK\\TwigSpreadsheetBundle\\Twig\\Node\\') === 0) { + if (str_starts_with($className, 'MewesK\\TwigSpreadsheetBundle\\Twig\\Node\\')) { $parentName = $className; break; } } // allow no parents (e.g. macros, includes) - if ($parentName === null) { + if (null === $parentName) { return; } @@ -114,6 +112,6 @@ private function checkAllowedParents(BaseNode $node) } } - throw new \Twig_Error_Syntax(sprintf('Node "%s" is not allowed inside of Node "%s".', \get_class($node), $parentName)); + throw new SyntaxError(sprintf('Node "%s" is not allowed inside of Node "%s".', $node::class, $parentName)); } } diff --git a/src/Twig/TokenParser/AlignmentTokenParser.php b/src/Twig/TokenParser/AlignmentTokenParser.php index b64e88e..436837b 100644 --- a/src/Twig/TokenParser/AlignmentTokenParser.php +++ b/src/Twig/TokenParser/AlignmentTokenParser.php @@ -4,22 +4,14 @@ use MewesK\TwigSpreadsheetBundle\Twig\Node\AlignmentNode; use MewesK\TwigSpreadsheetBundle\Wrapper\HeaderFooterWrapper; +use Twig\Node\Node; -/** - * Class AlignmentTokenParser. - */ class AlignmentTokenParser extends BaseTokenParser { - /** - * @var string - */ - private $alignment; + private string $alignment; /** - * AlignmentTokenParser constructor. - * - * @param array $attributes optional attributes for the corresponding node - * @param string $alignment + * @param array $attributes optional attributes for the corresponding node * * @throws \InvalidArgumentException */ @@ -35,7 +27,7 @@ public function __construct(array $attributes = [], string $alignment = HeaderFo * * @throws \InvalidArgumentException */ - public function createNode(array $nodes = [], int $lineNo = 0): \Twig_Node + public function createNode(array $nodes = [], int $lineNo = 0): Node { return new AlignmentNode($nodes, $this->getAttributes(), $lineNo, $this->getTag(), $this->alignment); } @@ -43,7 +35,7 @@ public function createNode(array $nodes = [], int $lineNo = 0): \Twig_Node /** * {@inheritdoc} */ - public function getTag() + public function getTag(): string { return 'xls'.$this->alignment; } diff --git a/src/Twig/TokenParser/BaseTokenParser.php b/src/Twig/TokenParser/BaseTokenParser.php index facbcc3..99dfc2f 100644 --- a/src/Twig/TokenParser/BaseTokenParser.php +++ b/src/Twig/TokenParser/BaseTokenParser.php @@ -2,49 +2,36 @@ namespace MewesK\TwigSpreadsheetBundle\Twig\TokenParser; -/** - * Class BaseTokenParser. - */ -abstract class BaseTokenParser extends \Twig_TokenParser +use Twig\Error\SyntaxError; +use Twig\Node\Expression\AbstractExpression; +use Twig\Node\Node; +use Twig\Token; +use Twig\TokenParser\AbstractTokenParser; + +abstract class BaseTokenParser extends AbstractTokenParser { /** * @var int */ - const PARAMETER_TYPE_ARRAY = 0; + public const PARAMETER_TYPE_ARRAY = 0; /** * @var int */ - const PARAMETER_TYPE_VALUE = 1; + public const PARAMETER_TYPE_VALUE = 1; /** - * @var array - */ - private $attributes; - - /** - * BaseTokenParser constructor. - * * @param array $attributes optional attributes for the corresponding node */ - public function __construct(array $attributes = []) + public function __construct(private array $attributes = []) { - $this->attributes = $attributes; } - /** - * @param \Twig_Token $token - * - * @return array - */ - public function configureParameters(\Twig_Token $token): array + public function configureParameters(Token $token): array { return []; } - /** - * @return array - */ public function getAttributes(): array { return $this->attributes; @@ -52,17 +39,9 @@ public function getAttributes(): array /** * Create a concrete node. - * - * @param array $nodes - * @param int $lineNo - * - * @return \Twig_Node */ - abstract public function createNode(array $nodes = [], int $lineNo = 0): \Twig_Node; + abstract public function createNode(array $nodes = [], int $lineNo = 0): Node; - /** - * @return bool - */ public function hasBody(): bool { return true; @@ -74,7 +53,7 @@ public function hasBody(): bool * @throws \Exception * @throws \InvalidArgumentException */ - public function parse(\Twig_Token $token) + public function parse(Token $token): Node { // parse parameters $nodes = $this->parseParameters($this->configureParameters($token)); @@ -88,43 +67,34 @@ public function parse(\Twig_Token $token) } /** - * @param array $parameterConfiguration - * * @throws \Exception * @throws \InvalidArgumentException - * @throws \Twig_Error_Syntax + * @throws SyntaxError * - * @return \Twig_Node_Expression[] + * @return AbstractExpression[] */ private function parseParameters(array $parameterConfiguration = []): array { // parse expressions $expressions = []; - while (!$this->parser->getStream()->test(\Twig_Token::BLOCK_END_TYPE)) { + while (!$this->parser->getStream()->test(Token::BLOCK_END_TYPE)) { $expressions[] = $this->parser->getExpressionParser()->parseExpression(); } // end of expressions - $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); + $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); // map expressions to parameters $parameters = []; foreach ($parameterConfiguration as $parameterName => $parameterOptions) { // try mapping expression $expression = reset($expressions); - if ($expression !== false) { - switch ($parameterOptions['type']) { - case self::PARAMETER_TYPE_ARRAY: - // check if expression is valid array - $valid = $expression instanceof \Twig_Node_Expression_Array; - break; - case self::PARAMETER_TYPE_VALUE: - // check if expression is valid value - $valid = !($expression instanceof \Twig_Node_Expression_Array); - break; - default: - throw new \InvalidArgumentException('Invalid parameter type'); - } + if (false !== $expression) { + $valid = match ($parameterOptions['type']) { + self::PARAMETER_TYPE_ARRAY => $expression instanceof \Twig\Node\Expression\ArrayExpression, + self::PARAMETER_TYPE_VALUE => !($expression instanceof \Twig\Node\Expression\ArrayExpression), + default => throw new \InvalidArgumentException('Invalid parameter type'), + }; if ($valid) { // set expression as parameter and remove it from expressions list @@ -134,28 +104,29 @@ private function parseParameters(array $parameterConfiguration = []): array } // set default as parameter otherwise or throw exception if default is false - if ($parameterOptions['default'] === false) { - throw new \Twig_Error_Syntax('A required parameter is missing'); + if (false === $parameterOptions['default']) { + throw new SyntaxError('A required parameter is missing'); } + $parameters[$parameterName] = $parameterOptions['default']; } - if (\count($expressions) > 0) { - throw new \Twig_Error_Syntax('Too many parameters'); + if ([] !== $expressions) { + throw new SyntaxError('Too many parameters'); } return $parameters; } /** - * @return \Twig_Node - * @throws \Twig_Error_Syntax + * @throws SyntaxError */ - private function parseBody(): \Twig_Node + private function parseBody(): Node { // parse till matching end tag is found - $body = $this->parser->subparse(function (\Twig_Token $token) { return $token->test('end'.$this->getTag()); }, true); - $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); + $body = $this->parser->subparse(fn (Token $token) => $token->test('end'.$this->getTag()), true); + $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); + return $body; } } diff --git a/src/Twig/TokenParser/CellTokenParser.php b/src/Twig/TokenParser/CellTokenParser.php index d040c69..1ed4df2 100644 --- a/src/Twig/TokenParser/CellTokenParser.php +++ b/src/Twig/TokenParser/CellTokenParser.php @@ -3,25 +3,26 @@ namespace MewesK\TwigSpreadsheetBundle\Twig\TokenParser; use MewesK\TwigSpreadsheetBundle\Twig\Node\CellNode; +use Twig\Node\Expression\ArrayExpression; +use Twig\Node\Expression\ConstantExpression; +use Twig\Node\Node; +use Twig\Token; -/** - * Class CellTokenParser. - */ class CellTokenParser extends BaseTokenParser { /** * {@inheritdoc} */ - public function configureParameters(\Twig_Token $token): array + public function configureParameters(Token $token): array { return [ 'index' => [ 'type' => self::PARAMETER_TYPE_VALUE, - 'default' => new \Twig_Node_Expression_Constant(null, $token->getLine()), + 'default' => new ConstantExpression(null, $token->getLine()), ], 'properties' => [ 'type' => self::PARAMETER_TYPE_ARRAY, - 'default' => new \Twig_Node_Expression_Array([], $token->getLine()), + 'default' => new ArrayExpression([], $token->getLine()), ], ]; } @@ -29,7 +30,7 @@ public function configureParameters(\Twig_Token $token): array /** * {@inheritdoc} */ - public function createNode(array $nodes = [], int $lineNo = 0): \Twig_Node + public function createNode(array $nodes = [], int $lineNo = 0): Node { return new CellNode($nodes, $this->getAttributes(), $lineNo, $this->getTag()); } @@ -37,7 +38,7 @@ public function createNode(array $nodes = [], int $lineNo = 0): \Twig_Node /** * {@inheritdoc} */ - public function getTag() + public function getTag(): string { return 'xlscell'; } diff --git a/src/Twig/TokenParser/DocumentTokenParser.php b/src/Twig/TokenParser/DocumentTokenParser.php index a0804d8..90a334d 100644 --- a/src/Twig/TokenParser/DocumentTokenParser.php +++ b/src/Twig/TokenParser/DocumentTokenParser.php @@ -3,21 +3,21 @@ namespace MewesK\TwigSpreadsheetBundle\Twig\TokenParser; use MewesK\TwigSpreadsheetBundle\Twig\Node\DocumentNode; +use Twig\Node\Expression\ArrayExpression; +use Twig\Node\Node; +use Twig\Token; -/** - * Class DocumentTokenParser. - */ class DocumentTokenParser extends BaseTokenParser { /** * {@inheritdoc} */ - public function configureParameters(\Twig_Token $token): array + public function configureParameters(Token $token): array { return [ 'properties' => [ 'type' => self::PARAMETER_TYPE_ARRAY, - 'default' => new \Twig_Node_Expression_Array([], $token->getLine()), + 'default' => new ArrayExpression([], $token->getLine()), ], ]; } @@ -25,7 +25,7 @@ public function configureParameters(\Twig_Token $token): array /** * {@inheritdoc} */ - public function createNode(array $nodes = [], int $lineNo = 0): \Twig_Node + public function createNode(array $nodes = [], int $lineNo = 0): Node { return new DocumentNode($nodes, $this->getAttributes(), $lineNo, $this->getTag()); } @@ -33,7 +33,7 @@ public function createNode(array $nodes = [], int $lineNo = 0): \Twig_Node /** * {@inheritdoc} */ - public function getTag() + public function getTag(): string { return 'xlsdocument'; } diff --git a/src/Twig/TokenParser/DrawingTokenParser.php b/src/Twig/TokenParser/DrawingTokenParser.php index 4442f83..d750373 100644 --- a/src/Twig/TokenParser/DrawingTokenParser.php +++ b/src/Twig/TokenParser/DrawingTokenParser.php @@ -3,16 +3,16 @@ namespace MewesK\TwigSpreadsheetBundle\Twig\TokenParser; use MewesK\TwigSpreadsheetBundle\Twig\Node\DrawingNode; +use Twig\Node\Expression\ArrayExpression; +use Twig\Node\Node; +use Twig\Token; -/** - * Class DrawingTokenParser. - */ class DrawingTokenParser extends BaseTokenParser { /** * {@inheritdoc} */ - public function configureParameters(\Twig_Token $token): array + public function configureParameters(Token $token): array { return [ 'path' => [ @@ -21,7 +21,7 @@ public function configureParameters(\Twig_Token $token): array ], 'properties' => [ 'type' => self::PARAMETER_TYPE_ARRAY, - 'default' => new \Twig_Node_Expression_Array([], $token->getLine()), + 'default' => new ArrayExpression([], $token->getLine()), ], ]; } @@ -29,7 +29,7 @@ public function configureParameters(\Twig_Token $token): array /** * {@inheritdoc} */ - public function createNode(array $nodes = [], int $lineNo = 0): \Twig_Node + public function createNode(array $nodes = [], int $lineNo = 0): Node { return new DrawingNode($nodes, $this->getAttributes(), $lineNo, $this->getTag()); } @@ -37,7 +37,7 @@ public function createNode(array $nodes = [], int $lineNo = 0): \Twig_Node /** * {@inheritdoc} */ - public function getTag() + public function getTag(): string { return 'xlsdrawing'; } diff --git a/src/Twig/TokenParser/HeaderFooterTokenParser.php b/src/Twig/TokenParser/HeaderFooterTokenParser.php index 01e64ea..3593e1b 100644 --- a/src/Twig/TokenParser/HeaderFooterTokenParser.php +++ b/src/Twig/TokenParser/HeaderFooterTokenParser.php @@ -4,22 +4,17 @@ use MewesK\TwigSpreadsheetBundle\Twig\Node\HeaderFooterNode; use MewesK\TwigSpreadsheetBundle\Wrapper\HeaderFooterWrapper; +use Twig\Node\Expression\ArrayExpression; +use Twig\Node\Expression\ConstantExpression; +use Twig\Node\Node; +use Twig\Token; -/** - * Class HeaderFooterTokenParser. - */ class HeaderFooterTokenParser extends BaseTokenParser { - /** - * @var string - */ - private $baseType; + private string $baseType; /** - * HeaderFooterTokenParser constructor. - * - * @param array $attributes optional attributes for the corresponding node - * @param string $baseType + * @param array $attributes optional attributes for the corresponding node * * @throws \InvalidArgumentException */ @@ -33,16 +28,16 @@ public function __construct(array $attributes = [], string $baseType = HeaderFoo /** * {@inheritdoc} */ - public function configureParameters(\Twig_Token $token): array + public function configureParameters(Token $token): array { return [ 'type' => [ 'type' => self::PARAMETER_TYPE_VALUE, - 'default' => new \Twig_Node_Expression_Constant(null, $token->getLine()), + 'default' => new ConstantExpression(null, $token->getLine()), ], 'properties' => [ 'type' => self::PARAMETER_TYPE_ARRAY, - 'default' => new \Twig_Node_Expression_Array([], $token->getLine()), + 'default' => new ArrayExpression([], $token->getLine()), ], ]; } @@ -52,7 +47,7 @@ public function configureParameters(\Twig_Token $token): array * * @throws \InvalidArgumentException */ - public function createNode(array $nodes = [], int $lineNo = 0): \Twig_Node + public function createNode(array $nodes = [], int $lineNo = 0): Node { return new HeaderFooterNode($nodes, $this->getAttributes(), $lineNo, $this->getTag(), $this->baseType); } @@ -60,7 +55,7 @@ public function createNode(array $nodes = [], int $lineNo = 0): \Twig_Node /** * {@inheritdoc} */ - public function getTag() + public function getTag(): string { return 'xls'.$this->baseType; } diff --git a/src/Twig/TokenParser/RowTokenParser.php b/src/Twig/TokenParser/RowTokenParser.php index 8b48b3e..57b4de9 100644 --- a/src/Twig/TokenParser/RowTokenParser.php +++ b/src/Twig/TokenParser/RowTokenParser.php @@ -3,21 +3,21 @@ namespace MewesK\TwigSpreadsheetBundle\Twig\TokenParser; use MewesK\TwigSpreadsheetBundle\Twig\Node\RowNode; +use Twig\Node\Expression\ConstantExpression; +use Twig\Node\Node; +use Twig\Token; -/** - * Class RowTokenParser. - */ class RowTokenParser extends BaseTokenParser { /** * {@inheritdoc} */ - public function configureParameters(\Twig_Token $token): array + public function configureParameters(Token $token): array { return [ 'index' => [ 'type' => self::PARAMETER_TYPE_VALUE, - 'default' => new \Twig_Node_Expression_Constant(null, $token->getLine()), + 'default' => new ConstantExpression(null, $token->getLine()), ], ]; } @@ -25,7 +25,7 @@ public function configureParameters(\Twig_Token $token): array /** * {@inheritdoc} */ - public function createNode(array $nodes = [], int $lineNo = 0): \Twig_Node + public function createNode(array $nodes = [], int $lineNo = 0): Node { return new RowNode($nodes, $this->getAttributes(), $lineNo, $this->getTag()); } @@ -33,7 +33,7 @@ public function createNode(array $nodes = [], int $lineNo = 0): \Twig_Node /** * {@inheritdoc} */ - public function getTag() + public function getTag(): string { return 'xlsrow'; } diff --git a/src/Twig/TokenParser/SheetTokenParser.php b/src/Twig/TokenParser/SheetTokenParser.php index 59cb7a7..d270113 100644 --- a/src/Twig/TokenParser/SheetTokenParser.php +++ b/src/Twig/TokenParser/SheetTokenParser.php @@ -3,25 +3,26 @@ namespace MewesK\TwigSpreadsheetBundle\Twig\TokenParser; use MewesK\TwigSpreadsheetBundle\Twig\Node\SheetNode; +use Twig\Node\Expression\ArrayExpression; +use Twig\Node\Expression\ConstantExpression; +use Twig\Node\Node; +use Twig\Token; -/** - * Class SheetTokenParser. - */ class SheetTokenParser extends BaseTokenParser { /** * {@inheritdoc} */ - public function configureParameters(\Twig_Token $token): array + public function configureParameters(Token $token): array { return [ 'index' => [ 'type' => self::PARAMETER_TYPE_VALUE, - 'default' => new \Twig_Node_Expression_Constant(null, $token->getLine()), + 'default' => new ConstantExpression(null, $token->getLine()), ], 'properties' => [ 'type' => self::PARAMETER_TYPE_ARRAY, - 'default' => new \Twig_Node_Expression_Array([], $token->getLine()), + 'default' => new ArrayExpression([], $token->getLine()), ], ]; } @@ -29,7 +30,7 @@ public function configureParameters(\Twig_Token $token): array /** * {@inheritdoc} */ - public function createNode(array $nodes = [], int $lineNo = 0): \Twig_Node + public function createNode(array $nodes = [], int $lineNo = 0): Node { return new SheetNode($nodes, $this->getAttributes(), $lineNo, $this->getTag()); } @@ -37,7 +38,7 @@ public function createNode(array $nodes = [], int $lineNo = 0): \Twig_Node /** * {@inheritdoc} */ - public function getTag() + public function getTag(): string { return 'xlssheet'; } diff --git a/src/Twig/TwigSpreadsheetExtension.php b/src/Twig/TwigSpreadsheetExtension.php index 8a83c46..541e359 100644 --- a/src/Twig/TwigSpreadsheetExtension.php +++ b/src/Twig/TwigSpreadsheetExtension.php @@ -2,6 +2,8 @@ namespace MewesK\TwigSpreadsheetBundle\Twig; +use InvalidArgumentException; +use MewesK\TwigSpreadsheetBundle\Helper\Arrays; use MewesK\TwigSpreadsheetBundle\Twig\NodeVisitor\MacroContextNodeVisitor; use MewesK\TwigSpreadsheetBundle\Twig\NodeVisitor\SyntaxCheckNodeVisitor; use MewesK\TwigSpreadsheetBundle\Twig\TokenParser\AlignmentTokenParser; @@ -13,31 +15,16 @@ use MewesK\TwigSpreadsheetBundle\Twig\TokenParser\SheetTokenParser; use MewesK\TwigSpreadsheetBundle\Wrapper\HeaderFooterWrapper; use MewesK\TwigSpreadsheetBundle\Wrapper\PhpSpreadsheetWrapper; +use Twig\Error\RuntimeError; +use Twig\Extension\AbstractExtension; +use Twig\TwigFunction; - -/** - * Class TwigSpreadsheetExtension. - */ -class TwigSpreadsheetExtension extends \Twig_Extension +class TwigSpreadsheetExtension extends AbstractExtension { - /** - * @var array - */ - private $attributes; - - /** - * TwigSpreadsheetExtension constructor. - * - * @param array $attributes - */ - public function __construct(array $attributes = []) + public function __construct(private array $attributes = []) { - $this->attributes = $attributes; } - /** - * @return array - */ public function getAttributes(): array { return $this->attributes; @@ -46,20 +33,21 @@ public function getAttributes(): array /** * {@inheritdoc} */ - public function getFunctions() + public function getFunctions(): array { return [ - new \Twig_SimpleFunction('xlsmergestyles', [$this, 'mergeStyles']), - new \Twig_SimpleFunction('xlsrowindex', [$this, 'getRowIndex'], ['needs_context' => true]), + new TwigFunction('xlsmergestyles', fn (array $style1, array $style2): array => $this->mergeStyles($style1, $style2)), + new TwigFunction('xlscellindex', fn (array $context): ?int => $this->getCurrentColumn($context), ['needs_context' => true]), + new TwigFunction('xlsrowindex', fn (array $context): ?int => $this->getCurrentRow($context), ['needs_context' => true]), ]; } /** * {@inheritdoc} * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ - public function getTokenParsers() + public function getTokenParsers(): array { return [ new AlignmentTokenParser([], HeaderFooterWrapper::ALIGNMENT_CENTER), @@ -78,7 +66,7 @@ public function getTokenParsers() /** * {@inheritdoc} */ - public function getNodeVisitors() + public function getNodeVisitors(): array { return [ new MacroContextNodeVisitor(), @@ -86,28 +74,32 @@ public function getNodeVisitors() ]; } + public function mergeStyles(array $style1, array $style2): array + { + return Arrays::mergeRecursive($style1, $style2); + } + /** - * @param array $style1 - * @param array $style2 - * - * @throws \Twig_Error_Runtime - * - * @return array + * @throws RuntimeError */ - public function mergeStyles(array $style1, array $style2): array + public function getCurrentColumn(array $context): ?int { - if (!\is_array($style1) || !\is_array($style2)) { - throw new \Twig_Error_Runtime('The xlsmergestyles function only works with arrays.'); + if (!isset($context[PhpSpreadsheetWrapper::INSTANCE_KEY])) { + throw new RuntimeError('The PhpSpreadsheetWrapper instance is missing.'); } - return array_merge_recursive($style1, $style2); + return $context[PhpSpreadsheetWrapper::INSTANCE_KEY]->getCurrentColumn(); } /** - * @param array $context - * @return int|null + * @throws RuntimeError */ - public function getRowIndex(array $context) { - return $context[PhpSpreadsheetWrapper::INSTANCE_KEY]->getSheetRow(); + public function getCurrentRow(array $context): ?int + { + if (!isset($context[PhpSpreadsheetWrapper::INSTANCE_KEY])) { + throw new RuntimeError('The PhpSpreadsheetWrapper instance is missing.'); + } + + return $context[PhpSpreadsheetWrapper::INSTANCE_KEY]->getCurrentRow(); } } diff --git a/src/Wrapper/BaseWrapper.php b/src/Wrapper/BaseWrapper.php index 57f9cb6..4b3bdc0 100644 --- a/src/Wrapper/BaseWrapper.php +++ b/src/Wrapper/BaseWrapper.php @@ -2,80 +2,37 @@ namespace MewesK\TwigSpreadsheetBundle\Wrapper; -/** - * Class BaseWrapper. - */ abstract class BaseWrapper { - /** - * @var array - */ - protected $context; - - /** - * @var \Twig_Environment - */ - protected $environment; + protected array $parameters = []; - /** - * @var array - */ - protected $parameters; - /** - * @var array - */ - protected $mappings; + protected array $mappings = []; - /** - * BaseWrapper constructor. - * - * @param array $context - * @param \Twig_Environment $environment - */ - public function __construct(array $context, \Twig_Environment $environment) + public function __construct(protected array $context, protected \Twig\Environment $environment) { - $this->context = $context; - $this->environment = $environment; - - $this->parameters = []; $this->mappings = $this->configureMappings(); } - /** - * @return array - */ public function getParameters(): array { return $this->parameters; } - /** - * @param array $parameters - */ public function setParameters(array $parameters) { $this->parameters = $parameters; } - /** - * @return array - */ public function getMappings(): array { return $this->mappings; } - /** - * @param array $mappings - */ - public function setMappings(array $mappings) + public function setMappings(array $mappings): void { $this->mappings = $mappings; } - /** - * @return array - */ protected function configureMappings(): array { return []; @@ -84,15 +41,11 @@ protected function configureMappings(): array /** * Calls the matching mapping callable for each property. * - * @param array $properties - * @param array|null $mappings - * @param string|null $column - * * @throws \RuntimeException */ - protected function setProperties(array $properties, array $mappings = null, string $column = null) + protected function setProperties(array $properties, array $mappings = null, string $column = null): void { - if ($mappings === null) { + if (null === $mappings) { $mappings = $this->mappings; } @@ -105,9 +58,6 @@ protected function setProperties(array $properties, array $mappings = null, stri // recursion if (isset($mappings[$key]['__multi'])) { // handle multi target structure (with columns) - /** - * @var array $value - */ foreach ($value as $_column => $_value) { $this->setProperties($_value, $mappings[$key], $_column); } @@ -120,7 +70,7 @@ protected function setProperties(array $properties, array $mappings = null, stri // if column is set it is used to get object from the callback in __multi $mappings[$key]( $value, - $column !== null ? $mappings['__multi']($column) : null + null !== $column ? $mappings['__multi']($column) : null ); } else { throw new \RuntimeException(sprintf('Invalid mapping for key "%s"', $key)); diff --git a/src/Wrapper/CellWrapper.php b/src/Wrapper/CellWrapper.php index 81fe104..24587f9 100644 --- a/src/Wrapper/CellWrapper.php +++ b/src/Wrapper/CellWrapper.php @@ -4,103 +4,80 @@ use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Exception; +use Twig\Environment; -/** - * Class CellWrapper. - */ class CellWrapper extends BaseWrapper { - /** - * @var SheetWrapper - */ - protected $sheetWrapper; - - /** - * @var Cell|null - */ - protected $object; + protected ?Cell $object = null; - /** - * CellWrapper constructor. - * - * @param array $context - * @param \Twig_Environment $environment - * @param SheetWrapper $sheetWrapper - */ - public function __construct(array $context, \Twig_Environment $environment, SheetWrapper $sheetWrapper) + public function __construct(array $context, Environment $environment, protected SheetWrapper $sheetWrapper) { parent::__construct($context, $environment); - - $this->sheetWrapper = $sheetWrapper; - - $this->object = null; } /** - * @param int|null $index - * @param mixed|null $value - * @param array $properties - * * @throws \InvalidArgumentException * @throws \LogicException - * @throws \PhpOffice\PhpSpreadsheet\Exception * @throws \RuntimeException */ - public function start(int $index = null, $value = null, array $properties = []) + public function start(int $index = null, array $properties = []): void { - if ($this->sheetWrapper->getObject() === null) { + if (null === $this->sheetWrapper->getObject()) { throw new \LogicException(); } - if ($index === null) { + if (null === $index) { $this->sheetWrapper->increaseColumn(); } else { $this->sheetWrapper->setColumn($index); } - $this->object = $this->sheetWrapper->getObject()->getCellByColumnAndRow($this->sheetWrapper->getColumn(), + $this->object = $this->sheetWrapper->getObject()->getCellByColumnAndRow( + $this->sheetWrapper->getColumn(), $this->sheetWrapper->getRow()); - if ($value !== null) { - if (isset($properties['dataType'])) { - $this->object->setValueExplicit($value, $properties['dataType']); + $this->parameters['value'] = null; + $this->parameters['properties'] = $properties; + $this->setProperties($properties); + } + + /** + * @param mixed|null $value + * + * @throws Exception + */ + public function value($value = null) + { + if (null !== $value) { + if (isset($this->parameters['properties']['dataType'])) { + $this->object->setValueExplicit($value, $this->parameters['properties']['dataType']); } else { $this->object->setValue($value); } } $this->parameters['value'] = $value; - $this->parameters['properties'] = $properties; - - $this->setProperties($properties); } - public function end() + public function end(): void { $this->object = null; $this->parameters = []; } - /** - * @return Cell|null - */ - public function getObject() + public function getObject(): ?Cell { return $this->object; } - /** - * @param Cell|null $object - */ - public function setObject(Cell $object = null) + public function setObject(Cell $object = null): void { $this->object = $object; } /** * {@inheritdoc} - * - * @throws \PhpOffice\PhpSpreadsheet\Exception */ protected function configureMappings(): array { @@ -126,6 +103,7 @@ protected function configureMappings(): array if (\is_int($value)) { $value = Coordinate::stringFromColumnIndex($value).$this->sheetWrapper->getRow(); } + $this->sheetWrapper->getObject()->mergeCells(sprintf('%s:%s', $this->object->getCoordinate(), $value)); }, 'style' => function ($value) { $this->sheetWrapper->getObject()->getStyle($this->object->getCoordinate())->applyFromArray($value); }, diff --git a/src/Wrapper/DocumentWrapper.php b/src/Wrapper/DocumentWrapper.php index 1895d51..c2cda09 100644 --- a/src/Wrapper/DocumentWrapper.php +++ b/src/Wrapper/DocumentWrapper.php @@ -2,51 +2,36 @@ namespace MewesK\TwigSpreadsheetBundle\Wrapper; +use InvalidArgumentException; +use LogicException; use MewesK\TwigSpreadsheetBundle\Helper\Filesystem; -use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\IOFactory; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\BaseWriter; +use PhpOffice\PhpSpreadsheet\Writer\Csv; +use PhpOffice\PhpSpreadsheet\Writer\Exception; use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf; +use RuntimeException; use Symfony\Bridge\Twig\AppVariable; +use Symfony\Component\Filesystem\Exception\IOException; +use Twig\Environment; +use Twig\Loader\FilesystemLoader; -/** - * Class DocumentWrapper. - */ class DocumentWrapper extends BaseWrapper { - /** - * @var Spreadsheet|null - */ - protected $object; - /** - * @var array - */ - protected $attributes; + protected ?Spreadsheet $object = null; - /** - * DocumentWrapper constructor. - * - * @param array $context - * @param \Twig_Environment $environment - * @param array $attributes - */ - public function __construct(array $context, \Twig_Environment $environment, array $attributes = []) + public function __construct(array $context, Environment $environment, protected array $attributes = []) { parent::__construct($context, $environment); - - $this->object = null; - $this->attributes = $attributes; } /** - * @param array $properties - * - * @throws \RuntimeException + * @throws RuntimeException * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception * @throws \PhpOffice\PhpSpreadsheet\Exception */ - public function start(array $properties = []) + public function start(array $properties = []): void { // load template if (isset($properties['template'])) { @@ -67,17 +52,17 @@ public function start(array $properties = []) } /** - * @throws \LogicException - * @throws \RuntimeException - * @throws \InvalidArgumentException + * @throws LogicException + * @throws RuntimeException + * @throws InvalidArgumentException * @throws \PhpOffice\PhpSpreadsheet\Exception - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception - * @throws \Symfony\Component\Filesystem\Exception\IOException + * @throws Exception + * @throws IOException */ - public function end() + public function end(): void { - if ($this->object === null) { - throw new \LogicException(); + if (null === $this->object) { + throw new LogicException(); } $format = null; @@ -87,29 +72,26 @@ public function end() $format = $this->parameters['format']; } - // try Symfony request + // try Symfony request elseif (isset($this->context['app'])) { /** - * @var AppVariable + * @var AppVariable $appVariable */ $appVariable = $this->context['app']; - if ($appVariable instanceof AppVariable && $appVariable->getRequest() !== null) { + if ($appVariable instanceof AppVariable && null !== $appVariable->getRequest()) { $format = $appVariable->getRequest()->getRequestFormat(); } } // set default - if ($format === null || !\is_string($format)) { - $format = 'xlsx'; - } else { - $format = strtolower($format); - } + $format = \is_string($format) ? strtolower($format) : 'xlsx'; // set up mPDF - if ($format === 'pdf') { - if (!class_exists('\Mpdf\Mpdf')) { - throw new \RuntimeException('Error loading mPDF. Is mPDF correctly installed?'); + if ('pdf' === $format) { + if (!class_exists(\Mpdf\Mpdf::class)) { + throw new RuntimeException('Error loading mPDF. Is mPDF correctly installed?'); } + IOFactory::registerWriter('Pdf', Mpdf::class); } @@ -117,40 +99,46 @@ public function end() * @var BaseWriter $writer */ $writer = IOFactory::createWriter($this->object, ucfirst($format)); - $writer->setPreCalculateFormulas($this->attributes['preCalculateFormulas'] ?? true); + $writer->setPreCalculateFormulas($this->attributes['pre_calculate_formulas'] ?? true); // set up XML cache - if ($this->attributes['cache']['xml'] !== false) { + if (false !== $this->attributes['cache']['xml']) { Filesystem::mkdir($this->attributes['cache']['xml']); $writer->setUseDiskCaching(true, $this->attributes['cache']['xml']); } + // set special CSV writer attributes + if ($writer instanceof Csv) { + /* + * @var Csv $writer + */ + $writer->setDelimiter($this->attributes['csv_writer']['delimiter']); + $writer->setEnclosure($this->attributes['csv_writer']['enclosure']); + $writer->setExcelCompatibility($this->attributes['csv_writer']['excel_compatibility']); + $writer->setIncludeSeparatorLine($this->attributes['csv_writer']['include_separator_line']); + $writer->setLineEnding($this->attributes['csv_writer']['line_ending']); + $writer->setSheetIndex($this->attributes['csv_writer']['sheet_index']); + $writer->setUseBOM($this->attributes['csv_writer']['use_bom']); + } + $writer->save('php://output'); $this->object = null; $this->parameters = []; } - /** - * @return Spreadsheet|null - */ - public function getObject() + public function getObject(): ?Spreadsheet { return $this->object; } - /** - * @param Spreadsheet|null $object - */ - public function setObject(Spreadsheet $object = null) + public function setObject(Spreadsheet $object = null): void { $this->object = $object; } /** * {@inheritdoc} - * - * @throws \PhpOffice\PhpSpreadsheet\Exception */ protected function configureMappings(): array { @@ -183,21 +171,17 @@ protected function configureMappings(): array * Resolves paths using Twig namespaces. * The path must start with the namespace. * Namespaces are case sensitive. - * - * @param string $path - * - * @return string */ private function expandPath(string $path): string { $loader = $this->environment->getLoader(); - if ($loader instanceof \Twig_Loader_Filesystem && mb_strpos($path, '@') === 0) { + if ($loader instanceof FilesystemLoader && str_starts_with($path, '@')) { /* - * @var \Twig_Loader_Filesystem + * @var \Twig\Loader\FilesystemLoader */ foreach ($loader->getNamespaces() as $namespace) { - if (mb_strpos($path, $namespace) === 1) { + if (1 === mb_strpos($path, $namespace)) { foreach ($loader->getPaths($namespace) as $namespacePath) { $expandedPathAttribute = str_replace('@'.$namespace, $namespacePath, $path); if (Filesystem::exists($expandedPathAttribute)) { diff --git a/src/Wrapper/DrawingWrapper.php b/src/Wrapper/DrawingWrapper.php index d7d015e..b8450dc 100644 --- a/src/Wrapper/DrawingWrapper.php +++ b/src/Wrapper/DrawingWrapper.php @@ -6,62 +6,28 @@ use PhpOffice\PhpSpreadsheet\Worksheet\Drawing; use PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing; -/** - * Class DrawingWrapper. - */ class DrawingWrapper extends BaseWrapper { - /** - * @var SheetWrapper - */ - protected $sheetWrapper; - /** - * @var HeaderFooterWrapper - */ - protected $headerFooterWrapper; - /** * @var Drawing|HeaderFooterDrawing|null */ - protected $object; - /** - * @var array - */ - protected $attributes; + protected $object = null; - /** - * DrawingWrapper constructor. - * - * @param array $context - * @param \Twig_Environment $environment - * @param SheetWrapper $sheetWrapper - * @param HeaderFooterWrapper $headerFooterWrapper - * @param array $attributes - */ - public function __construct(array $context, \Twig_Environment $environment, SheetWrapper $sheetWrapper, HeaderFooterWrapper $headerFooterWrapper, array $attributes = []) + public function __construct(array $context, \Twig\Environment $environment, protected SheetWrapper $sheetWrapper, protected HeaderFooterWrapper $headerFooterWrapper, protected array $attributes = []) { parent::__construct($context, $environment); - - $this->sheetWrapper = $sheetWrapper; - $this->headerFooterWrapper = $headerFooterWrapper; - - $this->object = null; - $this->attributes = $attributes; } /** - * @param string $path - * @param array $properties - * * @throws \Symfony\Component\Filesystem\Exception\IOException * @throws \LogicException * @throws \InvalidArgumentException * @throws \RuntimeException * @throws \PhpOffice\PhpSpreadsheet\Exception */ - public function start(string $path, array $properties = []) + public function start(string $path, array $properties = []): void { - if ($this->sheetWrapper->getObject() === null) { + if (null === $this->sheetWrapper->getObject()) { throw new \LogicException(); } @@ -69,7 +35,7 @@ public function start(string $path, array $properties = []) $tempPath = $this->createTempCopy($path); // add to header/footer - if ($this->headerFooterWrapper->getObject()) { + if (null !== $this->headerFooterWrapper->getObject()) { $headerFooterParameters = $this->headerFooterWrapper->getParameters(); $alignment = $this->headerFooterWrapper->getAlignmentParameters()['type']; $location = ''; @@ -91,7 +57,7 @@ public function start(string $path, array $properties = []) throw new \InvalidArgumentException(sprintf('Unknown alignment type "%s"', $alignment)); } - $location .= $headerFooterParameters['baseType'] === HeaderFooterWrapper::BASETYPE_HEADER ? 'H' : 'F'; + $location .= HeaderFooterWrapper::BASETYPE_HEADER === $headerFooterParameters['baseType'] ? 'H' : 'F'; $this->object = new HeaderFooterDrawing(); $this->object->setPath($tempPath); @@ -109,24 +75,18 @@ public function start(string $path, array $properties = []) $this->setProperties($properties); } - public function end() + public function end(): void { $this->object = null; $this->parameters = []; } - /** - * @return Drawing - */ public function getObject(): Drawing { return $this->object; } - /** - * @param Drawing $object - */ - public function setObject(Drawing $object) + public function setObject(Drawing $object): void { $this->object = $object; } @@ -159,25 +119,22 @@ protected function configureMappings(): array } /** - * @param string $path - * * @throws \InvalidArgumentException * @throws \Symfony\Component\Filesystem\Exception\IOException - * - * @return string */ private function createTempCopy(string $path): string { // create temp path - $extension = pathinfo($path, PATHINFO_EXTENSION); - $tempPath = sprintf('%s/tsb_%s%s', $this->attributes['cache']['bitmap'], md5($path), $extension ? '.'.$extension : ''); + $extension = pathinfo($path, \PATHINFO_EXTENSION); + $tempPath = sprintf('%s/tsb_%s%s', $this->attributes['cache']['bitmap'], md5($path), '' !== $extension && '0' !== $extension ? '.'.$extension : ''); // create local copy if (!Filesystem::exists($tempPath)) { $data = file_get_contents($path); - if ($data === false) { + if (false === $data) { throw new \InvalidArgumentException($path.' does not exist.'); } + Filesystem::dumpFile($tempPath, $data); unset($data); } diff --git a/src/Wrapper/HeaderFooterWrapper.php b/src/Wrapper/HeaderFooterWrapper.php index df2612e..804d8ea 100644 --- a/src/Wrapper/HeaderFooterWrapper.php +++ b/src/Wrapper/HeaderFooterWrapper.php @@ -3,60 +3,61 @@ namespace MewesK\TwigSpreadsheetBundle\Wrapper; use PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooter; +use Twig\Environment; -/** - * Class HeaderFooterWrapper. - */ class HeaderFooterWrapper extends BaseWrapper { - const ALIGNMENT_CENTER = 'center'; - const ALIGNMENT_LEFT = 'left'; - const ALIGNMENT_RIGHT = 'right'; + /** + * @var string + */ + public const ALIGNMENT_CENTER = 'center'; - const BASETYPE_FOOTER = 'footer'; - const BASETYPE_HEADER = 'header'; + /** + * @var string + */ + public const ALIGNMENT_LEFT = 'left'; - const TYPE_EVEN = 'even'; - const TYPE_FIRST = 'first'; - const TYPE_ODD = 'odd'; + /** + * @var string + */ + public const ALIGNMENT_RIGHT = 'right'; /** - * @var SheetWrapper + * @var string */ - protected $sheetWrapper; + public const BASETYPE_FOOTER = 'footer'; /** - * @var HeaderFooter|null + * @var string */ - protected $object; + public const BASETYPE_HEADER = 'header'; + /** - * @var array + * @var string */ - protected $alignmentParameters; + public const TYPE_EVEN = 'even'; /** - * HeaderFooterWrapper constructor. - * - * @param array $context - * @param \Twig_Environment $environment - * @param SheetWrapper $sheetWrapper + * @var string */ - public function __construct(array $context, \Twig_Environment $environment, SheetWrapper $sheetWrapper) - { - parent::__construct($context, $environment); + public const TYPE_FIRST = 'first'; - $this->sheetWrapper = $sheetWrapper; + /** + * @var string + */ + public const TYPE_ODD = 'odd'; - $this->object = null; - $this->alignmentParameters = []; + protected ?HeaderFooter $object = null; + + protected array $alignmentParameters = []; + + public function __construct(array $context, Environment $environment, protected SheetWrapper $sheetWrapper) + { + parent::__construct($context, $environment); } /** - * @param string $alignment - * * @throws \InvalidArgumentException - * - * @return string */ public static function validateAlignment(string $alignment): string { @@ -68,11 +69,7 @@ public static function validateAlignment(string $alignment): string } /** - * @param string $baseType - * * @throws \InvalidArgumentException - * - * @return string */ public static function validateBaseType(string $baseType): string { @@ -84,21 +81,17 @@ public static function validateBaseType(string $baseType): string } /** - * @param string $baseType - * @param string|null $type - * @param array $properties - * * @throws \InvalidArgumentException * @throws \LogicException * @throws \RuntimeException */ - public function start(string $baseType, string $type = null, array $properties = []) + public function start(string $baseType, string $type = null, array $properties = []): void { - if ($this->sheetWrapper->getObject() === null) { + if (null === $this->sheetWrapper->getObject()) { throw new \LogicException(); } - if ($type !== null) { + if (null !== $type) { $type = strtolower($type); if (!\in_array($type, [self::TYPE_EVEN, self::TYPE_FIRST, self::TYPE_ODD], true)) { @@ -119,9 +112,9 @@ public function start(string $baseType, string $type = null, array $properties = * @throws \InvalidArgumentException * @throws \LogicException */ - public function end() + public function end(): void { - if ($this->object === null) { + if (null === $this->object) { throw new \LogicException(); } @@ -129,7 +122,7 @@ public function end() switch ($this->parameters['type']) { case null: - if ($this->parameters['baseType'] === self::BASETYPE_HEADER) { + if (self::BASETYPE_HEADER === $this->parameters['baseType']) { $this->object->setOddHeader($value); $this->object->setEvenHeader($value); $this->object->setFirstHeader($value); @@ -138,30 +131,34 @@ public function end() $this->object->setEvenFooter($value); $this->object->setFirstFooter($value); } + break; case self::TYPE_EVEN: $this->object->setDifferentOddEven(true); - if ($this->parameters['baseType'] === self::BASETYPE_HEADER) { + if (self::BASETYPE_HEADER === $this->parameters['baseType']) { $this->object->setEvenHeader($value); } else { $this->object->setEvenFooter($value); } + break; case self::TYPE_FIRST: $this->object->setDifferentFirst(true); - if ($this->parameters['baseType'] === self::BASETYPE_HEADER) { + if (self::BASETYPE_HEADER === $this->parameters['baseType']) { $this->object->setFirstHeader($value); } else { $this->object->setFirstFooter($value); } + break; case self::TYPE_ODD: $this->object->setDifferentOddEven(true); - if ($this->parameters['baseType'] === self::BASETYPE_HEADER) { + if (self::BASETYPE_HEADER === $this->parameters['baseType']) { $this->object->setOddHeader($value); } else { $this->object->setOddFooter($value); } + break; } @@ -170,15 +167,12 @@ public function end() } /** - * @param string $alignment - * @param array $properties - * * @throws \InvalidArgumentException * @throws \LogicException */ - public function startAlignment(string $alignment, array $properties = []) + public function startAlignment(string $alignment, array $properties = []): void { - if ($this->object === null) { + if (null === $this->object) { throw new \LogicException(); } @@ -206,47 +200,35 @@ public function startAlignment(string $alignment, array $properties = []) * @throws \InvalidArgumentException * @throws \LogicException */ - public function endAlignment($value) + public function endAlignment($value): void { - if ($this->object === null || !isset($this->alignmentParameters['type'])) { + if (null === $this->object || !isset($this->alignmentParameters['type'])) { throw new \LogicException(); } - if (strpos($this->parameters['value'][$this->alignmentParameters['type']], '&G') === false) { + if (!str_contains($this->parameters['value'][$this->alignmentParameters['type']], '&G')) { $this->parameters['value'][$this->alignmentParameters['type']] .= $value; } $this->alignmentParameters = []; } - /** - * @return null|HeaderFooter - */ - public function getObject() + public function getObject(): ?HeaderFooter { return $this->object; } - /** - * @param null|HeaderFooter $object - */ - public function setObject(HeaderFooter $object = null) + public function setObject(HeaderFooter $object = null): void { $this->object = $object; } - /** - * @return array - */ public function getAlignmentParameters(): array { return $this->alignmentParameters; } - /** - * @param array $alignmentParameters - */ - public function setAlignmentParameters(array $alignmentParameters) + public function setAlignmentParameters(array $alignmentParameters): void { $this->alignmentParameters = $alignmentParameters; } diff --git a/src/Wrapper/PhpSpreadsheetWrapper.php b/src/Wrapper/PhpSpreadsheetWrapper.php index 6f37035..0336335 100644 --- a/src/Wrapper/PhpSpreadsheetWrapper.php +++ b/src/Wrapper/PhpSpreadsheetWrapper.php @@ -2,58 +2,28 @@ namespace MewesK\TwigSpreadsheetBundle\Wrapper; -/** - * Class PhpSpreadsheetWrapper. - */ +use Twig\Environment; + class PhpSpreadsheetWrapper { /** * @var string */ - const INSTANCE_KEY = '_tsb'; + public const INSTANCE_KEY = '_tsb'; - /** - * @var DocumentWrapper - */ - private $documentWrapper; - /** - * @var SheetWrapper - */ - private $sheetWrapper; - /** - * @var RowWrapper - */ - private $rowWrapper; - /** - * @var CellWrapper - */ - private $cellWrapper; - /** - * @var HeaderFooterWrapper - */ - private $headerFooterWrapper; - /** - * @var DrawingWrapper - */ - private $drawingWrapper; + private DocumentWrapper $documentWrapper; - /** - * @var int|null - */ - private $cellIndex; - /** - * @var int|null - */ - private $rowIndex; + private SheetWrapper $sheetWrapper; - /** - * PhpSpreadsheetWrapper constructor. - * - * @param array $context - * @param \Twig_Environment $environment - * @param array $attributes - */ - public function __construct(array $context, \Twig_Environment $environment, array $attributes = []) + private RowWrapper $rowWrapper; + + private CellWrapper $cellWrapper; + + private HeaderFooterWrapper $headerFooterWrapper; + + private DrawingWrapper $drawingWrapper; + + public function __construct(array $context, Environment $environment, array $attributes = []) { $this->documentWrapper = new DocumentWrapper($context, $environment, $attributes); $this->sheetWrapper = new SheetWrapper($context, $environment, $this->documentWrapper); @@ -64,20 +34,17 @@ public function __construct(array $context, \Twig_Environment $environment, arra } /** - * @param array $context - * - * @return array + * Copies the PhpSpreadsheetWrapper instance from 'varargs' to '_tsb'. This is necessary for all Twig code running + * in sub-functions (e.g. block, macro, ...) since the root context is lost. To fix the sub-context a reference to + * the PhpSpreadsheetWrapper instance is included in all function calls. */ public static function fixContext(array $context): array { if (!isset($context[self::INSTANCE_KEY]) && isset($context['varargs']) && \is_array($context['varargs'])) { - /** - * @var array $args - */ - $args = $context['varargs']; - foreach ($args as $arg) { + foreach ($context['varargs'] as $arg) { if ($arg instanceof self) { $context[self::INSTANCE_KEY] = $arg; + break; } } } @@ -85,39 +52,47 @@ public static function fixContext(array $context): array return $context; } + public function getCurrentColumn(): ?int + { + return $this->sheetWrapper->getColumn(); + } + + public function getCurrentRow(): ?int + { + return $this->sheetWrapper->getRow(); + } + /** - * @param array $properties - * * @throws \PhpOffice\PhpSpreadsheet\Exception * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception * @throws \RuntimeException */ - public function startDocument(array $properties = []) + public function startDocument(array $properties = []): void { $this->documentWrapper->start($properties); } /** + * @throws \RuntimeException * @throws \LogicException * @throws \InvalidArgumentException * @throws \PhpOffice\PhpSpreadsheet\Exception * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception * @throws \Symfony\Component\Filesystem\Exception\IOException */ - public function endDocument() + public function endDocument(): void { $this->documentWrapper->end(); } /** * @param int|string|null $index - * @param array $properties * * @throws \LogicException * @throws \PhpOffice\PhpSpreadsheet\Exception * @throws \RuntimeException */ - public function startSheet($index = null, array $properties = []) + public function startSheet($index = null, array $properties = []): void { $this->sheetWrapper->start($index, $properties); } @@ -126,7 +101,7 @@ public function startSheet($index = null, array $properties = []) * @throws \LogicException * @throws \Exception */ - public function endSheet() + public function endSheet(): void { $this->sheetWrapper->end(); } @@ -134,48 +109,50 @@ public function endSheet() /** * @throws \LogicException */ - public function startRow() + public function startRow(int $index = null): void { - $this->rowWrapper->start($this->rowIndex); + $this->rowWrapper->start($index); } /** * @throws \LogicException */ - public function endRow() + public function endRow(): void { $this->rowWrapper->end(); } /** - * @param null|mixed $value - * @param array $properties - * * @throws \InvalidArgumentException * @throws \LogicException - * @throws \PhpOffice\PhpSpreadsheet\Exception * @throws \RuntimeException */ - public function startCell($value = null, array $properties = []) + public function startCell(int $index = null, array $properties = []): void + { + $this->cellWrapper->start($index, $properties); + } + + /** + * @param mixed|null $value + * + * @throws \PhpOffice\PhpSpreadsheet\Exception + */ + public function setCellValue($value = null): void { - $this->cellWrapper->start($this->cellIndex, $value, $properties); + $this->cellWrapper->value($value); } - public function endCell() + public function endCell(): void { $this->cellWrapper->end(); } /** - * @param string $baseType - * @param string|null $type - * @param array $properties - * * @throws \LogicException * @throws \RuntimeException * @throws \InvalidArgumentException */ - public function startHeaderFooter(string $baseType, string $type = null, array $properties = []) + public function startHeaderFooter(string $baseType, string $type = null, array $properties = []): void { $this->headerFooterWrapper->start($baseType, $type, $properties); } @@ -184,95 +161,43 @@ public function startHeaderFooter(string $baseType, string $type = null, array $ * @throws \LogicException * @throws \InvalidArgumentException */ - public function endHeaderFooter() + public function endHeaderFooter(): void { $this->headerFooterWrapper->end(); } /** - * @param null|string $type - * @param array $properties - * * @throws \InvalidArgumentException * @throws \LogicException */ - public function startAlignment(string $type = null, array $properties = []) + public function startAlignment(string $type = null, array $properties = []): void { $this->headerFooterWrapper->startAlignment($type, $properties); } /** - * @param null|string $value - * * @throws \InvalidArgumentException * @throws \LogicException */ - public function endAlignment(string $value = null) + public function endAlignment(string $value = null): void { $this->headerFooterWrapper->endAlignment($value); } /** - * @param string $path - * @param array $properties - * * @throws \Symfony\Component\Filesystem\Exception\IOException * @throws \InvalidArgumentException * @throws \LogicException * @throws \RuntimeException * @throws \PhpOffice\PhpSpreadsheet\Exception */ - public function startDrawing(string $path, array $properties = []) + public function startDrawing(string $path, array $properties = []): void { $this->drawingWrapper->start($path, $properties); } - public function endDrawing() + public function endDrawing(): void { $this->drawingWrapper->end(); } - - /** - * @return int|null - */ - public function getCellIndex() - { - return $this->cellIndex; - } - - /** - * @param int|null $cellIndex - */ - public function setCellIndex(int $cellIndex = null) - { - $this->cellIndex = $cellIndex; - } - - /** - * @return int|null - */ - public function getRowIndex() - { - return $this->rowIndex; - } - - /** - * @param int|null $rowIndex - */ - public function setRowIndex(int $rowIndex = null) - { - $this->rowIndex = $rowIndex; - } - - /** - * Returns the current row of the sheet. - * - * Since the row property of this PhpSpreadsheetWrapper remains null, - * a helper function that gets the row from SheetWrapper is used. - * - * @return int|null - */ - public function getSheetRow() { - return $this->sheetWrapper->getRow(); - } } diff --git a/src/Wrapper/RowWrapper.php b/src/Wrapper/RowWrapper.php index 7b14e7a..6f4aaf8 100644 --- a/src/Wrapper/RowWrapper.php +++ b/src/Wrapper/RowWrapper.php @@ -2,42 +2,25 @@ namespace MewesK\TwigSpreadsheetBundle\Wrapper; -/** - * Class SheetWrapper. - */ +use Twig\Environment; + class RowWrapper extends BaseWrapper { - /** - * @var SheetWrapper - */ - protected $sheetWrapper; - - /** - * RowWrapper constructor. - * - * @param array $context - * @param \Twig_Environment $environment - * @param SheetWrapper $sheetWrapper - */ - public function __construct(array $context, \Twig_Environment $environment, SheetWrapper $sheetWrapper) + public function __construct(array $context, Environment $environment, protected SheetWrapper $sheetWrapper) { parent::__construct($context, $environment); - - $this->sheetWrapper = $sheetWrapper; } /** - * @param null|int $index - * * @throws \LogicException */ - public function start(int $index = null) + public function start(int $index = null): void { - if ($this->sheetWrapper->getObject() === null) { + if (null === $this->sheetWrapper->getObject()) { throw new \LogicException(); } - if ($index === null) { + if (null === $index) { $this->sheetWrapper->increaseRow(); } else { $this->sheetWrapper->setRow($index); @@ -47,9 +30,9 @@ public function start(int $index = null) /** * @throws \LogicException */ - public function end() + public function end(): void { - if ($this->sheetWrapper->getObject() === null) { + if (null === $this->sheetWrapper->getObject()) { throw new \LogicException(); } diff --git a/src/Wrapper/SheetWrapper.php b/src/Wrapper/SheetWrapper.php index af2762f..a734ee9 100644 --- a/src/Wrapper/SheetWrapper.php +++ b/src/Wrapper/SheetWrapper.php @@ -3,71 +3,43 @@ namespace MewesK\TwigSpreadsheetBundle\Wrapper; use PhpOffice\PhpSpreadsheet\Exception; -use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use PhpOffice\PhpSpreadsheet\Worksheet\ColumnDimension; use PhpOffice\PhpSpreadsheet\Worksheet\RowDimension; +use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; -/** - * Class SheetWrapper. - */ class SheetWrapper extends BaseWrapper { /** * @var int */ - const COLUMN_DEFAULT = 1; + public const COLUMN_DEFAULT = 1; + /** * @var int */ - const ROW_DEFAULT = 1; + public const ROW_DEFAULT = 1; - /** - * @var DocumentWrapper - */ - protected $documentWrapper; + protected ?Worksheet $object = null; - /** - * @var Worksheet|null - */ - protected $object; - /** - * @var null|int - */ - protected $row; - /** - * @var null|int - */ - protected $column; + protected ?int $row = null; - /** - * SheetWrapper constructor. - * - * @param array $context - * @param \Twig_Environment $environment - * @param DocumentWrapper $documentWrapper - */ - public function __construct(array $context, \Twig_Environment $environment, DocumentWrapper $documentWrapper) + protected ?int $column = null; + + public function __construct(array $context, \Twig\Environment $environment, protected DocumentWrapper $documentWrapper) { parent::__construct($context, $environment); - - $this->documentWrapper = $documentWrapper; - - $this->object = null; - $this->row = null; - $this->column = null; } /** * @param int|string|null $index - * @param array $properties * * @throws \PhpOffice\PhpSpreadsheet\Exception * @throws \RuntimeException * @throws \LogicException */ - public function start($index, array $properties = []) + public function start($index, array $properties = []): void { - if ($this->documentWrapper->getObject() === null) { + if (null === $this->documentWrapper->getObject()) { throw new \LogicException(); } @@ -78,6 +50,7 @@ public function start($index, array $properties = []) // create new sheet with a name $this->documentWrapper->getObject()->createSheet()->setTitle($index); } + $this->object = $this->documentWrapper->getObject()->setActiveSheetIndexByName($index); } else { // create new sheet without a name @@ -95,9 +68,9 @@ public function start($index, array $properties = []) * @throws \Exception * @throws \LogicException */ - public function end() + public function end(): void { - if ($this->object === null) { + if (null === $this->object) { throw new \LogicException(); } @@ -112,7 +85,7 @@ public function end() $columnDimension = $this->parameters['properties']['columnDimension']; foreach ($columnDimension as $key => $value) { if (isset($value['autoSize'])) { - if ($key === 'default') { + if ('default' === $key) { try { $cellIterator = $this->object->getRowIterator()->current()->getCellIterator(); $cellIterator->setIterateOnlyExistingCells(true); @@ -120,7 +93,7 @@ public function end() foreach ($cellIterator as $cell) { $this->object->getColumnDimension($cell->getColumn())->setAutoSize($value['autoSize']); } - } catch (Exception $e) { + } catch (Exception) { // ignore exceptions thrown when no cells are defined } } else { @@ -130,91 +103,84 @@ public function end() } } - $this->object = null; $this->parameters = []; + $this->object = null; $this->row = null; + $this->column = null; } - public function increaseRow() + public function increaseRow(): void { - $this->row = $this->row === null ? self::ROW_DEFAULT : $this->row + 1; + $this->row = null === $this->row ? self::ROW_DEFAULT : $this->row + 1; } - public function increaseColumn() + public function increaseColumn(): void { - $this->column = $this->column === null ? self::COLUMN_DEFAULT : $this->column + 1; + $this->column = null === $this->column ? self::COLUMN_DEFAULT : $this->column + 1; } - /** - * @return Worksheet - */ public function getObject(): Worksheet { return $this->object; } - /** - * @param Worksheet $object - */ - public function setObject(Worksheet $object) + public function setObject(Worksheet $object): void { $this->object = $object; } - /** - * @return int|null - */ - public function getRow() + public function getRow(): ?int { return $this->row; } - /** - * @param int|null $row - */ - public function setRow($row) + public function setRow(?int $row): void { $this->row = $row; } - /** - * @return int|null - */ - public function getColumn() + public function getColumn(): ?int { return $this->column; } - /** - * @param int|null $column - */ - public function setColumn($column) + public function setColumn(?int $column): void { $this->column = $column; } /** * {@inheritdoc} - * - * @throws \PhpOffice\PhpSpreadsheet\Exception */ protected function configureMappings(): array { return [ 'autoFilter' => function ($value) { $this->object->setAutoFilter($value); }, 'columnDimension' => [ - '__multi' => function ($column = 'default'): ColumnDimension { - return $column === 'default' ? - $this->object->getDefaultColumnDimension() : - $this->object->getColumnDimension($column); + '__multi' => fn ($index = 'default'): ColumnDimension => 'default' === $index ? + $this->object->getDefaultColumnDimension() : + $this->object->getColumnDimension($index), + 'autoSize' => static function ($value, ColumnDimension $object) { + $object->setAutoSize($value); + }, + 'collapsed' => static function ($value, ColumnDimension $object) { + $object->setCollapsed($value); + }, + 'columnIndex' => static function ($value, ColumnDimension $object) { + $object->setColumnIndex($value); + }, + 'outlineLevel' => static function ($value, ColumnDimension $object) { + $object->setOutlineLevel($value); + }, + 'visible' => static function ($value, ColumnDimension $object) { + $object->setVisible($value); + }, + 'width' => static function ($value, ColumnDimension $object) { + $object->setWidth($value); + }, + 'xfIndex' => static function ($value, ColumnDimension $object) { + $object->setXfIndex($value); }, - 'autoSize' => function ($value, ColumnDimension $object) { $object->setAutoSize($value); }, - 'collapsed' => function ($value, ColumnDimension $object) { $object->setCollapsed($value); }, - 'columnIndex' => function ($value, ColumnDimension $object) { $object->setColumnIndex($value); }, - 'outlineLevel' => function ($value, ColumnDimension $object) { $object->setOutlineLevel($value); }, - 'visible' => function ($value, ColumnDimension $object) { $object->setVisible($value); }, - 'width' => function ($value, ColumnDimension $object) { $object->setWidth($value); }, - 'xfIndex' => function ($value, ColumnDimension $object) { $object->setXfIndex($value); }, ], 'pageMargins' => [ 'top' => function ($value) { $this->object->getPageMargins()->setTop($value); }, @@ -257,18 +223,30 @@ protected function configureMappings(): array ], 'rightToLeft' => function ($value) { $this->object->setRightToLeft($value); }, 'rowDimension' => [ - '__multi' => function ($column = 'default'): RowDimension { - return $column === 'default' ? - $this->object->getDefaultRowDimension() : - $this->object->getRowDimension($column); + '__multi' => fn ($index = 'default'): RowDimension => 'default' === $index ? + $this->object->getDefaultRowDimension() : + $this->object->getRowDimension($index), + 'collapsed' => static function ($value, RowDimension $object) { + $object->setCollapsed($value); + }, + 'outlineLevel' => static function ($value, RowDimension $object) { + $object->setOutlineLevel($value); + }, + 'rowHeight' => static function ($value, RowDimension $object) { + $object->setRowHeight($value); + }, + 'rowIndex' => static function ($value, RowDimension $object) { + $object->setRowIndex($value); + }, + 'visible' => static function ($value, RowDimension $object) { + $object->setVisible($value); + }, + 'xfIndex' => static function ($value, RowDimension $object) { + $object->setXfIndex($value); + }, + 'zeroHeight' => static function ($value, RowDimension $object) { + $object->setZeroHeight($value); }, - 'collapsed' => function ($value, RowDimension $object) { $object->setCollapsed($value); }, - 'outlineLevel' => function ($value, RowDimension $object) { $object->setOutlineLevel($value); }, - 'rowHeight' => function ($value, RowDimension $object) { $object->setRowHeight($value); }, - 'rowIndex' => function ($value, RowDimension $object) { $object->setRowIndex($value); }, - 'visible' => function ($value, RowDimension $object) { $object->setVisible($value); }, - 'xfIndex' => function ($value, RowDimension $object) { $object->setXfIndex($value); }, - 'zeroHeight' => function ($value, RowDimension $object) { $object->setZeroHeight($value); }, ], 'sheetState' => function ($value) { $this->object->setSheetState($value); }, 'showGridlines' => function ($value) { $this->object->setShowGridlines($value); }, diff --git a/tests/Functional/BaseFunctionalTest.php b/tests/Functional/BaseFunctionalTest.php deleted file mode 100644 index 2d526b2..0000000 --- a/tests/Functional/BaseFunctionalTest.php +++ /dev/null @@ -1,119 +0,0 @@ -setCacheDir(sprintf('%s/../../../var/cache/%s', $kernel->getRootDir(), str_replace('\\', DIRECTORY_SEPARATOR, static::class))); - $kernel->setLogDir(sprintf('%s/../../../var/logs/%s', $kernel->getRootDir(), str_replace('\\', DIRECTORY_SEPARATOR, static::class))); - - return $kernel; - } - - /** - * @throws \Symfony\Component\Filesystem\Exception\IOException - */ - public function setUp() - { - // create client - static::$client = static::createClient(['environment' => static::$ENVIRONMENT, 'debug' => false]); - } - - /** - * @param string $routeName - * @param array $routeParameters - * @param string $format - * - * @throws \Symfony\Component\Filesystem\Exception\IOException - * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception - * - * @return Spreadsheet - */ - protected function getDocument(string $routeName, array $routeParameters = [], string $format = 'xlsx'): Spreadsheet - { - // create document content - $content = $this->getResponse($routeName, $routeParameters)->getContent(); - - // create path for temp file - $format = strtolower($format); - $resultPath = sprintf('%s/%s/%s/%s.%s', __DIR__, static::RESULT_PATH, str_replace('\\', DIRECTORY_SEPARATOR, static::class), static::$ENVIRONMENT, $format); - - // save content - Filesystem::dumpFile($resultPath, $content); - - // load document - return IOFactory::createReader(ucfirst($format))->load($resultPath); - } - - /** - * @param string $routeName - * @param array $routeParameters - * - * @return Response - */ - protected function getResponse(string $routeName, array $routeParameters = []): Response - { - /** - * @var Router $router - */ - $router = static::$kernel->getContainer()->get('router'); - static::$client->request(Request::METHOD_GET, $router->generate($routeName, $routeParameters)); - - return static::$client->getResponse(); - } -} diff --git a/tests/Functional/ConfigFunctionalTest.php b/tests/Functional/ConfigFunctionalTest.php deleted file mode 100644 index d87e02d..0000000 --- a/tests/Functional/ConfigFunctionalTest.php +++ /dev/null @@ -1,50 +0,0 @@ -getContainer()->get('mewes_k_twig_spreadsheet.twig_spreadsheet_extension'); - - static::assertFalse($extension->getAttributes()['pre_calculate_formulas'], 'Unexpected attribute'); - } - - /** - * @throws \Exception - */ - public function testXmlCacheDirectory() - { - // make request to fill the disk cache - $response = $this->getResponse('test_default', ['templateName' => 'simple']); - static::assertNotNull($response, 'Response does not exist'); - - /** - * @var TwigSpreadsheetExtension $extension - */ - $extension = static::$kernel->getContainer()->get('mewes_k_twig_spreadsheet.twig_spreadsheet_extension'); - - static::assertDirectoryExists($extension->getAttributes()['cache']['xml'], 'Cache directory does not exist'); - } -} diff --git a/tests/Functional/Fixtures/TestAppKernel.php b/tests/Functional/Fixtures/TestAppKernel.php deleted file mode 100644 index f15c16a..0000000 --- a/tests/Functional/Fixtures/TestAppKernel.php +++ /dev/null @@ -1,78 +0,0 @@ -load(sprintf('%s/config/config_%s.yml', $this->rootDir, $this->getEnvironment())); - } - - /** - * {@inheritdoc} - */ - public function getCacheDir() - { - return $this->cacheDir; - } - - /** - * @param string $cacheDir - */ - public function setCacheDir(string $cacheDir) - { - $this->cacheDir = $cacheDir; - } - - /** - * {@inheritdoc} - */ - public function getLogDir() - { - return $this->logDir; - } - - /** - * @param string $logDir - */ - public function setLogDir(string $logDir) - { - $this->logDir = $logDir; - } -} diff --git a/tests/Functional/Fixtures/TestBundle/Controller/TestController.php b/tests/Functional/Fixtures/TestBundle/Controller/TestController.php deleted file mode 100644 index 5e401ab..0000000 --- a/tests/Functional/Fixtures/TestBundle/Controller/TestController.php +++ /dev/null @@ -1,86 +0,0 @@ -render( - '@Test/Default/'.$templateName.'.twig', - [ - 'data' => [ - ['name' => 'Everette Grim', 'salary' => 5458.0], - ['name' => 'Nam Poirrier', 'salary' => 3233.0], - ['name' => 'Jolynn Ell', 'salary' => 5718.0], - ['name' => 'Ta Burdette', 'salary' => 1255.0], - ['name' => 'Aida Salvas', 'salary' => 5226.0], - ['name' => 'Gilbert Navarrette', 'salary' => 1431.0], - ['name' => 'Kirk Figgins', 'salary' => 7429.0], - ['name' => 'Rashad Cloutier', 'salary' => 8457.0], - ['name' => 'Traci Schmitmeyer', 'salary' => 7521.0], - ['name' => 'Cecila Statham', 'salary' => 7180.0], - ['name' => 'Chong Robicheaux', 'salary' => 3511.0], - ['name' => 'Romona Stockstill', 'salary' => 2943.0], - ['name' => 'Roseann Sather', 'salary' => 9126.0], - ['name' => 'Vera Racette', 'salary' => 4566.0], - ['name' => 'Tennille Waltripv', 'salary' => 4485.0], - ['name' => 'Dot Hedgpeth', 'salary' => 7687.0], - ['name' => 'Thersa Havis', 'salary' => 2264.0], - ['name' => 'Long Kenner', 'salary' => 4051.0], - ['name' => 'Kena Kea', 'salary' => 4090.0], - ['name' => 'Evita Chittum', 'salary' => 4639.0], - ], - 'kernelPath' => $this->get('kernel')->getRootDir(), - ] - ); - } - - /** - * @param $templateName - * - * @throws \InvalidArgumentException - * - * @return \Symfony\Component\HttpFoundation\Response - * - * @Route("/custom-response/{templateName}.{_format}", name="test_custom_response", defaults={"templateName" = "simple", "_format" = "xlsx"}) - */ - public function customResponseAction($templateName): Response - { - $response = new Response( - $this->render( - '@Test/Default/'.$templateName.'.twig', - [ - 'data' => [ - ['name' => 'Everette Grim', 'salary' => 5458.0], - ['name' => 'Nam Poirrier', 'salary' => 3233.0], - ['name' => 'Jolynn Ell', 'salary' => 5718.0], - ], - ] - ) - ); - - $response->headers->set('Content-Disposition', $response->headers->makeDisposition( - ResponseHeaderBag::DISPOSITION_ATTACHMENT, - 'foobar.bin' - )); - $response->setMaxAge(600); - - return $response; - } -} diff --git a/tests/Functional/Fixtures/TestBundle/Resources/views/Default/documentTemplatePath1.twig b/tests/Functional/Fixtures/TestBundle/Resources/views/Default/documentTemplatePath1.twig deleted file mode 100644 index 8bde424..0000000 --- a/tests/Functional/Fixtures/TestBundle/Resources/views/Default/documentTemplatePath1.twig +++ /dev/null @@ -1,2 +0,0 @@ -{% xlsdocument { 'template': kernelPath ~ '/TestBundle/Resources/views/Default/template.xlsx' } %} -{% endxlsdocument %} diff --git a/tests/Functional/Fixtures/TestBundle/Resources/views/Default/documentTemplatePath2.twig b/tests/Functional/Fixtures/TestBundle/Resources/views/Default/documentTemplatePath2.twig deleted file mode 100644 index b078aef..0000000 --- a/tests/Functional/Fixtures/TestBundle/Resources/views/Default/documentTemplatePath2.twig +++ /dev/null @@ -1,2 +0,0 @@ -{% xlsdocument { 'template': '@Test/Default/template.xlsx' } %} -{% endxlsdocument %} diff --git a/tests/Functional/Fixtures/TestBundle/Resources/views/Default/simple.twig b/tests/Functional/Fixtures/TestBundle/Resources/views/Default/simple.twig deleted file mode 100644 index 0334155..0000000 --- a/tests/Functional/Fixtures/TestBundle/Resources/views/Default/simple.twig +++ /dev/null @@ -1,24 +0,0 @@ -{% xlsdocument %} - {% xlssheet 'Test' %} - {% xlsrow %} - {% xlscell %}Name{% endxlscell %} - {% xlscell %}Salary{% endxlscell %} - {% endxlsrow %} - {% set total = 0 %} - {% for entity in data %} - {% xlsrow %} - {% xlscell %}{{ entity['name'] }}{% endxlscell %} - {% xlscell %}{{ entity['salary']|raw }}{% endxlscell %} - {% endxlsrow %} - {% set total = total + entity['salary'] %} - {% endfor %} - {% xlsrow %} - {% xlscell %}Total (PHP){% endxlscell %} - {% xlscell %}{{ total }}{% endxlscell %} - {% endxlsrow %} - {% xlsrow %} - {% xlscell %}Total (Spreadsheet){% endxlscell %} - {% xlscell %}=SUM(B2:B21){% endxlscell %} - {% endxlsrow %} - {% endxlssheet %} -{% endxlsdocument %} diff --git a/tests/Functional/Fixtures/TestBundle/Resources/views/Default/template.xlsx b/tests/Functional/Fixtures/TestBundle/Resources/views/Default/template.xlsx deleted file mode 100644 index f55effa..0000000 Binary files a/tests/Functional/Fixtures/TestBundle/Resources/views/Default/template.xlsx and /dev/null differ diff --git a/tests/Functional/Fixtures/TestBundle/TestBundle.php b/tests/Functional/Fixtures/TestBundle/TestBundle.php deleted file mode 100644 index b1976c9..0000000 --- a/tests/Functional/Fixtures/TestBundle/TestBundle.php +++ /dev/null @@ -1,12 +0,0 @@ -getDocument('test_default', ['templateName' => 'simple', '_format' => $format], $format); - static::assertNotNull($document, 'Document does not exist'); - - $sheet = $document->getSheetByName('Test'); - static::assertNotNull($sheet, 'Sheet does not exist'); - - static::assertEquals(100270, $sheet->getCell('B22')->getValue(), 'Unexpected value in B22'); - - static::assertEquals('=SUM(B2:B21)', $sheet->getCell('B23')->getValue(), 'Unexpected value in B23'); - static::assertTrue($sheet->getCell('B23')->isFormula(), 'Unexpected value in isFormula'); - static::assertEquals(100270, $sheet->getCell('B23')->getCalculatedValue(), 'Unexpected calculated value in B23'); - } - - /** - * @param string $format - * - * @throws \Exception - * - * @dataProvider formatProvider - */ - public function testCustomResponse($format) - { - $response = $this->getResponse('test_custom_response', ['templateName' => 'simple', '_format' => $format]); - - static::assertNotNull($response, 'Response does not exist'); - static::assertContains('foobar.bin', $response->headers->get('Content-Disposition'), 'Unexpected or missing header "Content-Disposition"'); - static::assertEquals(600, $response->getMaxAge(), 'Unexpected value in maxAge'); - } - - /** - * @param string $format - * - * @throws \Exception - * - * @dataProvider formatProvider - */ - public function testDocumentTemplatePath1($format) - { - $document = $this->getDocument('test_default', ['templateName' => 'documentTemplatePath1', '_format' => $format], $format); - static::assertNotNull($document, 'Document does not exist'); - - $sheet = $document->getSheet(0); - static::assertNotNull($sheet, 'Sheet does not exist'); - - static::assertEquals('Hello', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); - static::assertEquals('World', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); - static::assertEquals('Foo', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); - static::assertEquals('Bar', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); - } - - /** - * @param string $format - * - * @throws \Exception - * - * @dataProvider formatProvider - */ - public function testDocumentTemplatePath2($format) - { - $document = $this->getDocument('test_default', ['templateName' => 'documentTemplatePath2', '_format' => $format], $format); - static::assertNotNull($document, 'Document does not exist'); - - $sheet = $document->getSheet(0); - static::assertNotNull($sheet, 'Sheet does not exist'); - - static::assertEquals('Hello', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); - static::assertEquals('World', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); - static::assertEquals('Foo', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); - static::assertEquals('Bar', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); - } -} diff --git a/tests/Twig/BaseTwigTest.php b/tests/Twig/BaseTwigTest.php index 441418c..1f77d76 100644 --- a/tests/Twig/BaseTwigTest.php +++ b/tests/Twig/BaseTwigTest.php @@ -10,63 +10,77 @@ use Symfony\Bridge\Twig\AppVariable; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; +use Twig\Environment; -/** - * Class BaseTwigTest. - */ abstract class BaseTwigTest extends TestCase { - const CACHE_PATH = './../../var/cache'; - const RESULT_PATH = './../../var/result'; - const RESOURCE_PATH = './Fixtures/views'; - const TEMPLATE_PATH = './Fixtures/templates'; + /** + * @var string + */ + public const CACHE_PATH = './../../var/cache'; + + /** + * @var string + */ + public const RESULT_PATH = './../../var/result'; + + /** + * @var string + */ + public const RESOURCE_PATH = './Fixtures/views'; /** - * @var \Twig_Environment + * @var string */ - protected static $environment; + public const TEMPLATE_PATH = './Fixtures/templates'; + + protected static Environment $environment; /** * {@inheritdoc} * - * @throws \Twig_Error_Loader + * @throws \Twig\Error\LoaderError */ - public static function setUpBeforeClass() + public static function setUpBeforeClass(): void { - $cachePath = sprintf('%s/%s/%s', __DIR__, static::CACHE_PATH, str_replace('\\', DIRECTORY_SEPARATOR, static::class)); + $cachePath = sprintf('%s/%s/%s', __DIR__, static::CACHE_PATH, str_replace('\\', \DIRECTORY_SEPARATOR, static::class)); // remove temp files Filesystem::remove($cachePath); - Filesystem::remove(sprintf('%s/%s/%s', __DIR__, static::RESULT_PATH, str_replace('\\', DIRECTORY_SEPARATOR, static::class))); + Filesystem::remove(sprintf('%s/%s/%s', __DIR__, static::RESULT_PATH, str_replace('\\', \DIRECTORY_SEPARATOR, static::class))); // set up Twig environment - $twigFileSystem = new \Twig_Loader_Filesystem([sprintf('%s/%s', __DIR__, static::RESOURCE_PATH)]); + $twigFileSystem = new \Twig\Loader\FilesystemLoader([sprintf('%s/%s', __DIR__, static::RESOURCE_PATH)]); $twigFileSystem->addPath(sprintf('%s/%s', __DIR__, static::TEMPLATE_PATH), 'templates'); - static::$environment = new \Twig_Environment($twigFileSystem, ['debug' => true, 'strict_variables' => true]); + static::$environment = new Environment($twigFileSystem, ['debug' => true, 'strict_variables' => true]); static::$environment->addExtension(new TwigSpreadsheetExtension([ 'pre_calculate_formulas' => true, 'cache' => [ 'bitmap' => $cachePath.'/spreadsheet/bitmap', - 'xml' => false + 'xml' => false, + ], + 'csv_writer' => [ + 'delimiter' => ',', + 'enclosure' => '"', + 'excel_compatibility' => false, + 'include_separator_line' => false, + 'line_ending' => \PHP_EOL, + 'sheet_index' => 0, + 'use_bom' => true, ], ])); static::$environment->setCache($cachePath.'/twig'); } /** - * @param string $templateName - * @param string $format - * - * @throws \Twig_Error_Syntax - * @throws \Twig_Error_Loader + * @throws \Twig\Error\SyntaxError + * @throws \Twig\Error\LoaderError * @throws \Symfony\Component\Filesystem\Exception\IOException - * - * @return Spreadsheet|string - * @throws \Twig_Error_Runtime + * @throws \Twig\Error\RuntimeError * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception */ - protected function getDocument($templateName, $format) + protected function getDocument(string $templateName, string $format): Spreadsheet|string { $format = strtolower($format); @@ -84,12 +98,15 @@ protected function getDocument($templateName, $format) $source = static::$environment->load($templateName.'.twig')->render(['app' => $appVariable]); // create path - $resultPath = sprintf('%s/%s/%s/%s.%s', __DIR__, static::RESULT_PATH, str_replace('\\', DIRECTORY_SEPARATOR, static::class), $templateName, $format); + $resultPath = sprintf('%s/%s/%s/%s.%s', __DIR__, static::RESULT_PATH, str_replace('\\', \DIRECTORY_SEPARATOR, static::class), $templateName, $format); // save source Filesystem::dumpFile($resultPath, $source); // load source or return path for PDFs - return $format === 'pdf' ? $resultPath : IOFactory::createReader(ucfirst($format))->load($resultPath); + return 'pdf' === $format + ? $resultPath + : IOFactory::createReader(ucfirst($format)) + ->load($resultPath); } } diff --git a/tests/Twig/CsvOdsXlsXlsxErrorTwigTest.php b/tests/Twig/CsvOdsXlsXlsxErrorTwigTest.php index ae6a98d..40ebf86 100644 --- a/tests/Twig/CsvOdsXlsXlsxErrorTwigTest.php +++ b/tests/Twig/CsvOdsXlsXlsxErrorTwigTest.php @@ -2,108 +2,78 @@ namespace MewesK\TwigSpreadsheetBundle\Tests\Twig; -/** - * Class CsvOdsXlsXlsxErrorTwigTest. - */ class CsvOdsXlsXlsxErrorTwigTest extends BaseTwigTest { - /** - * @return array - */ public function formatProvider(): array { return [['csv'], ['ods'], ['xls'], ['xlsx']]; } - // - // Tests - // - /** - * @param string $format - * * @throws \Exception - * * @dataProvider formatProvider */ - public function testCellIndexError($format) + public function testDocumentError(string $format): void { - $this->expectException(\TypeError::class); - $this->expectExceptionMessage('Argument 1 passed to MewesK\TwigSpreadsheetBundle\Wrapper\PhpSpreadsheetWrapper::setCellIndex() must be of the type integer'); + $this->expectException(\Twig\Error\SyntaxError::class); + $this->expectExceptionMessage('Node "MewesK\TwigSpreadsheetBundle\Twig\Node\DocumentNode" is not allowed inside of Node "MewesK\TwigSpreadsheetBundle\Twig\Node\SheetNode"'); - $this->getDocument('cellIndexError', $format); + $this->getDocument('documentError', $format); } /** - * @param string $format - * * @throws \Exception - * * @dataProvider formatProvider */ - public function testDocumentError($format) + public function testDocumentErrorTextAfter(string $format): void { - $this->expectException(\Twig_Error_Syntax::class); - $this->expectExceptionMessage('Node "MewesK\TwigSpreadsheetBundle\Twig\Node\DocumentNode" is not allowed inside of Node "MewesK\TwigSpreadsheetBundle\Twig\Node\SheetNode"'); + $this->expectException(\Twig\Error\SyntaxError::class); + $this->expectExceptionMessage('Node "'.\Twig\Node\TextNode::class.'" is not allowed after Node "MewesK\TwigSpreadsheetBundle\Twig\Node\DocumentNode"'); - $this->getDocument('documentError', $format); + $this->getDocument('documentErrorTextAfter', $format); } /** - * @param string $format - * * @throws \Exception - * * @dataProvider formatProvider */ - public function testDocumentErrorTextAfter($format) + public function testDocumentErrorTextBefore(string $format): void { - $this->expectException(\Twig_Error_Syntax::class); - $this->expectExceptionMessage('Node "Twig_Node_Text" is not allowed after Node "MewesK\TwigSpreadsheetBundle\Twig\Node\DocumentNode"'); + $this->expectException(\Twig\Error\SyntaxError::class); + $this->expectExceptionMessage('Node "'.\Twig\Node\TextNode::class.'" is not allowed before Node "MewesK\TwigSpreadsheetBundle\Twig\Node\DocumentNode"'); - $this->getDocument('documentErrorTextAfter', $format); + $this->getDocument('documentErrorTextBefore', $format); } /** - * @param string $format - * * @throws \Exception - * * @dataProvider formatProvider */ - public function testDocumentErrorTextBefore($format) + public function testStartCellIndexError(string $format): void { - $this->expectException(\Twig_Error_Syntax::class); - $this->expectExceptionMessage('Node "Twig_Node_Text" is not allowed before Node "MewesK\TwigSpreadsheetBundle\Twig\Node\DocumentNode"'); + $this->expectException(\TypeError::class); - $this->getDocument('documentErrorTextBefore', $format); + $this->getDocument('cellIndexError', $format); } /** - * @param string $format - * * @throws \Exception - * * @dataProvider formatProvider */ - public function testRowIndexError($format) + public function testStartRowIndexError(string $format): void { $this->expectException(\TypeError::class); - $this->expectExceptionMessage('Argument 1 passed to MewesK\TwigSpreadsheetBundle\Wrapper\PhpSpreadsheetWrapper::setRowIndex() must be of the type integer'); $this->getDocument('rowIndexError', $format); } /** - * @param string $format - * * @throws \Exception - * * @dataProvider formatProvider */ - public function testSheetError($format) + public function testSheetError(string $format): void { - $this->expectException(\Twig_Error_Syntax::class); + $this->expectException(\Twig\Error\SyntaxError::class); $this->expectExceptionMessage('Node "MewesK\TwigSpreadsheetBundle\Twig\Node\RowNode" is not allowed inside of Node "MewesK\TwigSpreadsheetBundle\Twig\Node\DocumentNode"'); $this->getDocument('sheetError', $format); diff --git a/tests/Twig/CsvOdsXlsXlsxTwigTest.php b/tests/Twig/CsvOdsXlsXlsxTwigTest.php index 2a0c88b..bd11fa9 100644 --- a/tests/Twig/CsvOdsXlsXlsxTwigTest.php +++ b/tests/Twig/CsvOdsXlsXlsxTwigTest.php @@ -2,31 +2,19 @@ namespace MewesK\TwigSpreadsheetBundle\Tests\Twig; -/** - * Class CsvOdsXlsXlsxTwigTest. - */ class CsvOdsXlsXlsxTwigTest extends BaseTwigTest { - /** - * @return array - */ public function formatProvider(): array { return [['csv'], ['ods'], ['xls'], ['xlsx']]; } - // - // Tests - // - /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testDocumentSimple($format) + public function testDocumentSimple(string $format): void { $document = $this->getDocument('documentSimple', $format); static::assertNotNull($document, 'Document does not exist'); @@ -34,20 +22,18 @@ public function testDocumentSimple($format) $sheet = $document->getActiveSheet(); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals('Foo', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); - static::assertEquals('Bar', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); - static::assertEquals('Hello', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); - static::assertEquals('World', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); + static::assertSame('Foo', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); + static::assertSame('Bar', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); + static::assertSame('Hello', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); + static::assertSame('World', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testDocumentTemplate($format) + public function testDocumentTemplate(string $format): void { $document = $this->getDocument('documentTemplate.'.$format, $format); static::assertNotNull($document, 'Document does not exist'); @@ -55,9 +41,28 @@ public function testDocumentTemplate($format) $sheet = $document->getSheet(0); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals('Hello2', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); - static::assertEquals('World', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); - static::assertEquals('Foo', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); - static::assertEquals('Bar2', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); + static::assertSame('Hello2', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); + static::assertSame('World', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); + static::assertSame('Foo', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); + static::assertSame('Bar2', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); + } + + /** + * @throws \Exception + * + * @dataProvider formatProvider + */ + public function testFunctionIndex(string $format): void + { + $document = $this->getDocument('functionIndex', $format); + static::assertNotNull($document, 'Document does not exist'); + + $sheet = $document->getSheet(0); + static::assertNotNull($sheet, 'Sheet does not exist'); + + static::assertSame(1, $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); + static::assertSame(2, $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); + static::assertNull($sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); + static::assertNull($sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); } } diff --git a/tests/Twig/Fixtures/views/cellProperties.twig b/tests/Twig/Fixtures/views/cellProperties.twig index f28e9e9..63bbfa1 100644 --- a/tests/Twig/Fixtures/views/cellProperties.twig +++ b/tests/Twig/Fixtures/views/cellProperties.twig @@ -23,7 +23,7 @@ 'size': 18.0 } }, - 'url': 'http://example.com/' + 'url': 'https://example.com/' } %}Foo{% endxlscell %} {% endxlsrow %} {% xlsrow %} diff --git a/tests/Twig/Fixtures/views/drawingProperties.twig b/tests/Twig/Fixtures/views/drawingProperties.twig index e3917f2..6f032cb 100644 --- a/tests/Twig/Fixtures/views/drawingProperties.twig +++ b/tests/Twig/Fixtures/views/drawingProperties.twig @@ -1,6 +1,6 @@ {% xlsdocument %} {% xlssheet 'Test' %} - {% xlsdrawing 'http://www.gravatar.com/avatar/0d9079a1311d9f89b0b28b13cea56a70?s=100' { + {% xlsdrawing 'https://www.gravatar.com/avatar/0d9079a1311d9f89b0b28b13cea56a70?s=100' { 'coordinates': 'B2', 'description': 'Test Description', 'height': 200, @@ -21,4 +21,4 @@ } } %} {% endxlssheet %} -{% endxlsdocument %} \ No newline at end of file +{% endxlsdocument %} diff --git a/tests/Twig/Fixtures/views/drawingSimple.twig b/tests/Twig/Fixtures/views/drawingSimple.twig index 542682c..fe55a77 100644 --- a/tests/Twig/Fixtures/views/drawingSimple.twig +++ b/tests/Twig/Fixtures/views/drawingSimple.twig @@ -1,5 +1,5 @@ {% xlsdocument %} {% xlssheet 'Test' %} - {% xlsdrawing 'http://www.gravatar.com/avatar/0d9079a1311d9f89b0b28b13cea56a70?s=100' %} + {% xlsdrawing 'https://www.gravatar.com/avatar/0d9079a1311d9f89b0b28b13cea56a70?s=100' %} {% endxlssheet %} -{% endxlsdocument %} \ No newline at end of file +{% endxlsdocument %} diff --git a/tests/Twig/Fixtures/views/functionIndex.twig b/tests/Twig/Fixtures/views/functionIndex.twig new file mode 100644 index 0000000..736c136 --- /dev/null +++ b/tests/Twig/Fixtures/views/functionIndex.twig @@ -0,0 +1,9 @@ +{% xlsdocument %} + {% xlssheet 'Test' %} + {% xlsrow %} + {% xlscell 1 %}1{% endxlscell %} + {% xlscell 2 %}2{% endxlscell %} + {% xlscell 3 %}3{% endxlscell %} + {% endxlsrow %} + {% endxlssheet %} +{% endxlsdocument %} diff --git a/tests/Twig/Fixtures/views/functionMergeStyles.twig b/tests/Twig/Fixtures/views/functionMergeStyles.twig new file mode 100644 index 0000000..fe55a77 --- /dev/null +++ b/tests/Twig/Fixtures/views/functionMergeStyles.twig @@ -0,0 +1,5 @@ +{% xlsdocument %} + {% xlssheet 'Test' %} + {% xlsdrawing 'https://www.gravatar.com/avatar/0d9079a1311d9f89b0b28b13cea56a70?s=100' %} + {% endxlssheet %} +{% endxlsdocument %} diff --git a/tests/Twig/Fixtures/views/headerFooterDrawing.twig b/tests/Twig/Fixtures/views/headerFooterDrawing.twig index 24919a8..dfc24fc 100644 --- a/tests/Twig/Fixtures/views/headerFooterDrawing.twig +++ b/tests/Twig/Fixtures/views/headerFooterDrawing.twig @@ -2,15 +2,15 @@ {% xlssheet 'Test' %} {% xlsheader %} {% xlsleft %} - {% xlsdrawing 'http://www.gravatar.com/avatar/0d9079a1311d9f89b0b28b13cea56a70?s=40' %} + {% xlsdrawing 'https://www.gravatar.com/avatar/0d9079a1311d9f89b0b28b13cea56a70?s=40' %} {% endxlsleft %} {% xlscenter %}Header{% endxlscenter %} {% endxlsheader %} {% xlsfooter %} {% xlsleft %}Footer{% endxlsleft %} {% xlsright %} - {% xlsdrawing 'http://www.gravatar.com/avatar/0d9079a1311d9f89b0b28b13cea56a70?s=20' %} + {% xlsdrawing 'https://www.gravatar.com/avatar/0d9079a1311d9f89b0b28b13cea56a70?s=20' %} {% endxlsright %} {% endxlsfooter %} {% endxlssheet %} -{% endxlsdocument %} \ No newline at end of file +{% endxlsdocument %} diff --git a/tests/Twig/OdsXlsXlsxTwigTest.php b/tests/Twig/OdsXlsXlsxTwigTest.php index a1f4e84..c9b2e67 100644 --- a/tests/Twig/OdsXlsXlsxTwigTest.php +++ b/tests/Twig/OdsXlsXlsxTwigTest.php @@ -4,31 +4,19 @@ use PhpOffice\PhpSpreadsheet\Cell\DataType; -/** - * Class OdsXlsXlsxTwigTest. - */ class OdsXlsXlsxTwigTest extends BaseTwigTest { - /** - * @return array - */ public function formatProvider(): array { return [['ods'], ['xls'], ['xlsx']]; } - // - // Tests - // - /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testBlock($format) + public function testBlock(string $format): void { $document = $this->getDocument('block', $format); static::assertNotNull($document, 'Document does not exist'); @@ -36,20 +24,18 @@ public function testBlock($format) $sheet = $document->getSheetByName('Test'); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals('Hello', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); - static::assertEquals('World', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); - static::assertEquals('Foo', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); - static::assertEquals('Bar', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); + static::assertSame('Hello', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); + static::assertSame('World', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); + static::assertSame('Foo', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); + static::assertSame('Bar', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testBlockOverrideCell($format) + public function testBlockOverrideCell(string $format): void { $document = $this->getDocument('blockOverrideCell', $format); static::assertNotNull($document, 'Document does not exist'); @@ -57,20 +43,18 @@ public function testBlockOverrideCell($format) $sheet = $document->getSheetByName('Test'); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals('Hello', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); - static::assertEquals('World', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); - static::assertEquals('Foo', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); - static::assertEquals('Bar2', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); + static::assertSame('Hello', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); + static::assertSame('World', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); + static::assertSame('Foo', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); + static::assertSame('Bar2', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testBlockOverrideContent($format) + public function testBlockOverrideContent(string $format): void { $document = $this->getDocument('blockOverrideContent', $format); static::assertNotNull($document, 'Document does not exist'); @@ -78,20 +62,18 @@ public function testBlockOverrideContent($format) $sheet = $document->getSheetByName('Test'); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals('Hello', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); - static::assertEquals('World', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); - static::assertEquals('Foo2', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); - static::assertEquals('Bar', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); + static::assertSame('Hello', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); + static::assertSame('World', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); + static::assertSame('Foo2', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); + static::assertSame('Bar', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testBlockOverrideRow($format) + public function testBlockOverrideRow(string $format): void { $document = $this->getDocument('blockOverrideRow', $format); static::assertNotNull($document, 'Document does not exist'); @@ -99,20 +81,18 @@ public function testBlockOverrideRow($format) $sheet = $document->getSheetByName('Test'); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals('Hello2', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); - static::assertEquals('World2', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); - static::assertEquals('Foo', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); - static::assertEquals('Bar', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); + static::assertSame('Hello2', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); + static::assertSame('World2', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); + static::assertSame('Foo', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); + static::assertSame('Bar', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testBlockOverrideSheet($format) + public function testBlockOverrideSheet(string $format): void { $document = $this->getDocument('blockOverrideSheet', $format); static::assertNotNull($document, 'Document does not exist'); @@ -120,20 +100,18 @@ public function testBlockOverrideSheet($format) $sheet = $document->getSheetByName('Test2'); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals('Hello3', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); - static::assertEquals('World3', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); - static::assertNotEquals('Foo', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); - static::assertNotEquals('Bar', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); + static::assertSame('Hello3', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); + static::assertSame('World3', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); + static::assertNotSame('Foo', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); + static::assertNotSame('Bar', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testCellFormula($format) + public function testCellFormula(string $format): void { $document = $this->getDocument('cellFormula', $format); static::assertNotNull($document, 'Document does not exist'); @@ -141,23 +119,21 @@ public function testCellFormula($format) $sheet = $document->getSheetByName('Test'); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals('=A1*B1+2', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); + static::assertSame('=A1*B1+2', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); static::assertTrue($sheet->getCell('A2')->isFormula(), 'Unexpected value in isFormula'); - static::assertEquals(1337, $sheet->getCell('A2')->getCalculatedValue(), 'Unexpected calculated value in A2'); + static::assertSame(1337, (int) $sheet->getCell('A2')->getCalculatedValue(), 'Unexpected calculated value in A2'); - static::assertEquals('=SUM(A1:B1)', $sheet->getCell('A3')->getValue(), 'Unexpected value in A3'); + static::assertSame('=SUM(A1:B1)', $sheet->getCell('A3')->getValue(), 'Unexpected value in A3'); static::assertTrue($sheet->getCell('A3')->isFormula(), 'Unexpected value in isFormula'); - static::assertEquals(669.5, $sheet->getCell('A3')->getCalculatedValue(), 'Unexpected calculated value in A3'); + static::assertSame(669.5, $sheet->getCell('A3')->getCalculatedValue(), 'Unexpected calculated value in A3'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testCellIndex($format) + public function testCellIndex(string $format): void { $document = $this->getDocument('cellIndex', $format); static::assertNotNull($document, 'Document does not exist'); @@ -165,29 +141,27 @@ public function testCellIndex($format) $sheet = $document->getSheetByName('Test'); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals('Foo', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); - static::assertEquals('Hello', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); - static::assertNotEquals('Bar', $sheet->getCell('C1')->getValue(), 'Unexpected value in C1'); - static::assertEquals('Lorem', $sheet->getCell('C1')->getValue(), 'Unexpected value in C1'); - static::assertEquals('Ipsum', $sheet->getCell('D1')->getValue(), 'Unexpected value in D1'); - static::assertEquals('World', $sheet->getCell('E1')->getValue(), 'Unexpected value in E1'); - - static::assertEquals('Foo', $sheet->getCell('A2')->getValue(), 'Unexpected value in A1'); - static::assertEquals('Bar', $sheet->getCell('B2')->getValue(), 'Unexpected value in B1'); - static::assertEquals('Lorem', $sheet->getCell('C2')->getValue(), 'Unexpected value in C1'); - static::assertEquals('Ipsum', $sheet->getCell('D2')->getValue(), 'Unexpected value in D1'); - static::assertEquals('Hello', $sheet->getCell('E2')->getValue(), 'Unexpected value in E1'); - static::assertEquals('World', $sheet->getCell('F2')->getValue(), 'Unexpected value in F1'); + static::assertSame('Foo', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); + static::assertSame('Hello', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); + static::assertNotSame('Bar', $sheet->getCell('C1')->getValue(), 'Unexpected value in C1'); + static::assertSame('Lorem', $sheet->getCell('C1')->getValue(), 'Unexpected value in C1'); + static::assertSame('Ipsum', $sheet->getCell('D1')->getValue(), 'Unexpected value in D1'); + static::assertSame('World', $sheet->getCell('E1')->getValue(), 'Unexpected value in E1'); + + static::assertSame('Foo', $sheet->getCell('A2')->getValue(), 'Unexpected value in A1'); + static::assertSame('Bar', $sheet->getCell('B2')->getValue(), 'Unexpected value in B1'); + static::assertSame('Lorem', $sheet->getCell('C2')->getValue(), 'Unexpected value in C1'); + static::assertSame('Ipsum', $sheet->getCell('D2')->getValue(), 'Unexpected value in D1'); + static::assertSame('Hello', $sheet->getCell('E2')->getValue(), 'Unexpected value in E1'); + static::assertSame('World', $sheet->getCell('F2')->getValue(), 'Unexpected value in F1'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testCellProperties($format) + public function testCellProperties(string $format): void { $document = $this->getDocument('cellProperties', $format); static::assertNotNull($document, 'Document does not exist'); @@ -204,42 +178,40 @@ public function testCellProperties($format) $style = $cell->getStyle(); static::assertNotNull($style, 'Style does not exist'); - static::assertEquals(42, $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); - static::assertEquals(DataType::TYPE_NUMERIC, $sheet->getCell('A2')->getDataType(), 'Unexpected value in dataType'); + static::assertSame(42, $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); + static::assertSame(DataType::TYPE_NUMERIC, $sheet->getCell('A2')->getDataType(), 'Unexpected value in dataType'); - static::assertEquals('42', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); - static::assertEquals(DataType::TYPE_STRING, $sheet->getCell('B2')->getDataType(), 'Unexpected value in dataType'); + static::assertSame('42', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); + static::assertSame(DataType::TYPE_STRING, $sheet->getCell('B2')->getDataType(), 'Unexpected value in dataType'); - static::assertEquals(42, $sheet->getCell('C2')->getValue(), 'Unexpected value in C2'); - static::assertEquals(DataType::TYPE_NUMERIC, $sheet->getCell('C2')->getDataType(), 'Unexpected value in dataType'); + static::assertSame(42, $sheet->getCell('C2')->getValue(), 'Unexpected value in C2'); + static::assertSame(DataType::TYPE_NUMERIC, $sheet->getCell('C2')->getDataType(), 'Unexpected value in dataType'); - static::assertEquals('007', $sheet->getCell('A3')->getValue(), 'Unexpected value in A3'); - static::assertEquals(DataType::TYPE_STRING, $sheet->getCell('A3')->getDataType(), 'Unexpected value in dataType'); + static::assertSame('007', $sheet->getCell('A3')->getValue(), 'Unexpected value in A3'); + static::assertSame(DataType::TYPE_STRING, $sheet->getCell('A3')->getDataType(), 'Unexpected value in dataType'); - static::assertEquals('007', $sheet->getCell('B3')->getValue(), 'Unexpected value in B3'); - static::assertEquals(DataType::TYPE_STRING, $sheet->getCell('B3')->getDataType(), 'Unexpected value in dataType'); + static::assertSame('007', $sheet->getCell('B3')->getValue(), 'Unexpected value in B3'); + static::assertSame(DataType::TYPE_STRING, $sheet->getCell('B3')->getDataType(), 'Unexpected value in dataType'); - static::assertEquals(7, $sheet->getCell('C3')->getValue(), 'Unexpected value in C3'); - static::assertEquals(DataType::TYPE_NUMERIC, $sheet->getCell('C3')->getDataType(), 'Unexpected value in dataType'); + static::assertSame(7, $sheet->getCell('C3')->getValue(), 'Unexpected value in C3'); + static::assertSame(DataType::TYPE_NUMERIC, $sheet->getCell('C3')->getDataType(), 'Unexpected value in dataType'); - static::assertEquals(0.1337, $sheet->getCell('A4')->getValue(), 'Unexpected value in A4'); - static::assertEquals(DataType::TYPE_NUMERIC, $sheet->getCell('A4')->getDataType(), 'Unexpected value in dataType'); + static::assertSame(0.1337, $sheet->getCell('A4')->getValue(), 'Unexpected value in A4'); + static::assertSame(DataType::TYPE_NUMERIC, $sheet->getCell('A4')->getDataType(), 'Unexpected value in dataType'); - static::assertEquals('0.13370', $sheet->getCell('B4')->getValue(), 'Unexpected value in B4'); - static::assertEquals(DataType::TYPE_STRING, $sheet->getCell('B4')->getDataType(), 'Unexpected value in dataType'); + static::assertSame('0.13370', $sheet->getCell('B4')->getValue(), 'Unexpected value in B4'); + static::assertSame(DataType::TYPE_STRING, $sheet->getCell('B4')->getDataType(), 'Unexpected value in dataType'); - static::assertEquals(0.1337, $sheet->getCell('C4')->getValue(), 'Unexpected value in C4'); - static::assertEquals(DataType::TYPE_NUMERIC, $sheet->getCell('C4')->getDataType(), 'Unexpected value in dataType'); + static::assertSame(0.1337, $sheet->getCell('C4')->getValue(), 'Unexpected value in C4'); + static::assertSame(DataType::TYPE_NUMERIC, $sheet->getCell('C4')->getDataType(), 'Unexpected value in dataType'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testCellValue($format) + public function testCellValue(string $format): void { $document = $this->getDocument('cellValue', $format); static::assertNotNull($document, 'Document does not exist'); @@ -247,29 +219,29 @@ public function testCellValue($format) $sheet = $document->getSheetByName('Test'); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals(667.5, $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); - static::assertEquals(DataType::TYPE_NUMERIC, $sheet->getCell('A1')->getDataType(), 'Unexpected value in dataType'); + static::assertSame(667.5, $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); + static::assertSame(DataType::TYPE_NUMERIC, $sheet->getCell('A1')->getDataType(), 'Unexpected value in dataType'); - static::assertEquals(2, $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); - static::assertEquals(DataType::TYPE_NUMERIC, $sheet->getCell('B1')->getDataType(), 'Unexpected value in dataType'); + static::assertSame(2, $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); + static::assertSame(DataType::TYPE_NUMERIC, $sheet->getCell('B1')->getDataType(), 'Unexpected value in dataType'); - static::assertEquals('007', $sheet->getCell('C1')->getValue(), 'Unexpected value in C1'); - static::assertEquals(DataType::TYPE_STRING, $sheet->getCell('C1')->getDataType(), 'Unexpected value in dataType'); + static::assertSame('007', $sheet->getCell('C1')->getValue(), 'Unexpected value in C1'); + static::assertSame(DataType::TYPE_STRING, $sheet->getCell('C1')->getDataType(), 'Unexpected value in dataType'); - static::assertEquals('foo', $sheet->getCell('D1')->getValue(), 'Unexpected value in D1'); - static::assertEquals(DataType::TYPE_STRING, $sheet->getCell('D1')->getDataType(), 'Unexpected value in dataType'); + static::assertSame('foo', $sheet->getCell('D1')->getValue(), 'Unexpected value in D1'); + static::assertSame(DataType::TYPE_STRING, $sheet->getCell('D1')->getDataType(), 'Unexpected value in dataType'); - static::assertEquals(0.42, $sheet->getCell('E1')->getValue(), 'Unexpected value in E1'); - static::assertEquals(DataType::TYPE_NUMERIC, $sheet->getCell('E1')->getDataType(), 'Unexpected value in dataType'); + static::assertSame(0.42, $sheet->getCell('E1')->getValue(), 'Unexpected value in E1'); + static::assertSame(DataType::TYPE_NUMERIC, $sheet->getCell('E1')->getDataType(), 'Unexpected value in dataType'); - static::assertEquals(21, $sheet->getCell('F1')->getValue(), 'Unexpected value in F1'); - static::assertEquals(DataType::TYPE_NUMERIC, $sheet->getCell('F1')->getDataType(), 'Unexpected value in dataType'); + static::assertSame(21, $sheet->getCell('F1')->getValue(), 'Unexpected value in F1'); + static::assertSame(DataType::TYPE_NUMERIC, $sheet->getCell('F1')->getDataType(), 'Unexpected value in dataType'); - static::assertEquals(1.2, $sheet->getCell('G1')->getValue(), 'Unexpected value in G1'); - static::assertEquals(DataType::TYPE_NUMERIC, $sheet->getCell('G1')->getDataType(), 'Unexpected value in dataType'); + static::assertSame(1.2, $sheet->getCell('G1')->getValue(), 'Unexpected value in G1'); + static::assertSame(DataType::TYPE_NUMERIC, $sheet->getCell('G1')->getDataType(), 'Unexpected value in dataType'); - static::assertEquals('BAR', $sheet->getCell('H1')->getValue(), 'Unexpected value in H1'); - static::assertEquals(DataType::TYPE_STRING, $sheet->getCell('H1')->getDataType(), 'Unexpected value in dataType'); + static::assertSame('BAR', $sheet->getCell('H1')->getValue(), 'Unexpected value in H1'); + static::assertSame(DataType::TYPE_STRING, $sheet->getCell('H1')->getDataType(), 'Unexpected value in dataType'); } /** @@ -280,13 +252,11 @@ public function testCellValue($format) * $security->getRevisionsPassword() -> 'test' * $security->getWorkbookPassword() -> 'test'. * - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testDocumentProperties($format) + public function testDocumentProperties(string $format): void { $document = $this->getDocument('documentProperties', $format); static::assertNotNull($document, 'Document does not exist'); @@ -295,33 +265,31 @@ public function testDocumentProperties($format) static::assertNotNull($properties, 'Properties do not exist'); // +/- 24h range to allow possible timezone differences (946684800) - static::assertGreaterThanOrEqual(946598400, $properties->getCreated(), 'Unexpected value in created'); - static::assertLessThanOrEqual(946771200, $properties->getCreated(), 'Unexpected value in created'); - static::assertEquals('Test creator', $properties->getCreator(), 'Unexpected value in creator'); + static::assertGreaterThanOrEqual(946_598_400, $properties->getCreated(), 'Unexpected value in created'); + static::assertLessThanOrEqual(946_771_200, $properties->getCreated(), 'Unexpected value in created'); + static::assertSame('Test creator', $properties->getCreator(), 'Unexpected value in creator'); $defaultStyle = $document->getDefaultStyle(); static::assertNotNull($defaultStyle, 'DefaultStyle does not exist'); - static::assertEquals('Test description', $properties->getDescription(), 'Unexpected value in description'); + static::assertSame('Test description', $properties->getDescription(), 'Unexpected value in description'); // +/- 24h range to allow possible timezone differences (946684800) - static::assertGreaterThanOrEqual(946598400, $properties->getModified(), 'Unexpected value in modified'); - static::assertLessThanOrEqual(946771200, $properties->getModified(), 'Unexpected value in modified'); + static::assertGreaterThanOrEqual(946_598_400, $properties->getModified(), 'Unexpected value in modified'); + static::assertLessThanOrEqual(946_771_200, $properties->getModified(), 'Unexpected value in modified'); $security = $document->getSecurity(); static::assertNotNull($security, 'Security does not exist'); - static::assertEquals('Test subject', $properties->getSubject(), 'Unexpected value in subject'); - static::assertEquals('Test title', $properties->getTitle(), 'Unexpected value in title'); + static::assertSame('Test subject', $properties->getSubject(), 'Unexpected value in subject'); + static::assertSame('Test title', $properties->getTitle(), 'Unexpected value in title'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testDocumentWhitespace($format) + public function testDocumentWhitespace(string $format): void { $document = $this->getDocument('documentWhitespace', $format); static::assertNotNull($document, 'Document does not exist'); @@ -329,20 +297,18 @@ public function testDocumentWhitespace($format) $sheet = $document->getSheetByName('Test'); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals('Foo', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); - static::assertEquals('Bar', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); - static::assertEquals('Hello', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); - static::assertEquals('World', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); + static::assertSame('Foo', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); + static::assertSame('Bar', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); + static::assertSame('Hello', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); + static::assertSame('World', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testInclude($format) + public function testInclude(string $format): void { $document = $this->getDocument('include', $format); static::assertNotNull($document, 'Document does not exist'); @@ -350,26 +316,24 @@ public function testInclude($format) $sheet = $document->getSheetByName('Test'); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals('Hello1', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); - static::assertEquals('World1', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); - static::assertEquals('Hello2', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); - static::assertEquals('World2', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); + static::assertSame('Hello1', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); + static::assertSame('World1', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); + static::assertSame('Hello2', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); + static::assertSame('World2', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); $sheet = $document->getSheetByName('Test2'); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals('Hello3', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); - static::assertEquals('World3', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); + static::assertSame('Hello3', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); + static::assertSame('World3', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testMacro($format) + public function testMacro(string $format): void { $document = $this->getDocument('macro', $format); static::assertNotNull($document, 'Document does not exist'); @@ -377,32 +341,30 @@ public function testMacro($format) $sheet = $document->getSheetByName('Test'); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals('Hello1', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); - static::assertEquals('World1', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); - static::assertEquals('Hello2', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); - static::assertEquals('World2', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); + static::assertSame('Hello1', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); + static::assertSame('World1', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); + static::assertSame('Hello2', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); + static::assertSame('World2', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); $sheet = $document->getSheetByName('Test2'); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals('Hello3', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); - static::assertEquals('World3', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); + static::assertSame('Hello3', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); + static::assertSame('World3', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); $sheet = $document->getSheetByName('Test3'); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals('Hello4', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); - static::assertEquals('World4', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); + static::assertSame('Hello4', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); + static::assertSame('World4', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testRowIndex($format) + public function testRowIndex(string $format): void { $document = $this->getDocument('rowIndex', $format); static::assertNotNull($document, 'Document does not exist'); @@ -410,58 +372,54 @@ public function testRowIndex($format) $sheet = $document->getSheetByName('Test'); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals('Foo', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); - static::assertNotEquals('Bar', $sheet->getCell('A3')->getValue(), 'Unexpected value in A3'); - static::assertEquals('Lorem', $sheet->getCell('A3')->getValue(), 'Unexpected value in A3'); - static::assertEquals('Ipsum', $sheet->getCell('A4')->getValue(), 'Unexpected value in A4'); - static::assertEquals('Hello', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); - static::assertEquals('World', $sheet->getCell('A5')->getValue(), 'Unexpected value in A5'); - - static::assertEquals('Foo', $sheet->getCell('A6')->getValue(), 'Unexpected value in A6'); - static::assertEquals('Bar', $sheet->getCell('A7')->getValue(), 'Unexpected value in A7'); - static::assertEquals('Lorem', $sheet->getCell('A8')->getValue(), 'Unexpected value in A8'); - static::assertEquals('Ipsum', $sheet->getCell('A9')->getValue(), 'Unexpected value in A9'); - static::assertEquals('Hello', $sheet->getCell('A10')->getValue(), 'Unexpected value in A10'); + static::assertSame('Foo', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); + static::assertNotSame('Bar', $sheet->getCell('A3')->getValue(), 'Unexpected value in A3'); + static::assertSame('Lorem', $sheet->getCell('A3')->getValue(), 'Unexpected value in A3'); + static::assertSame('Ipsum', $sheet->getCell('A4')->getValue(), 'Unexpected value in A4'); + static::assertSame('Hello', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); + static::assertSame('World', $sheet->getCell('A5')->getValue(), 'Unexpected value in A5'); + + static::assertSame('Foo', $sheet->getCell('A6')->getValue(), 'Unexpected value in A6'); + static::assertSame('Bar', $sheet->getCell('A7')->getValue(), 'Unexpected value in A7'); + static::assertSame('Lorem', $sheet->getCell('A8')->getValue(), 'Unexpected value in A8'); + static::assertSame('Ipsum', $sheet->getCell('A9')->getValue(), 'Unexpected value in A9'); + static::assertSame('Hello', $sheet->getCell('A10')->getValue(), 'Unexpected value in A10'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testSheet($format) + public function testSheet(string $format): void { $document = $this->getDocument('documentSimple', $format); static::assertNotNull($document, 'Document does not exist'); $sheet = $document->getSheetByName('Test'); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals($sheet, $document->getActiveSheet(), 'Sheets are not equal'); + static::assertSame($sheet, $document->getActiveSheet(), 'Sheets are not equal'); static::assertCount(1, $document->getAllSheets(), 'Unexpected sheet count'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testSheetComplex($format) + public function testSheetComplex(string $format): void { $document = $this->getDocument('sheetComplex', $format); static::assertNotNull($document, 'Document does not exist'); $sheet = $document->getSheetByName('Test 1'); static::assertNotNull($sheet, 'Sheet "Test 1" does not exist'); - static::assertEquals('Foo', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); - static::assertEquals('Bar', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); + static::assertSame('Foo', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); + static::assertSame('Bar', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); $sheet = $document->getSheetByName('Test 2'); static::assertNotNull($sheet, 'Sheet "Test 2" does not exist'); - static::assertEquals('Hello World', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); + static::assertSame('Hello World', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); } /** @@ -484,13 +442,11 @@ public function testSheetComplex($format) * $rowDimension->getzeroHeight() -> true * $sheet->getShowGridlines() -> false. * - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testSheetProperties($format) + public function testSheetProperties(string $format): void { $document = $this->getDocument('sheetProperties', $format); static::assertNotNull($document, 'Document does not exist'); @@ -500,27 +456,27 @@ public function testSheetProperties($format) $defaultColumnDimension = $sheet->getDefaultColumnDimension(); static::assertNotNull($defaultColumnDimension, 'DefaultColumnDimension does not exist'); - static::assertEquals(0, $defaultColumnDimension->getOutlineLevel(), 'Unexpected value in outlineLevel'); - static::assertEquals(-1, $defaultColumnDimension->getWidth(), 'Unexpected value in width'); - static::assertEquals(0, $defaultColumnDimension->getXfIndex(), 'Unexpected value in xfIndex'); + static::assertSame(0, $defaultColumnDimension->getOutlineLevel(), 'Unexpected value in outlineLevel'); + static::assertSame(-1.0, $defaultColumnDimension->getWidth(), 'Unexpected value in width'); + static::assertSame(0, $defaultColumnDimension->getXfIndex(), 'Unexpected value in xfIndex'); $columnDimension = $sheet->getColumnDimension('D'); static::assertNotNull($columnDimension, 'ColumnDimension does not exist'); - static::assertEquals(0, $columnDimension->getXfIndex(), 'Unexpected value in xfIndex'); + static::assertSame(0, $columnDimension->getXfIndex(), 'Unexpected value in xfIndex'); $pageSetup = $sheet->getPageSetup(); static::assertNotNull($pageSetup, 'PageSetup does not exist'); - static::assertEquals(1, $pageSetup->getFitToHeight(), 'Unexpected value in fitToHeight'); + static::assertSame(1, $pageSetup->getFitToHeight(), 'Unexpected value in fitToHeight'); static::assertFalse($pageSetup->getFitToPage(), 'Unexpected value in fitToPage'); - static::assertEquals(1, $pageSetup->getFitToWidth(), 'Unexpected value in fitToWidth'); + static::assertSame(1, $pageSetup->getFitToWidth(), 'Unexpected value in fitToWidth'); static::assertFalse($pageSetup->getHorizontalCentered(), 'Unexpected value in horizontalCentered'); - static::assertEquals(100, $pageSetup->getScale(), 'Unexpected value in scale'); + static::assertSame(100, $pageSetup->getScale(), 'Unexpected value in scale'); static::assertFalse($pageSetup->getVerticalCentered(), 'Unexpected value in verticalCentered'); $defaultRowDimension = $sheet->getDefaultRowDimension(); static::assertNotNull($defaultRowDimension, 'DefaultRowDimension does not exist'); - static::assertEquals(0, $defaultRowDimension->getOutlineLevel(), 'Unexpected value in outlineLevel'); - static::assertEquals(-1, $defaultRowDimension->getRowHeight(), 'Unexpected value in rowHeight'); - static::assertEquals(0, $defaultRowDimension->getXfIndex(), 'Unexpected value in xfIndex'); + static::assertSame(0, $defaultRowDimension->getOutlineLevel(), 'Unexpected value in outlineLevel'); + static::assertSame(-1, $defaultRowDimension->getRowHeight(), 'Unexpected value in rowHeight'); + static::assertSame(0, (int) $defaultRowDimension->getXfIndex(), 'Unexpected value in xfIndex'); } } diff --git a/tests/Twig/PdfTwigTest.php b/tests/Twig/PdfTwigTest.php index 1955ac3..f2f3b89 100644 --- a/tests/Twig/PdfTwigTest.php +++ b/tests/Twig/PdfTwigTest.php @@ -2,31 +2,18 @@ namespace MewesK\TwigSpreadsheetBundle\Tests\Twig; -/** - * Class PdfTwigTest. - */ class PdfTwigTest extends BaseTwigTest { - /** - * @return array - */ public function formatProvider(): array { return [['pdf']]; } - // - // Tests - // - /** - * @param string $format - * * @throws \Exception - * * @dataProvider formatProvider */ - public function testBasic($format) + public function testBasic(string $format): void { $path = $this->getDocument('cellProperties', $format); diff --git a/tests/Twig/XlsXlsxTwigTest.php b/tests/Twig/XlsXlsxTwigTest.php index 7536c6b..b1306e8 100644 --- a/tests/Twig/XlsXlsxTwigTest.php +++ b/tests/Twig/XlsXlsxTwigTest.php @@ -4,31 +4,19 @@ use PhpOffice\PhpSpreadsheet\Shared\PasswordHasher; -/** - * Class XlsXlsxTwigTest. - */ class XlsXlsxTwigTest extends BaseTwigTest { - /** - * @return array - */ public function formatProvider(): array { return [['xls'], ['xlsx']]; } - // - // Tests - // - /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testCellIndexMerge($format) + public function testCellIndexMerge(string $format): void { $document = $this->getDocument('cellIndexMerge', $format); static::assertNotNull($document, 'Document does not exist'); @@ -36,19 +24,17 @@ public function testCellIndexMerge($format) $sheet = $document->getSheetByName('Test'); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals('A2:C2', $sheet->getCell('A2')->getMergeRange(), 'Unexpected value in mergeRange'); - static::assertEquals('A3:C3', $sheet->getCell('A3')->getMergeRange(), 'Unexpected value in mergeRange'); - static::assertEquals('A4:A6', $sheet->getCell('A4')->getMergeRange(), 'Unexpected value in mergeRange'); + static::assertSame('A2:C2', $sheet->getCell('A2')->getMergeRange(), 'Unexpected value in mergeRange'); + static::assertSame('A3:C3', $sheet->getCell('A3')->getMergeRange(), 'Unexpected value in mergeRange'); + static::assertSame('A4:A6', $sheet->getCell('A4')->getMergeRange(), 'Unexpected value in mergeRange'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testCellProperties($format) + public function testCellProperties(string $format): void { $document = $this->getDocument('cellProperties', $format); static::assertNotNull($document, 'Document does not exist'); @@ -67,9 +53,9 @@ public function testCellProperties($format) $font = $cell->getStyle()->getFont(); static::assertNotNull($font, 'Font does not exist'); - static::assertEquals(18, $font->getSize(), 'Unexpected value in size'); + static::assertSame(18, (int) $font->getSize(), 'Unexpected value in size'); - static::assertEquals('http://example.com/', $cell->getHyperlink()->getUrl(), 'Unexpected value in url'); + static::assertSame('https://example.com/', $cell->getHyperlink()->getUrl(), 'Unexpected value in url'); } /** @@ -80,37 +66,33 @@ public function testCellProperties($format) * $security->getRevisionsPassword() -> 'test' * $security->getWorkbookPassword() -> 'test'. * - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testDocumentProperties($format) + public function testDocumentProperties(string $format): void { $document = $this->getDocument('documentProperties', $format); static::assertNotNull($document, 'Document does not exist'); $properties = $document->getProperties(); - static::assertEquals('Test category', $properties->getCategory(), 'Unexpected value in category'); + static::assertSame('Test category', $properties->getCategory(), 'Unexpected value in category'); $font = $document->getDefaultStyle()->getFont(); static::assertNotNull($font, 'Font does not exist'); - static::assertEquals(18, $font->getSize(), 'Unexpected value in size'); + static::assertSame(18, (int) $font->getSize(), 'Unexpected value in size'); - static::assertEquals('Test keywords', $properties->getKeywords(), 'Unexpected value in keywords'); - static::assertEquals('Test modifier', $properties->getLastModifiedBy(), 'Unexpected value in lastModifiedBy'); + static::assertSame('Test keywords', $properties->getKeywords(), 'Unexpected value in keywords'); + static::assertSame('Test modifier', $properties->getLastModifiedBy(), 'Unexpected value in lastModifiedBy'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testDrawingProperties($format) + public function testDrawingProperties(string $format): void { $document = $this->getDocument('drawingProperties', $format); static::assertNotNull($document, 'Document does not exist'); @@ -125,23 +107,21 @@ public function testDrawingProperties($format) $drawing = $drawings[0]; static::assertNotNull($drawing, 'Drawing is null'); - static::assertEquals('B2', $drawing->getCoordinates(), 'Unexpected value in coordinates'); - static::assertEquals(200, $drawing->getHeight(), 'Unexpected value in height'); + static::assertSame('B2', $drawing->getCoordinates(), 'Unexpected value in coordinates'); + static::assertSame(200, $drawing->getHeight(), 'Unexpected value in height'); static::assertFalse($drawing->getResizeProportional(), 'Unexpected value in resizeProportional'); - static::assertEquals(300, $drawing->getWidth(), 'Unexpected value in width'); + static::assertSame(300, $drawing->getWidth(), 'Unexpected value in width'); $shadow = $drawing->getShadow(); static::assertNotNull($shadow, 'Shadow is null'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testDrawingSimple($format) + public function testDrawingSimple(string $format): void { $document = $this->getDocument('drawingSimple', $format); static::assertNotNull($document, 'Document does not exist'); @@ -155,18 +135,36 @@ public function testDrawingSimple($format) $drawing = $drawings[0]; static::assertNotNull($drawing, 'Drawing is null'); - static::assertEquals(100, $drawing->getWidth(), 'Unexpected value in width'); - static::assertEquals(100, $drawing->getHeight(), 'Unexpected value in height'); + static::assertSame(100, $drawing->getWidth(), 'Unexpected value in width'); + static::assertSame(100, $drawing->getHeight(), 'Unexpected value in height'); } /** - * @param string $format + * @throws \Exception * + * @dataProvider formatProvider + */ + public function testFunctionMergeStyles(string $format): void + { + $document = $this->getDocument('functionMergeStyles', $format); + static::assertNotNull($document, 'Document does not exist'); + + $sheet = $document->getSheet(0); + static::assertNotNull($sheet, 'Sheet does not exist'); + + static::assertSame('Calibri', $sheet->getCell('A1')->getStyle()->getFont()->getName(), 'Unexpected value in A1'); + static::assertSame(11, (int) $sheet->getCell('A1')->getStyle()->getFont()->getSize(), 'Unexpected value in A1'); + static::assertSame(11, (int) $sheet->getCell('A2')->getStyle()->getFont()->getSize(), 'Unexpected value in A2'); + static::assertSame(11, (int) $sheet->getCell('A3')->getStyle()->getFont()->getSize(), 'Unexpected value in A3'); + static::assertSame(11, (int) $sheet->getCell('A4')->getStyle()->getFont()->getSize(), 'Unexpected value in B3'); + } + + /** * @throws \Exception * * @dataProvider formatProvider */ - public function testHeaderFooterComplex($format) + public function testHeaderFooterComplex(string $format): void { $document = $this->getDocument('headerFooterComplex', $format); static::assertNotNull($document, 'Document does not exist'); @@ -177,8 +175,8 @@ public function testHeaderFooterComplex($format) $headerFooter = $sheet->getHeaderFooter(); static::assertNotNull($headerFooter, 'HeaderFooter does not exist'); - static::assertEquals('&LoddHeader left&CoddHeader center&RoddHeader right', $headerFooter->getOddHeader(), 'Unexpected value in oddHeader'); - static::assertEquals('&LoddFooter left&CoddFooter center&RoddFooter right', $headerFooter->getOddFooter(), 'Unexpected value in oddFooter'); + static::assertSame('&LoddHeader left&CoddHeader center&RoddHeader right', $headerFooter->getOddHeader(), 'Unexpected value in oddHeader'); + static::assertSame('&LoddFooter left&CoddFooter center&RoddFooter right', $headerFooter->getOddFooter(), 'Unexpected value in oddFooter'); } /** @@ -201,13 +199,11 @@ public function testHeaderFooterComplex($format) * $rowDimension->getzeroHeight() -> true * $sheet->getShowGridlines() -> false. * - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testSheetProperties($format) + public function testSheetProperties(string $format): void { $document = $this->getDocument('sheetProperties', $format); static::assertNotNull($document, 'Document does not exist'); @@ -216,22 +212,22 @@ public function testSheetProperties($format) static::assertNotNull($sheet, 'Sheet does not exist'); $columnDimension = $sheet->getColumnDimension('D'); - static::assertEquals(1, $columnDimension->getOutlineLevel(), 'Unexpected value in outlineLevel'); - static::assertEquals(200, $columnDimension->getWidth(), 'Unexpected value in width'); + static::assertSame(1, $columnDimension->getOutlineLevel(), 'Unexpected value in outlineLevel'); + static::assertSame(200, (int) $columnDimension->getWidth(), 'Unexpected value in width'); $pageMargins = $sheet->getPageMargins(); static::assertNotNull($pageMargins, 'PageMargins does not exist'); - static::assertEquals(1, $pageMargins->getTop(), 'Unexpected value in top'); - static::assertEquals(1, $pageMargins->getBottom(), 'Unexpected value in bottom'); - static::assertEquals(0.75, $pageMargins->getLeft(), 'Unexpected value in left'); - static::assertEquals(0.75, $pageMargins->getRight(), 'Unexpected value in right'); - static::assertEquals(0.5, $pageMargins->getHeader(), 'Unexpected value in header'); - static::assertEquals(0.5, $pageMargins->getFooter(), 'Unexpected value in footer'); + static::assertSame(1, (int) $pageMargins->getTop(), 'Unexpected value in top'); + static::assertSame(1, (int) $pageMargins->getBottom(), 'Unexpected value in bottom'); + static::assertSame(0.75, $pageMargins->getLeft(), 'Unexpected value in left'); + static::assertSame(0.75, $pageMargins->getRight(), 'Unexpected value in right'); + static::assertSame(0.5, $pageMargins->getHeader(), 'Unexpected value in header'); + static::assertSame(0.5, $pageMargins->getFooter(), 'Unexpected value in footer'); $pageSetup = $sheet->getPageSetup(); - static::assertEquals('landscape', $pageSetup->getOrientation(), 'Unexpected value in orientation'); - static::assertEquals(9, $pageSetup->getPaperSize(), 'Unexpected value in paperSize'); - static::assertEquals('A1:B1', $pageSetup->getPrintArea(), 'Unexpected value in printArea'); + static::assertSame('landscape', $pageSetup->getOrientation(), 'Unexpected value in orientation'); + static::assertSame(9, $pageSetup->getPaperSize(), 'Unexpected value in paperSize'); + static::assertSame('A1:B1', $pageSetup->getPrintArea(), 'Unexpected value in printArea'); $protection = $sheet->getProtection(); static::assertTrue($protection->getAutoFilter(), 'Unexpected value in autoFilter'); @@ -245,7 +241,7 @@ public function testSheetProperties($format) static::assertTrue($protection->getInsertHyperlinks(), 'Unexpected value in insertHyperlinks'); static::assertTrue($protection->getInsertRows(), 'Unexpected value in insertRows'); static::assertTrue($protection->getObjects(), 'Unexpected value in objects'); - static::assertEquals(PasswordHasher::hashPassword('testpassword'), $protection->getPassword(), 'Unexpected value in password'); + static::assertSame(PasswordHasher::hashPassword('testpassword'), $protection->getPassword(), 'Unexpected value in password'); static::assertTrue($protection->getPivotTables(), 'Unexpected value in pivotTables'); static::assertTrue($protection->getScenarios(), 'Unexpected value in scenarios'); static::assertTrue($protection->getSelectLockedCells(), 'Unexpected value in selectLockedCells'); @@ -255,13 +251,13 @@ public function testSheetProperties($format) static::assertTrue($sheet->getPrintGridlines(), 'Unexpected value in printGridlines'); static::assertTrue($sheet->getRightToLeft(), 'Unexpected value in rightToLeft'); - static::assertEquals('c0c0c0', strtolower($sheet->getTabColor()->getRGB()), 'Unexpected value in tabColor'); - static::assertEquals(75, $sheet->getSheetView()->getZoomScale(), 'Unexpected value in zoomScale'); + static::assertSame('c0c0c0', strtolower($sheet->getTabColor()->getRGB()), 'Unexpected value in tabColor'); + static::assertSame(75, $sheet->getSheetView()->getZoomScale(), 'Unexpected value in zoomScale'); $rowDimension = $sheet->getRowDimension(2); static::assertNotNull($rowDimension, 'RowDimension does not exist'); - static::assertEquals(1, $rowDimension->getOutlineLevel(), 'Unexpected value in outlineLevel'); - static::assertEquals(30, $rowDimension->getRowHeight(), 'Unexpected value in rowHeight'); - static::assertEquals(0, $rowDimension->getXfIndex(), 'Unexpected value in xfIndex'); + static::assertSame(1, $rowDimension->getOutlineLevel(), 'Unexpected value in outlineLevel'); + static::assertSame(30, (int) $rowDimension->getRowHeight(), 'Unexpected value in rowHeight'); + static::assertSame(0, (int) $rowDimension->getXfIndex(), 'Unexpected value in xfIndex'); } } diff --git a/tests/Twig/XlsxTwigTest.php b/tests/Twig/XlsxTwigTest.php index 67124f2..4d8fd6a 100644 --- a/tests/Twig/XlsxTwigTest.php +++ b/tests/Twig/XlsxTwigTest.php @@ -2,31 +2,19 @@ namespace MewesK\TwigSpreadsheetBundle\Tests\Twig; -/** - * Class XlsxTwigTest. - */ class XlsxTwigTest extends BaseTwigTest { - /** - * @return array - */ public function formatProvider(): array { return [['xlsx']]; } - // - // Tests - // - /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testCellProperties($format) + public function testCellProperties(string $format): void { $document = $this->getDocument('cellProperties', $format); $sheet = $document->getSheetByName('Test'); @@ -34,13 +22,13 @@ public function testCellProperties($format) $dataValidation = $cell->getDataValidation(); static::assertTrue($dataValidation->getAllowBlank(), 'Unexpected value in allowBlank'); - static::assertEquals('Test error', $dataValidation->getError(), 'Unexpected value in error'); - static::assertEquals('Test errorTitle', $dataValidation->getErrorTitle(), 'Unexpected value in errorTitle'); - static::assertEquals('', $dataValidation->getFormula1(), 'Unexpected value in formula1'); - static::assertEquals('', $dataValidation->getFormula2(), 'Unexpected value in formula2'); - static::assertEquals('', $dataValidation->getOperator(), 'Unexpected value in operator'); - static::assertEquals('Test prompt', $dataValidation->getPrompt(), 'Unexpected value in prompt'); - static::assertEquals('Test promptTitle', $dataValidation->getPromptTitle(), 'Unexpected value in promptTitle'); + static::assertSame('Test error', $dataValidation->getError(), 'Unexpected value in error'); + static::assertSame('Test errorTitle', $dataValidation->getErrorTitle(), 'Unexpected value in errorTitle'); + static::assertSame('', $dataValidation->getFormula1(), 'Unexpected value in formula1'); + static::assertSame('', $dataValidation->getFormula2(), 'Unexpected value in formula2'); + static::assertSame('', $dataValidation->getOperator(), 'Unexpected value in operator'); + static::assertSame('Test prompt', $dataValidation->getPrompt(), 'Unexpected value in prompt'); + static::assertSame('Test promptTitle', $dataValidation->getPromptTitle(), 'Unexpected value in promptTitle'); static::assertTrue($dataValidation->getShowDropDown(), 'Unexpected value in showDropDown'); static::assertTrue($dataValidation->getShowErrorMessage(), 'Unexpected value in showErrorMessage'); static::assertTrue($dataValidation->getShowInputMessage(), 'Unexpected value in showInputMessage'); @@ -54,29 +42,25 @@ public function testCellProperties($format) * $security->getRevisionsPassword() -> 'test' * $security->getWorkbookPassword() -> 'test'. * - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testDocumentProperties($format) + public function testDocumentProperties(string $format): void { $document = $this->getDocument('documentProperties', $format); $properties = $document->getProperties(); - static::assertEquals('Test company', $properties->getCompany(), 'Unexpected value in company'); - static::assertEquals('Test manager', $properties->getManager(), 'Unexpected value in manager'); + static::assertSame('Test company', $properties->getCompany(), 'Unexpected value in company'); + static::assertSame('Test manager', $properties->getManager(), 'Unexpected value in manager'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testDocumentTemplate($format) + public function testDocumentTemplate(string $format): void { $document = $this->getDocument('documentTemplateAdvanced', $format); static::assertNotNull($document, 'Document does not exist'); @@ -84,41 +68,45 @@ public function testDocumentTemplate($format) $sheet = $document->getSheet(0); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals('Hello2', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); - static::assertEquals('World', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); - static::assertEquals('Foo', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); - static::assertEquals('Bar2', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); + static::assertSame('Hello2', $sheet->getCell('A1')->getValue(), 'Unexpected value in A1'); + static::assertSame('World', $sheet->getCell('B1')->getValue(), 'Unexpected value in B1'); + static::assertSame('Foo', $sheet->getCell('A2')->getValue(), 'Unexpected value in A2'); + static::assertSame('Bar2', $sheet->getCell('B2')->getValue(), 'Unexpected value in B2'); static::assertTrue($sheet->getCell('A1')->getStyle()->getFont()->getBold(), 'Unexpected value in bold'); static::assertTrue($sheet->getCell('B1')->getStyle()->getFont()->getItalic(), 'Unexpected value in italic'); - static::assertEquals('single', $sheet->getCell('A2')->getStyle()->getFont()->getUnderline(), 'Unexpected value in underline'); - static::assertEquals('FFFF3333', $sheet->getCell('B2')->getStyle()->getFont()->getColor()->getARGB(), 'Unexpected value in color'); + static::assertSame('single', $sheet->getCell('A2')->getStyle()->getFont()->getUnderline(), 'Unexpected value in underline'); + static::assertSame('FFFF3333', $sheet->getCell('B2')->getStyle()->getFont()->getColor()->getARGB(), 'Unexpected value in color'); $headerFooter = $sheet->getHeaderFooter(); static::assertNotNull($headerFooter, 'HeaderFooter does not exist'); - static::assertContains('Left area header', $headerFooter->getOddHeader(), 'Unexpected value in oddHeader'); - static::assertContains('12Center area header', $headerFooter->getOddHeader(), 'Unexpected value in oddHeader'); - static::assertContains('12Right area header', $headerFooter->getOddHeader(), 'Unexpected value in oddHeader'); - static::assertContains('Left area footer', $headerFooter->getOddFooter(), 'Unexpected value in oddFooter'); - static::assertContains('12Center area footer', $headerFooter->getOddFooter(), 'Unexpected value in oddFooter'); - static::assertContains('12Right area footer', $headerFooter->getOddFooter(), 'Unexpected value in oddFooter'); + static::assertStringContainsString('Left area header', $headerFooter->getOddHeader(), + 'Unexpected value in oddHeader'); + static::assertStringContainsString('12Center area header', $headerFooter->getOddHeader(), + 'Unexpected value in oddHeader'); + static::assertStringContainsString('12Right area header', $headerFooter->getOddHeader(), + 'Unexpected value in oddHeader'); + static::assertStringContainsString('Left area footer', $headerFooter->getOddFooter(), + 'Unexpected value in oddFooter'); + static::assertStringContainsString('12Center area footer', $headerFooter->getOddFooter(), + 'Unexpected value in oddFooter'); + static::assertStringContainsString('12Right area footer', $headerFooter->getOddFooter(), + 'Unexpected value in oddFooter'); $drawings = $sheet->getDrawingCollection(); static::assertCount(1, $drawings, 'Not enough drawings exist'); $drawing = $drawings[0]; - static::assertEquals(196, $drawing->getWidth(), 'Unexpected value in width'); - static::assertEquals(187, $drawing->getHeight(), 'Unexpected value in height'); + static::assertSame(196, $drawing->getWidth(), 'Unexpected value in width'); + static::assertSame(187, $drawing->getHeight(), 'Unexpected value in height'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testDrawingProperties($format) + public function testDrawingProperties(string $format): void { $document = $this->getDocument('drawingProperties', $format); static::assertNotNull($document, 'Document does not exist'); @@ -130,30 +118,28 @@ public function testDrawingProperties($format) static::assertCount(1, $drawings, 'Not enough drawings exist'); $drawing = $drawings[0]; - static::assertEquals('Test Description', $drawing->getDescription(), 'Unexpected value in description'); - static::assertEquals('Test Name', $drawing->getName(), 'Unexpected value in name'); - static::assertEquals(30, $drawing->getOffsetX(), 'Unexpected value in offsetX'); - static::assertEquals(20, $drawing->getOffsetY(), 'Unexpected value in offsetY'); - static::assertEquals(45, $drawing->getRotation(), 'Unexpected value in rotation'); + static::assertSame('Test Description', $drawing->getDescription(), 'Unexpected value in description'); + static::assertSame('Test Name', $drawing->getName(), 'Unexpected value in name'); + static::assertSame(30, $drawing->getOffsetX(), 'Unexpected value in offsetX'); + static::assertSame(20, $drawing->getOffsetY(), 'Unexpected value in offsetY'); + static::assertSame(45, $drawing->getRotation(), 'Unexpected value in rotation'); $shadow = $drawing->getShadow(); - static::assertEquals('ctr', $shadow->getAlignment(), 'Unexpected value in alignment'); - static::assertEquals(100, $shadow->getAlpha(), 'Unexpected value in alpha'); - static::assertEquals(11, $shadow->getBlurRadius(), 'Unexpected value in blurRadius'); - static::assertEquals('0000cc', $shadow->getColor()->getRGB(), 'Unexpected value in color'); - static::assertEquals(30, $shadow->getDirection(), 'Unexpected value in direction'); - static::assertEquals(4, $shadow->getDistance(), 'Unexpected value in distance'); + static::assertSame('ctr', $shadow->getAlignment(), 'Unexpected value in alignment'); + static::assertSame(100, $shadow->getAlpha(), 'Unexpected value in alpha'); + static::assertSame(11, $shadow->getBlurRadius(), 'Unexpected value in blurRadius'); + static::assertSame('0000cc', $shadow->getColor()->getRGB(), 'Unexpected value in color'); + static::assertSame(30, $shadow->getDirection(), 'Unexpected value in direction'); + static::assertSame(4, $shadow->getDistance(), 'Unexpected value in distance'); static::assertTrue($shadow->getVisible(), 'Unexpected value in visible'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testHeaderFooterComplex($format) + public function testHeaderFooterComplex(string $format): void { $document = $this->getDocument('headerFooterComplex', $format); static::assertNotNull($document, 'Document does not exist'); @@ -163,28 +149,26 @@ public function testHeaderFooterComplex($format) $headerFooter = $sheet->getHeaderFooter(); static::assertNotNull($headerFooter, 'HeaderFooter does not exist'); - static::assertEquals('&LfirstHeader left&CfirstHeader center&RfirstHeader right', + static::assertSame('&LfirstHeader left&CfirstHeader center&RfirstHeader right', $headerFooter->getFirstHeader(), 'Unexpected value in firstHeader'); - static::assertEquals('&LevenHeader left&CevenHeader center&RevenHeader right', + static::assertSame('&LevenHeader left&CevenHeader center&RevenHeader right', $headerFooter->getEvenHeader(), 'Unexpected value in evenHeader'); - static::assertEquals('&LfirstFooter left&CfirstFooter center&RfirstFooter right', + static::assertSame('&LfirstFooter left&CfirstFooter center&RfirstFooter right', $headerFooter->getFirstFooter(), 'Unexpected value in firstFooter'); - static::assertEquals('&LevenFooter left&CevenFooter center&RevenFooter right', + static::assertSame('&LevenFooter left&CevenFooter center&RevenFooter right', $headerFooter->getEvenFooter(), 'Unexpected value in evenFooter'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testHeaderFooterDrawing($format) + public function testHeaderFooterDrawing(string $format): void { $document = $this->getDocument('headerFooterDrawing', $format); static::assertNotNull($document, 'Document does not exist'); @@ -194,12 +178,12 @@ public function testHeaderFooterDrawing($format) $headerFooter = $sheet->getHeaderFooter(); static::assertNotNull($headerFooter, 'HeaderFooter does not exist'); - static::assertEquals('&L&G&CHeader', $headerFooter->getFirstHeader(), 'Unexpected value in firstHeader'); - static::assertEquals('&L&G&CHeader', $headerFooter->getEvenHeader(), 'Unexpected value in evenHeader'); - static::assertEquals('&L&G&CHeader', $headerFooter->getOddHeader(), 'Unexpected value in oddHeader'); - static::assertEquals('&LFooter&R&G', $headerFooter->getFirstFooter(), 'Unexpected value in firstFooter'); - static::assertEquals('&LFooter&R&G', $headerFooter->getEvenFooter(), 'Unexpected value in evenFooter'); - static::assertEquals('&LFooter&R&G', $headerFooter->getOddFooter(), 'Unexpected value in oddFooter'); + static::assertSame('&L&G&CHeader', $headerFooter->getFirstHeader(), 'Unexpected value in firstHeader'); + static::assertSame('&L&G&CHeader', $headerFooter->getEvenHeader(), 'Unexpected value in evenHeader'); + static::assertSame('&L&G&CHeader', $headerFooter->getOddHeader(), 'Unexpected value in oddHeader'); + static::assertSame('&LFooter&R&G', $headerFooter->getFirstFooter(), 'Unexpected value in firstFooter'); + static::assertSame('&LFooter&R&G', $headerFooter->getEvenFooter(), 'Unexpected value in evenFooter'); + static::assertSame('&LFooter&R&G', $headerFooter->getOddFooter(), 'Unexpected value in oddFooter'); $drawings = $headerFooter->getImages(); static::assertCount(2, $drawings, 'Sheet has not exactly 2 drawings'); @@ -208,23 +192,21 @@ public function testHeaderFooterDrawing($format) $drawing = $drawings['LH']; static::assertNotNull($drawing, 'Header drawing is null'); - static::assertEquals(40, $drawing->getWidth(), 'Unexpected value in width'); - static::assertEquals(40, $drawing->getHeight(), 'Unexpected value in height'); + static::assertSame(40, $drawing->getWidth(), 'Unexpected value in width'); + static::assertSame(40, $drawing->getHeight(), 'Unexpected value in height'); $drawing = $drawings['RF']; static::assertNotNull($drawing, 'Footer drawing is null'); - static::assertEquals(20, $drawing->getWidth(), 'Unexpected value in width'); - static::assertEquals(20, $drawing->getHeight(), 'Unexpected value in height'); + static::assertSame(20, $drawing->getWidth(), 'Unexpected value in width'); + static::assertSame(20, $drawing->getHeight(), 'Unexpected value in height'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testHeaderFooterProperties($format) + public function testHeaderFooterProperties(string $format): void { $document = $this->getDocument('headerFooterProperties', $format); static::assertNotNull($document, 'Document does not exist'); @@ -235,31 +217,29 @@ public function testHeaderFooterProperties($format) $headerFooter = $sheet->getHeaderFooter(); static::assertNotNull($headerFooter, 'HeaderFooter does not exist'); - static::assertEquals('&CHeader', $headerFooter->getFirstHeader(), 'Unexpected value in firstHeader'); - static::assertEquals('&CHeader', $headerFooter->getEvenHeader(), 'Unexpected value in evenHeader'); - static::assertEquals('&CHeader', $headerFooter->getOddHeader(), 'Unexpected value in oddHeader'); - static::assertEquals('&CFooter', $headerFooter->getFirstFooter(), 'Unexpected value in firstFooter'); - static::assertEquals('&CFooter', $headerFooter->getEvenFooter(), 'Unexpected value in evenFooter'); - static::assertEquals('&CFooter', $headerFooter->getOddFooter(), 'Unexpected value in oddFooter'); + static::assertSame('&CHeader', $headerFooter->getFirstHeader(), 'Unexpected value in firstHeader'); + static::assertSame('&CHeader', $headerFooter->getEvenHeader(), 'Unexpected value in evenHeader'); + static::assertSame('&CHeader', $headerFooter->getOddHeader(), 'Unexpected value in oddHeader'); + static::assertSame('&CFooter', $headerFooter->getFirstFooter(), 'Unexpected value in firstFooter'); + static::assertSame('&CFooter', $headerFooter->getEvenFooter(), 'Unexpected value in evenFooter'); + static::assertSame('&CFooter', $headerFooter->getOddFooter(), 'Unexpected value in oddFooter'); static::assertFalse($headerFooter->getAlignWithMargins(), 'Unexpected value in alignWithMargins'); static::assertFalse($headerFooter->getScaleWithDocument(), 'Unexpected value in scaleWithDocument'); } /** - * @param string $format - * * @throws \Exception * * @dataProvider formatProvider */ - public function testSheetProperties($format) + public function testSheetProperties(string $format): void { $document = $this->getDocument('sheetProperties', $format); static::assertNotNull($document, 'Document does not exist'); $sheet = $document->getSheetByName('Test'); static::assertNotNull($sheet, 'Sheet does not exist'); - static::assertEquals('A1:B1', $sheet->getAutoFilter()->getRange(), 'Unexpected value in autoFilter'); + static::assertSame('A1:B1', $sheet->getAutoFilter()->getRange(), 'Unexpected value in autoFilter'); } }