From 32f57490a4832e34615335427f85201d92324773 Mon Sep 17 00:00:00 2001 From: Paul Date: Wed, 23 Sep 2026 09:52:50 +0200 Subject: [PATCH 1/7] fix getAllResults (cherry picked from commit 7091e2182cc8101bdf5b7320727f47495ddab0d2) --- Datagrid/DoctrineDatagrid.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Datagrid/DoctrineDatagrid.php b/Datagrid/DoctrineDatagrid.php index 9b16fa5..bbaa1ef 100644 --- a/Datagrid/DoctrineDatagrid.php +++ b/Datagrid/DoctrineDatagrid.php @@ -675,6 +675,10 @@ public function getNbPages(): int public function getAllResults(): mixed { + if (null === $this->filterObject) { + $this->buildForm(); + } + $this->doSort(); $this->doFilter(); From 6cc5a693933e7fd04b727c1774cc2d1b0321c963 Mon Sep 17 00:00:00 2001 From: Hugues Date: Tue, 10 Nov 2026 11:40:32 +0100 Subject: [PATCH 2/7] Apply PHP CS Fixer (@Symfony, @PHP82Migration) Coding standards only, no functional change. Adds the .php-cs-fixer.dist.php configuration. Co-Authored-By: Claude Opus 5.5 --- .php-cs-fixer.dist.php | 14 ++++ Datagrid/DoctrineDatagrid.php | 72 ++++++------------- Datagrid/DoctrineDatagridFactory.php | 10 +-- Datagrid/Export/AbstractXlsExport.php | 2 +- Datagrid/Export/CsvExport.php | 2 +- Datagrid/FilterObject.php | 3 +- Datagrid/Util.php | 2 +- DependencyInjection/Configuration.php | 3 - .../DoctrineDatagridExtension.php | 3 - Tests/Datagrid/DoctrineDatagridTest.php | 14 +++- Tests/Datagrid/QueryBuilderTest.php | 31 +++++--- Tests/bootstrap.php | 2 +- 12 files changed, 77 insertions(+), 81 deletions(-) create mode 100644 .php-cs-fixer.dist.php diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 0000000..828c0ec --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,14 @@ +in(__DIR__) + ->exclude(['var', 'vendor']) +; + +return (new PhpCsFixer\Config()) + ->setRules([ + '@Symfony' => true, + '@PHP82Migration' => true, + ]) + ->setFinder($finder) +; diff --git a/Datagrid/DoctrineDatagrid.php b/Datagrid/DoctrineDatagrid.php index bbaa1ef..dc7a3c0 100644 --- a/Datagrid/DoctrineDatagrid.php +++ b/Datagrid/DoctrineDatagrid.php @@ -51,7 +51,6 @@ class DoctrineDatagrid public const ALLOWED_SORT_DIRECTIONS = ['ASC', 'DESC']; - public const PARAM1 = 'param1'; public const PARAM2 = 'param2'; @@ -112,9 +111,6 @@ class DoctrineDatagrid */ protected mixed $options; - /** - * @var string - */ protected string $select; protected string $id; @@ -141,8 +137,7 @@ public function __construct( private readonly RouterInterface $router, private string $name, private array $params = [] - ) - { + ) { $this->session = $requestStack->getSession(); } @@ -232,27 +227,27 @@ private function getSessionValue(string $name, mixed $default = null): mixed { return $this->getRequest() ->getSession() - ->get($this->getSessionName() . '.' . $name, $default); + ->get($this->getSessionName().'.'.$name, $default); } private function setSessionValue(string $name, mixed $value): void { $this->getRequest() ->getSession() - ->set($this->getSessionName() . '.' . $name, $value); + ->set($this->getSessionName().'.'.$name, $value); } private function removeSessionValue(string $name) { return $this->getRequest() ->getSession() - ->remove($this->getSessionName() . '.' . $name); + ->remove($this->getSessionName().'.'.$name); } protected function getQueryResults(): Paginator|array { $countQb = $this->createCountQb($this->qb); - $countSelect = 'COUNT(' . ($this->distinct ? 'DISTINCT ' : '') . $this->id . ')'; + $countSelect = 'COUNT('.($this->distinct ? 'DISTINCT ' : '').$this->id.')'; $this->nbResults = $countQb->select($countSelect) ->orderBy($this->id) ->getQuery() @@ -260,7 +255,7 @@ protected function getQueryResults(): Paginator|array $this->nbPages = (int) ceil($this->nbResults / $this->getMaxPerPage()); - $qb = $this->qb->select(($this->distinct ? 'DISTINCT ' : '') . $this->select) + $qb = $this->qb->select(($this->distinct ? 'DISTINCT ' : '').$this->select) ->setFirstResult(($this->getCurrentPage() - 1) * $this->getMaxPerPage()) ->setMaxResults($this->getMaxPerPage()); @@ -286,10 +281,7 @@ protected function createCountQb(QueryBuilder $qb): QueryBuilder return $this->getUnorderedQueryBuilder($qb); } - /*********************************/ /** Query features ***************/ - /*********************************/ - public function select(string|array $select): static { if (is_array($select)) { @@ -334,10 +326,8 @@ public function query(callable $callback): static } /** - * @param string $name * @param class-string $type - * @param mixed[] $options - * @param callable $callback + * @param mixed[] $options */ public function filter(string $name, string $type, array $options, callable $callback): static { @@ -368,16 +358,13 @@ public function id(string $id): static return $this; } - /*********************************/ /** Filter features here *********/ - /*********************************/ - private function doFilter(): static { if (in_array( - $this->getRequest()->getMethod(), - $this->getAllowedFilterMethods() - ) && $this->filterObject && $this->getRequestParams($this->getRequest())->all($this->filterObject->getForm()->getName()) + $this->getRequest()->getMethod(), + $this->getAllowedFilterMethods() + ) && $this->filterObject && $this->getRequestParams($this->getRequest())->all($this->filterObject->getForm()->getName()) ) { $this->setCurrentPage(1); $data = $this->getRequestParams($this->getRequest())->all($this->filterObject->getForm()->getName()); @@ -497,7 +484,6 @@ public function getFilterFormView(): ?FormView */ public function configureFilterBuilder(FormBuilderInterface $builder): void { - return; } /** @@ -508,13 +494,11 @@ public function getAllowedFilterMethods(): array if (isset($this->params['method']) && ('get' === $this->params['method'])) { return [Request::METHOD_GET]; } + return [Request::METHOD_POST]; } - /*********************************/ /** Sort features here ***********/ - /*********************************/ - public function setDefaultSort($defaultSort): static { $this->defaultSorts = $defaultSort; @@ -585,10 +569,7 @@ public function resetSort(): static return $this; } - /*********************************/ /** Export features here *********/ - /*********************************/ - public function export(string $name, array $params = []): mixed { $class = $this->getExport($name); @@ -596,7 +577,7 @@ public function export(string $name, array $params = []): mixed $this->doSort(); $this->doFilter(); - $qb = $this->getQueryBuilder()->select(($this->distinct ? 'DISTINCT ' : '') . $this->select); + $qb = $this->getQueryBuilder()->select(($this->distinct ? 'DISTINCT ' : '').$this->select); $export = new $class($qb, $params); @@ -608,7 +589,7 @@ protected function getExport(string $name): ?string $exports = $this->getExports(); if (!isset($exports[$name])) { - throw new \Exception('The "' . $name . '" export doesn\'t exist in this datagrid.'); + throw new \Exception('The "'.$name.'" export doesn\'t exist in this datagrid.'); } return $exports[$name]; @@ -634,7 +615,7 @@ protected function getExports(): array public function getSessionName(): string { - return 'datagrid.' . $this->name; + return 'datagrid.'.$this->name; } protected function updatePage(): static @@ -682,15 +663,12 @@ public function getAllResults(): mixed $this->doSort(); $this->doFilter(); - $qb = $this->getQueryBuilder()->select(($this->distinct ? 'DISTINCT ' : '') . $this->select); + $qb = $this->getQueryBuilder()->select(($this->distinct ? 'DISTINCT ' : '').$this->select); return $qb->getQuery()->execute(); } - /*********************************/ /** Dynamic columns feature here */ - /*********************************/ - private function removeColumn(): void { $columnToRemove = $this->getRequestedColumnRemoval(); @@ -758,10 +736,7 @@ public function getColumns() return $this->getSessionValue('columns', $this->getDefaultColumns()); } - /*********************************/ /** Max per page feature here ****/ - /*********************************/ - private function limit(): void { $limit = $this->getRequestedLimit(); @@ -803,17 +778,14 @@ public function setMaxPerPage(int $value): static return $this; } - /*********************************/ /** Routing helper methods here **/ - /*********************************/ /** - * @param null|'action'|'datagrid'|'page'|'sort'|'remove-sort'|'reset'|'limit'|'add-column'|'remove-column' $default - * @return string + * @param 'action'|'datagrid'|'page'|'sort'|'remove-sort'|'reset'|'limit'|'add-column'|'remove-column'|null $default */ protected function getRequestedAction(?string $default = null): string { - Assert::inArray($default, [null, ...self::ALLOWED_ACTIONS], 'Action must be one of: ' . implode(', ', self::ALLOWED_ACTIONS) . '. %s given.'); + Assert::inArray($default, [null, ...self::ALLOWED_ACTIONS], 'Action must be one of: '.implode(', ', self::ALLOWED_ACTIONS).'. %s given.'); return $this->getRequestParams($this->getRequest())->get(self::ACTION, $default); } @@ -836,8 +808,7 @@ protected function getRequestedSortColumn(?string $default = null): ?string } /** - * @param null|'ASC'|'DESC'|'asc'|'desc' $default - * @return string|null + * @param 'ASC'|'DESC'|'asc'|'desc'|null $default */ protected function getRequestedSortOrder(?string $default = null): ?string { @@ -884,10 +855,7 @@ protected function getRequestedLimit(?int $default = null): int return $this->getRequestParams($this->getRequest())->get(self::PARAM1, $default); } - /*********************************/ /** Global service shortcuts *****/ - /*********************************/ - protected function getRequest(): Request { return $this->requestStack->getCurrentRequest(); @@ -1031,7 +999,7 @@ public function getMaxPerPagePath(string $route, int $limit, array $extraParams public function getBatchData(): array { - return (array)json_decode($this->getRequest()->cookies->get($this->name . '_batch')); + return (array) json_decode($this->getRequest()->cookies->get($this->name.'_batch')); } public function isBatchChecked(mixed $identifier): bool @@ -1092,7 +1060,7 @@ public function shouldFetchJoinCollection(bool $shouldFetchJoinCollection): stat public function getRequestParams(Request $request): ParameterBag { - if ($request->getMethod() === Request::METHOD_POST) { + if (Request::METHOD_POST === $request->getMethod()) { return $request->request; } diff --git a/Datagrid/DoctrineDatagridFactory.php b/Datagrid/DoctrineDatagridFactory.php index b9a0cbd..8f32a94 100644 --- a/Datagrid/DoctrineDatagridFactory.php +++ b/Datagrid/DoctrineDatagridFactory.php @@ -15,11 +15,11 @@ class DoctrineDatagridFactory /** * Just a simple constructor. */ - public function __construct( - private EntityManagerInterface $em, - private RequestStack $requestStack, - private FormFactoryInterface $formFactory, - private RouterInterface $router + public function __construct( + private EntityManagerInterface $em, + private RequestStack $requestStack, + private FormFactoryInterface $formFactory, + private RouterInterface $router ) { } diff --git a/Datagrid/Export/AbstractXlsExport.php b/Datagrid/Export/AbstractXlsExport.php index a562aba..56287b8 100644 --- a/Datagrid/Export/AbstractXlsExport.php +++ b/Datagrid/Export/AbstractXlsExport.php @@ -36,7 +36,7 @@ public function getData(QueryBuilder $qb): mixed } /** - * Do anything you want before the export, like modifying the query + * Do anything you want before the export, like modifying the query. */ public function preExecute(): void { diff --git a/Datagrid/Export/CsvExport.php b/Datagrid/Export/CsvExport.php index 6b749d0..9b46278 100644 --- a/Datagrid/Export/CsvExport.php +++ b/Datagrid/Export/CsvExport.php @@ -26,7 +26,7 @@ public function __construct($qb, $params) } /** - * Do anything you want before the export, like modifying the query + * Do anything you want before the export, like modifying the query. */ public function preExecute(): void { diff --git a/Datagrid/FilterObject.php b/Datagrid/FilterObject.php index fe9a42d..33dfea1 100644 --- a/Datagrid/FilterObject.php +++ b/Datagrid/FilterObject.php @@ -3,10 +3,9 @@ namespace Spyrit\Bundle\DoctrineDatagridBundle\Datagrid; use Symfony\Component\Form\Extension\Core\Type\FormType; +use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormFactory; use Symfony\Component\Form\FormInterface; -use Symfony\Component\HttpKernel\Kernel; -use Symfony\Component\Form\FormBuilderInterface; /** * @author Maxime CORSON diff --git a/Datagrid/Util.php b/Datagrid/Util.php index 2a8886f..33563f5 100644 --- a/Datagrid/Util.php +++ b/Datagrid/Util.php @@ -22,4 +22,4 @@ public static function validateSortDirection(string $direction): string return $sortDirection; } -} \ No newline at end of file +} diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 95456e8..0076c5b 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -12,9 +12,6 @@ */ class Configuration implements ConfigurationInterface { - /** - * {@inheritdoc} - */ public function getConfigTreeBuilder(): TreeBuilder { return new TreeBuilder('doctrine_datagrid'); diff --git a/DependencyInjection/DoctrineDatagridExtension.php b/DependencyInjection/DoctrineDatagridExtension.php index 30f2ddb..387321e 100644 --- a/DependencyInjection/DoctrineDatagridExtension.php +++ b/DependencyInjection/DoctrineDatagridExtension.php @@ -14,9 +14,6 @@ */ class DoctrineDatagridExtension extends Extension { - /** - * {@inheritdoc} - */ public function load(array $configs, ContainerBuilder $container): void { /*$configuration = new Configuration(); diff --git a/Tests/Datagrid/DoctrineDatagridTest.php b/Tests/Datagrid/DoctrineDatagridTest.php index 591afed..70fbfb3 100644 --- a/Tests/Datagrid/DoctrineDatagridTest.php +++ b/Tests/Datagrid/DoctrineDatagridTest.php @@ -18,7 +18,7 @@ private function createDatagrid(Request $request, array &$sessionStore, array $p { $em = $this->createMock(EntityManagerInterface::class); $formFactory = $this->createMock(FormFactoryInterface::class); - $router = $router ?? $this->createMock(RouterInterface::class); + $router ??= $this->createMock(RouterInterface::class); // Session mock with in-memory storage $session = $this->createMock(SessionInterface::class); @@ -158,8 +158,15 @@ public function testDynamicColumnsAvailability(): void // Anonymous subclass to provide default/appendable columns $dg = new class(...$this->extractCtorArgs($request, $store)) extends DoctrineDatagrid { - public function getDefaultColumns(): array { return ['id' => 'ID', 'name' => 'Name']; } - public function getAppendableColumns(): array { return ['email' => 'Email', 'country' => 'Country']; } + public function getDefaultColumns(): array + { + return ['id' => 'ID', 'name' => 'Name']; + } + + public function getAppendableColumns(): array + { + return ['email' => 'Email', 'country' => 'Country']; + } }; // When nothing stored in session, current columns are defaults, so available appendables exclude defaults @@ -224,6 +231,7 @@ private function extractRawServices(Request $request, array &$sessionStore): arr private function extractCtorArgs(Request $request, array &$sessionStore): array { [$em, $requestStack, $formFactory, $router] = $this->extractRawServices($request, $sessionStore); + return [$em, $requestStack, $formFactory, $router, 'dg', []]; } } diff --git a/Tests/Datagrid/QueryBuilderTest.php b/Tests/Datagrid/QueryBuilderTest.php index 9ce9f3d..7a1d6f8 100644 --- a/Tests/Datagrid/QueryBuilderTest.php +++ b/Tests/Datagrid/QueryBuilderTest.php @@ -2,17 +2,15 @@ namespace Spyrit\Bundle\DoctrineDatagridBundle\Tests\Datagrid; -use Doctrine\ORM\AbstractQuery; -use Doctrine\ORM\EntityManagerInterface as DoctrineEm; -use Doctrine\ORM\Query as DoctrineQuery; -use Doctrine\ORM\Configuration as DoctrineConfig; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\QueryBuilder; use Doctrine\ORM\Tools\Pagination\Paginator as DoctrinePaginator; class MinimalPaginator { - public function __construct(public bool $fetchJoin) {} + public function __construct(public bool $fetchJoin) + { + } } use PHPUnit\Framework\TestCase; use Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\DoctrineDatagrid; @@ -132,6 +130,7 @@ public function testQueryInitializationCallsCallbackAndStoresQueryBuilder(): voi $called = true; // developer callback may configure and must return a QB $this->assertSame($qb, $passedQb); + return $passedQb; }); @@ -175,7 +174,10 @@ public function testGetQueryResultsAppliesPaginationAndGroupBy(): void // For count() path, return a tiny stub exposing only getSingleScalarResult $countQuery = new class { - public function getSingleScalarResult() { return 123; } + public function getSingleScalarResult() + { + return 123; + } }; // Only one getQuery() call in this safe path @@ -217,7 +219,10 @@ public function testNbResultsAndNbPagesWithDifferentLimits(): void $qb->expects($this->once())->method('setMaxResults')->with(50)->willReturn($qb); $countQuery = new class { - public function getSingleScalarResult() { return 200; } + public function getSingleScalarResult() + { + return 200; + } }; $qb->expects($this->once()) @@ -254,7 +259,10 @@ public function testFetchJoinCollectionFlagIsPassedToPaginator(): void $qb->method('orderBy')->willReturn($qb); $countQuery = new class { - public function getSingleScalarResult() { return 0; } + public function getSingleScalarResult() + { + return 0; + } }; $qb->expects($this->once()) @@ -280,7 +288,12 @@ public function getSingleScalarResult() { return 0; } $qb2->method('setFirstResult')->willReturn($qb2); $qb2->method('setMaxResults')->willReturn($qb2); $qb2->method('orderBy')->willReturn($qb2); - $countQuery2 = new class { public function getSingleScalarResult() { return 0; } }; + $countQuery2 = new class { + public function getSingleScalarResult() + { + return 0; + } + }; $qb2->expects($this->once())->method('getQuery')->willReturn($countQuery2); $dg2 = $this->createDatagrid(new Request(), $store); diff --git a/Tests/bootstrap.php b/Tests/bootstrap.php index 60e4c9d..227ccd6 100644 --- a/Tests/bootstrap.php +++ b/Tests/bootstrap.php @@ -11,7 +11,7 @@ } elseif (is_file($composerAutoload)) { $loader = include $composerAutoload; } else { - die('Unable to find autoload.php file, please use composer to load dependencies: + exit('Unable to find autoload.php file, please use composer to load dependencies: wget http://getcomposer.org/composer.phar php composer.phar install From eb50ee9afe696fc5678ae8430c7549bb3e5d3d1d Mon Sep 17 00:00:00 2001 From: Hugues Date: Tue, 10 Nov 2026 11:41:16 +0100 Subject: [PATCH 3/7] Modernize the stack and remove deprecations Stack: - Require Symfony ^7.4|^8.0 (7.0-7.3 are EOL) and Doctrine ORM ^2.20|^3.3 - Declare the dependencies actually used (dependency-injection, deprecation-contracts); symfony/yaml is no longer needed - Use AbstractBundle instead of the Extension/Configuration classes - Replace Travis CI by GitHub Actions (PHP 8.2 to 8.5, lowest/highest deps), add PHPStan and PHP CS Fixer - Remove dead files (Propel/Symfony 2 test fixtures, routing.yml, tracked .phpunit.result.cache) Deprecations: - Exports no longer call the deprecated postExecute() unless overridden (a deprecation is then triggered) - Remove the deprecated Twig "spaceless" filter from the templates - Fix json_decode(null) in getBatchData() when there is no batch cookie - Drop the PhpSpreadsheet < 1.23 compatibility code - Migrate the PHPUnit configuration, fail on deprecations Fixes: - getAllResults() returned only the current page after execute() - getRequestedAction() threw a TypeError when no action was requested - The session was required at construction time (console commands) - FilterObject now accepts any FormFactoryInterface - batchHeader macro referenced a non-existent "pager" property Tests: rewritten on real Symfony services and an in-memory SQLite database (Doctrine Query is final and can no longer be mocked). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 60 ++++ .gitignore | 5 +- .phpunit.result.cache | 1 - .travis.yml | 17 - Bridge/Doctrine/Helper/QueryBuilderHelper.php | 38 +-- Datagrid/DoctrineDatagrid.php | 65 ++-- Datagrid/Export/AbstractXlsExport.php | 31 +- Datagrid/Export/CsvExport.php | 28 +- Datagrid/FilterObject.php | 8 +- DependencyInjection/Configuration.php | 19 -- .../DoctrineDatagridExtension.php | 29 -- DoctrineDatagridBundle.php | 22 +- README.md | 227 +++++++------ Resources/config/routing.yml | 7 - Resources/config/services.yml | 4 - Resources/views/Datagrid/macros.html.twig | 27 +- Resources/views/Datagrid/pagination.html.twig | 66 ++-- Tests/Bridge/QueryBuilderHelperTest.php | 26 ++ Tests/Datagrid/DoctrineDatagridTest.php | 262 ++++----------- Tests/Datagrid/FilterTest.php | 79 ++--- Tests/Datagrid/PagerTest.php | 43 +-- Tests/Datagrid/QueryBuilderTest.php | 309 ------------------ Tests/Datagrid/QueryTest.php | 181 ++++++++++ Tests/Datagrid/SortTest.php | 123 ++++--- Tests/DatagridTestTrait.php | 70 ++++ Tests/DoctrineDatagridBundleTest.php | 33 ++ Tests/Export/ExportTest.php | 99 ++++++ Tests/Fixtures/App/app/AppKernel.php | 47 --- Tests/Fixtures/App/app/config/config.yml | 33 -- Tests/Fixtures/App/app/config/config_test.yml | 7 - .../App/app/config/parameters.yml.dist | 12 - Tests/Fixtures/App/app/config/routing.yml | 2 - Tests/Fixtures/App/app/console | 22 -- Tests/Fixtures/App/app/propel/sql/sqldb.map | 2 - Tests/Fixtures/Entity/Author.php | 20 ++ Tests/Fixtures/Entity/Book.php | 24 ++ Tests/Fixtures/Export/BookCsvExport.php | 27 ++ Tests/Fixtures/Export/BookXlsExport.php | 27 ++ Tests/Fixtures/Export/LegacyBookCsvExport.php | 18 + Tests/OrmTestTrait.php | 62 ++++ Tests/TemplatesTest.php | 87 +++++ Tests/bootstrap.php | 25 -- composer.json | 47 ++- phpstan.dist.neon | 18 + phpunit.xml.dist | 39 ++- 45 files changed, 1231 insertions(+), 1167 deletions(-) create mode 100644 .github/workflows/ci.yml delete mode 100644 .phpunit.result.cache delete mode 100644 .travis.yml delete mode 100644 DependencyInjection/Configuration.php delete mode 100644 DependencyInjection/DoctrineDatagridExtension.php delete mode 100644 Resources/config/routing.yml delete mode 100644 Resources/config/services.yml create mode 100644 Tests/Bridge/QueryBuilderHelperTest.php delete mode 100644 Tests/Datagrid/QueryBuilderTest.php create mode 100644 Tests/Datagrid/QueryTest.php create mode 100644 Tests/DatagridTestTrait.php create mode 100644 Tests/DoctrineDatagridBundleTest.php create mode 100644 Tests/Export/ExportTest.php delete mode 100644 Tests/Fixtures/App/app/AppKernel.php delete mode 100644 Tests/Fixtures/App/app/config/config.yml delete mode 100644 Tests/Fixtures/App/app/config/config_test.yml delete mode 100644 Tests/Fixtures/App/app/config/parameters.yml.dist delete mode 100644 Tests/Fixtures/App/app/config/routing.yml delete mode 100644 Tests/Fixtures/App/app/console delete mode 100644 Tests/Fixtures/App/app/propel/sql/sqldb.map create mode 100644 Tests/Fixtures/Entity/Author.php create mode 100644 Tests/Fixtures/Entity/Book.php create mode 100644 Tests/Fixtures/Export/BookCsvExport.php create mode 100644 Tests/Fixtures/Export/BookXlsExport.php create mode 100644 Tests/Fixtures/Export/LegacyBookCsvExport.php create mode 100644 Tests/OrmTestTrait.php create mode 100644 Tests/TemplatesTest.php delete mode 100644 Tests/bootstrap.php create mode 100644 phpstan.dist.neon diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..8a0ff99 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,60 @@ +name: CI + +on: + push: + branches: [master] + pull_request: + +permissions: + contents: read + +jobs: + tests: + name: PHP ${{ matrix.php }} - ${{ matrix.dependencies }} deps + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + # Symfony 7.4, Doctrine ORM 2.20, PHPUnit 11 + - php: '8.2' + dependencies: lowest + # Symfony 7.4 + - php: '8.3' + dependencies: highest + # Symfony 8 + - php: '8.4' + dependencies: highest + - php: '8.5' + dependencies: highest + steps: + - uses: actions/checkout@v4 + + - uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: pdo_sqlite + coverage: none + + - uses: ramsey/composer-install@v3 + with: + dependency-versions: ${{ matrix.dependencies }} + + - run: vendor/bin/phpunit + + quality: + name: PHPStan & PHP CS Fixer + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.2' + coverage: none + + - uses: ramsey/composer-install@v3 + + - run: vendor/bin/phpstan analyse --no-progress + - run: vendor/bin/php-cs-fixer fix --dry-run --diff + - run: composer audit diff --git a/.gitignore b/.gitignore index e437a5c..3a78969 100644 --- a/.gitignore +++ b/.gitignore @@ -23,4 +23,7 @@ catalog.xml .htpasswd vendor/ composer.lock -/.phpunit.result.cache \ No newline at end of file +/.phpunit.result.cache +/.phpunit.cache/ +/.php-cs-fixer.cache +/var/ diff --git a/.phpunit.result.cache b/.phpunit.result.cache deleted file mode 100644 index bcd1db3..0000000 --- a/.phpunit.result.cache +++ /dev/null @@ -1 +0,0 @@ -{"version":2,"defects":{"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\DoctrineDatagridTest::testRoutingHelpersBuildExpectedParameters":7,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\FilterTest::testResetClearsSortAndPage":7,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\FilterTest::testResetRestoresDefaultSortAndResetsPage":7,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\QueryBuilderTest::testGetQueryResultsAppliesPaginationAndGroupBy":8,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\QueryBuilderTest::testNbResultsAndNbPagesWithDifferentLimits":8,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\QueryBuilderTest::testFetchJoinCollectionFlagIsPassedToPaginator":7,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\ReproductionErrorTest::testGetQueryResultsWithoutSelectThrowsError":8},"times":{"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\DoctrineDatagridTest::testGetSessionName":0.005,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\DoctrineDatagridTest::testRoutingHelpersBuildExpectedParameters":0,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\DoctrineDatagridTest::testDefaultSortStateFromConfiguration":0,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\DoctrineDatagridTest::testUpdateSortWithWhitelist":0.001,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\DoctrineDatagridTest::testRemoveSort":0,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\DoctrineDatagridTest::testPaginationStateUsingSession":0,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\DoctrineDatagridTest::testDynamicColumnsAvailability":0,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\DoctrineDatagridTest::testFactoryCreatesDatagridWithGivenName":0,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\FilterTest::testPlaceholder":0,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\PagerTest::testPlaceholder":0,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\SortTest::testPlaceholder":0,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\FilterTest::testResetClearsSortAndPage":0,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\PagerTest::testPaginationStateUsingSession":0,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\SortTest::testDefaultSortStateFromConfiguration":0,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\SortTest::testUpdateSortWithWhitelist":0,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\SortTest::testRemoveSort":0,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\FilterTest::testResetRestoresDefaultSortAndResetsPage":0,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\QueryBuilderTest::testQueryInitializationCallsCallbackAndStoresQueryBuilder":0.001,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\QueryBuilderTest::testGetQueryResultsAppliesPaginationAndGroupBy":0.002,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\QueryBuilderTest::testNbResultsAndNbPagesWithDifferentLimits":0,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\QueryBuilderTest::testFetchJoinCollectionFlagIsPassedToPaginator":0,"Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\Datagrid\\ReproductionErrorTest::testGetQueryResultsWithoutSelectThrowsError":0.011}} \ No newline at end of file diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index bed2c75..0000000 --- a/.travis.yml +++ /dev/null @@ -1,17 +0,0 @@ -language: php -php: - - 8.2 - - 8.3 - - 8.4 - -before_script: - - cp Tests/Fixtures/App/app/config/parameters.yml.dist Tests/Fixtures/App/app/config/parameters.yml - - composer install --dev - - ./Tests/Fixtures/App/app/console propel:database:create - - ./Tests/Fixtures/App/app/console propel:sql:insert - - ./Tests/Fixtures/App/app/console propel:build - -notifications: - email: - - maxime.corson@spyrit.net - - charles.henzel@spyrit.net diff --git a/Bridge/Doctrine/Helper/QueryBuilderHelper.php b/Bridge/Doctrine/Helper/QueryBuilderHelper.php index 44803da..1446e5d 100644 --- a/Bridge/Doctrine/Helper/QueryBuilderHelper.php +++ b/Bridge/Doctrine/Helper/QueryBuilderHelper.php @@ -2,48 +2,24 @@ namespace Spyrit\Bundle\DoctrineDatagridBundle\Bridge\Doctrine\Helper; +use Doctrine\ORM\Query\Expr\Join; use Doctrine\ORM\QueryBuilder; class QueryBuilderHelper { public static function addLeftJoin(string $field, string $alias, QueryBuilder $qb): QueryBuilder { - $parts = $qb->getDQLParts()['join']; - $exists = false; + /** @var array $joinsByRootAlias */ + $joinsByRootAlias = $qb->getDQLPart('join'); - foreach ($parts as $joins) { + foreach ($joinsByRootAlias as $joins) { foreach ($joins as $join) { - foreach ((array) $join as $key => $val) { - if ($val == $alias) { - $exists = true; - break 3; - } + if ($join->getAlias() === $alias) { + return $qb; } } } - /* - * The following code is only available for Doctrine 2.5 - */ - /*$parts = $qb->getDQLPart('join'); - $exists = false; - - foreach ($parts as $joins) - { - foreach ($joins as $join) - { - if ($join->getAlias() === $alias) - { - $exists = true; - break 2; - } - } - }*/ - - if (!$exists) { - $qb->leftJoin($field, $alias); - } - - return $qb; + return $qb->leftJoin($field, $alias); } } diff --git a/Datagrid/DoctrineDatagrid.php b/Datagrid/DoctrineDatagrid.php index dc7a3c0..55ab33c 100644 --- a/Datagrid/DoctrineDatagrid.php +++ b/Datagrid/DoctrineDatagrid.php @@ -25,7 +25,10 @@ */ class DoctrineDatagrid { - public const VERSION_SYMFONY7 = 'symfony7'; + /** + * Package version used when triggering deprecations. + */ + public const VERSION_SYMFONY7 = '7.0'; public const ACTION = 'action'; public const ACTION_DATAGRID = 'datagrid'; @@ -54,8 +57,6 @@ class DoctrineDatagrid public const PARAM1 = 'param1'; public const PARAM2 = 'param2'; - protected SessionInterface $session; - /** * The query builder that filter the results. */ @@ -69,7 +70,8 @@ class DoctrineDatagrid * array{ * type: class-string, * options: mixed[], - * query: callable + * query: callable, + * value?: mixed * } * > */ @@ -136,9 +138,8 @@ public function __construct( private readonly FormFactoryInterface $formFactory, private readonly RouterInterface $router, private string $name, - private array $params = [] + private array $params = [], ) { - $this->session = $requestStack->getSession(); } public function create($name, $params = []): void @@ -218,30 +219,19 @@ private function isRequestedDatagrid(): bool return $this->getRequestedDatagrid() === $this->name; } - private function isRequestedAction(?string $action): bool - { - return $this->getRequest()->getString(self::ACTION) === $action; - } - private function getSessionValue(string $name, mixed $default = null): mixed { - return $this->getRequest() - ->getSession() - ->get($this->getSessionName().'.'.$name, $default); + return $this->getSession()->get($this->getSessionName().'.'.$name, $default); } private function setSessionValue(string $name, mixed $value): void { - $this->getRequest() - ->getSession() - ->set($this->getSessionName().'.'.$name, $value); + $this->getSession()->set($this->getSessionName().'.'.$name, $value); } - private function removeSessionValue(string $name) + private function removeSessionValue(string $name): void { - return $this->getRequest() - ->getSession() - ->remove($this->getSessionName().'.'.$name); + $this->getSession()->remove($this->getSessionName().'.'.$name); } protected function getQueryResults(): Paginator|array @@ -417,7 +407,7 @@ private function buildForm(): void $this->filterObject->add( $name, $filter['type'], - $filter['options'] ?? [], + $filter['options'], $filter['value'] ?? null ); } @@ -458,18 +448,6 @@ public function resetFilters(): static return $this; } - private function getSessionFilter(mixed $default = []): mixed - { - return $this->getSessionValue('filter', $default); - } - - private function setSessionFilter(mixed $value): static - { - $this->setSessionValue('filter', $value); - - return $this; - } - /** * Shortcut. */ @@ -663,7 +641,11 @@ public function getAllResults(): mixed $this->doSort(); $this->doFilter(); - $qb = $this->getQueryBuilder()->select(($this->distinct ? 'DISTINCT ' : '').$this->select); + // The query builder may already be paginated if execute() has been called before + $qb = (clone $this->getQueryBuilder()) + ->select(($this->distinct ? 'DISTINCT ' : '').$this->select) + ->setFirstResult(0) + ->setMaxResults(null); return $qb->getQuery()->execute(); } @@ -783,7 +765,7 @@ public function setMaxPerPage(int $value): static /** * @param 'action'|'datagrid'|'page'|'sort'|'remove-sort'|'reset'|'limit'|'add-column'|'remove-column'|null $default */ - protected function getRequestedAction(?string $default = null): string + protected function getRequestedAction(?string $default = null): ?string { Assert::inArray($default, [null, ...self::ALLOWED_ACTIONS], 'Action must be one of: '.implode(', ', self::ALLOWED_ACTIONS).'. %s given.'); @@ -850,9 +832,9 @@ protected function getRequestedColumnRemoval(?string $default = null) return $this->getRequestParams($this->getRequest())->get(self::PARAM1, $default); } - protected function getRequestedLimit(?int $default = null): int + protected function getRequestedLimit(int $default = 0): int { - return $this->getRequestParams($this->getRequest())->get(self::PARAM1, $default); + return $this->getRequestParams($this->getRequest())->getInt(self::PARAM1, $default); } /** Global service shortcuts *****/ @@ -863,7 +845,7 @@ protected function getRequest(): Request protected function getSession(): SessionInterface { - return $this->session; + return $this->requestStack->getSession(); } /** @@ -999,7 +981,10 @@ public function getMaxPerPagePath(string $route, int $limit, array $extraParams public function getBatchData(): array { - return (array) json_decode($this->getRequest()->cookies->get($this->name.'_batch')); + $cookie = $this->getRequest()->cookies->get($this->name.'_batch'); + $data = null !== $cookie ? json_decode($cookie, true) : null; + + return is_array($data) ? $data : []; } public function isBatchChecked(mixed $identifier): bool diff --git a/Datagrid/Export/AbstractXlsExport.php b/Datagrid/Export/AbstractXlsExport.php index 56287b8..dad759f 100644 --- a/Datagrid/Export/AbstractXlsExport.php +++ b/Datagrid/Export/AbstractXlsExport.php @@ -7,12 +7,13 @@ use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; use Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\DoctrineDatagrid; +use Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\Util; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\ResponseHeaderBag; abstract class AbstractXlsExport implements Export { - protected $content; + protected ?string $content = null; protected array $params; @@ -42,18 +43,33 @@ public function preExecute(): void { } + /** + * @deprecated since 7.0, override preExecute() instead + */ #[\Deprecated(message: 'postExecute has been deprecated, as it is implemented as a preExecute. Use preExecute instead', since: DoctrineDatagrid::VERSION_SYMFONY7)] public function postExecute() { return $this; } - public function execute(): static + /** + * Keeps BC for exports still overriding postExecute(), without triggering + * a deprecation for the others. + */ + private function callDeprecatedPostExecute(): void { - $this->preExecute(); + if (self::class === (new \ReflectionMethod($this, 'postExecute'))->getDeclaringClass()->getName()) { + return; + } - // postExecute before executing ? Meh. + Util::triggerDeprecation(sprintf('Overriding "%s::postExecute()" is deprecated, override "preExecute()" instead.', self::class), DoctrineDatagrid::VERSION_SYMFONY7); $this->postExecute(); + } + + public function execute(): static + { + $this->preExecute(); + $this->callDeprecatedPostExecute(); if (!class_exists(Spreadsheet::class)) { throw new \LogicException('PhpSpreadsheet is required to export to XLSX. Try `composer require phpoffice/phpspreadsheet`'); @@ -80,12 +96,7 @@ public function execute(): static if (isset($headers[$name])) { $col = 1; foreach ($headers[$name] as $value) { - if (method_exists($sheet, 'setCellValueByColumnAndRow')) { - // setCellValueByColumnAndRow is deprecated in PhpSpreadsheet v1.23 - $sheet->setCellValueByColumnAndRow($col, $row, $value); - } else { - $sheet->setCellValue([$col, $row], $value); - } + $sheet->setCellValue([$col, $row], $value); ++$col; } ++$row; diff --git a/Datagrid/Export/CsvExport.php b/Datagrid/Export/CsvExport.php index 9b46278..d5af349 100644 --- a/Datagrid/Export/CsvExport.php +++ b/Datagrid/Export/CsvExport.php @@ -5,6 +5,7 @@ use CSanquer\ColibriCsv\CsvWriter; use Doctrine\ORM\QueryBuilder; use Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\DoctrineDatagrid; +use Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\Util; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\ResponseHeaderBag; @@ -13,13 +14,13 @@ */ abstract class CsvExport implements Export { - protected $content; + protected ?string $content = null; protected array $params; protected QueryBuilder $qb; - public function __construct($qb, $params) + public function __construct(QueryBuilder $qb, array $params) { $this->qb = $qb; $this->params = $params; @@ -32,18 +33,33 @@ public function preExecute(): void { } + /** + * @deprecated since 7.0, override preExecute() instead + */ #[\Deprecated(message: 'postExecute has been deprecated, as it is implemented as a preExecute. Use preExecute instead', since: DoctrineDatagrid::VERSION_SYMFONY7)] public function postExecute() { return $this; } - public function execute(): static + /** + * Keeps BC for exports still overriding postExecute(), without triggering + * a deprecation for the others. + */ + private function callDeprecatedPostExecute(): void { - $this->preExecute(); + if (self::class === (new \ReflectionMethod($this, 'postExecute'))->getDeclaringClass()->getName()) { + return; + } - // postExecute before executing ? Meh. + Util::triggerDeprecation(sprintf('Overriding "%s::postExecute()" is deprecated, override "preExecute()" instead.', self::class), DoctrineDatagrid::VERSION_SYMFONY7); $this->postExecute(); + } + + public function execute(): static + { + $this->preExecute(); + $this->callDeprecatedPostExecute(); $writer = new CsvWriter($this->getCsvWriterOptions()); $writer->createTempStream(); @@ -79,7 +95,7 @@ public function getResponse(): Response $response->headers->set('Expires', '0'); $response->headers->set('Cache-Control', 'must-revalidate, post-check=0, pre-check=0'); $response->headers->set('Pragma', 'public'); - $response->headers->set('Content-Length', strlen($this->content)); + $response->headers->set('Content-Length', (string) strlen($this->content)); $response->setCharset('UTF-8'); return $response; diff --git a/Datagrid/FilterObject.php b/Datagrid/FilterObject.php index 33dfea1..5a8373c 100644 --- a/Datagrid/FilterObject.php +++ b/Datagrid/FilterObject.php @@ -4,7 +4,7 @@ use Symfony\Component\Form\Extension\Core\Type\FormType; use Symfony\Component\Form\FormBuilderInterface; -use Symfony\Component\Form\FormFactory; +use Symfony\Component\Form\FormFactoryInterface; use Symfony\Component\Form\FormInterface; /** @@ -20,9 +20,9 @@ class FilterObject protected FormBuilderInterface $builder; - protected $form; + protected ?FormInterface $form = null; - public function __construct(FormFactory $factory, $name, $options = ['csrf_protection' => false]) + public function __construct(FormFactoryInterface $factory, string $name, array $options = ['csrf_protection' => false]) { $this->builder = $factory->createNamedBuilder('filter_'.$name, FormType::class, null, $options); } @@ -62,7 +62,7 @@ public function getForm(): FormInterface return $this->form; } - public function getType($field): mixed + public function getType(mixed $field): mixed { return $this->types[$field] ?? null; } diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php deleted file mode 100644 index 0076c5b..0000000 --- a/DependencyInjection/Configuration.php +++ /dev/null @@ -1,19 +0,0 @@ -processConfiguration($configuration, $configs);*/ - - $loader = new Loader\YamlFileLoader( - $container, - new FileLocator(__DIR__.'/../Resources/config') - ); - - $loader->load('services.yml'); - } -} diff --git a/DoctrineDatagridBundle.php b/DoctrineDatagridBundle.php index dbf4062..03caca2 100644 --- a/DoctrineDatagridBundle.php +++ b/DoctrineDatagridBundle.php @@ -2,8 +2,26 @@ namespace Spyrit\Bundle\DoctrineDatagridBundle; -use Symfony\Component\HttpKernel\Bundle\Bundle; +use Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\DoctrineDatagridFactory; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; +use Symfony\Component\HttpKernel\Bundle\AbstractBundle; -class DoctrineDatagridBundle extends Bundle +class DoctrineDatagridBundle extends AbstractBundle { + /** + * The bundle sources live at the package root (no "src/" directory). + */ + public function getPath(): string + { + return __DIR__; + } + + public function loadExtension(array $config, ContainerConfigurator $container, ContainerBuilder $builder): void + { + $container->services() + ->set(DoctrineDatagridFactory::class) + ->autowire() + ; + } } diff --git a/README.md b/README.md index 3b5b011..56792d3 100644 --- a/README.md +++ b/README.md @@ -9,136 +9,165 @@ This make it easy to implement and use in both back-end and front-end applicatio Still skeptical? Let's see how it works! +## Requirements + +- PHP 8.2+ +- Symfony 7.4 / 8.x +- Doctrine ORM 2.20+ / 3.x +- `phpoffice/phpspreadsheet` (optional) to export to XLSX + ## Installation ### Get the code To install this bundle automatically, use Composer: - composer req spyrit/doctrine-datagrid-bundle +```bash +composer require spyrit/doctrine-datagrid-bundle +``` ### Use it Create your datagrids: - datagrid = $factory - ->create('video', ['multi_sort' => false]) - ->select(['video']) - ->id('video.id') - ->query(function ($qb) { - return $qb->from(Video::class, 'video'); - }) - ->filter('title', TextType::class, [ - 'attr' => [ - 'placeholder' => 'Title', - ], - 'translation_domain' => false, - 'required' => false, - ], function ($value, $qb) { - return $qb->andWhere('video.title LIKE :title') - ->setParameter('title', '%'.$value.'%'); - }) - ->setDefaultSort(['video.id' => 'desc']) - ->setDefaultMaxPerPage(30); - } - - public function execute(): DoctrineDatagrid - { - return $this->datagrid->execute(); - } + $this->datagrid = $factory + ->create('video', ['multi_sort' => false]) + ->select(['video']) + ->id('video.id') + ->query(fn (QueryBuilder $qb): QueryBuilder => $qb->from(Video::class, 'video')) + ->filter('title', TextType::class, [ + 'attr' => [ + 'placeholder' => 'Title', + ], + 'translation_domain' => false, + 'required' => false, + ], fn (string $value, QueryBuilder $qb): QueryBuilder => $qb + ->andWhere('video.title LIKE :title') + ->setParameter('title', '%'.$value.'%')) + // Restrict the columns a user can sort on (recommended) + ->setAllowedSorts(['video.id', 'video.title']) + ->setDefaultSort(['video.id' => 'DESC']) + ->setDefaultMaxPerPage(30); } + public function execute(): DoctrineDatagrid + { + return $this->datagrid->execute(); + } +} +``` + +> Sort directions must be uppercase (`ASC` / `DESC`): lowercase values are deprecated. + Use your datagrids in your controllers: - render('video/index.html.twig', [ - 'datagrid' => $datagrid->execute(), - ]); - } + return $this->render('video/index.html.twig', [ + 'datagrid' => $datagrid->execute(), + ]); } +} +``` Render them in your views: - {% extends 'layout.html.twig' %} - {% import '@DoctrineDatagrid/Datagrid/macros.html.twig' as macros %} - - {% set form = datagrid.filterFormView %} - {% set route = app.request.attributes.get('_route') %} - - {% block body %} - - - - {{ form_start(form) }} - - - {{ form_end(form) }} +```twig +{% extends 'layout.html.twig' %} +{% import '@DoctrineDatagrid/Datagrid/macros.html.twig' as macros %} + +{% set form = datagrid.filterFormView %} +{% set route = app.request.attributes.get('_route') %} + +{% block body %} +
- {{ form_widget(form.title) }} - - - {{ 'Reset' }} -
+ + + {{ form_start(form) }} + + + {{ form_end(form) }} + + + + + + + + {% for video in datagrid.results %} + + + + {% else %} - - + - - - {% for video in datagrid.results %} - - - - - {% else %} - - - - {% endfor %} - -
+ {{ form_widget(form.title) }} + + + {{ 'Reset' }} +
{{ 'Title' }}{{ 'Description' }}
{{ video.title }}{{ video.description }}
{{ 'Title' }}{{ 'Description' }}{{ 'No video' }}
{{ video.title }}{{ video.description }}
{{ 'No video' }}
-
-
-
- {% include '@DoctrineDatagrid/Datagrid/pagination_info.html.twig' %} -
-
- {% include '@DoctrineDatagrid/Datagrid/pagination.html.twig' %} -
+ {% endfor %} + + +
+
+
+ {% include '@DoctrineDatagrid/Datagrid/pagination_info.html.twig' %} +
+
+ {% include '@DoctrineDatagrid/Datagrid/pagination.html.twig' %}
- {% endblock %} +
+{% endblock %} +``` + +## Exports + +Declare export classes extending `CsvExport` or `AbstractXlsExport` with `setExports(['csv' => BookCsvExport::class])`, +then call `$datagrid->export('csv')->getResponse()`. Override `preExecute()` to alter the query before the export +(`postExecute()` is deprecated). + +## Development + +```bash +composer install +composer test # PHPUnit +composer phpstan # static analysis +composer cs # coding standards (composer cs-fix to fix them) +``` ## Credit diff --git a/Resources/config/routing.yml b/Resources/config/routing.yml deleted file mode 100644 index e4dec4d..0000000 --- a/Resources/config/routing.yml +++ /dev/null @@ -1,7 +0,0 @@ -datagrid_list: - pattern: /datagrid/demo/book/list/{action}/{datagrid}/{param1}/{param2} - defaults: { _controller: DoctrineDatagridBundle:Demo:list, action: null, datagrid: null, param1: null, param2: null } - -datagrid_export: - pattern: /datagrid/demo/book/export/{name} - defaults: { _controller: DoctrineDatagridBundle:Demo:export } \ No newline at end of file diff --git a/Resources/config/services.yml b/Resources/config/services.yml deleted file mode 100644 index 7f2463b..0000000 --- a/Resources/config/services.yml +++ /dev/null @@ -1,4 +0,0 @@ -services: - _defaults: - autowire: true - Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\DoctrineDatagridFactory: ~ \ No newline at end of file diff --git a/Resources/views/Datagrid/macros.html.twig b/Resources/views/Datagrid/macros.html.twig index 1274294..90820c2 100644 --- a/Resources/views/Datagrid/macros.html.twig +++ b/Resources/views/Datagrid/macros.html.twig @@ -35,23 +35,23 @@ {% macro columnActions(column, route, datagrid, extraParams = {}) %}
- +
- +
-
'|escape('html') }} - {% endif %} - {{ (' Supprimer la colonne')|escape('html') }} - {% endapply %}"> +
'|escape('html') -}} + {%- endif -%} + {{- (' Supprimer la colonne')|escape('html') -}} + "> {% endmacro %} @@ -62,7 +62,7 @@ data-trigger="manual" data-placement="bottom" data-html="true" - data-content="Les {{ datagrid.pager.results|length }} enregistrements de cette page sont sélectionnés. Sélectionner les {{ datagrid.results|length }} enregistrements de la recherche." + data-content="Les {{ datagrid.results.iterator|length }} enregistrements de cette page sont sélectionnés. Sélectionner les {{ datagrid.nbResults }} enregistrements de la recherche." {% endif %} {% if datagrid.hasAllCheckedBatch %} checked="checked" @@ -78,7 +78,6 @@ value="{{ identifier }}" {% if datagrid.isBatchChecked(identifier) %} checked="checked" - {% else %} {% endif %} /> {% endmacro %} diff --git a/Resources/views/Datagrid/pagination.html.twig b/Resources/views/Datagrid/pagination.html.twig index 971e89d..6a826e7 100644 --- a/Resources/views/Datagrid/pagination.html.twig +++ b/Resources/views/Datagrid/pagination.html.twig @@ -1,44 +1,26 @@ -{% apply spaceless %} -{% set extraParameters = extraParameters|default({}) %} -{% set display = display|default(2) %} -{% set page = datagrid.currentPage %} -{% set pages = datagrid.nbPages %} +{%- set extraParameters = extraParameters|default({}) -%} +{%- set display = display|default(2) -%} +{%- set page = datagrid.currentPage -%} +{%- set pages = datagrid.nbPages -%} -{% if pages > 1 %} -{% set available = ['1'] %} -{% set i = page - display %} -{% set min = page - display %} -{% set max = page + display %} -{% for min in i..max %} - {% if(min > 1 and min < pages) %} - {% set available = available|merge([min]) %} - {% endif %} - {% set min = min + 1 %} -{% endfor %} +{%- if pages > 1 -%} + {%- set available = [1] -%} + {%- for candidate in (page - display)..(page + display) -%} + {%- if candidate > 1 and candidate < pages -%} + {%- set available = available|merge([candidate]) -%} + {%- endif -%} + {%- endfor -%} + {%- set available = available|merge([pages]) -%} -{% set available = available|merge([pages]) %} - -
    - {% set next = available[0] %} - {% set i = 0 %} - {% for currentPage in available %} - {% if(next != currentPage) %} -
  • - ... -
  • - {% if(available[i+1] is defined) %}{% set next = available[i+1] %}{% endif %} - {% else %} - {% set next = next + 1 %} - {% endif %} -
  • - - {{ currentPage }} - -
  • - {% set i = i + 1 %} - {% endfor %} -
-{% endif %} -{% endapply %} +
    + {%- set previous = 0 -%} + {%- for currentPage in available -%} + {%- if currentPage > previous + 1 -%} +
  • ...
  • + {%- endif -%} + {%- set isCurrent = currentPage == page -%} +
  • {{ currentPage }}
  • + {%- set previous = currentPage -%} + {%- endfor -%} +
+{%- endif -%} diff --git a/Tests/Bridge/QueryBuilderHelperTest.php b/Tests/Bridge/QueryBuilderHelperTest.php new file mode 100644 index 0000000..8cbc11c --- /dev/null +++ b/Tests/Bridge/QueryBuilderHelperTest.php @@ -0,0 +1,26 @@ +createEntityManager()->createQueryBuilder()->select('b')->from(Book::class, 'b'); + + QueryBuilderHelper::addLeftJoin('b.author', 'a', $qb); + QueryBuilderHelper::addLeftJoin('b.author', 'a', $qb); + + $this->assertSame( + 'SELECT b FROM '.Book::class.' b LEFT JOIN b.author a', + $qb->getDQL(), + ); + } +} diff --git a/Tests/Datagrid/DoctrineDatagridTest.php b/Tests/Datagrid/DoctrineDatagridTest.php index 70fbfb3..f90a29b 100644 --- a/Tests/Datagrid/DoctrineDatagridTest.php +++ b/Tests/Datagrid/DoctrineDatagridTest.php @@ -6,232 +6,114 @@ use PHPUnit\Framework\TestCase; use Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\DoctrineDatagrid; use Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\DoctrineDatagridFactory; -use Symfony\Component\Form\FormFactoryInterface; +use Spyrit\Bundle\DoctrineDatagridBundle\Tests\DatagridTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; -use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\Routing\RouterInterface; final class DoctrineDatagridTest extends TestCase { - private function createDatagrid(Request $request, array &$sessionStore, array $params = [], ?RouterInterface $router = null): DoctrineDatagrid - { - $em = $this->createMock(EntityManagerInterface::class); - $formFactory = $this->createMock(FormFactoryInterface::class); - $router ??= $this->createMock(RouterInterface::class); - - // Session mock with in-memory storage - $session = $this->createMock(SessionInterface::class); - $session->method('get')->willReturnCallback(function (string $name, $default = null) use (&$sessionStore) { - return $sessionStore[$name] ?? $default; - }); - $session->method('set')->willReturnCallback(function (string $name, $value) use (&$sessionStore) { - $sessionStore[$name] = $value; - }); - $session->method('remove')->willReturnCallback(function (string $name) use (&$sessionStore) { - unset($sessionStore[$name]); - }); - - // Attach session to request - $request->setSession($session); - - // RequestStack mock that provides current request and direct session access - $requestStack = $this->getMockBuilder(RequestStack::class) - ->onlyMethods(['getCurrentRequest', 'getSession']) - ->getMock(); - $requestStack->method('getCurrentRequest')->willReturn($request); - $requestStack->method('getSession')->willReturn($session); - - return new DoctrineDatagrid($em, $requestStack, $formFactory, $router, 'dg', $params); - } + use DatagridTestTrait; public function testGetSessionName(): void { - $request = new Request(); - $store = []; - $dg = $this->createDatagrid($request, $store); - $this->assertSame('datagrid.dg', $dg->getSessionName()); + $this->assertSame('datagrid.dg', $this->createDatagrid()->getSessionName()); } - public function testRoutingHelpersBuildExpectedParameters(): void + public function testConstructionDoesNotRequireASession(): void { - $request = new Request(); - $store = []; - - $router = $this->createMock(RouterInterface::class); - // Assert parameters for pagination - $router->expects($this->atLeastOnce()) - ->method('generate') - ->with( - $this->anything(), - $this->callback(function (array $params) { - // Accept any route name, just validate mandatory params exist - return isset($params['action'], $params['datagrid']); - }) - ) - ->willReturn('/ok'); - - $dg = $this->createDatagrid($request, $store, [], $router); - $this->assertSame('/ok', $dg->getPaginationPath('route_name', 2)); - $this->assertSame('/ok', $dg->getResetPath('route_name')); - $this->assertSame('/ok', $dg->getSortPath('route_name', 'col', 'asc')); - $this->assertSame('/ok', $dg->getRemoveSortPath('route_name', 'col')); + // e.g. a datagrid built from a console command, before any request is handled + $dg = new DoctrineDatagrid( + $this->createStub(EntityManagerInterface::class), + new RequestStack(), + $this->createFormFactory(), + $this->createStub(RouterInterface::class), + 'dg', + ); + + $this->assertSame('datagrid.dg', $dg->getSessionName()); } - public function testDefaultSortStateFromConfiguration(): void + public function testRoutingHelpersBuildExpectedParameters(): void { - $request = new Request(); - $store = []; - $dg = $this->createDatagrid($request, $store); + $generated = []; + $router = $this->createStub(RouterInterface::class); + $router->method('generate')->willReturnCallback(function (string $route, array $params) use (&$generated): string { + $generated[] = $params; - $dg->setDefaultSort(['foo' => 'asc']); + return '/'.$route; + }); - $this->assertTrue($dg->isSortedColumn('foo')); - $this->assertSame('asc', $dg->getSortedColumnOrder('foo')); - $this->assertSame(0, $dg->getSortedColumnPriority('foo')); - $this->assertSame(1, $dg->getSortCount()); + $dg = $this->createDatagrid(router: $router); + + $this->assertSame('/books', $dg->getPaginationPath('books', 2, ['foo' => 'bar'])); + $dg->getResetPath('books'); + $dg->getSortPath('books', 'b.title', 'DESC'); + $dg->getRemoveSortPath('books', 'b.title'); + $dg->getNewColumnPath('books', 'email', 'name'); + $dg->getRemoveColumnPath('books', 'email'); + $dg->getMaxPerPagePath('books', 50); + + $this->assertSame([ + ['action' => 'page', 'datagrid' => 'dg', 'param1' => 2, 'foo' => 'bar'], + ['action' => 'reset', 'datagrid' => 'dg'], + ['action' => 'sort', 'datagrid' => 'dg', 'param1' => 'b.title', 'param2' => 'DESC'], + ['action' => 'remove-sort', 'datagrid' => 'dg', 'param1' => 'b.title'], + ['action' => 'add-column', 'datagrid' => 'dg', 'param1' => 'email', 'param2' => 'name'], + ['action' => 'remove-column', 'datagrid' => 'dg', 'param1' => 'email'], + ['action' => 'limit', 'datagrid' => 'dg', 'param1' => 50], + ], $generated); } - public function testUpdateSortWithWhitelist(): void + public function testDynamicColumnsAvailability(): void { - // Prepare a sort request for column "bar" desc - $request = new Request([ - 'action' => 'sort', - 'datagrid' => 'dg', - 'param1' => 'bar', - 'param2' => 'desc', - ]); - $store = []; - $dg = $this->createDatagrid($request, $store, ['multi_sort' => true]); - $dg->setDefaultSort(['foo' => 'asc']); - $dg->setAllowedSorts(['bar', 'baz']); - - $dg->updateSort(); - - $this->assertTrue($dg->isSortedColumn('bar')); - $this->assertSame('desc', $dg->getSortedColumnOrder('bar')); - // Multi sort keeps previous defaults too - $this->assertSame(2, $dg->getSortCount()); - } + $dg = $this->createDatagrid(class: ColumnsDatagrid::class); - public function testRemoveSort(): void - { - // Start with two sorts stored in session - $request = new Request([ - 'action' => 'remove_sort', - 'datagrid' => 'dg', - 'param1' => 'bar', - ]); - $store = []; - $dg = $this->createDatagrid($request, $store); - // prime session with sorts - // Using public API: set session "sort" by calling setDefaultSort then updateSort twice - $dg->setDefaultSort(['foo' => 'asc', 'bar' => 'desc']); - - $this->assertSame(2, $dg->getSortCount()); - $dg->removeSort(); - $this->assertSame(1, $dg->getSortCount()); - $this->assertFalse($dg->isSortedColumn('bar')); + $this->assertSame(['id' => 'ID', 'name' => 'Name'], $dg->getColumns()); + $this->assertSame(['email' => 'Email', 'country' => 'Country'], $dg->getAvailableAppendableColumns()); } - public function testPaginationStateUsingSession(): void + public function testFactoryCreatesDatagridWithGivenName(): void { - $request = new Request(); - $store = []; - $dg = $this->createDatagrid($request, $store); - - $this->assertSame(1, $dg->getCurrentPage()); - $dg->setCurrentPage(3); - $this->assertSame(3, $dg->getCurrentPage()); - - $dg->setDefaultMaxPerPage(30); - $this->assertSame(30, $dg->getMaxPerPage()); - $dg->setMaxPerPage(50); - $this->assertSame(50, $dg->getMaxPerPage()); - $this->assertSame([15, 30, 50], $dg->getAvailableMaxPerPage()); + $factory = new DoctrineDatagridFactory( + $this->createStub(EntityManagerInterface::class), + $this->createRequestStack(new Request()), + $this->createFormFactory(), + $this->createStub(RouterInterface::class), + ); + + $this->assertSame('datagrid.custom', $factory->create('custom')->getSessionName()); } - public function testDynamicColumnsAvailability(): void + public function testBatchHelpers(): void { - $request = new Request(); - $store = []; - - // Anonymous subclass to provide default/appendable columns - $dg = new class(...$this->extractCtorArgs($request, $store)) extends DoctrineDatagrid { - public function getDefaultColumns(): array - { - return ['id' => 'ID', 'name' => 'Name']; - } - - public function getAppendableColumns(): array - { - return ['email' => 'Email', 'country' => 'Country']; - } - }; - - // When nothing stored in session, current columns are defaults, so available appendables exclude defaults - $available = $dg->getAvailableAppendableColumns(); - $this->assertArrayHasKey('email', $available); - $this->assertArrayHasKey('country', $available); - $this->assertArrayNotHasKey('id', $available); - $this->assertArrayNotHasKey('name', $available); + $request = new Request(cookies: ['dg_batch' => json_encode(['type' => 'include', 'checked' => [1, 3]])]); + $dg = $this->createDatagrid($request); + + $this->assertTrue($dg->isBatchChecked(1)); + $this->assertFalse($dg->isBatchChecked(2)); + $this->assertSame(['type' => 'include', 'checked' => [1, 3]], $dg->getBatchData()); } - public function testFactoryCreatesDatagridWithGivenName(): void + public function testBatchHelpersWithoutCookie(): void { - $request = new Request(); - $store = []; - - [$em, $requestStack, $formFactory, $router] = $this->extractRawServices($request, $store); - $factory = new DoctrineDatagridFactory($em, $requestStack, $formFactory, $router); - $dg = $factory->create('custom'); + $dg = $this->createDatagrid(); - $this->assertInstanceOf(DoctrineDatagrid::class, $dg); - $this->assertSame('datagrid.custom', $dg->getSessionName()); + $this->assertSame([], $dg->getBatchData()); + $this->assertFalse($dg->isBatchChecked(1)); + $this->assertFalse($dg->hasCheckedBatch()); } +} - /** - * Helper to reuse the same service mocks as createDatagrid but return raw args for subclassing. - * - * @return array{0: EntityManagerInterface, 1: RequestStack, 2: FormFactoryInterface, 3: RouterInterface} - */ - private function extractRawServices(Request $request, array &$sessionStore): array +class ColumnsDatagrid extends DoctrineDatagrid +{ + public function getDefaultColumns(): array { - $em = $this->createMock(EntityManagerInterface::class); - $formFactory = $this->createMock(FormFactoryInterface::class); - $router = $this->createMock(RouterInterface::class); - - $session = $this->createMock(SessionInterface::class); - $session->method('get')->willReturnCallback(function (string $name, $default = null) use (&$sessionStore) { - return $sessionStore[$name] ?? $default; - }); - $session->method('set')->willReturnCallback(function (string $name, $value) use (&$sessionStore) { - $sessionStore[$name] = $value; - }); - $session->method('remove')->willReturnCallback(function (string $name) use (&$sessionStore) { - unset($sessionStore[$name]); - }); - - $request->setSession($session); - - $requestStack = $this->getMockBuilder(RequestStack::class) - ->onlyMethods(['getCurrentRequest', 'getSession']) - ->getMock(); - $requestStack->method('getCurrentRequest')->willReturn($request); - $requestStack->method('getSession')->willReturn($session); - - return [$em, $requestStack, $formFactory, $router]; + return ['id' => 'ID', 'name' => 'Name']; } - /** - * Same as extractRawServices but returns spreadable constructor args for DoctrineDatagrid. - * - * @return array{0: EntityManagerInterface, 1: RequestStack, 2: FormFactoryInterface, 3: RouterInterface, 4: string, 5: array} - */ - private function extractCtorArgs(Request $request, array &$sessionStore): array + public function getAppendableColumns(): array { - [$em, $requestStack, $formFactory, $router] = $this->extractRawServices($request, $sessionStore); - - return [$em, $requestStack, $formFactory, $router, 'dg', []]; + return ['email' => 'Email', 'country' => 'Country']; } } diff --git a/Tests/Datagrid/FilterTest.php b/Tests/Datagrid/FilterTest.php index 85e8618..fa072bf 100644 --- a/Tests/Datagrid/FilterTest.php +++ b/Tests/Datagrid/FilterTest.php @@ -2,79 +2,42 @@ namespace Spyrit\Bundle\DoctrineDatagridBundle\Tests\Datagrid; -use Doctrine\ORM\EntityManagerInterface; use PHPUnit\Framework\TestCase; -use Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\DoctrineDatagrid; -use Symfony\Component\Form\FormFactoryInterface; +use Spyrit\Bundle\DoctrineDatagridBundle\Tests\DatagridTestTrait; use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\RequestStack; -use Symfony\Component\HttpFoundation\Session\SessionInterface; -use Symfony\Component\Routing\RouterInterface; final class FilterTest extends TestCase { - private function createDatagrid(Request $request, array &$sessionStore, array $params = []): DoctrineDatagrid - { - $em = $this->createMock(EntityManagerInterface::class); - $formFactory = $this->createMock(FormFactoryInterface::class); - $router = $this->createMock(RouterInterface::class); - - // Session mock with in-memory storage - $session = $this->createMock(SessionInterface::class); - $session->method('get')->willReturnCallback(function (string $name, $default = null) use (&$sessionStore) { - return $sessionStore[$name] ?? $default; - }); - $session->method('set')->willReturnCallback(function (string $name, $value) use (&$sessionStore) { - $sessionStore[$name] = $value; - }); - $session->method('remove')->willReturnCallback(function (string $name) use (&$sessionStore) { - unset($sessionStore[$name]); - }); - - // Attach session to request - $request->setSession($session); - - // RequestStack mock that provides current request and direct session access - $requestStack = $this->getMockBuilder(RequestStack::class) - ->onlyMethods(['getCurrentRequest', 'getSession']) - ->getMock(); - $requestStack->method('getCurrentRequest')->willReturn($request); - $requestStack->method('getSession')->willReturn($session); - - return new DoctrineDatagrid($em, $requestStack, $formFactory, $router, 'dg', $params); - } + use DatagridTestTrait; public function testResetRestoresDefaultSortAndResetsPage(): void { - // First create a datagrid and set defaults - $request = new Request(); - $store = []; - $dg = $this->createDatagrid($request, $store); - $dg->setDefaultSort(['foo' => 'asc']); - - // Change state: page and sort (override default 'asc' to 'desc') + $dg = $this->createDatagrid(); + $dg->setDefaultSort(['foo' => 'ASC']); $dg->setCurrentPage(4); $this->assertSame(4, $dg->getCurrentPage()); - $requestSort = new Request([ - 'action' => 'sort', - 'datagrid' => 'dg', - 'param1' => 'foo', - 'param2' => 'desc', - ]); - // Use same session store to persist state across instances - $dg2 = $this->createDatagrid($requestSort, $store); - // Re-apply defaults for this instance as well - $dg2->setDefaultSort(['foo' => 'asc']); + // Same session, new request + $dg2 = $this->createDatagrid(new Request(['action' => 'sort', 'datagrid' => 'dg', 'param1' => 'foo', 'param2' => 'DESC'])); + $dg2->setDefaultSort(['foo' => 'ASC']); $dg2->updateSort(); - $this->assertSame('desc', $dg2->getSortedColumnOrder('foo')); + $this->assertSame('DESC', $dg2->getSortedColumnOrder('foo')); - // Reset should clear session and restore default sort + reset page $dg2->reset(); $this->assertSame(1, $dg2->getCurrentPage()); - // After reset, the default sort ('asc') should be effective again - $this->assertTrue($dg2->isSortedColumn('foo')); - $this->assertSame('asc', $dg2->getSortedColumnOrder('foo')); + $this->assertSame('ASC', $dg2->getSortedColumnOrder('foo')); + } + + public function testIsFiltered(): void + { + $dg = $this->createDatagrid(); + $this->assertFalse($dg->isFiltered()); + + $dg->setFilterValue('genre', 'essay'); + $this->assertTrue($dg->isFiltered()); + + $dg->resetFilters(); + $this->assertFalse($dg->isFiltered()); } } diff --git a/Tests/Datagrid/PagerTest.php b/Tests/Datagrid/PagerTest.php index 21b62bd..146651a 100644 --- a/Tests/Datagrid/PagerTest.php +++ b/Tests/Datagrid/PagerTest.php @@ -2,53 +2,16 @@ namespace Spyrit\Bundle\DoctrineDatagridBundle\Tests\Datagrid; -use Doctrine\ORM\EntityManagerInterface; use PHPUnit\Framework\TestCase; -use Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\DoctrineDatagrid; -use Symfony\Component\Form\FormFactoryInterface; -use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\RequestStack; -use Symfony\Component\HttpFoundation\Session\SessionInterface; -use Symfony\Component\Routing\RouterInterface; +use Spyrit\Bundle\DoctrineDatagridBundle\Tests\DatagridTestTrait; final class PagerTest extends TestCase { - private function createDatagrid(Request $request, array &$sessionStore, array $params = []): DoctrineDatagrid - { - $em = $this->createMock(EntityManagerInterface::class); - $formFactory = $this->createMock(FormFactoryInterface::class); - $router = $this->createMock(RouterInterface::class); - - // Session mock with in-memory storage - $session = $this->createMock(SessionInterface::class); - $session->method('get')->willReturnCallback(function (string $name, $default = null) use (&$sessionStore) { - return $sessionStore[$name] ?? $default; - }); - $session->method('set')->willReturnCallback(function (string $name, $value) use (&$sessionStore) { - $sessionStore[$name] = $value; - }); - $session->method('remove')->willReturnCallback(function (string $name) use (&$sessionStore) { - unset($sessionStore[$name]); - }); - - // Attach session to request - $request->setSession($session); - - // RequestStack mock that provides current request and direct session access - $requestStack = $this->getMockBuilder(RequestStack::class) - ->onlyMethods(['getCurrentRequest', 'getSession']) - ->getMock(); - $requestStack->method('getCurrentRequest')->willReturn($request); - $requestStack->method('getSession')->willReturn($session); - - return new DoctrineDatagrid($em, $requestStack, $formFactory, $router, 'dg', $params); - } + use DatagridTestTrait; public function testPaginationStateUsingSession(): void { - $request = new Request(); - $store = []; - $dg = $this->createDatagrid($request, $store); + $dg = $this->createDatagrid(); $this->assertSame(1, $dg->getCurrentPage()); $dg->setCurrentPage(3); diff --git a/Tests/Datagrid/QueryBuilderTest.php b/Tests/Datagrid/QueryBuilderTest.php deleted file mode 100644 index 7a1d6f8..0000000 --- a/Tests/Datagrid/QueryBuilderTest.php +++ /dev/null @@ -1,309 +0,0 @@ -forcedCountQb = $qb; - } - - protected function createCountQb(QueryBuilder $qb): QueryBuilder - { - return $this->forcedCountQb ?? parent::createCountQb($qb); - } - - protected function createPaginator($query): DoctrinePaginator - { - return parent::createPaginator($query); - } - - public function runCountAndPaginateOnly(): array - { - // Replicate getQueryResults() without creating a Paginator - $countQb = $this->createCountQb($this->qb); - $this->nbResults = $countQb->select('COUNT(DISTINCT '.$this->id.')') - ->orderBy($this->id) - ->getQuery() - ->getSingleScalarResult(); - - $this->nbPages = (int) ceil($this->nbResults / $this->getMaxPerPage()); - - $this->qb->select('DISTINCT '.$this->select) - ->setFirstResult(($this->getCurrentPage() - 1) * $this->getMaxPerPage()) - ->setMaxResults($this->getMaxPerPage()); - - if ($this->groupBy) { - $this->qb->groupBy($this->groupBy); - } - - // Return empty results to avoid touching Doctrine Paginator internals in unit tests - return []; - } -} - -final class QueryBuilderTest extends TestCase -{ - private function createDatagrid(Request $request, array &$sessionStore, array $params = []): TestableDoctrineDatagrid - { - $em = $this->createMock(EntityManagerInterface::class); - $formFactory = $this->createMock(FormFactoryInterface::class); - $router = $this->createMock(RouterInterface::class); - - $session = $this->createMock(SessionInterface::class); - $session->method('get')->willReturnCallback(function (string $name, $default = null) use (&$sessionStore) { - return $sessionStore[$name] ?? $default; - }); - $session->method('set')->willReturnCallback(function (string $name, $value) use (&$sessionStore) { - $sessionStore[$name] = $value; - }); - $session->method('remove')->willReturnCallback(function (string $name) use (&$sessionStore) { - unset($sessionStore[$name]); - }); - - $request->setSession($session); - - $requestStack = $this->getMockBuilder(RequestStack::class) - ->onlyMethods(['getCurrentRequest', 'getSession']) - ->getMock(); - $requestStack->method('getCurrentRequest')->willReturn($request); - $requestStack->method('getSession')->willReturn($session); - - return new TestableDoctrineDatagrid($em, $requestStack, $formFactory, $router, 'dg', $params); - } - - public function testQueryInitializationCallsCallbackAndStoresQueryBuilder(): void - { - $request = new Request(); - $store = []; - - $em = $this->createMock(EntityManagerInterface::class); - $formFactory = $this->createMock(FormFactoryInterface::class); - $router = $this->createMock(RouterInterface::class); - - $session = $this->createMock(SessionInterface::class); - $session->method('get')->willReturnCallback(function (string $name, $default = null) use (&$store) { - return $store[$name] ?? $default; - }); - $request->setSession($session); - - $requestStack = $this->getMockBuilder(RequestStack::class) - ->onlyMethods(['getCurrentRequest', 'getSession']) - ->getMock(); - $requestStack->method('getCurrentRequest')->willReturn($request); - $requestStack->method('getSession')->willReturn($session); - - $dg = new TestableDoctrineDatagrid($em, $requestStack, $formFactory, $router, 'dg', []); - - $qb = $this->getMockBuilder(QueryBuilder::class) - ->disableOriginalConstructor() - ->onlyMethods(['select']) - ->getMock(); - - $em->expects($this->once()) - ->method('createQueryBuilder') - ->willReturn($qb); - - $called = false; - $dg->query(function (QueryBuilder $passedQb) use ($qb, &$called) { - $called = true; - // developer callback may configure and must return a QB - $this->assertSame($qb, $passedQb); - - return $passedQb; - }); - - $this->assertTrue($called, 'The query(callback) must be executed'); - $this->assertSame($qb, $dg->getQueryBuilder()); - } - - public function testGetQueryResultsAppliesPaginationAndGroupBy(): void - { - $request = new Request(); - $store = []; - $dg = $this->createDatagrid($request, $store); - - // Configure pagination state - $dg->setDefaultMaxPerPage(30); - $dg->setCurrentPage(3); // expecting firstResult = (3-1)*30 = 60 - $dg->id('e.id'); - $dg->select('e'); - // No groupBy to keep the unit test isolated from Doctrine internals - - // Build a QB mock that records pagination and grouping - $qb = $this->getMockBuilder(QueryBuilder::class) - ->disableOriginalConstructor() - ->onlyMethods(['select', 'orderBy', 'setFirstResult', 'setMaxResults', 'groupBy', 'getQuery']) - ->getMock(); - - // Loosen select expectations: it is called for COUNT and for DISTINCT data select - $qb->method('select')->willReturn($qb); - - $qb->expects($this->once()) - ->method('setFirstResult') - ->with(60) - ->willReturn($qb); - - $qb->expects($this->once()) - ->method('setMaxResults') - ->with(30) - ->willReturn($qb); - - // No groupBy expectation here - - // For count() path, return a tiny stub exposing only getSingleScalarResult - $countQuery = new class { - public function getSingleScalarResult() - { - return 123; - } - }; - - // Only one getQuery() call in this safe path - $qb->expects($this->once()) - ->method('getQuery') - ->willReturn($countQuery); - - // orderBy is invoked on the COUNT clone; we don’t assert arguments here to keep it DB-agnostic - $qb->method('orderBy')->willReturn($qb); - - $dg->setQueryBuilder($qb); - $dg->setForcedCountQb($qb); - - // Call a safe path that computes counts and applies pagination without constructing a Paginator - $dg->runCountAndPaginateOnly(); - - // Validate that nbResults and nbPages were set from the count query - $this->assertSame(123, $dg->getNbResults()); - $this->assertSame((int) ceil(123 / 30), $dg->getNbPages()); - } - - public function testNbResultsAndNbPagesWithDifferentLimits(): void - { - $request = new Request(); - $store = []; - $dg = $this->createDatagrid($request, $store); - - $dg->setDefaultMaxPerPage(50); - $dg->id('e.id'); - $dg->select('e'); - - $qb = $this->getMockBuilder(QueryBuilder::class) - ->disableOriginalConstructor() - ->onlyMethods(['select', 'orderBy', 'setFirstResult', 'setMaxResults', 'getQuery']) - ->getMock(); - - $qb->method('select')->willReturn($qb); - $qb->expects($this->once())->method('setFirstResult')->with(0)->willReturn($qb); - $qb->expects($this->once())->method('setMaxResults')->with(50)->willReturn($qb); - - $countQuery = new class { - public function getSingleScalarResult() - { - return 200; - } - }; - - $qb->expects($this->once()) - ->method('getQuery') - ->willReturn($countQuery); - $qb->method('orderBy')->willReturn($qb); - - $dg->setQueryBuilder($qb); - $dg->setForcedCountQb($qb); - $dg->runCountAndPaginateOnly(); - - $this->assertSame(200, $dg->getNbResults()); - $this->assertSame(4, $dg->getNbPages()); // 200 / 50 - } - - public function testFetchJoinCollectionFlagIsPassedToPaginator(): void - { - $request = new Request(); - $store = []; - $dg = $this->createDatagrid($request, $store); - - $dg->id('e.id'); - $dg->select('e'); - - $qb = $this->getMockBuilder(QueryBuilder::class) - ->disableOriginalConstructor() - ->onlyMethods(['select', 'orderBy', 'setFirstResult', 'setMaxResults', 'getQuery']) - ->getMock(); - - // Minimal stubs for pagination phase - $qb->method('select')->willReturn($qb); - $qb->method('setFirstResult')->willReturn($qb); - $qb->method('setMaxResults')->willReturn($qb); - $qb->method('orderBy')->willReturn($qb); - - $countQuery = new class { - public function getSingleScalarResult() - { - return 0; - } - }; - - $qb->expects($this->once()) - ->method('getQuery') - ->willReturn($countQuery); - - $dg->setQueryBuilder($qb); - $dg->setForcedCountQb($qb); - - // Case 1: true - $dg->shouldFetchJoinCollection(true); - // Do not construct a Paginator; just ensure no crash and state is computed - $dg->runCountAndPaginateOnly(); - $this->assertSame(0, $dg->getNbResults()); - $this->assertSame(0, $dg->getNbPages()); - - // Case 2: false with a fresh QB mock - $qb2 = $this->getMockBuilder(QueryBuilder::class) - ->disableOriginalConstructor() - ->onlyMethods(['select', 'orderBy', 'setFirstResult', 'setMaxResults', 'getQuery']) - ->getMock(); - $qb2->method('select')->willReturn($qb2); - $qb2->method('setFirstResult')->willReturn($qb2); - $qb2->method('setMaxResults')->willReturn($qb2); - $qb2->method('orderBy')->willReturn($qb2); - $countQuery2 = new class { - public function getSingleScalarResult() - { - return 0; - } - }; - $qb2->expects($this->once())->method('getQuery')->willReturn($countQuery2); - - $dg2 = $this->createDatagrid(new Request(), $store); - $dg2->id('e.id'); - $dg2->select('e'); - $dg2->setQueryBuilder($qb2); - $dg2->setForcedCountQb($qb2); - $dg2->shouldFetchJoinCollection(false); - $dg2->runCountAndPaginateOnly(); - $this->assertSame(0, $dg2->getNbResults()); - $this->assertSame(0, $dg2->getNbPages()); - } -} diff --git a/Tests/Datagrid/QueryTest.php b/Tests/Datagrid/QueryTest.php new file mode 100644 index 0000000..9475819 --- /dev/null +++ b/Tests/Datagrid/QueryTest.php @@ -0,0 +1,181 @@ +em = $this->createEntityManager(); + $this->loadBooks($this->em); + } + + public function testQueryCallbackReceivesAFreshQueryBuilder(): void + { + $received = null; + $dg = $this->createDatagrid(em: $this->em)->query(function (QueryBuilder $qb) use (&$received): QueryBuilder { + $received = $qb; + + return $qb->from(Book::class, 'b'); + }); + + $this->assertSame($received, $dg->getQueryBuilder()); + } + + public function testExecutePaginatesResults(): void + { + $dg = $this->bookDatagrid(); + $dg->setDefaultMaxPerPage(3); + $dg->setCurrentPage(3); + $dg->execute(); + + $this->assertSame(7, $dg->getNbResults()); + $this->assertSame(3, $dg->getNbPages()); + // 1984, A Nice Cup of Tea, Foundation | I, Robot, Politics…, The End of Eternity | Why I Write + $this->assertSame(['Why I Write'], $this->titles($dg->getResults())); + } + + public function testPageActionUpdatesCurrentPage(): void + { + $dg = $this->bookDatagrid(new Request(['action' => 'page', 'datagrid' => 'dg', 'param1' => '2'])); + $dg->setDefaultMaxPerPage(5); + $dg->execute(); + + $this->assertSame(2, $dg->getCurrentPage()); + $this->assertCount(2, iterator_to_array($dg->getResults())); + } + + public function testLimitActionOnlyAcceptsAvailableValues(): void + { + $accepted = $this->bookDatagrid(new Request(['action' => 'limit', 'datagrid' => 'dg', 'param1' => '15']))->execute(); + $this->assertSame(15, $accepted->getMaxPerPage()); + $this->assertSame(1, $accepted->getNbPages()); + + $rejected = $this->bookDatagrid(new Request(['action' => 'limit', 'datagrid' => 'dg', 'param1' => '100000']))->execute(); + $this->assertSame(15, $rejected->getMaxPerPage(), 'The limit stored in session is kept'); + } + + public function testRequestedDatagridWithoutActionIsHandled(): void + { + $dg = $this->bookDatagrid(new Request(['datagrid' => 'dg']))->execute(); + + $this->assertSame(7, $dg->getNbResults()); + } + + public function testSortIsAppliedToTheQuery(): void + { + $dg = $this->bookDatagrid(new Request(['action' => 'sort', 'datagrid' => 'dg', 'param1' => 'b.title', 'param2' => 'DESC'])); + $dg->setDefaultMaxPerPage(2); + $dg->execute(); + + $this->assertSame(['Why I Write', 'The End of Eternity'], $this->titles($dg->getResults())); + } + + public function testPostedFilterIsAppliedAndStoredInSession(): void + { + $request = Request::create('/', 'POST', ['filter_dg' => ['genre' => 'essay']]); + $dg = $this->bookDatagrid($request); + $dg->setCurrentPage(2); + $dg->execute(); + + $this->assertSame(3, $dg->getNbResults()); + $this->assertSame(1, $dg->getCurrentPage()); + $this->assertTrue($dg->isFiltered()); + $this->assertNotNull($dg->getFilterFormView()); + + // Next GET request: the filter is restored from the session + $this->assertSame(3, $this->bookDatagrid()->execute()->getNbResults()); + } + + public function testGetAllResultsIgnoresPagination(): void + { + $request = Request::create('/', 'POST', ['filter_dg' => ['genre' => 'novel']]); + $dg = $this->bookDatagrid($request); + $dg->setDefaultMaxPerPage(2); + $dg->execute(); + + $this->assertCount(2, iterator_to_array($dg->getResults())); + $this->assertCount(4, $dg->getAllResults()); + } + + public function testGetAllResultsWithoutExecuteAppliesFilters(): void + { + // Filter submitted on a previous request, then e.g. an export action calling getAllResults() directly + $this->bookDatagrid(Request::create('/', 'POST', ['filter_dg' => ['genre' => 'essay']]))->execute(); + + $this->assertCount(3, $this->bookDatagrid()->getAllResults()); + } + + public function testGroupBy(): void + { + $dg = $this->createDatagrid(em: $this->em) + ->query(fn (QueryBuilder $qb): QueryBuilder => $qb->from(Book::class, 'b')) + ->select(['b.genre', 'COUNT(b.id) AS total']) + ->id('b.genre') + ->groupBy('b.genre') + ->shouldFetchJoinCollection(false) + ->setDefaultSort(['b.genre' => 'ASC']) + ->execute(); + + $this->assertSame(2, $dg->getNbResults()); + $this->assertEquals( + [['genre' => 'essay', 'total' => 3], ['genre' => 'novel', 'total' => 4]], + iterator_to_array($dg->getResults()), + ); + } + + public function testUnorderedQueryBuilderIsAClone(): void + { + $dg = $this->bookDatagrid(); + $qb = $dg->getQueryBuilder()->orderBy('b.title'); + + $unordered = $dg->getUnorderedQueryBuilder($qb); + + $this->assertNotSame($qb, $unordered); + $this->assertSame([], $unordered->getDQLPart('orderBy')); + $this->assertNotEmpty($qb->getDQLPart('orderBy')); + } + + private function bookDatagrid(?Request $request = null): DoctrineDatagrid + { + return $this->createDatagrid($request, em: $this->em) + ->query(fn (QueryBuilder $qb): QueryBuilder => $qb->from(Book::class, 'b')) + ->select('b') + ->id('b.id') + ->setDefaultSort(['b.title' => 'ASC']) + ->filter('genre', TextType::class, [], fn (string $genre, QueryBuilder $qb): QueryBuilder => $qb + ->andWhere('b.genre = :genre') + ->setParameter('genre', $genre)) + ; + } + + /** + * @param iterable $books + * + * @return string[] + */ + private function titles(iterable $books): array + { + $titles = []; + foreach ($books as $book) { + $titles[] = $book->title; + } + + return $titles; + } +} diff --git a/Tests/Datagrid/SortTest.php b/Tests/Datagrid/SortTest.php index 593a9ac..bb6186c 100644 --- a/Tests/Datagrid/SortTest.php +++ b/Tests/Datagrid/SortTest.php @@ -2,100 +2,93 @@ namespace Spyrit\Bundle\DoctrineDatagridBundle\Tests\Datagrid; -use Doctrine\ORM\EntityManagerInterface; +use PHPUnit\Framework\Attributes\IgnoreDeprecations; use PHPUnit\Framework\TestCase; -use Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\DoctrineDatagrid; -use Symfony\Component\Form\FormFactoryInterface; +use Spyrit\Bundle\DoctrineDatagridBundle\Tests\DatagridTestTrait; use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\RequestStack; -use Symfony\Component\HttpFoundation\Session\SessionInterface; -use Symfony\Component\Routing\RouterInterface; final class SortTest extends TestCase { - private function createDatagrid(Request $request, array &$sessionStore, array $params = []): DoctrineDatagrid - { - $em = $this->createMock(EntityManagerInterface::class); - $formFactory = $this->createMock(FormFactoryInterface::class); - $router = $this->createMock(RouterInterface::class); - - // Session mock with in-memory storage - $session = $this->createMock(SessionInterface::class); - $session->method('get')->willReturnCallback(function (string $name, $default = null) use (&$sessionStore) { - return $sessionStore[$name] ?? $default; - }); - $session->method('set')->willReturnCallback(function (string $name, $value) use (&$sessionStore) { - $sessionStore[$name] = $value; - }); - $session->method('remove')->willReturnCallback(function (string $name) use (&$sessionStore) { - unset($sessionStore[$name]); - }); - - // Attach session to request - $request->setSession($session); - - // RequestStack mock that provides current request and direct session access - $requestStack = $this->getMockBuilder(RequestStack::class) - ->onlyMethods(['getCurrentRequest', 'getSession']) - ->getMock(); - $requestStack->method('getCurrentRequest')->willReturn($request); - $requestStack->method('getSession')->willReturn($session); - - return new DoctrineDatagrid($em, $requestStack, $formFactory, $router, 'dg', $params); - } + use DatagridTestTrait; public function testDefaultSortStateFromConfiguration(): void { - $request = new Request(); - $store = []; - $dg = $this->createDatagrid($request, $store); - - $dg->setDefaultSort(['foo' => 'asc']); + $dg = $this->createDatagrid(); + $dg->setDefaultSort(['foo' => 'ASC']); $this->assertTrue($dg->isSortedColumn('foo')); - $this->assertSame('asc', $dg->getSortedColumnOrder('foo')); + $this->assertSame('ASC', $dg->getSortedColumnOrder('foo')); $this->assertSame(0, $dg->getSortedColumnPriority('foo')); $this->assertSame(1, $dg->getSortCount()); } public function testUpdateSortWithWhitelist(): void { - // Prepare a sort request for column "bar" desc - $request = new Request([ - 'action' => 'sort', - 'datagrid' => 'dg', - 'param1' => 'bar', - 'param2' => 'desc', - ]); - $store = []; - $dg = $this->createDatagrid($request, $store, ['multi_sort' => true]); - $dg->setDefaultSort(['foo' => 'asc']); + $dg = $this->createDatagrid($this->sortRequest('bar', 'DESC'), ['multi_sort' => true]); + $dg->setDefaultSort(['foo' => 'ASC']); $dg->setAllowedSorts(['bar', 'baz']); $dg->updateSort(); - $this->assertTrue($dg->isSortedColumn('bar')); - $this->assertSame('desc', $dg->getSortedColumnOrder('bar')); - // Multi sort keeps previous defaults too + $this->assertSame('DESC', $dg->getSortedColumnOrder('bar')); + // Multi sort keeps the previous sorts $this->assertSame(2, $dg->getSortCount()); } + public function testUpdateSortIgnoresColumnsOutsideTheWhitelist(): void + { + $dg = $this->createDatagrid($this->sortRequest('password', 'DESC')); + $dg->setAllowedSorts(['bar']); + + $dg->updateSort(); + + $this->assertFalse($dg->isSortedColumn('password')); + $this->assertSame(0, $dg->getSortCount()); + } + + public function testSingleSortReplacesPreviousSorts(): void + { + $dg = $this->createDatagrid($this->sortRequest('bar', 'ASC'), ['multi_sort' => false]); + $dg->setDefaultSort(['foo' => 'ASC']); + + $dg->updateSort(); + + $this->assertFalse($dg->isSortedColumn('foo')); + $this->assertSame('ASC', $dg->getSortedColumnOrder('bar')); + } + + #[IgnoreDeprecations] + public function testLowercaseSortDirectionIsDeprecatedAndNormalized(): void + { + $this->expectUserDeprecationMessageMatches('/Providing lowercase sort order is deprecated/'); + + $dg = $this->createDatagrid($this->sortRequest('bar', 'desc')); + $dg->updateSort(); + + $this->assertSame('DESC', $dg->getSortedColumnOrder('bar')); + } + + public function testInvalidSortDirectionIsRejected(): void + { + $dg = $this->createDatagrid($this->sortRequest('bar', 'SIDEWAYS')); + + $this->expectException(\InvalidArgumentException::class); + $dg->updateSort(); + } + public function testRemoveSort(): void { - // Start with two sorts stored in session - $request = new Request([ - 'action' => 'remove_sort', - 'datagrid' => 'dg', - 'param1' => 'bar', - ]); - $store = []; - $dg = $this->createDatagrid($request, $store); - // prime session with sorts - $dg->setDefaultSort(['foo' => 'asc', 'bar' => 'desc']); + $dg = $this->createDatagrid(new Request(['action' => 'remove-sort', 'datagrid' => 'dg', 'param1' => 'bar'])); + $dg->setDefaultSort(['foo' => 'ASC', 'bar' => 'DESC']); $this->assertSame(2, $dg->getSortCount()); $dg->removeSort(); $this->assertSame(1, $dg->getSortCount()); $this->assertFalse($dg->isSortedColumn('bar')); } + + private function sortRequest(string $column, string $direction): Request + { + return new Request(['action' => 'sort', 'datagrid' => 'dg', 'param1' => $column, 'param2' => $direction]); + } } diff --git a/Tests/DatagridTestTrait.php b/Tests/DatagridTestTrait.php new file mode 100644 index 0000000..e1113d2 --- /dev/null +++ b/Tests/DatagridTestTrait.php @@ -0,0 +1,70 @@ + $class + * + * @return T + */ + private function createDatagrid( + ?Request $request = null, + array $params = [], + ?RouterInterface $router = null, + ?EntityManagerInterface $em = null, + string $name = 'dg', + string $class = DoctrineDatagrid::class, + ): DoctrineDatagrid { + return new $class( + $em ?? $this->createStub(EntityManagerInterface::class), + $this->createRequestStack($request ?? new Request()), + $this->createFormFactory(), + $router ?? $this->createStub(RouterInterface::class), + $name, + $params, + ); + } + + /** + * The session is shared by every request created during a test, like a real user session. + */ + private function createRequestStack(Request $request): RequestStack + { + $this->session ??= new Session(new MockArraySessionStorage()); + $request->setSession($this->session); + + $requestStack = new RequestStack(); + $requestStack->push($request); + + return $requestStack; + } + + private function createFormFactory(): FormFactoryInterface + { + // Like a full-stack application: the CSRF extension defines the "csrf_protection" option + return Forms::createFormFactoryBuilder() + ->addExtension(new CsrfExtension(new CsrfTokenManager())) + ->getFormFactory(); + } +} diff --git a/Tests/DoctrineDatagridBundleTest.php b/Tests/DoctrineDatagridBundleTest.php new file mode 100644 index 0000000..69362ab --- /dev/null +++ b/Tests/DoctrineDatagridBundleTest.php @@ -0,0 +1,33 @@ +setParameter('kernel.environment', 'test'); + $container->setParameter('kernel.build_dir', sys_get_temp_dir()); + $extension = $bundle->getContainerExtension(); + + $this->assertNotNull($extension); + $this->assertSame('doctrine_datagrid', $extension->getAlias()); + + $extension->load([], $container); + + $this->assertTrue($container->hasDefinition(DoctrineDatagridFactory::class)); + $this->assertTrue($container->getDefinition(DoctrineDatagridFactory::class)->isAutowired()); + } + + public function testTemplatesAreLocatedInTheBundlePath(): void + { + $this->assertFileExists((new DoctrineDatagridBundle())->getPath().'/Resources/views/Datagrid/pagination.html.twig'); + } +} diff --git a/Tests/Export/ExportTest.php b/Tests/Export/ExportTest.php new file mode 100644 index 0000000..36088a6 --- /dev/null +++ b/Tests/Export/ExportTest.php @@ -0,0 +1,99 @@ +em = $this->createEntityManager(); + $this->loadBooks($this->em); + } + + public function testCsvExport(): void + { + $response = $this->datagrid()->export('csv', ['csvWriter' => ['encoding' => 'UTF-8', 'eol' => "\n"]])->getResponse(); + + $this->assertSame('text/csv', $response->headers->get('Content-Type')); + $this->assertSame('attachment; filename=books.csv', $response->headers->get('Content-Disposition')); + $this->assertSame((string) strlen($response->getContent()), $response->headers->get('Content-Length')); + $this->assertSame( + "Title;Genre\nPolitics and the English Language;essay\nWhy I Write;essay\n", + $response->getContent(), + ); + } + + public function testExportWithoutPostExecuteOverrideDoesNotTriggerDeprecation(): void + { + // failOnDeprecation in phpunit.xml.dist makes this test fail on any deprecation + $this->assertNotEmpty($this->datagrid()->export('csv')->getResponse()->getContent()); + } + + #[IgnoreDeprecations] + public function testOverridingPostExecuteIsDeprecated(): void + { + $this->expectUserDeprecationMessageMatches('/Overriding ".*::postExecute\(\)" is deprecated/'); + + $export = $this->datagrid()->export('legacy'); + + $this->assertInstanceOf(LegacyBookCsvExport::class, $export); + $this->assertTrue($export->postExecuted); + } + + public function testUnknownExport(): void + { + $this->expectExceptionMessage('The "pdf" export doesn\'t exist in this datagrid.'); + + $this->datagrid()->export('pdf'); + } + + public function testXlsxExport(): void + { + if (!class_exists(Spreadsheet::class)) { + $this->markTestSkipped('phpoffice/phpspreadsheet is not installed.'); + } + + $response = $this->datagrid()->export('xlsx')->getResponse(); + + $this->assertSame('attachment; filename=books.xlsx', $response->headers->get('Content-Disposition')); + $this->assertStringStartsWith('PK', $response->getContent()); + } + + private function datagrid(): DoctrineDatagrid + { + $dg = $this->createDatagrid(em: $this->em) + ->query(fn (QueryBuilder $qb): QueryBuilder => $qb + ->from(Book::class, 'b') + ->andWhere('b.genre = :genre') + ->setParameter('genre', 'essay') + ->andWhere('b.author IS NOT NULL')) + ->select('b') + ->id('b.id') + ->setDefaultSort(['b.title' => 'ASC']) + ->setExports([ + 'csv' => BookCsvExport::class, + 'legacy' => LegacyBookCsvExport::class, + 'xlsx' => BookXlsExport::class, + ]); + + return $dg; + } +} diff --git a/Tests/Fixtures/App/app/AppKernel.php b/Tests/Fixtures/App/app/AppKernel.php deleted file mode 100644 index 0d1f8b8..0000000 --- a/Tests/Fixtures/App/app/AppKernel.php +++ /dev/null @@ -1,47 +0,0 @@ -load(__DIR__.'/config/config_test.yml'); - } - - /** - * @return string - */ - public function getCacheDir() - { - return sys_get_temp_dir().'/SpyritPropelDatagridBundle/cache'; - } - - /** - * @return string - */ - public function getLogDir() - { - return sys_get_temp_dir().'/SpyritPropelDatagridBundle/logs'; - } -} diff --git a/Tests/Fixtures/App/app/config/config.yml b/Tests/Fixtures/App/app/config/config.yml deleted file mode 100644 index b1dffc4..0000000 --- a/Tests/Fixtures/App/app/config/config.yml +++ /dev/null @@ -1,33 +0,0 @@ -imports: - - { resource: parameters.yml } - -framework: - secret: %secret% - router: { resource: "%kernel.root_dir%/config/routing.yml" } - form: true - csrf_protection: true - session: ~ - default_locale: en - translator: { fallback: en } - profiler: { only_exceptions: false } - templating: - engines: [ twig ] - -propel: - build_properties: - propel.database: mysql - propel.php.dir: "%kernel.root_dir%/../src/Spyrit/TestBundle/Model" - - path: "%kernel.root_dir%/../../../../vendor/propel/propel1" - phing_path: "%kernel.root_dir%/../../../../vendor/phing" - logging: %kernel.debug% - dbal: - default_connection: bookstore - connections: - bookstore: - driver: %database_driver% - user: %database_user% - password: %database_password% - dsn: %database_driver%:host=%database_host%;dbname=%database_name%;charset=UTF8 - options: {} - attributes: {} \ No newline at end of file diff --git a/Tests/Fixtures/App/app/config/config_test.yml b/Tests/Fixtures/App/app/config/config_test.yml deleted file mode 100644 index 86da388..0000000 --- a/Tests/Fixtures/App/app/config/config_test.yml +++ /dev/null @@ -1,7 +0,0 @@ -imports: - - { resource: config.yml } - -framework: - test: ~ - session: - storage_id: session.storage.filesystem \ No newline at end of file diff --git a/Tests/Fixtures/App/app/config/parameters.yml.dist b/Tests/Fixtures/App/app/config/parameters.yml.dist deleted file mode 100644 index fc68519..0000000 --- a/Tests/Fixtures/App/app/config/parameters.yml.dist +++ /dev/null @@ -1,12 +0,0 @@ -parameters: - database_driver: pdo_mysql - database_host: 127.0.0.1 - database_port: ~ - database_name: bookstore - database_user: travis - database_password: ~ - locale: en - secret: dz7am99bonp0tbd215iznv2571bwffq3pri6966710484fy0 - debug_toolbar: true - debug_redirects: false - use_assetic_controller: true diff --git a/Tests/Fixtures/App/app/config/routing.yml b/Tests/Fixtures/App/app/config/routing.yml deleted file mode 100644 index c845924..0000000 --- a/Tests/Fixtures/App/app/config/routing.yml +++ /dev/null @@ -1,2 +0,0 @@ -#spyrit_propel_datagrid: -# resource: "@SpyritPropelDatagridBundle/Resources/config/routing.yml" \ No newline at end of file diff --git a/Tests/Fixtures/App/app/console b/Tests/Fixtures/App/app/console deleted file mode 100644 index 9ca7b67..0000000 --- a/Tests/Fixtures/App/app/console +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env php -getParameterOption(array('--env', '-e'), getenv('SYMFONY_ENV') ?: 'test'); -$debug = getenv('SYMFONY_DEBUG') !== '0' && !$input->hasParameterOption(array('--no-debug', '')) && $env !== 'prod'; - -$kernel = new AppKernel($env, $debug); -$application = new Application($kernel); -$application->run($input); \ No newline at end of file diff --git a/Tests/Fixtures/App/app/propel/sql/sqldb.map b/Tests/Fixtures/App/app/propel/sql/sqldb.map deleted file mode 100644 index 9841df5..0000000 --- a/Tests/Fixtures/App/app/propel/sql/sqldb.map +++ /dev/null @@ -1,2 +0,0 @@ -# Sqlfile -> Database map -bookstore.sql=bookstore diff --git a/Tests/Fixtures/Entity/Author.php b/Tests/Fixtures/Entity/Author.php new file mode 100644 index 0000000..45b38a8 --- /dev/null +++ b/Tests/Fixtures/Entity/Author.php @@ -0,0 +1,20 @@ +title, $object->genre]; + } +} diff --git a/Tests/Fixtures/Export/BookXlsExport.php b/Tests/Fixtures/Export/BookXlsExport.php new file mode 100644 index 0000000..b267952 --- /dev/null +++ b/Tests/Fixtures/Export/BookXlsExport.php @@ -0,0 +1,27 @@ +title, $object->genre]; + } +} diff --git a/Tests/Fixtures/Export/LegacyBookCsvExport.php b/Tests/Fixtures/Export/LegacyBookCsvExport.php new file mode 100644 index 0000000..5d1774b --- /dev/null +++ b/Tests/Fixtures/Export/LegacyBookCsvExport.php @@ -0,0 +1,18 @@ +postExecuted = true; + + return $this; + } +} diff --git a/Tests/OrmTestTrait.php b/Tests/OrmTestTrait.php new file mode 100644 index 0000000..45feb8d --- /dev/null +++ b/Tests/OrmTestTrait.php @@ -0,0 +1,62 @@ += 80400 && method_exists($config, 'enableNativeLazyObjects')) { + $config->enableNativeLazyObjects(true); + } + + $connection = DriverManager::getConnection(['driver' => 'pdo_sqlite', 'memory' => true], $config); + $em = new EntityManager($connection, $config); + + (new SchemaTool($em))->createSchema($em->getMetadataFactory()->getAllMetadata()); + + return $em; + } + + /** + * 7 books: 4 "novel" (3 by Asimov), 3 "essay". + */ + private function loadBooks(EntityManagerInterface $em): void + { + $asimov = new Author('Asimov'); + $orwell = new Author('Orwell'); + $em->persist($asimov); + $em->persist($orwell); + + foreach ([ + ['Foundation', 'novel', $asimov], + ['I, Robot', 'novel', $asimov], + ['The End of Eternity', 'novel', $asimov], + ['1984', 'novel', $orwell], + ['Politics and the English Language', 'essay', $orwell], + ['Why I Write', 'essay', $orwell], + ['A Nice Cup of Tea', 'essay', null], + ] as [$title, $genre, $author]) { + $em->persist(new Book($title, $genre, $author)); + } + + $em->flush(); + $em->clear(); + } +} diff --git a/Tests/TemplatesTest.php b/Tests/TemplatesTest.php new file mode 100644 index 0000000..e2e3dd2 --- /dev/null +++ b/Tests/TemplatesTest.php @@ -0,0 +1,87 @@ + + */ + public static function templates(): iterable + { + foreach (glob(self::VIEWS_DIR.'/Datagrid/*.html.twig') as $file) { + yield basename($file) => ['Datagrid/'.basename($file)]; + } + } + + #[DataProvider('templates')] + public function testTemplateCompiles(string $template): void + { + $twig = $this->createTwig(); + $code = $twig->getLoader()->getSourceContext($template)->getCode(); + + $this->assertNotEmpty($twig->compileSource(new Source($code, $template))); + } + + /** + * @return iterable + */ + public static function paginationCases(): iterable + { + yield 'middle page' => [5, 10, '1 … 3 4 [5] 6 7 … 10']; + yield 'first page' => [1, 10, '[1] 2 3 … 10']; + yield 'last page' => [10, 10, '1 … 8 9 [10]']; + yield 'no gap' => [3, 5, '1 2 [3] 4 5']; + yield 'two pages' => [2, 2, '1 [2]']; + yield 'single page' => [1, 1, '']; + } + + #[DataProvider('paginationCases')] + public function testPagination(int $page, int $pages, string $expected): void + { + $datagrid = new class($page, $pages) { + public function __construct(public int $currentPage, public int $nbPages) + { + } + + public function getPaginationPath(string $route, int $page, array $extraParams = []): string + { + return '/'.$route.'/'.$page; + } + }; + + $html = $this->createTwig()->render('Datagrid/pagination.html.twig', ['datagrid' => $datagrid, 'route' => 'books']); + + $this->assertStringNotContainsString(' assertSame($expected, $this->summarize($html)); + } + + private function summarize(string $html): string + { + preg_match_all('#
  • ]*>([^<]+)
  • #', $html, $matches, \PREG_SET_ORDER); + + return implode(' ', array_map(static fn (array $m): string => match ($m[1]) { + ' active' => '['.$m[2].']', + ' disabled' => '…', + default => $m[2], + }, $matches)); + } + + private function createTwig(): Environment + { + $twig = new Environment(new FilesystemLoader(self::VIEWS_DIR), ['strict_variables' => true]); + // Provided by symfony/twig-bridge in applications + $twig->addFilter(new TwigFilter('trans', static fn (string $message): string => $message)); + + return $twig; + } +} diff --git a/Tests/bootstrap.php b/Tests/bootstrap.php deleted file mode 100644 index 227ccd6..0000000 --- a/Tests/bootstrap.php +++ /dev/null @@ -1,25 +0,0 @@ -add('Spyrit\PropelDatagridBundle\Tests', __DIR__); -$loader->add('Spyrit\TestBundle', __DIR__.'/Fixtures/App/src'); diff --git a/composer.json b/composer.json index f196165..3f913ab 100644 --- a/composer.json +++ b/composer.json @@ -2,7 +2,7 @@ "name": "spyrit/doctrine-datagrid-bundle", "description": "Symfony Datagrid Bundle for Doctrine.", "keywords": ["datagrid", "symfony", "doctrine"], - "homepage": "https://github.com/spyrit/DoctrineDatagridBundle.git", + "homepage": "https://github.com/spyrit/DoctrineDatagridBundle", "type": "symfony-bundle", "license": "MIT", "authors": [ @@ -22,24 +22,45 @@ }, "require": { "php": "^8.2", - "csanquer/colibri-csv": "1.2.*", - "doctrine/orm": "^2.2|^3.0", - "symfony/form": "^7.0|^8.0", - "symfony/http-foundation": "^7.0|^8.0", - "symfony/routing": "^7.0|^8.0", - "symfony/config": "^7.0|^8.0", - "symfony/http-kernel": "^7.0|^8.0", + "csanquer/colibri-csv": "^1.2", + "doctrine/orm": "^2.20|^3.3", + "symfony/config": "^7.4|^8.0", + "symfony/dependency-injection": "^7.4|^8.0", + "symfony/deprecation-contracts": "^3.5", + "symfony/form": "^7.4|^8.0", + "symfony/http-foundation": "^7.4|^8.0", + "symfony/http-kernel": "^7.4|^8.0", + "symfony/routing": "^7.4|^8.0", "webmozart/assert": "^2.1.2" }, "require-dev": { - "phpunit/phpunit": "^12.0" + "friendsofphp/php-cs-fixer": "^3.64", + "phpstan/phpstan": "^2.1", + "phpunit/phpunit": "^11.5|^12.5", + "symfony/cache": "^7.4|^8.0", + "symfony/security-csrf": "^7.4|^8.0", + "twig/twig": "^3.12" + }, + "suggest": { + "phpoffice/phpspreadsheet": "Required to export datagrids to XLSX (AbstractXlsExport)" + }, + "conflict": { + "phpoffice/phpspreadsheet": "<1.23" }, "autoload": { - "psr-4": { "Spyrit\\Bundle\\DoctrineDatagridBundle\\": "" } + "psr-4": { "Spyrit\\Bundle\\DoctrineDatagridBundle\\": "" }, + "exclude-from-classmap": ["/Tests/"] + }, + "autoload-dev": { + "psr-4": { "Spyrit\\Bundle\\DoctrineDatagridBundle\\Tests\\": "Tests/" } + }, + "scripts": { + "test": "phpunit", + "phpstan": "phpstan analyse", + "cs": "php-cs-fixer fix --dry-run --diff", + "cs-fix": "php-cs-fixer fix" }, "config": { - "allow-plugins": { - "infection/extension-installer": true - } + "sort-packages": true } } diff --git a/phpstan.dist.neon b/phpstan.dist.neon new file mode 100644 index 0000000..033e37a --- /dev/null +++ b/phpstan.dist.neon @@ -0,0 +1,18 @@ +parameters: + level: 5 + paths: + - Bridge + - Datagrid + - DoctrineDatagridBundle.php + - Tests + tmpDir: var/cache/phpstan + reportUnmatchedIgnoredErrors: false + ignoreErrors: + # phpoffice/phpspreadsheet is an optional dependency (requires ext-gd) + - + identifier: class.notFound + path: Datagrid/Export/AbstractXlsExport.php + # compatibility with doctrine/orm 2.x (lowest dependencies) + - + identifier: function.alreadyNarrowedType + path: Tests/OrmTestTrait.php diff --git a/phpunit.xml.dist b/phpunit.xml.dist index cfcc0b3..fa190ad 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,22 +1,29 @@ - - + - - ./Tests/ + + ./Tests/ - - - - - + + ./ - - ./Resources - ./Tests - ./vendor - - - + + + ./Resources + ./Tests + ./vendor + + From 1a8fbcfdbf5306e1664731c1fd77cad87dff3757 Mon Sep 17 00:00:00 2001 From: Hugues Date: Tue, 10 Nov 2026 11:41:31 +0100 Subject: [PATCH 4/7] Replace abandoned colibri-csv and jquery.cookie dependencies CSV: csanquer/colibri-csv (and ddeboer/transcoder) have not been released since 2015 and trigger a PHP 8.1+ deprecation for every null cell. They are replaced by an internal CsvWriter accepting the same "csvWriter" options with the same defaults (Excel dialect: ";", CP1252, CRLF). The output is byte-identical (checked on 1,792 option combinations). Projects using colibri-csv classes directly must now require it themselves. JS: jquery.batch.js no longer needs the jquery.cookie plugin (abandoned). Native helpers keep the same cookie format, so existing batch selections stay readable; cookies are now SameSite=Lax (and Secure over HTTPS). Also fixes the "select all" checkbox never being updated (wrong selector) and the shared default data being mutated. Co-Authored-By: Claude Opus 5.5 --- Datagrid/Export/CsvExport.php | 10 +- Datagrid/Export/CsvWriter.php | 191 ++++++++++++++++++++++++++++ README.md | 14 +- Resources/public/js/jquery.batch.js | 50 ++++++-- Tests/Export/CsvWriterTest.php | 72 +++++++++++ composer.json | 1 - package.json | 5 - 7 files changed, 321 insertions(+), 22 deletions(-) create mode 100644 Datagrid/Export/CsvWriter.php create mode 100644 Tests/Export/CsvWriterTest.php delete mode 100644 package.json diff --git a/Datagrid/Export/CsvExport.php b/Datagrid/Export/CsvExport.php index d5af349..20b70a2 100644 --- a/Datagrid/Export/CsvExport.php +++ b/Datagrid/Export/CsvExport.php @@ -2,7 +2,6 @@ namespace Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\Export; -use CSanquer\ColibriCsv\CsvWriter; use Doctrine\ORM\QueryBuilder; use Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\DoctrineDatagrid; use Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\Util; @@ -62,7 +61,6 @@ public function execute(): static $this->callDeprecatedPostExecute(); $writer = new CsvWriter($this->getCsvWriterOptions()); - $writer->createTempStream(); if ($this->getHeader()) { $writer->writeRow($this->getHeader()); @@ -74,8 +72,7 @@ public function execute(): static $writer->writeRow($this->getRow($result)); } - $this->content = $writer->getFileContent(); - $writer->close(); + $this->content = $writer->getContent(); return $this; } @@ -110,6 +107,11 @@ public function getDelimiter(): string return ';'; } + /** + * Options of the CSV writer, from the "csvWriter" export parameter. + * + * @see CsvWriter::__construct() + */ protected function getCsvWriterOptions(): array { if (isset($this->params['csvWriter'])) { diff --git a/Datagrid/Export/CsvWriter.php b/Datagrid/Export/CsvWriter.php new file mode 100644 index 0000000..e43b1dc --- /dev/null +++ b/Datagrid/Export/CsvWriter.php @@ -0,0 +1,191 @@ + ';', + 'enclosure' => '"', + 'enclosing_mode' => self::ENCLOSING_MINIMAL, + 'encoding' => 'CP1252', + 'eol' => "\r\n", + 'escape' => '\\', + 'escape_double' => true, + 'bom' => false, + 'translit' => 'translit', + 'first_row_header' => false, + 'trim' => false, + ]; + + private const LINE_ENDINGS = [ + 'unix' => "\n", + 'linux' => "\n", + "\n" => "\n", + 'mac' => "\r", + 'macos' => "\r", + "\r" => "\r", + ]; + + private const BOMS = [ + 'UTF-8' => "\xEF\xBB\xBF", + 'UTF-16BE' => "\xFE\xFF", + 'UTF-16LE' => "\xFF\xFE", + 'UTF-32BE' => "\x00\x00\xFE\xFF", + 'UTF-32LE' => "\xFF\xFE\x00\x00", + ]; + + private string $delimiter; + private string $enclosure; + private string $enclosingMode; + private string $encoding; + private string $eol; + private string $escape; + private bool $escapeDouble; + private ?string $translit; + private bool $firstRowHeader; + private bool $trim; + + private string $content = ''; + private bool $headerWritten = false; + + /** + * @param array $options Same options as colibri-csv: delimiter, enclosure, + * enclosing_mode (all|minimal|nonnumeric), encoding, eol + * (unix|linux|mac|macos|windows|win or the characters), + * escape, escape_double, bom, translit (translit|ignore|null), + * first_row_header, trim. Reader-only options are ignored. + */ + public function __construct(array $options = []) + { + $options = array_merge(self::DEFAULT_OPTIONS, array_change_key_case($options, \CASE_LOWER)); + + // Empty values fall back to the defaults, like colibri-csv + $this->delimiter = (string) ($options['delimiter'] ?: self::DEFAULT_OPTIONS['delimiter']); + $this->enclosure = (string) ($options['enclosure'] ?: self::DEFAULT_OPTIONS['enclosure']); + $this->encoding = (string) ($options['encoding'] ?: self::DEFAULT_OPTIONS['encoding']); + $this->escape = (string) ($options['escape'] ?: self::DEFAULT_OPTIONS['escape']); + $this->enclosingMode = \in_array($options['enclosing_mode'], [self::ENCLOSING_ALL, self::ENCLOSING_MINIMAL, self::ENCLOSING_NONNUMERIC], true) + ? $options['enclosing_mode'] + : self::ENCLOSING_MINIMAL; + $this->eol = self::LINE_ENDINGS[$options['eol']] ?? "\r\n"; + $this->escapeDouble = (bool) $options['escape_double']; + $translit = strtolower((string) $options['translit']); + $this->translit = \in_array($translit, ['translit', 'ignore'], true) ? $translit : null; + $this->firstRowHeader = (bool) $options['first_row_header']; + $this->trim = (bool) $options['trim']; + + if ($options['bom']) { + $this->content = self::BOMS[$this->encoding] ?? ''; + } + } + + /** + * @param array $values Scalars, null or \Stringable objects + */ + public function writeRow(array $values): self + { + if ($this->firstRowHeader && !$this->headerWritten) { + $this->headerWritten = true; + $this->write(array_keys($values)); + } + + $this->write($values); + + return $this; + } + + /** + * @param iterable> $rows + */ + public function writeRows(iterable $rows): self + { + foreach ($rows as $values) { + $this->writeRow($values); + } + + return $this; + } + + public function getContent(): string + { + return $this->content; + } + + /** + * @param array $values + */ + private function write(array $values): void + { + $line = implode($this->delimiter, array_map($this->formatField(...), $values)).$this->eol; + + $this->content .= $this->transcode($line); + } + + private function formatField(mixed $value): string + { + $value = match (true) { + null === $value => '', + \is_bool($value) => $value ? '1' : '', + \is_scalar($value), $value instanceof \Stringable => (string) $value, + default => throw new \InvalidArgumentException(\sprintf('A CSV field must be a scalar, null or a \Stringable object, "%s" given.', get_debug_type($value))), + }; + + if ($this->trim) { + $value = trim($value); + } + + $value = str_replace( + $this->enclosure, + ($this->escapeDouble ? $this->enclosure : $this->escape).$this->enclosure, + $value, + ); + + $mustEnclose = match ($this->enclosingMode) { + self::ENCLOSING_ALL => true, + self::ENCLOSING_NONNUMERIC => 1 === preg_match('/[^\d\.]+/', $value), + default => 1 === preg_match('/['.preg_quote($this->enclosure.$this->delimiter.$this->eol, '/').']+/', $value), + }; + + return $mustEnclose ? $this->enclosure.$value.$this->enclosure : $value; + } + + private function transcode(string $line): string + { + if ('UTF-8' === $this->encoding) { + return $line; + } + + if (\function_exists('iconv')) { + $target = $this->encoding.(null !== $this->translit ? '//'.strtoupper($this->translit) : ''); + + set_error_handler(static fn (int $type, string $message): never => throw new \UnexpectedValueException(\sprintf('Unable to convert the CSV line to "%s": %s', $target, $message))); + try { + $result = iconv('UTF-8', $target, $line); + } finally { + restore_error_handler(); + } + + if (false === $result) { + throw new \UnexpectedValueException(\sprintf('Unable to convert the CSV line to "%s".', $target)); + } + + return $result; + } + + // mbstring only knows Windows code pages by their "Windows-125x" name + $encoding = preg_replace('/^CP(125[0-8])$/i', 'Windows-$1', $this->encoding); + + return mb_convert_encoding($line, $encoding, 'UTF-8'); + } +} diff --git a/README.md b/README.md index 56792d3..3f36e73 100644 --- a/README.md +++ b/README.md @@ -160,6 +160,18 @@ Declare export classes extending `CsvExport` or `AbstractXlsExport` with `setExp then call `$datagrid->export('csv')->getResponse()`. Override `preExecute()` to alter the query before the export (`postExecute()` is deprecated). +CSV options can be given with the `csvWriter` parameter, e.g. +`$datagrid->export('csv', ['csvWriter' => ['encoding' => 'UTF-8', 'delimiter' => ',', 'bom' => true]])`. +Available options (same as the former *Colibri CSV* library, Excel-friendly defaults): +`delimiter` (`;`), `enclosure` (`"`), `enclosing_mode` (`minimal`|`all`|`nonnumeric`), `encoding` (`CP1252`), +`eol` (`windows`|`unix`|`mac`), `escape` (`\`), `escape_double` (`true`), `bom` (`false`), +`translit` (`translit`|`ignore`|`null`), `first_row_header` (`false`), `trim` (`false`). + +## Batch actions (JavaScript) + +`Resources/public/js/jquery.batch.js` (published with `assets:install`) only requires jQuery +(and Bootstrap popovers for the "select all" feature): the *jquery.cookie* plugin is no longer needed. + ## Development ```bash @@ -173,5 +185,5 @@ composer cs # coding standards (composer cs-fix to fix them) Our special thanks go to ... -- Charles SANQUER for its fork of the *LightCSV* library : *Colibri CSV* used in the export feature. +- Charles SANQUER for its fork of the *LightCSV* library : *Colibri CSV*, which inspired the CSV writer of the export feature. - Subosito for its standalone *Inflector* [class](http://subosito.com/inflector-in-symfony-2/) transformed in a service for our needs. diff --git a/Resources/public/js/jquery.batch.js b/Resources/public/js/jquery.batch.js index 074a100..7b8daa9 100644 --- a/Resources/public/js/jquery.batch.js +++ b/Resources/public/js/jquery.batch.js @@ -1,6 +1,7 @@ /** - * jQuery Batch Plugin v1.0.0 + * jQuery Batch Plugin v1.1.0 * This class provide javascript batch/checkboxes features + * No dependency other than jQuery (and Bootstrap popovers). * * Copyright 2013, 2014 Maxime CORSON * @@ -19,6 +20,32 @@ type: 'include', checked: [] }; + + // Same format as the former jquery.cookie plugin (URI-encoded value), so existing cookies stay readable + function readCookie(name) { + var prefix = encodeURIComponent(name) + '='; + var cookies = document.cookie ? document.cookie.split('; ') : []; + for (var i = 0; i < cookies.length; i++) { + if (cookies[i].indexOf(prefix) === 0) { + try { + return decodeURIComponent(cookies[i].substring(prefix.length).replace(/\+/g, ' ')); + } catch (e) { + return null; + } + } + } + return null; + } + + function writeCookie(name, value, days) { + var expires = new Date(); + expires.setTime(expires.getTime() + days * 864e5); + document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) + + '; expires=' + expires.toUTCString() + + '; path=/' + + '; SameSite=Lax' + + (window.location.protocol === 'https:' ? '; Secure' : ''); + } return this.each(function() { var $this = $(this); @@ -93,19 +120,20 @@ }); }, getData: function(){ - var data = $.cookie(this.name+'_batch'); + var data = readCookie(this.name+'_batch'); if(!data){ - return defaultData; + // copy: the default object must never be mutated + return { type: defaultData.type, checked: [] }; + } + try { + return JSON.parse(data); + } catch (e) { + return { type: defaultData.type, checked: [] }; } - return JSON.parse(data); }, setData: function(data){ - $.cookie( - this.name+'_batch', - JSON.stringify(data), - { expires: 7, path: '/' } - ); - }, + writeCookie(this.name+'_batch', JSON.stringify(data), 7); + }, addChecked: function(value){ var data = this.getData(); data.checked.push(value); @@ -172,7 +200,7 @@ }, updateBatchAllCheckbox: function(){ var data = this.getData(); - var $checkbox = $this.find(this.batchAllSelector); + var $checkbox = $this.find(this.params.batchAllSelector); if(data.type === 'include'){ if(data.checked.length > 0) diff --git a/Tests/Export/CsvWriterTest.php b/Tests/Export/CsvWriterTest.php new file mode 100644 index 0000000..710dbb2 --- /dev/null +++ b/Tests/Export/CsvWriterTest.php @@ -0,0 +1,72 @@ +writeRow(['Élodie', 'a;b'])->getContent(); + + // CP1252, ";" delimiter, minimal enclosing, CRLF + $this->assertSame("\xC9lodie;\"a;b\"\r\n", $content); + } + + public function testNullAndNonStringValues(): void + { + $writer = new CsvWriter(['encoding' => 'UTF-8', 'eol' => 'unix']); + $writer->writeRow(['a', null, 12, 1.5, true, false, new class implements \Stringable { + public function __toString(): string + { + return 'str'; + } + }]); + + $this->assertSame("a;;12;1.5;1;;str\n", $writer->getContent()); + } + + public function testNonStringableValueIsRejected(): void + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('"DateTimeImmutable" given'); + + (new CsvWriter())->writeRow([new \DateTimeImmutable()]); + } + + /** + * @return iterable, string}> + */ + public static function optionsCases(): iterable + { + yield 'enclosure doubled' => [[], "\"il a dit \"\"oui\"\"\";x\n"]; + yield 'enclosure escaped' => [['escape_double' => false], "\"il a dit \\\"oui\\\"\";x\n"]; + yield 'enclose all' => [['enclosing_mode' => 'all'], "\"il a dit \"\"oui\"\"\";\"x\"\n"]; + yield 'custom delimiter' => [['delimiter' => ','], "\"il a dit \"\"oui\"\"\",x\n"]; + yield 'BOM' => [['bom' => true], "\xEF\xBB\xBF\"il a dit \"\"oui\"\"\";x\n"]; + yield 'header from keys' => [['first_row_header' => true], "col1;col2\n\"il a dit \"\"oui\"\"\";x\n"]; + yield 'case-insensitive options' => [['DELIMITER' => '|'], "\"il a dit \"\"oui\"\"\"|x\n"]; + } + + /** + * @param array $options + */ + #[DataProvider('optionsCases')] + public function testOptions(array $options, string $expected): void + { + $writer = new CsvWriter($options + ['encoding' => 'UTF-8', 'eol' => "\n"]); + $writer->writeRow(['col1' => 'il a dit "oui"', 'col2' => 'x']); + + $this->assertSame($expected, $writer->getContent()); + } + + public function testUnsupportedEncoding(): void + { + $this->expectException(\UnexpectedValueException::class); + + (new CsvWriter(['encoding' => 'NOT-AN-ENCODING']))->writeRow(['a']); + } +} diff --git a/composer.json b/composer.json index 3f913ab..0d1b86b 100644 --- a/composer.json +++ b/composer.json @@ -22,7 +22,6 @@ }, "require": { "php": "^8.2", - "csanquer/colibri-csv": "^1.2", "doctrine/orm": "^2.20|^3.3", "symfony/config": "^7.4|^8.0", "symfony/dependency-injection": "^7.4|^8.0", diff --git a/package.json b/package.json deleted file mode 100644 index c9b5a0b..0000000 --- a/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "dependencies": { - "jquery.cookie": "^1.4.1" - } -} From 57e7e384acb8e17e25d88693f995638832ae5721 Mon Sep 17 00:00:00 2001 From: Hugues Date: Tue, 10 Nov 2026 11:41:45 +0100 Subject: [PATCH 5/7] Prepare the 8.0 release Add UPGRADE-8.0.md and the "8.x-dev" branch alias for master. Co-Authored-By: Claude Opus 5.5 --- UPGRADE-8.0.md | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++ composer.json | 5 +++++ 2 files changed, 61 insertions(+) create mode 100644 UPGRADE-8.0.md diff --git a/UPGRADE-8.0.md b/UPGRADE-8.0.md new file mode 100644 index 0000000..cf72e1d --- /dev/null +++ b/UPGRADE-8.0.md @@ -0,0 +1,56 @@ +# Upgrade from 7.x to 8.0 + +## Requirements + +- PHP 8.2+ (unchanged) +- Symfony **7.4** or 8.x: Symfony 7.0 to 7.3 are no longer supported (end of life). +- Doctrine ORM **2.20+** or 3.x. +- `phpoffice/phpspreadsheet` 1.23+ when using `AbstractXlsExport` (still optional). + +## CSV exports + +`csanquer/colibri-csv` is no longer a dependency: it is abandoned and triggered a PHP 8.1+ deprecation +for every `null` cell. `CsvExport` now uses the bundle's own +`Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\Export\CsvWriter`. + +- The `csvWriter` export options are unchanged (same names, same defaults), and so is the generated CSV. +- If your code uses `CSanquer\ColibriCsv\*` classes directly (e.g. in an overridden `execute()`), either + require `csanquer/colibri-csv` in your project or switch to the new `CsvWriter` + (`getFileContent()` becomes `getContent()`, no `createTempStream()` / `close()` calls needed). +- A cell value must be a scalar, `null` or a `\Stringable` object: other values (e.g. `\DateTimeInterface`) + now throw an `\InvalidArgumentException`. Format them in `getRow()`. + +## Exports: `postExecute()` + +`postExecute()` was already deprecated since 7.0. It is now only called when an export overrides it, +and a deprecation is triggered in that case: move the code to `preExecute()`. + +## Sort directions + +Lowercase sort directions (`asc`, `desc`) are deprecated (since 7.0): use `ASC` / `DESC`, +including in `setDefaultSort()` and in the `getSortPath()` calls of your templates. + +## `DoctrineDatagrid` subclasses + +- The protected `$session` property has been removed: use `$this->getSession()`. +- `getRequestedAction()` now returns `?string` (it threw a `TypeError` when no action was requested). +- `getRequestedLimit()` signature is now `getRequestedLimit(int $default = 0): int`. +- The unused private methods `isRequestedAction()`, `getSessionFilter()` and `setSessionFilter()` have been removed. + +## Bundle configuration + +- `DependencyInjection\DoctrineDatagridExtension` and `DependencyInjection\Configuration` have been removed: + the bundle now extends `AbstractBundle`. The `DoctrineDatagridFactory` service is unchanged. +- `Resources/config/routing.yml` (demo routes pointing to a non-existent controller) has been removed: + remove any import of it from your routing configuration. + +## Templates + +- The deprecated Twig `spaceless` filter is no longer used; the rendered HTML is unchanged. +- The `batchHeader` macro now displays the number of results of the current page and the total number + of results (it referenced a non-existent `datagrid.pager` property). + +## JavaScript (`jquery.batch.js`) + +The `jquery.cookie` plugin is no longer needed: you can remove it from your `package.json` and layouts. +The cookie format is unchanged, so current selections are kept. diff --git a/composer.json b/composer.json index 0d1b86b..8b86567 100644 --- a/composer.json +++ b/composer.json @@ -59,6 +59,11 @@ "cs": "php-cs-fixer fix --dry-run --diff", "cs-fix": "php-cs-fixer fix" }, + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, "config": { "sort-packages": true } From 471fec183157cf40e8117717b84c6472003c895d Mon Sep 17 00:00:00 2001 From: Hugues Date: Tue, 10 Nov 2026 11:45:57 +0100 Subject: [PATCH 6/7] Configure the Doctrine proxy directory in tests on PHP < 8.4 Doctrine ORM 3 requires a proxy directory when native lazy objects are not available (PHP < 8.4). Co-Authored-By: Claude Opus 5.5 --- Tests/OrmTestTrait.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Tests/OrmTestTrait.php b/Tests/OrmTestTrait.php index 45feb8d..854264f 100644 --- a/Tests/OrmTestTrait.php +++ b/Tests/OrmTestTrait.php @@ -24,6 +24,10 @@ private function createEntityManager(): EntityManagerInterface if (\PHP_VERSION_ID >= 80400 && method_exists($config, 'enableNativeLazyObjects')) { $config->enableNativeLazyObjects(true); + } else { + // Without native lazy objects (PHP < 8.4), Doctrine generates proxy classes + $config->setProxyDir(sys_get_temp_dir().'/doctrine-datagrid-bundle-proxies'); + $config->setProxyNamespace('DoctrineDatagridBundleProxies'); } $connection = DriverManager::getConnection(['driver' => 'pdo_sqlite', 'memory' => true], $config); From cddab172067cf9582a61b15775d079d3ab30d2e1 Mon Sep 17 00:00:00 2001 From: Hugues Date: Tue, 10 Nov 2026 14:22:25 +0100 Subject: [PATCH 7/7] Make exports generic and support any PhpSpreadsheet writer As suggested in #19: - New AbstractExport base class: the response is built from getContentType() and getFilename() instead of being duplicated in each export - New AbstractSpreadsheetExport accepting any PhpSpreadsheet writer (ODS, HTML, PDF...) through createWriter(); AbstractXlsExport is now its XLSX flavour - CsvExport and AbstractXlsExport keep the same content and headers Also fixes XLSX exports containing an extra empty column after the last header. Spreadsheet exports are now tested in CI (PHP 8.4 job). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 9 +- Datagrid/Export/AbstractExport.php | 96 ++++++++++++ Datagrid/Export/AbstractSpreadsheetExport.php | 97 ++++++++++++ Datagrid/Export/AbstractXlsExport.php | 140 ++---------------- Datagrid/Export/CsvExport.php | 91 ++---------- README.md | 52 ++++++- Tests/Export/ExportTest.php | 53 ++++++- Tests/Fixtures/Export/BookHtmlExport.php | 40 +++++ Tests/Fixtures/Export/BookOdsExport.php | 40 +++++ UPGRADE-8.0.md | 10 ++ phpstan.dist.neon | 10 +- 11 files changed, 420 insertions(+), 218 deletions(-) create mode 100644 Datagrid/Export/AbstractExport.php create mode 100644 Datagrid/Export/AbstractSpreadsheetExport.php create mode 100644 Tests/Fixtures/Export/BookHtmlExport.php create mode 100644 Tests/Fixtures/Export/BookOdsExport.php diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8a0ff99..c6b8e78 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,9 +22,10 @@ jobs: # Symfony 7.4 - php: '8.3' dependencies: highest - # Symfony 8 + # Symfony 8, with the optional PhpSpreadsheet exports - php: '8.4' dependencies: highest + spreadsheet: true - php: '8.5' dependencies: highest steps: @@ -33,9 +34,13 @@ jobs: - uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php }} - extensions: pdo_sqlite + extensions: pdo_sqlite, gd, zip coverage: none + - name: Require PhpSpreadsheet + if: ${{ matrix.spreadsheet }} + run: composer require --dev --no-update phpoffice/phpspreadsheet + - uses: ramsey/composer-install@v3 with: dependency-versions: ${{ matrix.dependencies }} diff --git a/Datagrid/Export/AbstractExport.php b/Datagrid/Export/AbstractExport.php new file mode 100644 index 0000000..3b133c1 --- /dev/null +++ b/Datagrid/Export/AbstractExport.php @@ -0,0 +1,96 @@ +qb = $qb; + $this->params = $params; + } + + /** + * MIME type of the generated file, e.g. "text/csv". + */ + abstract public function getContentType(): string; + + /** + * Generates the content of the file. + */ + abstract protected function generateContent(): string; + + /** + * Do anything you want before the export, like modifying the query. + */ + public function preExecute(): void + { + } + + /** + * @deprecated since 7.0, override preExecute() instead + */ + #[\Deprecated(message: 'postExecute has been deprecated, as it is implemented as a preExecute. Use preExecute instead', since: DoctrineDatagrid::VERSION_SYMFONY7)] + public function postExecute() + { + return $this; + } + + public function execute(): static + { + $this->preExecute(); + $this->callDeprecatedPostExecute(); + + $this->content = $this->generateContent(); + + return $this; + } + + public function getResponse(): Response + { + $content = (string) $this->content; + $response = new Response($content); + $disposition = $response->headers->makeDisposition( + ResponseHeaderBag::DISPOSITION_ATTACHMENT, + $this->getFilename() + ); + + $response->headers->set('Content-Disposition', $disposition); + $response->headers->set('Content-Type', $this->getContentType()); + $response->headers->set('Expires', '0'); + $response->headers->set('Cache-Control', 'must-revalidate, post-check=0, pre-check=0'); + $response->headers->set('Content-Length', (string) \strlen($content)); + $response->setCharset('UTF-8'); + + return $response; + } + + /** + * Keeps BC for exports still overriding postExecute(), without triggering + * a deprecation for the others. + */ + private function callDeprecatedPostExecute(): void + { + if (self::class === (new \ReflectionMethod($this, 'postExecute'))->getDeclaringClass()->getName()) { + return; + } + + Util::triggerDeprecation(\sprintf('Overriding "postExecute()" in "%s" is deprecated, override "preExecute()" instead.', static::class), DoctrineDatagrid::VERSION_SYMFONY7); + $this->postExecute(); + } +} diff --git a/Datagrid/Export/AbstractSpreadsheetExport.php b/Datagrid/Export/AbstractSpreadsheetExport.php new file mode 100644 index 0000000..b408e83 --- /dev/null +++ b/Datagrid/Export/AbstractSpreadsheetExport.php @@ -0,0 +1,97 @@ +> + */ + abstract public function getHeader(): array; + + abstract public function getRow($object); + + /** + * Creates the PhpSpreadsheet writer of the export format. + */ + abstract public function createWriter(Spreadsheet $spreadsheet): IWriter; + + /** + * Data of each sheet: use string keys to name the sheets. + */ + public function getData(QueryBuilder $qb): mixed + { + return [$qb->getQuery()->execute()]; + } + + protected function generateContent(): string + { + if (!class_exists(Spreadsheet::class)) { + throw new \LogicException(\sprintf('PhpSpreadsheet is required to use "%s". Try `composer require phpoffice/phpspreadsheet`.', static::class)); + } + + $spreadsheet = new Spreadsheet(); + $spreadsheet->removeSheetByIndex(0); + + $headers = $this->getHeader(); + + foreach ($this->getData($this->qb) as $name => $data) { + $sheet = \is_string($name) ? new Worksheet($spreadsheet, $name) : new Worksheet($spreadsheet); + $spreadsheet->addSheet($sheet); + + $col = 0; + $row = 1; + if (isset($headers[$name])) { + $col = 1; + foreach ($headers[$name] as $value) { + $sheet->setCellValue([$col, $row], $value); + ++$col; + } + ++$row; + } + + foreach ($data as $value) { + $sheet->fromArray($this->getRow($value), null, 'A'.$row); + ++$row; + } + + // $col is the column following the last header + for ($i = 1; $i < $col; ++$i) { + $sheet->getColumnDimensionByColumn($i)->setAutoSize(true); + } + } + + $writer = $this->createWriter($spreadsheet); + + ob_start(); + try { + $writer->save('php://output'); + } finally { + $content = ob_get_clean(); + } + + return (string) $content; + } +} diff --git a/Datagrid/Export/AbstractXlsExport.php b/Datagrid/Export/AbstractXlsExport.php index dad759f..8c25b9d 100644 --- a/Datagrid/Export/AbstractXlsExport.php +++ b/Datagrid/Export/AbstractXlsExport.php @@ -2,144 +2,22 @@ namespace Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\Export; -use Doctrine\ORM\QueryBuilder; use PhpOffice\PhpSpreadsheet\Spreadsheet; -use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use PhpOffice\PhpSpreadsheet\Writer\IWriter; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; -use Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\DoctrineDatagrid; -use Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\Util; -use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\HttpFoundation\ResponseHeaderBag; -abstract class AbstractXlsExport implements Export +/** + * XLSX (Excel) export. + */ +abstract class AbstractXlsExport extends AbstractSpreadsheetExport { - protected ?string $content = null; - - protected array $params; - - protected QueryBuilder $qb; - - public function __construct(QueryBuilder $qb, array $params) - { - $this->qb = $qb; - $this->params = $params; - } - - abstract public function getFilename(): string; - - abstract public function getHeader(): array; - - abstract public function getRow($object); - - public function getData(QueryBuilder $qb): mixed + public function createWriter(Spreadsheet $spreadsheet): IWriter { - return [$qb->getQuery()->execute()]; + return new Xlsx($spreadsheet); } - /** - * Do anything you want before the export, like modifying the query. - */ - public function preExecute(): void + public function getContentType(): string { - } - - /** - * @deprecated since 7.0, override preExecute() instead - */ - #[\Deprecated(message: 'postExecute has been deprecated, as it is implemented as a preExecute. Use preExecute instead', since: DoctrineDatagrid::VERSION_SYMFONY7)] - public function postExecute() - { - return $this; - } - - /** - * Keeps BC for exports still overriding postExecute(), without triggering - * a deprecation for the others. - */ - private function callDeprecatedPostExecute(): void - { - if (self::class === (new \ReflectionMethod($this, 'postExecute'))->getDeclaringClass()->getName()) { - return; - } - - Util::triggerDeprecation(sprintf('Overriding "%s::postExecute()" is deprecated, override "preExecute()" instead.', self::class), DoctrineDatagrid::VERSION_SYMFONY7); - $this->postExecute(); - } - - public function execute(): static - { - $this->preExecute(); - $this->callDeprecatedPostExecute(); - - if (!class_exists(Spreadsheet::class)) { - throw new \LogicException('PhpSpreadsheet is required to export to XLSX. Try `composer require phpoffice/phpspreadsheet`'); - } - - $spreadsheet = new Spreadsheet(); - - $spreadsheet->removeSheetByIndex(0); - - $headers = $this->getHeader(); - $datas = $this->getData($this->qb); - - $writer = new Xlsx($spreadsheet); - - foreach ($datas as $name => $data) { - $col = 0; - if (is_string($name)) { - $sheet = new Worksheet($spreadsheet, $name); - } else { - $sheet = new Worksheet($spreadsheet); - } - $spreadsheet->addSheet($sheet); - $row = 1; - if (isset($headers[$name])) { - $col = 1; - foreach ($headers[$name] as $value) { - $sheet->setCellValue([$col, $row], $value); - ++$col; - } - ++$row; - } - - foreach ($data as $value) { - $sheet->fromArray( - $this->getRow($value), - null, - 'A'.$row - ); - ++$row; - } - for ($i = 1; $i <= $col; ++$i) { - $sheet - ->getColumnDimensionByColumn($i) - ->setAutoSize(true) - ; - } - } - - ob_start(); - $writer->save('php://output'); - $this->content = ob_get_clean(); - - return $this; - } - - public function getResponse(): Response - { - $response = new Response($this->content); - $disposition = $response->headers->makeDisposition( - ResponseHeaderBag::DISPOSITION_ATTACHMENT, - $this->getFilename() - ); - - $response->headers->set('Content-Disposition', $disposition); - $response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); - $response->headers->set('Expires', '0'); - $response->headers->set('Cache-Control', 'must-revalidate, post-check=0, pre-check=0'); - $response->headers->set('Content-Length', (string) strlen($this->content)); - $response->setCharset('UTF-8'); - - return $response; + return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; } } diff --git a/Datagrid/Export/CsvExport.php b/Datagrid/Export/CsvExport.php index 20b70a2..a88a8bc 100644 --- a/Datagrid/Export/CsvExport.php +++ b/Datagrid/Export/CsvExport.php @@ -2,109 +2,50 @@ namespace Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\Export; -use Doctrine\ORM\QueryBuilder; -use Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\DoctrineDatagrid; -use Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\Util; use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\HttpFoundation\ResponseHeaderBag; /** * @author Maxime CORSON */ -abstract class CsvExport implements Export +abstract class CsvExport extends AbstractExport { - protected ?string $content = null; - - protected array $params; + abstract public function getHeader(); - protected QueryBuilder $qb; + abstract public function getRow($object); - public function __construct(QueryBuilder $qb, array $params) + public function getContentType(): string { - $this->qb = $qb; - $this->params = $params; + return 'text/csv'; } - /** - * Do anything you want before the export, like modifying the query. - */ - public function preExecute(): void + public function getResponse(): Response { - } + $response = parent::getResponse(); + $response->headers->set('Content-Description', 'File Transfer'); + $response->headers->set('Content-Transfer-Encoding', 'binary'); + $response->headers->set('Pragma', 'public'); - /** - * @deprecated since 7.0, override preExecute() instead - */ - #[\Deprecated(message: 'postExecute has been deprecated, as it is implemented as a preExecute. Use preExecute instead', since: DoctrineDatagrid::VERSION_SYMFONY7)] - public function postExecute() - { - return $this; + return $response; } - /** - * Keeps BC for exports still overriding postExecute(), without triggering - * a deprecation for the others. - */ - private function callDeprecatedPostExecute(): void + public function getDelimiter(): string { - if (self::class === (new \ReflectionMethod($this, 'postExecute'))->getDeclaringClass()->getName()) { - return; - } - - Util::triggerDeprecation(sprintf('Overriding "%s::postExecute()" is deprecated, override "preExecute()" instead.', self::class), DoctrineDatagrid::VERSION_SYMFONY7); - $this->postExecute(); + return ';'; } - public function execute(): static + protected function generateContent(): string { - $this->preExecute(); - $this->callDeprecatedPostExecute(); - $writer = new CsvWriter($this->getCsvWriterOptions()); if ($this->getHeader()) { $writer->writeRow($this->getHeader()); } - $results = $this->qb->getQuery()->execute(); - - foreach ($results as $result) { + foreach ($this->qb->getQuery()->execute() as $result) { $writer->writeRow($this->getRow($result)); } - $this->content = $writer->getContent(); - - return $this; - } - - public function getResponse(): Response - { - $response = new Response($this->content); - $disposition = $response->headers->makeDisposition( - ResponseHeaderBag::DISPOSITION_ATTACHMENT, - $this->getFilename() - ); - - $response->headers->set('Content-Description', 'File Transfer'); - $response->headers->set('Content-Disposition', $disposition); - $response->headers->set('Content-Type', 'text/csv'); - $response->headers->set('Content-Transfer-Encoding', 'binary'); - $response->headers->set('Expires', '0'); - $response->headers->set('Cache-Control', 'must-revalidate, post-check=0, pre-check=0'); - $response->headers->set('Pragma', 'public'); - $response->headers->set('Content-Length', (string) strlen($this->content)); - $response->setCharset('UTF-8'); - - return $response; - } - - abstract public function getHeader(); - - abstract public function getRow($object); - - public function getDelimiter(): string - { - return ';'; + return $writer->getContent(); } /** diff --git a/README.md b/README.md index 3f36e73..e25dd95 100644 --- a/README.md +++ b/README.md @@ -156,9 +156,55 @@ Render them in your views: ## Exports -Declare export classes extending `CsvExport` or `AbstractXlsExport` with `setExports(['csv' => BookCsvExport::class])`, -then call `$datagrid->export('csv')->getResponse()`. Override `preExecute()` to alter the query before the export -(`postExecute()` is deprecated). +Declare export classes with `setExports(['csv' => BookCsvExport::class])`, then call +`$datagrid->export('csv')->getResponse()`. Override `preExecute()` to alter the query before the export +(`postExecute()` is deprecated). Available base classes: + +- `CsvExport`: CSV, no dependency; +- `AbstractXlsExport`: XLSX (requires `phpoffice/phpspreadsheet`); +- `AbstractSpreadsheetExport`: any format supported by PhpSpreadsheet (ODS, HTML, PDF...), by providing the writer + and the content type; +- `AbstractExport`: any other format, by implementing `generateContent()` and `getContentType()`. + +```php +use PhpOffice\PhpSpreadsheet\Spreadsheet; +use PhpOffice\PhpSpreadsheet\Writer\IWriter; +use PhpOffice\PhpSpreadsheet\Writer\Ods; +use Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\Export\AbstractSpreadsheetExport; + +class BookOdsExport extends AbstractSpreadsheetExport +{ + public function createWriter(Spreadsheet $spreadsheet): IWriter + { + return new Ods($spreadsheet); + } + + public function getContentType(): string + { + return 'application/vnd.oasis.opendocument.spreadsheet'; + } + + public function getFilename(): string + { + return 'books.ods'; + } + + public function getHeader(): array + { + return [['Title', 'Genre']]; + } + + public function getRow($book): array + { + return [$book->getTitle(), $book->getGenre()]; + } +} +``` + +Other PhpSpreadsheet writers: `Html` (`text/html`, only the first sheet unless `writeAllSheets()` is called), +`Pdf\Dompdf`, `Pdf\Tcpdf` or `Pdf\Mpdf` (`application/pdf`). The PDF writers need an extra library that this +bundle does not require: check its license before choosing one (`mpdf/mpdf` is GPL-2.0, `dompdf/dompdf` LGPL-2.1, +`tecnickcom/tcpdf` LGPL-3.0). HTML and PDF rendering are slow and memory-hungry on large datagrids. CSV options can be given with the `csvWriter` parameter, e.g. `$datagrid->export('csv', ['csvWriter' => ['encoding' => 'UTF-8', 'delimiter' => ',', 'bom' => true]])`. diff --git a/Tests/Export/ExportTest.php b/Tests/Export/ExportTest.php index 36088a6..7de659f 100644 --- a/Tests/Export/ExportTest.php +++ b/Tests/Export/ExportTest.php @@ -4,13 +4,17 @@ use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\QueryBuilder; +use PhpOffice\PhpSpreadsheet\IOFactory; use PhpOffice\PhpSpreadsheet\Spreadsheet; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\IgnoreDeprecations; use PHPUnit\Framework\TestCase; use Spyrit\Bundle\DoctrineDatagridBundle\Datagrid\DoctrineDatagrid; use Spyrit\Bundle\DoctrineDatagridBundle\Tests\DatagridTestTrait; use Spyrit\Bundle\DoctrineDatagridBundle\Tests\Fixtures\Entity\Book; use Spyrit\Bundle\DoctrineDatagridBundle\Tests\Fixtures\Export\BookCsvExport; +use Spyrit\Bundle\DoctrineDatagridBundle\Tests\Fixtures\Export\BookHtmlExport; +use Spyrit\Bundle\DoctrineDatagridBundle\Tests\Fixtures\Export\BookOdsExport; use Spyrit\Bundle\DoctrineDatagridBundle\Tests\Fixtures\Export\BookXlsExport; use Spyrit\Bundle\DoctrineDatagridBundle\Tests\Fixtures\Export\LegacyBookCsvExport; use Spyrit\Bundle\DoctrineDatagridBundle\Tests\OrmTestTrait; @@ -50,7 +54,7 @@ public function testExportWithoutPostExecuteOverrideDoesNotTriggerDeprecation(): #[IgnoreDeprecations] public function testOverridingPostExecuteIsDeprecated(): void { - $this->expectUserDeprecationMessageMatches('/Overriding ".*::postExecute\(\)" is deprecated/'); + $this->expectUserDeprecationMessageMatches('/Overriding "postExecute\(\)" in ".*LegacyBookCsvExport" is deprecated/'); $export = $this->datagrid()->export('legacy'); @@ -65,16 +69,53 @@ public function testUnknownExport(): void $this->datagrid()->export('pdf'); } - public function testXlsxExport(): void + public function testCsvResponseKeepsItsHeaders(): void + { + $headers = $this->datagrid()->export('csv')->getResponse()->headers; + + $this->assertSame('File Transfer', $headers->get('Content-Description')); + $this->assertSame('binary', $headers->get('Content-Transfer-Encoding')); + $this->assertSame('public', $headers->get('Pragma')); + $this->assertSame('0', $headers->get('Expires')); + } + + /** + * @return iterable + */ + public static function spreadsheetExports(): iterable + { + yield 'xlsx' => ['xlsx', 'books.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']; + yield 'ods' => ['ods', 'books.ods', 'application/vnd.oasis.opendocument.spreadsheet']; + yield 'html' => ['html', 'books.html', 'text/html']; + } + + #[DataProvider('spreadsheetExports')] + public function testSpreadsheetExport(string $export, string $filename, string $contentType): void { if (!class_exists(Spreadsheet::class)) { $this->markTestSkipped('phpoffice/phpspreadsheet is not installed.'); } - $response = $this->datagrid()->export('xlsx')->getResponse(); + $response = $this->datagrid()->export($export)->getResponse(); + + $this->assertSame('attachment; filename='.$filename, $response->headers->get('Content-Disposition')); + $this->assertSame($contentType, $response->headers->get('Content-Type')); + $this->assertSame((string) strlen($response->getContent()), $response->headers->get('Content-Length')); + + $reader = IOFactory::createReader(ucfirst($export)); + $file = tempnam(sys_get_temp_dir(), 'export'); + try { + file_put_contents($file, $response->getContent()); + $rows = $reader->load($file)->getActiveSheet()->toArray(); + } finally { + unlink($file); + } - $this->assertSame('attachment; filename=books.xlsx', $response->headers->get('Content-Disposition')); - $this->assertStringStartsWith('PK', $response->getContent()); + $this->assertSame([ + ['Title', 'Genre'], + ['Politics and the English Language', 'essay'], + ['Why I Write', 'essay'], + ], $rows); } private function datagrid(): DoctrineDatagrid @@ -92,6 +133,8 @@ private function datagrid(): DoctrineDatagrid 'csv' => BookCsvExport::class, 'legacy' => LegacyBookCsvExport::class, 'xlsx' => BookXlsExport::class, + 'ods' => BookOdsExport::class, + 'html' => BookHtmlExport::class, ]); return $dg; diff --git a/Tests/Fixtures/Export/BookHtmlExport.php b/Tests/Fixtures/Export/BookHtmlExport.php new file mode 100644 index 0000000..4361778 --- /dev/null +++ b/Tests/Fixtures/Export/BookHtmlExport.php @@ -0,0 +1,40 @@ +title, $object->genre]; + } +} diff --git a/Tests/Fixtures/Export/BookOdsExport.php b/Tests/Fixtures/Export/BookOdsExport.php new file mode 100644 index 0000000..3233ac6 --- /dev/null +++ b/Tests/Fixtures/Export/BookOdsExport.php @@ -0,0 +1,40 @@ +title, $object->genre]; + } +} diff --git a/UPGRADE-8.0.md b/UPGRADE-8.0.md index cf72e1d..50d19d5 100644 --- a/UPGRADE-8.0.md +++ b/UPGRADE-8.0.md @@ -20,6 +20,16 @@ for every `null` cell. `CsvExport` now uses the bundle's own - A cell value must be a scalar, `null` or a `\Stringable` object: other values (e.g. `\DateTimeInterface`) now throw an `\InvalidArgumentException`. Format them in `getRow()`. +## Exports + +`CsvExport` and `AbstractXlsExport` now share a new `AbstractExport` base class (common `getResponse()`), and +`AbstractXlsExport` extends the new `AbstractSpreadsheetExport`, which accepts any PhpSpreadsheet writer +(ODS, HTML, PDF...). Existing exports keep working unchanged (same content and HTTP headers), except: + +- XLSX exports no longer contain an extra empty column after the last header. +- If your export already defines a `getContentType()`, `generateContent()` or `createWriter()` method, + check that its signature is compatible with the new base classes. + ## Exports: `postExecute()` `postExecute()` was already deprecated since 7.0. It is now only called when an export overrides it, diff --git a/phpstan.dist.neon b/phpstan.dist.neon index 033e37a..d991d26 100644 --- a/phpstan.dist.neon +++ b/phpstan.dist.neon @@ -10,8 +10,14 @@ parameters: ignoreErrors: # phpoffice/phpspreadsheet is an optional dependency (requires ext-gd) - - identifier: class.notFound - path: Datagrid/Export/AbstractXlsExport.php + identifiers: + - class.notFound + - return.type + paths: + - Datagrid/Export/AbstractSpreadsheetExport.php + - Datagrid/Export/AbstractXlsExport.php + - Tests/Fixtures/Export/* + - Tests/Export/ExportTest.php # compatibility with doctrine/orm 2.x (lowest dependencies) - identifier: function.alreadyNarrowedType