From 0b19aa0e89eca293749c2fb40f2a1b27d0e80916 Mon Sep 17 00:00:00 2001 From: Massimiliano Arione Date: Sat, 17 Sep 2022 17:35:12 +0200 Subject: [PATCH] v4 (#314) --- .github/workflows/build.yaml | 4 +- CHANGELOG.md | 7 ++ composer.json | 21 ++--- docs/pager/config.md | 14 +--- docs/pager/intro.md | 14 ++-- docs/pager/usage.md | 15 +++- .../ArgumentAccessInterface.php | 12 +++ .../ArgumentAccess/RequestArgumentAccess.php | 40 +++++++++ src/Knp/Component/Pager/Event/BeforeEvent.php | 12 +-- src/Knp/Component/Pager/Event/ItemsEvent.php | 12 +-- .../Component/Pager/Event/PaginationEvent.php | 4 +- .../Doctrine/ORM/Query/WhereWalker.php | 14 ++-- .../Doctrine/ORM/QuerySubscriber.php | 14 ++-- .../Filtration/FiltrationSubscriber.php | 4 +- .../Filtration/PropelQuerySubscriber.php | 16 ++-- .../Paginate/SolariumQuerySubscriber.php | 6 +- .../Subscriber/Sortable/ArraySubscriber.php | 40 ++++----- .../Doctrine/ODM/MongoDB/QuerySubscriber.php | 16 ++-- .../Sortable/Doctrine/ORM/QuerySubscriber.php | 23 +++--- .../Sortable/ElasticaQuerySubscriber.php | 16 ++-- .../Sortable/PropelQuerySubscriber.php | 20 ++--- .../Sortable/SolariumQuerySubscriber.php | 22 ++--- .../Sortable/SortableSubscriber.php | 14 ++-- .../Pager/Pagination/AbstractPagination.php | 45 +++++----- .../Pager/Pagination/PaginationInterface.php | 8 +- src/Knp/Component/Pager/Paginator.php | 25 +++--- .../Component/Pager/PaginatorInterface.php | 2 +- tests/Test/Mock/PaginationSubscriber.php | 1 - .../Pagination/AbstractPaginationTest.php | 4 +- .../Pager/Pagination/CustomParameterTest.php | 4 +- .../Filtration/Doctrine/ORM/AllowListTest.php | 13 ++- .../Filtration/Doctrine/ORM/QueryTest.php | 82 +++++++++++++------ .../Filtration/FiltrationSubscriberTest.php | 5 +- .../Pager/Subscriber/Paginate/ArrayTest.php | 7 +- .../Paginate/Callback/CallbackTest.php | 7 +- .../Paginate/Doctrine/CollectionTest.php | 10 ++- .../ODM/PHPCR/QuerySubscriberTest.php | 4 +- .../Subscriber/Paginate/ElasticaTest.php | 4 +- .../Paginate/PaginationSubscriberTest.php | 6 +- .../Paginate/SolariumQuerySubscriberTest.php | 4 +- .../Sortable/ArraySubscriberTest.php | 25 ++++-- .../Doctrine/ODM/MongoDB/QueryTest.php | 10 ++- .../Sortable/Doctrine/ORM/QueryTest.php | 35 ++++---- .../Sortable/SolariumQuerySubscriberTest.php | 7 +- .../Sortable/SortableSubscriberTest.php | 5 +- tests/Test/Tool/BaseTestCase.php | 13 +-- 46 files changed, 400 insertions(+), 286 deletions(-) create mode 100644 src/Knp/Component/Pager/ArgumentAccess/ArgumentAccessInterface.php create mode 100644 src/Knp/Component/Pager/ArgumentAccess/RequestArgumentAccess.php diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 2dc7089f..b4ab181f 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -31,10 +31,8 @@ jobs: matrix: include: - description: 'Lowest' - php: '7.4' - composer_option: '--prefer-lowest' - - description: '8.0' php: '8.0' + composer_option: '--prefer-lowest' - description: '8.1' php: '8.1' name: PHP ${{ matrix.php }} tests (${{ matrix.description }}) diff --git a/CHANGELOG.md b/CHANGELOG.md index 36c8e30c..07226a7c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## 4.0.0 + +*Unreleased* + +* Paginator constructor now accepts as second argument an instance of ArgumentAccessInterface, instead of + a RequestStack. So you can now paginate outside the web context + ## 3.6.0 *Released at 2022-08-18* diff --git a/composer.json b/composer.json index 3559b973..e7c554fb 100644 --- a/composer.json +++ b/composer.json @@ -22,22 +22,22 @@ } ], "require": { - "php": "^7.4 || ^8.0", - "symfony/event-dispatcher-contracts": "^2.0 || ^3.0", - "symfony/http-foundation": "^4.4 || ^5.4 || ^6.0" + "php": "^8.0", + "symfony/event-dispatcher-contracts": "^3.0" }, "require-dev": { "ext-pdo_sqlite": "*", "doctrine/mongodb-odm": "^2.4", - "doctrine/orm": "^2.11", - "doctrine/phpcr-odm": "^1.2", - "jackalope/jackalope-doctrine-dbal": "^1.2", + "doctrine/orm": "^2.12", + "doctrine/phpcr-odm": "^1.6", + "jackalope/jackalope-doctrine-dbal": "^1.8", "phpunit/phpunit": "^9.5", "propel/propel1": "^1.7", "ruflin/elastica": "^7.0", "solarium/solarium": "^6.0", - "symfony/http-kernel": "^4.4 || ^5.4 || ^6.0", - "symfony/property-access": "^4.4 || ^5.4 || ^6.0" + "symfony/http-foundation": "^5.4 || ^6.0", + "symfony/http-kernel": "^5.4 || ^6.0", + "symfony/property-access": "^5.4 || ^6.0" }, "suggest": { "doctrine/common": "to allow usage pagination with Doctrine ArrayCollection", @@ -47,14 +47,15 @@ "propel/propel1": "to allow usage pagination with Propel ORM", "ruflin/elastica": "to allow usage pagination with ElasticSearch Client", "solarium/solarium": "to allow usage pagination with Solarium Client", - "symfony/property-access": "To allow sorting arrays" + "symfony/http-foundation": "to retrieve arguments from Request", + "symfony/property-access": "to allow sorting arrays" }, "conflict": { "doctrine/dbal": "<2.10" }, "extra": { "branch-alias": { - "dev-master": "3.x-dev" + "dev-master": "4.x-dev" } }, "autoload": { diff --git a/docs/pager/config.md b/docs/pager/config.md index e49254f5..a931e44f 100644 --- a/docs/pager/config.md +++ b/docs/pager/config.md @@ -1,12 +1,10 @@ ## Configuration - Some subscribers will take into account some options. These options can be passed as the 4th argument of `Paginator::paginate()`. For example, Doctrine ORM subscriber will generate different sql queries if the `distinct` options changes. - The list of existing options are: | name | type | default value | subscribers | @@ -32,7 +30,6 @@ The list of existing options are: If set to true, will add a distinct sql keyword on orm queries to ensuire unicity of counted results - ### `wrap-queries` If set to true, will take advantage of doctrine 2.3 output walkers by using subqueries to handle composite keys and HAVING queries. @@ -42,22 +39,19 @@ If you want to order your results by a column from a fetch joined t-many associa you have to set `wrap-queries` to `true`. Otherwise you will get an exception with this warning: *"Cannot select distinct identifiers from query with LIMIT and ORDER BY on a column from a fetch joined to-many association. Use output walkers."* - ### `defaultSortFieldName` Used as default field name for the sorting. It can take an array for sorting by multiple fields. -\* **Attention**: Arrays are only supported for *Doctrine's ORM*. - +> **Attention**: Arrays are only supported for *Doctrine's ORM*. ### `defaultFilterFields` Used as default field names for the filtration. It can take an array for filtering by multiple fields. - ### `pageOutOfRange` Defines behavior if page number is out of range (i.g. exceeds the last page number): - * 'ignore' - do nothing; - * 'fix' - replace page number with max page; - * 'throwException' - throw PageNumberOutOfRangeException (if you want to handle this case in the app). +* 'ignore' - do nothing; +* 'fix' - replace page number with max page; +* 'throwException' - throw PageNumberOutOfRangeException (if you want to handle this case in the app). diff --git a/docs/pager/intro.md b/docs/pager/intro.md index 50a50de8..fcc0c7e0 100644 --- a/docs/pager/intro.md +++ b/docs/pager/intro.md @@ -1,8 +1,6 @@ # Intro to Knp Pager Component -This is a PHP 7 paginator with a totally different core concept. - -**Note:** it is still experimental, any ideas on structural design are very welcome +This is a PHP 8 paginator with a totally different core concept. How is it different? First of all, it uses Symfony's **event dispatcher** to paginate whatever is needed. The pagination process involves triggering events which hit the **subscribers**. If the subscriber @@ -17,6 +15,7 @@ Why reinvent the wheel? Can someone tell me what's the definition of **wheel** i ## Requirements: - Symfony EventDispatcher component +- Symfony HttpFoundation component (optional, if you want to retrieve data from Symfony Request) - Namespace based autoloader for this library ## Features: @@ -36,7 +35,10 @@ pagination view - for representation purposes. ### Controller ```php -$paginator = new Knp\Component\Pager\Paginator; +// see usage.md for full vars +$dispatcher = '[..]'; +$accessor = '[..]'; +$paginator = new Knp\Component\Pager\Paginator($dispatcher, $accessor); $target = range('a', 'u'); // uses event subscribers to paginate $target $pagination = $paginator->paginate($target, 2/*page*/, 10/*limit*/); @@ -49,7 +51,7 @@ echo $pagination; // renders pagination // overriding view rendering -$pagination->renderer = function($data) use ($template) { +$pagination->renderer = function ($data) use ($template) { return $twig->render($template, $data); }; @@ -68,7 +70,7 @@ $pagination = $paginator->paginate($em->createQuery('SELECT a FROM Entity\Articl ### Custom data repository pagination For applications having custom data repositories (like DDD repositories, CQRS read models) you can provide custom -data rerieval inside callbacks. +data retrieval inside callbacks. ```php $repository = ...; diff --git a/docs/pager/usage.md b/docs/pager/usage.md index 4803dbba..7bbd5d16 100644 --- a/docs/pager/usage.md +++ b/docs/pager/usage.md @@ -19,13 +19,24 @@ require 'vendor/autoload.php'; // usage examples will continue here -use Knp\Component\Pager\Paginator; // used class name +use Knp\Component\Pager\Paginator; +use Knp\Component\Pager\ArgumentAccess\RequestArgumentAccess; +use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\HttpFoundation\RequestStack; // end of line and tab definition define('EOL', php_sapi_name() === 'cli' ? PHP_EOL : '
'); define('TAB', php_sapi_name() === 'cli' ? "\t" : ''); -$paginator = new Paginator; // initializes default event dispatcher, with standard listeners +$dispatcher = new EventDispatcher(); +$dispatcher->addSubscriber(new PaginationSubscriber()); +$dispatcher->addSubscriber(new SortableSubscriber()); + +// here we're using the the default access to arguments, based on Symfony Request +// you can use your preferred way to retrieve them, by implementing RequestArgumentAccessInterface +$accessor = new RequestArgumentAccess(RequestStack::createFromGlobals()); + +$paginator = new Paginator($dispatcher, $accessor); $target = range('a', 'z'); // an array to paginate // paginate target and generate representation class, it can be overrided by event listener $pagination = $paginator->paginate($target, 1/*page number*/, 10/*limit per page*/); diff --git a/src/Knp/Component/Pager/ArgumentAccess/ArgumentAccessInterface.php b/src/Knp/Component/Pager/ArgumentAccess/ArgumentAccessInterface.php new file mode 100644 index 00000000..70c370d4 --- /dev/null +++ b/src/Knp/Component/Pager/ArgumentAccess/ArgumentAccessInterface.php @@ -0,0 +1,12 @@ +requestStack = $requestStack; + } + + public function has(string $name): bool + { + return $this->getRequest()->query->has($name); + } + + public function get(string $name): string|int|float|bool|null + { + return $this->getRequest()->query->get($name); + } + + public function set(string $name, string|int|float|bool|null $value): void + { + $this->getRequest()->query->set($name, $value); + } + + private function getRequest(): Request + { + if (null === $request = $this->requestStack->getCurrentRequest()) { + $request = Request::createFromGlobals(); + } + + return $request; + } +} diff --git a/src/Knp/Component/Pager/Event/BeforeEvent.php b/src/Knp/Component/Pager/Event/BeforeEvent.php index 428796b1..ca260b19 100644 --- a/src/Knp/Component/Pager/Event/BeforeEvent.php +++ b/src/Knp/Component/Pager/Event/BeforeEvent.php @@ -2,7 +2,7 @@ namespace Knp\Component\Pager\Event; -use Symfony\Component\HttpFoundation\Request; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; use Symfony\Contracts\EventDispatcher\Event; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; @@ -13,12 +13,12 @@ final class BeforeEvent extends Event { private EventDispatcherInterface $eventDispatcher; - private ?Request $request; + private ArgumentAccessInterface $argumentAccess; - public function __construct(EventDispatcherInterface $eventDispatcher, ?Request $request) + public function __construct(EventDispatcherInterface $eventDispatcher, ArgumentAccessInterface $argumentAccess) { $this->eventDispatcher = $eventDispatcher; - $this->request = $request; + $this->argumentAccess = $argumentAccess; } public function getEventDispatcher(): EventDispatcherInterface @@ -26,8 +26,8 @@ public function getEventDispatcher(): EventDispatcherInterface return $this->eventDispatcher; } - public function getRequest(): Request + public function getArgumentAccess(): ArgumentAccessInterface { - return $this->request ?? Request::createFromGlobals(); + return $this->argumentAccess; } } diff --git a/src/Knp/Component/Pager/Event/ItemsEvent.php b/src/Knp/Component/Pager/Event/ItemsEvent.php index 63e943d0..2411e048 100644 --- a/src/Knp/Component/Pager/Event/ItemsEvent.php +++ b/src/Knp/Component/Pager/Event/ItemsEvent.php @@ -11,10 +11,8 @@ final class ItemsEvent extends Event { /** * A target being paginated - * - * @var mixed */ - public $target; + public mixed $target = null; /** * List of options @@ -23,10 +21,8 @@ final class ItemsEvent extends Event /** * Items result - * - * @var mixed */ - public $items; + public mixed $items = null; /** * Count result @@ -43,7 +39,7 @@ public function __construct(int $offset, int $limit) $this->limit = $limit; } - public function setCustomPaginationParameter($name, $value): void + public function setCustomPaginationParameter(string $name, mixed $value): void { $this->customPaginationParams[$name] = $value; } @@ -53,7 +49,7 @@ public function getCustomPaginationParameters(): array return $this->customPaginationParams; } - public function unsetCustomPaginationParameter($name): void + public function unsetCustomPaginationParameter(string $name): void { if (isset($this->customPaginationParams[$name])) { unset($this->customPaginationParams[$name]); diff --git a/src/Knp/Component/Pager/Event/PaginationEvent.php b/src/Knp/Component/Pager/Event/PaginationEvent.php index 22a95622..50f6f956 100644 --- a/src/Knp/Component/Pager/Event/PaginationEvent.php +++ b/src/Knp/Component/Pager/Event/PaginationEvent.php @@ -12,10 +12,8 @@ final class PaginationEvent extends Event { /** * A target being paginated - * - * @var mixed */ - public $target; + public mixed $target = null; /** * List of options diff --git a/src/Knp/Component/Pager/Event/Subscriber/Filtration/Doctrine/ORM/Query/WhereWalker.php b/src/Knp/Component/Pager/Event/Subscriber/Filtration/Doctrine/ORM/Query/WhereWalker.php index 4ac6e415..17c06fb9 100644 --- a/src/Knp/Component/Pager/Event/Subscriber/Filtration/Doctrine/ORM/Query/WhereWalker.php +++ b/src/Knp/Component/Pager/Event/Subscriber/Filtration/Doctrine/ORM/Query/WhereWalker.php @@ -3,12 +3,12 @@ namespace Knp\Component\Pager\Event\Subscriber\Filtration\Doctrine\ORM\Query; use Doctrine\DBAL\Types\Types as Type; -use Doctrine\ORM\Query\AST\Functions\LowerFunction; use Doctrine\ORM\Query\AST\ComparisonExpression; use Doctrine\ORM\Query\AST\ConditionalExpression; use Doctrine\ORM\Query\AST\ConditionalFactor; use Doctrine\ORM\Query\AST\ConditionalPrimary; use Doctrine\ORM\Query\AST\ConditionalTerm; +use Doctrine\ORM\Query\AST\Functions\LowerFunction; use Doctrine\ORM\Query\AST\LikeExpression; use Doctrine\ORM\Query\AST\Literal; use Doctrine\ORM\Query\AST\Node; @@ -34,18 +34,15 @@ class WhereWalker extends TreeWalkerAdapter public const HINT_PAGINATOR_FILTER_VALUE = 'knp_paginator.filter.value'; /** - * Filter strings in a case insensitive way + * Filter strings in a case-insensitive way */ - const HINT_PAGINATOR_FILTER_CASE_INSENSITIVE = 'knp_paginator.filter.case_insensitive'; + public const HINT_PAGINATOR_FILTER_CASE_INSENSITIVE = 'knp_paginator.filter.case_insensitive'; /** * Walks down a SelectStatement AST node, modifying it to * filter the query like requested by url - * - * @param SelectStatement $AST - * @return void|string */ - public function walkSelectStatement(SelectStatement $AST) + public function walkSelectStatement(SelectStatement $AST): void { $query = $this->_getQuery(); $queriedValue = $query->getHint(self::HINT_PAGINATOR_FILTER_VALUE); @@ -96,7 +93,8 @@ public function walkSelectStatement(SelectStatement $AST) Type::BIGINT, Type::FLOAT, Type::DECIMAL, - ] + ], + true ) ) ) { diff --git a/src/Knp/Component/Pager/Event/Subscriber/Filtration/Doctrine/ORM/QuerySubscriber.php b/src/Knp/Component/Pager/Event/Subscriber/Filtration/Doctrine/ORM/QuerySubscriber.php index 770b1243..5eecfeb1 100644 --- a/src/Knp/Component/Pager/Event/Subscriber/Filtration/Doctrine/ORM/QuerySubscriber.php +++ b/src/Knp/Component/Pager/Event/Subscriber/Filtration/Doctrine/ORM/QuerySubscriber.php @@ -3,27 +3,27 @@ namespace Knp\Component\Pager\Event\Subscriber\Filtration\Doctrine\ORM; use Doctrine\ORM\Query; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; use Knp\Component\Pager\Event\ItemsEvent; use Knp\Component\Pager\Event\Subscriber\Filtration\Doctrine\ORM\Query\WhereWalker; use Knp\Component\Pager\Event\Subscriber\Paginate\Doctrine\ORM\Query\Helper as QueryHelper; use Knp\Component\Pager\PaginatorInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; -use Symfony\Component\HttpFoundation\Request; class QuerySubscriber implements EventSubscriberInterface { - private Request $request; + private ArgumentAccessInterface $argumentAccess; - public function __construct(?Request $request) + public function __construct(ArgumentAccessInterface $argumentAccess) { - $this->request = $request ?? Request::createFromGlobals(); + $this->argumentAccess = $argumentAccess; } public function items(ItemsEvent $event): void { if ($event->target instanceof Query) { $filterValue = $this->getQueryParameter($event->options[PaginatorInterface::FILTER_VALUE_PARAMETER_NAME]); - if (null === $filterValue || (empty($filterValue) && $filterValue !== '0')) { + if ((empty($filterValue) && $filterValue !== '0')) { return; } $filterName = $this->getQueryParameter($event->options[PaginatorInterface::FILTER_FIELD_PARAMETER_NAME]); @@ -35,7 +35,7 @@ public function items(ItemsEvent $event): void return; } $value = $this->getQueryParameter($event->options[PaginatorInterface::FILTER_VALUE_PARAMETER_NAME]); - if (false !== strpos($value, '*')) { + if (str_contains($value, '*')) { $value = str_replace('*', '%', $value); } if (is_string($columns) && false !== strpos($columns, ',')) { @@ -65,6 +65,6 @@ public static function getSubscribedEvents(): array private function getQueryParameter(string $name): ?string { - return $this->request->query->get($name); + return $this->argumentAccess->get($name); } } diff --git a/src/Knp/Component/Pager/Event/Subscriber/Filtration/FiltrationSubscriber.php b/src/Knp/Component/Pager/Event/Subscriber/Filtration/FiltrationSubscriber.php index 6faaa364..d0774e7c 100644 --- a/src/Knp/Component/Pager/Event/Subscriber/Filtration/FiltrationSubscriber.php +++ b/src/Knp/Component/Pager/Event/Subscriber/Filtration/FiltrationSubscriber.php @@ -22,8 +22,8 @@ public function before(BeforeEvent $event): void /** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher */ $dispatcher = $event->getEventDispatcher(); // hook all standard filtration subscribers - $dispatcher->addSubscriber(new Doctrine\ORM\QuerySubscriber($event->getRequest())); - $dispatcher->addSubscriber(new PropelQuerySubscriber($event->getRequest())); + $dispatcher->addSubscriber(new Doctrine\ORM\QuerySubscriber($event->getArgumentAccess())); + $dispatcher->addSubscriber(new PropelQuerySubscriber($event->getArgumentAccess())); $this->isLoaded = true; } diff --git a/src/Knp/Component/Pager/Event/Subscriber/Filtration/PropelQuerySubscriber.php b/src/Knp/Component/Pager/Event/Subscriber/Filtration/PropelQuerySubscriber.php index 849cef21..8337b856 100644 --- a/src/Knp/Component/Pager/Event/Subscriber/Filtration/PropelQuerySubscriber.php +++ b/src/Knp/Component/Pager/Event/Subscriber/Filtration/PropelQuerySubscriber.php @@ -2,29 +2,29 @@ namespace Knp\Component\Pager\Event\Subscriber\Filtration; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; use Knp\Component\Pager\Event\ItemsEvent; use Knp\Component\Pager\PaginatorInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; -use Symfony\Component\HttpFoundation\Request; class PropelQuerySubscriber implements EventSubscriberInterface { - private Request $request; + private ArgumentAccessInterface $argumentAccess; - public function __construct(?Request $request) + public function __construct(ArgumentAccessInterface $argumentAccess) { - $this->request = $request ?? Request::createFromGlobals(); + $this->argumentAccess = $argumentAccess; } public function items(ItemsEvent $event): void { $query = $event->target; if ($query instanceof \ModelCriteria) { - if (!$this->request->query->has($event->options[PaginatorInterface::FILTER_VALUE_PARAMETER_NAME])) { + if (!$this->argumentAccess->has($event->options[PaginatorInterface::FILTER_VALUE_PARAMETER_NAME])) { return; } - if ($this->request->query->has($event->options[PaginatorInterface::FILTER_FIELD_PARAMETER_NAME])) { - $columns = $this->request->query->get($event->options[PaginatorInterface::FILTER_FIELD_PARAMETER_NAME]); + if ($this->argumentAccess->has($event->options[PaginatorInterface::FILTER_FIELD_PARAMETER_NAME])) { + $columns = $this->argumentAccess->get($event->options[PaginatorInterface::FILTER_FIELD_PARAMETER_NAME]); } elseif (!empty($event->options[PaginatorInterface::DEFAULT_FILTER_FIELDS])) { $columns = $event->options[PaginatorInterface::DEFAULT_FILTER_FIELDS]; } else { @@ -41,7 +41,7 @@ public function items(ItemsEvent $event): void } } } - $value = $this->request->query->get($event->options[PaginatorInterface::FILTER_VALUE_PARAMETER_NAME]); + $value = $this->argumentAccess->get($event->options[PaginatorInterface::FILTER_VALUE_PARAMETER_NAME]); $criteria = \Criteria::EQUAL; if (false !== strpos($value, '*')) { $value = str_replace('*', '%', $value); diff --git a/src/Knp/Component/Pager/Event/Subscriber/Paginate/SolariumQuerySubscriber.php b/src/Knp/Component/Pager/Event/Subscriber/Paginate/SolariumQuerySubscriber.php index dbc7118c..7d6f4076 100644 --- a/src/Knp/Component/Pager/Event/Subscriber/Paginate/SolariumQuerySubscriber.php +++ b/src/Knp/Component/Pager/Event/Subscriber/Paginate/SolariumQuerySubscriber.php @@ -3,6 +3,8 @@ namespace Knp\Component\Pager\Event\Subscriber\Paginate; use Knp\Component\Pager\Event\ItemsEvent; +use Solarium\Client; +use Solarium\QueryType\Select\Query\Query; use Symfony\Component\EventDispatcher\EventSubscriberInterface; /** @@ -14,11 +16,11 @@ class SolariumQuerySubscriber implements EventSubscriberInterface { public function items(ItemsEvent $event): void { - if (is_array($event->target) && 2 == count($event->target)) { + if (is_array($event->target) && 2 === count($event->target)) { $values = array_values($event->target); [$client, $query] = $values; - if ($client instanceof \Solarium\Client && $query instanceof \Solarium\QueryType\Select\Query\Query) { + if ($client instanceof Client && $query instanceof Query) { $query->setStart($event->getOffset())->setRows($event->getLimit()); $solrResult = $client->select($query); diff --git a/src/Knp/Component/Pager/Event/Subscriber/Sortable/ArraySubscriber.php b/src/Knp/Component/Pager/Event/Subscriber/Sortable/ArraySubscriber.php index 3abe4935..639e4d2e 100644 --- a/src/Knp/Component/Pager/Event/Subscriber/Sortable/ArraySubscriber.php +++ b/src/Knp/Component/Pager/Event/Subscriber/Sortable/ArraySubscriber.php @@ -2,10 +2,10 @@ namespace Knp\Component\Pager\Event\Subscriber\Sortable; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; use Knp\Component\Pager\Event\ItemsEvent; use Knp\Component\Pager\PaginatorInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; -use Symfony\Component\HttpFoundation\Request; use Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException; use Symfony\Component\PropertyAccess\PropertyAccess; use Symfony\Component\PropertyAccess\PropertyAccessorInterface; @@ -24,42 +24,38 @@ class ArraySubscriber implements EventSubscriberInterface private ?PropertyAccessorInterface $propertyAccessor; - private Request $request; + private ArgumentAccessInterface $argumentAccess; - public function __construct(Request $request = null, PropertyAccessorInterface $accessor = null) + public function __construct(ArgumentAccessInterface $argumentAccess, PropertyAccessorInterface $accessor = null) { if (!$accessor && class_exists(PropertyAccess::class)) { $accessor = PropertyAccess::createPropertyAccessorBuilder()->enableMagicCall()->getPropertyAccessor(); } $this->propertyAccessor = $accessor; - // check needed because $request must be nullable, being the second parameter (with the first one nullable) - if (null === $request) { - throw new \InvalidArgumentException('Request must be initialized.'); - } - $this->request = $request; + $this->argumentAccess = $argumentAccess; } public function items(ItemsEvent $event): void { - // Check if the result has already been sorted by an other sort subscriber + // Check if the result has already been sorted by another sort subscriber $customPaginationParameters = $event->getCustomPaginationParameters(); if (!empty($customPaginationParameters['sorted']) ) { return; } $sortField = $event->options[PaginatorInterface::SORT_FIELD_PARAMETER_NAME]; - if (!is_array($event->target) || null === $sortField || !$this->request->query->has($sortField)) { + if (!is_array($event->target) || null === $sortField || !$this->argumentAccess->has($sortField)) { return; } $event->setCustomPaginationParameter('sorted', true); - if (isset($event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST]) && !in_array($this->request->query->get($sortField), $event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST])) { - throw new \UnexpectedValueException("Cannot sort by: [{$this->request->query->get($sortField)}] this field is not in allow list."); + if (isset($event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST]) && !in_array($this->argumentAccess->get($sortField), $event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST])) { + throw new \UnexpectedValueException("Cannot sort by: [{$this->argumentAccess->get($sortField)}] this field is not in allow list."); } $sortFunction = $event->options['sortFunction'] ?? [$this, 'proxySortFunction']; - $sortField = $this->request->query->get($sortField); + $sortField = $this->argumentAccess->get($sortField); // compatibility layer if ($sortField[0] === '.') { @@ -75,10 +71,10 @@ public function items(ItemsEvent $event): void private function getSortDirection(array $options): string { - if (!$this->request->query->has($options[PaginatorInterface::SORT_DIRECTION_PARAMETER_NAME])) { + if (!$this->argumentAccess->has($options[PaginatorInterface::SORT_DIRECTION_PARAMETER_NAME])) { return 'desc'; } - $direction = $this->request->query->get($options[PaginatorInterface::SORT_DIRECTION_PARAMETER_NAME]); + $direction = $this->argumentAccess->get($options[PaginatorInterface::SORT_DIRECTION_PARAMETER_NAME]); if (strtolower($direction) === 'asc') { return 'asc'; } @@ -94,13 +90,7 @@ private function proxySortFunction(&$target, $sortField, $sortDirection): bool return usort($target, [$this, 'sortFunction']); } - /** - * @param mixed $object1 first object to compare - * @param mixed $object2 second object to compare - * - * @return int - */ - private function sortFunction($object1, $object2): int + private function sortFunction(object|array $object1, object|array $object2): int { if (null === $this->propertyAccessor) { throw new \UnexpectedValueException('You need symfony/property-access component to use this sorting function'); @@ -112,14 +102,14 @@ private function sortFunction($object1, $object2): int try { $fieldValue1 = $this->propertyAccessor->getValue($object1, $this->currentSortingField); - } catch (UnexpectedTypeException $e) { + } catch (UnexpectedTypeException) { return -1 * $this->getSortCoefficient(); } try { $fieldValue2 = $this->propertyAccessor->getValue($object2, $this->currentSortingField); - } catch (UnexpectedTypeException $e) { - return 1 * $this->getSortCoefficient(); + } catch (UnexpectedTypeException) { + return $this->getSortCoefficient(); } if (is_string($fieldValue1)) { diff --git a/src/Knp/Component/Pager/Event/Subscriber/Sortable/Doctrine/ODM/MongoDB/QuerySubscriber.php b/src/Knp/Component/Pager/Event/Subscriber/Sortable/Doctrine/ODM/MongoDB/QuerySubscriber.php index 32f9935b..59b34b98 100644 --- a/src/Knp/Component/Pager/Event/Subscriber/Sortable/Doctrine/ODM/MongoDB/QuerySubscriber.php +++ b/src/Knp/Component/Pager/Event/Subscriber/Sortable/Doctrine/ODM/MongoDB/QuerySubscriber.php @@ -3,23 +3,23 @@ namespace Knp\Component\Pager\Event\Subscriber\Sortable\Doctrine\ODM\MongoDB; use Doctrine\ODM\MongoDB\Query\Query; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; use Knp\Component\Pager\Event\ItemsEvent; use Knp\Component\Pager\PaginatorInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; -use Symfony\Component\HttpFoundation\Request; class QuerySubscriber implements EventSubscriberInterface { - private Request $request; + private ArgumentAccessInterface $argumentAccess; - public function __construct(Request $request) + public function __construct(ArgumentAccessInterface $argumentAccess) { - $this->request = $request; + $this->argumentAccess = $argumentAccess; } public function items(ItemsEvent $event): void { - // Check if the result has already been sorted by an other sort subscriber + // Check if the result has already been sorted by another sort subscriber $customPaginationParameters = $event->getCustomPaginationParameters(); if (!empty($customPaginationParameters['sorted']) ) { return; @@ -29,9 +29,9 @@ public function items(ItemsEvent $event): void $event->setCustomPaginationParameter('sorted', true); $sortField = $event->options[PaginatorInterface::SORT_FIELD_PARAMETER_NAME]; $sortDir = $event->options[PaginatorInterface::SORT_DIRECTION_PARAMETER_NAME]; - if (null !== $sortField && $this->request->query->has($sortField)) { - $field = $this->request->query->get($sortField); - $dir = null !== $sortDir && strtolower($this->request->query->get($sortDir)) === 'asc' ? 1 : -1; + if (null !== $sortField && $this->argumentAccess->has($sortField)) { + $field = $this->argumentAccess->get($sortField); + $dir = null !== $sortDir && strtolower($this->argumentAccess->get($sortDir)) === 'asc' ? 1 : -1; if (isset($event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST])) { if (!in_array($field, $event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST])) { diff --git a/src/Knp/Component/Pager/Event/Subscriber/Sortable/Doctrine/ORM/QuerySubscriber.php b/src/Knp/Component/Pager/Event/Subscriber/Sortable/Doctrine/ORM/QuerySubscriber.php index 742ce224..8f33814f 100644 --- a/src/Knp/Component/Pager/Event/Subscriber/Sortable/Doctrine/ORM/QuerySubscriber.php +++ b/src/Knp/Component/Pager/Event/Subscriber/Sortable/Doctrine/ORM/QuerySubscriber.php @@ -3,28 +3,25 @@ namespace Knp\Component\Pager\Event\Subscriber\Sortable\Doctrine\ORM; use Doctrine\ORM\Query; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; use Knp\Component\Pager\Event\ItemsEvent; use Knp\Component\Pager\Event\Subscriber\Paginate\Doctrine\ORM\Query\Helper as QueryHelper; use Knp\Component\Pager\Event\Subscriber\Sortable\Doctrine\ORM\Query\OrderByWalker; use Knp\Component\Pager\PaginatorInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; -use Symfony\Component\HttpFoundation\Request; class QuerySubscriber implements EventSubscriberInterface { - /** - * @var Request - */ - private $request; + private ArgumentAccessInterface $argumentAccess; - public function __construct(Request $request) + public function __construct(ArgumentAccessInterface $argumentAccess) { - $this->request = $request; + $this->argumentAccess = $argumentAccess; } public function items(ItemsEvent $event): void { - // Check if the result has already been sorted by an other sort subscriber + // Check if the result has already been sorted by another sort subscriber $customPaginationParameters = $event->getCustomPaginationParameters(); if (!empty($customPaginationParameters['sorted']) ) { return; @@ -34,16 +31,16 @@ public function items(ItemsEvent $event): void $event->setCustomPaginationParameter('sorted', true); $sortField = $event->options[PaginatorInterface::SORT_FIELD_PARAMETER_NAME]; $sortDir = $event->options[PaginatorInterface::SORT_DIRECTION_PARAMETER_NAME]; - if (null !== $sortField && $this->request->query->has($sortField)) { - $dir = null !== $sortDir && $this->request->query->has($sortDir) && strtolower($this->request->query->get($sortDir)) === 'asc' ? 'asc' : 'desc'; + if (null !== $sortField && $this->argumentAccess->has($sortField)) { + $dir = null !== $sortDir && $this->argumentAccess->has($sortDir) && strtolower($this->argumentAccess->get($sortDir)) === 'asc' ? 'asc' : 'desc'; if (isset($event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST])) { - if (!in_array($this->request->query->get($sortField), $event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST])) { - throw new \UnexpectedValueException("Cannot sort by: [{$this->request->query->get($sortField)}] this field is not in allow list."); + if (!in_array($this->argumentAccess->get($sortField), $event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST])) { + throw new \UnexpectedValueException("Cannot sort by: [{$this->argumentAccess->get($sortField)}] this field is not in allow list."); } } - $sortFieldParameterNames = $this->request->query->get($sortField); + $sortFieldParameterNames = $this->argumentAccess->get($sortField); $fields = []; $aliases = []; if (!is_string($sortFieldParameterNames)) { diff --git a/src/Knp/Component/Pager/Event/Subscriber/Sortable/ElasticaQuerySubscriber.php b/src/Knp/Component/Pager/Event/Subscriber/Sortable/ElasticaQuerySubscriber.php index 6f25f748..435a3b2e 100644 --- a/src/Knp/Component/Pager/Event/Subscriber/Sortable/ElasticaQuerySubscriber.php +++ b/src/Knp/Component/Pager/Event/Subscriber/Sortable/ElasticaQuerySubscriber.php @@ -4,23 +4,23 @@ use Elastica\Query; use Elastica\SearchableInterface; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; use Knp\Component\Pager\Event\ItemsEvent; use Knp\Component\Pager\PaginatorInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; -use Symfony\Component\HttpFoundation\Request; class ElasticaQuerySubscriber implements EventSubscriberInterface { - private Request $request; + private ArgumentAccessInterface $argumentAccess; - public function __construct(Request $request) + public function __construct(ArgumentAccessInterface $argumentAccess) { - $this->request = $request; + $this->argumentAccess = $argumentAccess; } public function items(ItemsEvent $event): void { - // Check if the result has already been sorted by an other sort subscriber + // Check if the result has already been sorted by another sort subscriber $customPaginationParameters = $event->getCustomPaginationParameters(); if (!empty($customPaginationParameters['sorted']) ) { return; @@ -31,9 +31,9 @@ public function items(ItemsEvent $event): void $event->setCustomPaginationParameter('sorted', true); $sortField = $event->options[PaginatorInterface::SORT_FIELD_PARAMETER_NAME]; $sortDir = $event->options[PaginatorInterface::SORT_DIRECTION_PARAMETER_NAME]; - if (null !== $sortField && $this->request->query->has($sortField)) { - $field = $this->request->query->get($sortField); - $dir = null !== $sortDir && $this->request->query->has($sortDir) && strtolower($this->request->query->get($sortDir)) === 'asc' ? 'asc' : 'desc'; + if (null !== $sortField && $this->argumentAccess->has($sortField)) { + $field = $this->argumentAccess->get($sortField); + $dir = null !== $sortDir && $this->argumentAccess->has($sortDir) && strtolower($this->argumentAccess->get($sortDir)) === 'asc' ? 'asc' : 'desc'; if (isset($event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST]) && !in_array($field, $event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST])) { throw new \UnexpectedValueException(sprintf('Cannot sort by: [%s] this field is not in allow list.', $field)); diff --git a/src/Knp/Component/Pager/Event/Subscriber/Sortable/PropelQuerySubscriber.php b/src/Knp/Component/Pager/Event/Subscriber/Sortable/PropelQuerySubscriber.php index 372d2001..da86142c 100644 --- a/src/Knp/Component/Pager/Event/Subscriber/Sortable/PropelQuerySubscriber.php +++ b/src/Knp/Component/Pager/Event/Subscriber/Sortable/PropelQuerySubscriber.php @@ -2,23 +2,23 @@ namespace Knp\Component\Pager\Event\Subscriber\Sortable; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; use Knp\Component\Pager\Event\ItemsEvent; use Knp\Component\Pager\PaginatorInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; -use Symfony\Component\HttpFoundation\Request; class PropelQuerySubscriber implements EventSubscriberInterface { - private Request $request; + private ArgumentAccessInterface $argumentAccess; - public function __construct(Request $request) + public function __construct(ArgumentAccessInterface $argumentAccess) { - $this->request = $request; + $this->argumentAccess = $argumentAccess; } public function items(ItemsEvent $event): void { - // Check if the result has already been sorted by an other sort subscriber + // Check if the result has already been sorted by another sort subscriber $customPaginationParameters = $event->getCustomPaginationParameters(); if (!empty($customPaginationParameters['sorted']) ) { return; @@ -29,14 +29,14 @@ public function items(ItemsEvent $event): void $event->setCustomPaginationParameter('sorted', true); $sortField = $event->options[PaginatorInterface::SORT_FIELD_PARAMETER_NAME]; $sortDir = $event->options[PaginatorInterface::SORT_DIRECTION_PARAMETER_NAME]; - if (null !== $sortField && $this->request->query->has($sortField)) { - $part = $this->request->query->get($sortField); - $direction = (null !== $sortDir && $this->request->query->has($sortDir) && strtolower($this->request->query->get($sortDir)) === 'asc') + if (null !== $sortField && $this->argumentAccess->has($sortField)) { + $part = $this->argumentAccess->get($sortField); + $direction = (null !== $sortDir && $this->argumentAccess->has($sortDir) && strtolower($this->argumentAccess->get($sortDir)) === 'asc') ? 'asc' : 'desc'; if (isset($event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST])) { - if (!in_array($this->request->query->get($sortField), $event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST])) { - throw new \UnexpectedValueException("Cannot sort by: [{$this->request->query->get($sortField)}] this field is not in allow list."); + if (!in_array($this->argumentAccess->get($sortField), $event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST])) { + throw new \UnexpectedValueException("Cannot sort by: [{$this->argumentAccess->get($sortField)}] this field is not in allow list."); } } diff --git a/src/Knp/Component/Pager/Event/Subscriber/Sortable/SolariumQuerySubscriber.php b/src/Knp/Component/Pager/Event/Subscriber/Sortable/SolariumQuerySubscriber.php index 12ae6c6d..66fdf91e 100644 --- a/src/Knp/Component/Pager/Event/Subscriber/Sortable/SolariumQuerySubscriber.php +++ b/src/Knp/Component/Pager/Event/Subscriber/Sortable/SolariumQuerySubscriber.php @@ -2,10 +2,10 @@ namespace Knp\Component\Pager\Event\Subscriber\Sortable; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; use Knp\Component\Pager\Event\ItemsEvent; use Knp\Component\Pager\PaginatorInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; -use Symfony\Component\HttpFoundation\Request; /** * Solarium query sorting @@ -14,16 +14,16 @@ */ class SolariumQuerySubscriber implements EventSubscriberInterface { - private Request $request; + private ArgumentAccessInterface $argumentAccess; - public function __construct(Request $request) + public function __construct(ArgumentAccessInterface $argumentAccess) { - $this->request = $request; + $this->argumentAccess = $argumentAccess; } public function items(ItemsEvent $event): void { - // Check if the result has already been sorted by an other sort subscriber + // Check if the result has already been sorted by another sort subscriber $customPaginationParameters = $event->getCustomPaginationParameters(); if (!empty($customPaginationParameters['sorted']) ) { return; @@ -36,14 +36,14 @@ public function items(ItemsEvent $event): void if ($client instanceof \Solarium\Client && $query instanceof \Solarium\QueryType\Select\Query\Query) { $event->setCustomPaginationParameter('sorted', true); $sortField = $event->options[PaginatorInterface::SORT_FIELD_PARAMETER_NAME]; - if (null !== $sortField && $this->request->query->has($sortField)) { + if (null !== $sortField && $this->argumentAccess->has($sortField)) { if (isset($event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST])) { - if (!in_array($this->request->query->get($sortField), $event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST])) { - throw new \UnexpectedValueException("Cannot sort by: [{$this->request->query->get($sortField)}] this field is not in allow list."); + if (!in_array($this->argumentAccess->get($sortField), $event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST])) { + throw new \UnexpectedValueException("Cannot sort by: [{$this->argumentAccess->get($sortField)}] this field is not in allow list."); } } - $query->addSort($this->request->query->get($sortField), $this->getSortDirection($event)); + $query->addSort($this->argumentAccess->get($sortField), $this->getSortDirection($event)); } } } @@ -61,7 +61,7 @@ private function getSortDirection($event): string { $sortDir = $event->options[PaginatorInterface::SORT_DIRECTION_PARAMETER_NAME]; - return null !== $sortDir && $this->request->query->has($sortDir) && - strtolower($this->request->query->get($sortDir)) === 'asc' ? 'asc' : 'desc'; + return null !== $sortDir && $this->argumentAccess->has($sortDir) && + strtolower($this->argumentAccess->get($sortDir)) === 'asc' ? 'asc' : 'desc'; } } diff --git a/src/Knp/Component/Pager/Event/Subscriber/Sortable/SortableSubscriber.php b/src/Knp/Component/Pager/Event/Subscriber/Sortable/SortableSubscriber.php index 7cf73f50..720f8d40 100644 --- a/src/Knp/Component/Pager/Event/Subscriber/Sortable/SortableSubscriber.php +++ b/src/Knp/Component/Pager/Event/Subscriber/Sortable/SortableSubscriber.php @@ -22,13 +22,13 @@ public function before(BeforeEvent $event): void /** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher */ $dispatcher = $event->getEventDispatcher(); // hook all standard sortable subscribers - $request = $event->getRequest(); - $dispatcher->addSubscriber(new Doctrine\ORM\QuerySubscriber($request)); - $dispatcher->addSubscriber(new Doctrine\ODM\MongoDB\QuerySubscriber($request)); - $dispatcher->addSubscriber(new ElasticaQuerySubscriber($request)); - $dispatcher->addSubscriber(new PropelQuerySubscriber($request)); - $dispatcher->addSubscriber(new SolariumQuerySubscriber($request)); - $dispatcher->addSubscriber(new ArraySubscriber($request)); + $argumentAccess = $event->getArgumentAccess(); + $dispatcher->addSubscriber(new Doctrine\ORM\QuerySubscriber($argumentAccess)); + $dispatcher->addSubscriber(new Doctrine\ODM\MongoDB\QuerySubscriber($argumentAccess)); + $dispatcher->addSubscriber(new ElasticaQuerySubscriber($argumentAccess)); + $dispatcher->addSubscriber(new PropelQuerySubscriber($argumentAccess)); + $dispatcher->addSubscriber(new SolariumQuerySubscriber($argumentAccess)); + $dispatcher->addSubscriber(new ArraySubscriber($argumentAccess)); $this->isLoaded = true; } diff --git a/src/Knp/Component/Pager/Pagination/AbstractPagination.php b/src/Knp/Component/Pager/Pagination/AbstractPagination.php index d2c6a0e5..14bec9ce 100644 --- a/src/Knp/Component/Pager/Pagination/AbstractPagination.php +++ b/src/Knp/Component/Pager/Pagination/AbstractPagination.php @@ -15,24 +15,28 @@ abstract class AbstractPagination implements Iterator, PaginationInterface public function rewind(): void { - reset($this->items); + if (is_object($this->items)) { + $items = get_mangled_object_vars($this->items); + reset($items); + $this->items = new \ArrayObject($items); + } else { + reset($this->items); + } } - /** - * @return mixed - */ - #[\ReturnTypeWillChange] - public function current() + public function current(): mixed { return current($this->items); } - /** - * @return bool|float|int|string|null - */ - #[\ReturnTypeWillChange] - public function key() + public function key(): string|int|null { + if (is_object($this->items)) { + $items = get_mangled_object_vars($this->items); + + return key($items); + } + return key($this->items); } @@ -43,7 +47,7 @@ public function next(): void public function valid(): bool { - return key($this->items) !== null; + return null !== $this->key(); } public function count(): int @@ -56,10 +60,7 @@ public function setCustomParameters(array $parameters): void $this->customParameters = $parameters; } - /** - * @return mixed|null - */ - public function getCustomParameter(string $name) + public function getCustomParameter(string $name): mixed { return $this->customParameters[$name] ?? null; } @@ -99,10 +100,7 @@ public function setPaginatorOptions(array $options): void $this->paginatorOptions = $options; } - /** - * @return mixed|null - */ - public function getPaginatorOption(string $name) + public function getPaginatorOption(string $name): mixed { return $this->paginatorOptions[$name] ?? null; } @@ -131,19 +129,16 @@ public function offsetExists($offset): bool /** * @param string|int|float|bool|null $offset - * @return mixed */ - #[\ReturnTypeWillChange] - public function offsetGet($offset) + public function offsetGet($offset): mixed { return $this->items[$offset]; } /** * @param string|int|float|bool|null $offset - * @param mixed $value */ - public function offsetSet($offset, $value): void + public function offsetSet($offset, mixed $value): void { if (null === $offset) { $this->items[] = $value; diff --git a/src/Knp/Component/Pager/Pagination/PaginationInterface.php b/src/Knp/Component/Pager/Pagination/PaginationInterface.php index fc5b9ee6..8863cfcd 100644 --- a/src/Knp/Component/Pager/Pagination/PaginationInterface.php +++ b/src/Knp/Component/Pager/Pagination/PaginationInterface.php @@ -46,10 +46,8 @@ public function setPaginatorOptions(array $options): void; /** * Get pagination alias - * - * @return mixed */ - public function getPaginatorOption(string $name); + public function getPaginatorOption(string $name): mixed; /** * @param array $parameters @@ -58,8 +56,6 @@ public function setCustomParameters(array $parameters): void; /** * Return custom parameter - * - * @return mixed */ - public function getCustomParameter(string $name); + public function getCustomParameter(string $name): mixed; } diff --git a/src/Knp/Component/Pager/Paginator.php b/src/Knp/Component/Pager/Paginator.php index 792cfeb5..82615e95 100644 --- a/src/Knp/Component/Pager/Paginator.php +++ b/src/Knp/Component/Pager/Paginator.php @@ -2,12 +2,11 @@ namespace Knp\Component\Pager; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; use Knp\Component\Pager\Exception\PageLimitInvalidException; use Knp\Component\Pager\Exception\PageNumberInvalidException; use Knp\Component\Pager\Exception\PageNumberOutOfRangeException; use Knp\Component\Pager\Pagination\PaginationInterface; -use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** @@ -23,7 +22,7 @@ final class Paginator implements PaginatorInterface /** * Default options of paginator * - * @var array + * @var array */ private array $defaultOptions = [ self::PAGE_PARAMETER_NAME => 'page', @@ -36,12 +35,12 @@ final class Paginator implements PaginatorInterface self::DEFAULT_LIMIT => self::DEFAULT_LIMIT_VALUE, ]; - private ?RequestStack $requestStack; + private ArgumentAccessInterface $argumentAccess; - public function __construct(EventDispatcherInterface $eventDispatcher, RequestStack $requestStack = null) + public function __construct(EventDispatcherInterface $eventDispatcher, ArgumentAccessInterface $argumentAccess) { $this->eventDispatcher = $eventDispatcher; - $this->requestStack = $requestStack; + $this->argumentAccess = $argumentAccess; } /** @@ -72,19 +71,19 @@ public function paginate($target, int $page = 1, int $limit = null, array $optio $options[PaginatorInterface::DEFAULT_SORT_FIELD_NAME] = implode('+', $options[PaginatorInterface::DEFAULT_SORT_FIELD_NAME]); } - $request = null === $this->requestStack ? Request::createFromGlobals() : $this->requestStack->getCurrentRequest(); - + $argumentAccess = $this->argumentAccess; + // default sort field and direction are set based on options (if available) - if (isset($options[self::DEFAULT_SORT_FIELD_NAME]) && !$request->query->has($options[self::SORT_FIELD_PARAMETER_NAME])) { - $request->query->set($options[self::SORT_FIELD_PARAMETER_NAME], $options[self::DEFAULT_SORT_FIELD_NAME]); + if (isset($options[self::DEFAULT_SORT_FIELD_NAME]) && !$argumentAccess->has($options[self::SORT_FIELD_PARAMETER_NAME])) { + $argumentAccess->set($options[self::SORT_FIELD_PARAMETER_NAME], $options[self::DEFAULT_SORT_FIELD_NAME]); - if (!$request->query->has($options[PaginatorInterface::SORT_DIRECTION_PARAMETER_NAME])) { - $request->query->set($options[PaginatorInterface::SORT_DIRECTION_PARAMETER_NAME], $options[PaginatorInterface::DEFAULT_SORT_DIRECTION] ?? 'asc'); + if (!$argumentAccess->has($options[PaginatorInterface::SORT_DIRECTION_PARAMETER_NAME])) { + $argumentAccess->set($options[PaginatorInterface::SORT_DIRECTION_PARAMETER_NAME], $options[PaginatorInterface::DEFAULT_SORT_DIRECTION] ?? 'asc'); } } // before pagination start - $beforeEvent = new Event\BeforeEvent($this->eventDispatcher, $request); + $beforeEvent = new Event\BeforeEvent($this->eventDispatcher, $this->argumentAccess); $this->eventDispatcher->dispatch($beforeEvent, 'knp_pager.before'); // items $itemsEvent = new Event\ItemsEvent($offset, $limit); diff --git a/src/Knp/Component/Pager/PaginatorInterface.php b/src/Knp/Component/Pager/PaginatorInterface.php index 3b262644..96b6ddf9 100644 --- a/src/Knp/Component/Pager/PaginatorInterface.php +++ b/src/Knp/Component/Pager/PaginatorInterface.php @@ -43,5 +43,5 @@ interface PaginatorInterface * string $alias pagination alias, default none * array $sortFieldAllowList sortable allow list for target fields being paginated */ - public function paginate($target, int $page = 1, int $limit = null, array $options = []): PaginationInterface; + public function paginate(mixed $target, int $page = 1, int $limit = null, array $options = []): PaginationInterface; } diff --git a/tests/Test/Mock/PaginationSubscriber.php b/tests/Test/Mock/PaginationSubscriber.php index 0ad11cb0..c0ec5db8 100644 --- a/tests/Test/Mock/PaginationSubscriber.php +++ b/tests/Test/Mock/PaginationSubscriber.php @@ -19,6 +19,5 @@ public function pagination(PaginationEvent $e): void { $e->setPagination(new SlidingPagination); $e->stopPropagation(); - #dump($e); } } diff --git a/tests/Test/Pager/Pagination/AbstractPaginationTest.php b/tests/Test/Pager/Pagination/AbstractPaginationTest.php index 86fba0b8..023bb1e2 100644 --- a/tests/Test/Pager/Pagination/AbstractPaginationTest.php +++ b/tests/Test/Pager/Pagination/AbstractPaginationTest.php @@ -2,6 +2,7 @@ namespace Test\Pager\Pagination; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; use Knp\Component\Pager\Event\Subscriber\Paginate\ArraySubscriber; use Knp\Component\Pager\Paginator; use Knp\Component\Pager\PaginatorInterface; @@ -19,7 +20,8 @@ public function shouldCustomizeParameterNames(): void $dispatcher = new EventDispatcher; $dispatcher->addSubscriber(new MockPaginationSubscriber); // pagination view $dispatcher->addSubscriber(new ArraySubscriber); - $p = new Paginator($dispatcher); + $accessor = $this->createMock(ArgumentAccessInterface::class); + $p = new Paginator($dispatcher, $accessor); $items = ['first', 'second']; $view = $p->paginate($items, 1, 10); diff --git a/tests/Test/Pager/Pagination/CustomParameterTest.php b/tests/Test/Pager/Pagination/CustomParameterTest.php index d422b8dd..176d5e48 100644 --- a/tests/Test/Pager/Pagination/CustomParameterTest.php +++ b/tests/Test/Pager/Pagination/CustomParameterTest.php @@ -2,6 +2,7 @@ namespace Test\Pager\Pagination; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; use Knp\Component\Pager\Paginator; use Symfony\Component\EventDispatcher\EventDispatcher; use Test\Mock\CustomParameterSubscriber; @@ -18,7 +19,8 @@ public function shouldGiveCustomParametersToPaginationView(): void $dispatcher = new EventDispatcher; $dispatcher->addSubscriber(new CustomParameterSubscriber); $dispatcher->addSubscriber(new MockPaginationSubscriber); // pagination view - $p = new Paginator($dispatcher); + $accessor = $this->createMock(ArgumentAccessInterface::class); + $p = new Paginator($dispatcher, $accessor); $items = ['first', 'second']; $view = $p->paginate($items, 1, 10); diff --git a/tests/Test/Pager/Subscriber/Filtration/Doctrine/ORM/AllowListTest.php b/tests/Test/Pager/Subscriber/Filtration/Doctrine/ORM/AllowListTest.php index 910b3aed..a0cddd2c 100644 --- a/tests/Test/Pager/Subscriber/Filtration/Doctrine/ORM/AllowListTest.php +++ b/tests/Test/Pager/Subscriber/Filtration/Doctrine/ORM/AllowListTest.php @@ -2,6 +2,7 @@ namespace Test\Pager\Subscriber\Filtration\Doctrine\ORM; +use Knp\Component\Pager\ArgumentAccess\RequestArgumentAccess; use Knp\Component\Pager\Event\Subscriber\Filtration\FiltrationSubscriber as Filtration; use Knp\Component\Pager\Event\Subscriber\Paginate\PaginationSubscriber; use Knp\Component\Pager\Paginator; @@ -26,7 +27,8 @@ public function shouldAllowListFiltrationFields(): void $dispatcher->addSubscriber(new PaginationSubscriber()); $dispatcher->addSubscriber(new Filtration()); $requestStack = $this->createRequestStack(['filterParam' => 'a.title', 'filterValue' => 'summer']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $filterFieldAllowList = ['a.invalid']; $view = $p->paginate($query, 1, 10, \compact(PaginatorInterface::FILTER_FIELD_ALLOW_LIST)); @@ -36,7 +38,8 @@ public function shouldAllowListFiltrationFields(): void self::assertEquals('summer', $items[0]->getTitle()); $requestStack = $this->createRequestStack(['filterParam' => 'a.id', 'filterValue' => 'summer']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $p->paginate($query, 1, 10, \compact(PaginatorInterface::FILTER_FIELD_ALLOW_LIST)); } @@ -52,7 +55,8 @@ public function shouldFilterWithoutSpecificAllowList(): void $dispatcher->addSubscriber(new PaginationSubscriber()); $dispatcher->addSubscriber(new Filtration()); $requestStack = $this->createRequestStack(['filterParam' => 'a.title', 'filterValue' => 'autumn']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $view = $p->paginate($query, 1, 10); $items = $view->getItems(); @@ -72,7 +76,8 @@ public function shouldFilterWithoutSpecificAllowList2(): void $dispatcher->addSubscriber(new Filtration()); $requestStack = $this->createRequestStack(['filterParam' => 'a.id', 'filterValue' => 'autumn']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $view = $p->paginate($query); $items = $view->getItems(); diff --git a/tests/Test/Pager/Subscriber/Filtration/Doctrine/ORM/QueryTest.php b/tests/Test/Pager/Subscriber/Filtration/Doctrine/ORM/QueryTest.php index b3c07d65..e5cdf63e 100644 --- a/tests/Test/Pager/Subscriber/Filtration/Doctrine/ORM/QueryTest.php +++ b/tests/Test/Pager/Subscriber/Filtration/Doctrine/ORM/QueryTest.php @@ -3,14 +3,16 @@ namespace Test\Pager\Subscriber\Filtration\Doctrine\ORM; use Doctrine\ORM\EntityManagerInterface; +use Knp\Component\Pager\ArgumentAccess\RequestArgumentAccess; +use Knp\Component\Pager\Event\Subscriber\Filtration\Doctrine\ORM\Query\WhereWalker; use Knp\Component\Pager\Event\Subscriber\Filtration\FiltrationSubscriber as Filtration; use Knp\Component\Pager\Event\Subscriber\Paginate\Doctrine\ORM\QuerySubscriber; use Knp\Component\Pager\Event\Subscriber\Paginate\PaginationSubscriber; -use Knp\Component\Pager\Event\Subscriber\Filtration\Doctrine\ORM\Query\WhereWalker; -use Knp\Component\Pager\Paginator; use Knp\Component\Pager\Pagination\SlidingPagination; +use Knp\Component\Pager\Paginator; use Knp\Component\Pager\PaginatorInterface; use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\HttpFoundation\RequestStack; use Test\Fixture\Entity\Article; use Test\Tool\BaseTestCaseORM; @@ -70,7 +72,8 @@ public function shouldFilterSimpleDoctrineQuery(): void $dispatcher->addSubscriber(new PaginationSubscriber()); $dispatcher->addSubscriber(new Filtration()); $requestStack = $this->createRequestStack(['filterParam' => 'a.title', 'filterValue' => '*er']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $this->startQueryLog(); $query = $this->em->createQuery('SELECT a FROM Test\Fixture\Entity\Article a'); @@ -102,7 +105,8 @@ public function shouldFilterSimpleDoctrineQueryWithoutWildcard(): void $dispatcher->addSubscriber(new Filtration()); $requestStack = $this->createRequestStack(['filterParam' => 'a.title', 'filterValue' => 'summer']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $this->startQueryLog(); $query = $this->em->createQuery('SELECT a FROM Test\Fixture\Entity\Article a'); @@ -131,7 +135,8 @@ public function shouldFilterBooleanFilterValuesWithInteger(): void $dispatcher->addSubscriber(new PaginationSubscriber()); $dispatcher->addSubscriber(new Filtration()); $requestStack = $this->createRequestStack(['filterParam' => 'a.enabled', 'filterValue' => '1']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $this->startQueryLog(); $query = $this->em->createQuery('SELECT a FROM Test\Fixture\Entity\Article a'); @@ -160,7 +165,8 @@ public function shouldFilterBooleanFilterValues(): void $dispatcher->addSubscriber(new PaginationSubscriber()); $dispatcher->addSubscriber(new Filtration()); $requestStack = $this->createRequestStack(['filterParam' => 'a.enabled', 'filterValue' => 'true']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $this->startQueryLog(); $query = $this->em->createQuery('SELECT a FROM Test\Fixture\Entity\Article a'); @@ -189,7 +195,8 @@ public function shouldFilterBooleanFilterValuesWithZero(): void $dispatcher->addSubscriber(new PaginationSubscriber()); $dispatcher->addSubscriber(new Filtration()); $requestStack = $this->createRequestStack(['filterParam' => 'a.enabled', 'filterValue' => '0']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $this->startQueryLog(); $query = $this->em->createQuery('SELECT a FROM Test\Fixture\Entity\Article a'); $query->setHint(QuerySubscriber::HINT_FETCH_JOIN_COLLECTION, false); @@ -218,7 +225,8 @@ public function shouldFilterBooleanFilterValuesFalse(): void $dispatcher->addSubscriber(new Filtration()); $this->startQueryLog(); $requestStack = $this->createRequestStack(['filterParam' => 'a.enabled', 'filterValue' => 'false']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $query = $this->em->createQuery('SELECT a FROM Test\Fixture\Entity\Article a'); $query->setHint(QuerySubscriber::HINT_FETCH_JOIN_COLLECTION, false); $view = $p->paginate($query); @@ -245,7 +253,8 @@ public function shouldNotFilterInvalidBooleanFilterValues(): void $dispatcher->addSubscriber(new PaginationSubscriber()); $dispatcher->addSubscriber(new Filtration()); $requestStack = $this->createRequestStack(['filterParam' => 'a.enabled', 'filterValue' => 'invalid_boolean']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $this->startQueryLog(); $query = $this->em->createQuery('SELECT a FROM Test\Fixture\Entity\Article a'); @@ -272,7 +281,8 @@ public function shouldFilterNumericFilterValues(): void $dispatcher->addSubscriber(new PaginationSubscriber()); $dispatcher->addSubscriber(new Filtration()); $requestStack = $this->createRequestStack(['filterParam' => 'a.title', 'filterValue' => '0']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $this->startQueryLog(); $query = $this->em->createQuery('SELECT a FROM Test\Fixture\Entity\Article a'); @@ -300,7 +310,8 @@ public function shouldFilterNumericFilterValuesOne(): void $dispatcher->addSubscriber(new PaginationSubscriber()); $dispatcher->addSubscriber(new Filtration()); $requestStack = $this->createRequestStack(['filterParam' => 'a.title', 'filterValue' => '1']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $this->startQueryLog(); $query = $this->em->createQuery('SELECT a FROM Test\Fixture\Entity\Article a'); @@ -329,7 +340,8 @@ public function shouldFilterComplexDoctrineQuery(): void $dispatcher->addSubscriber(new PaginationSubscriber()); $dispatcher->addSubscriber(new Filtration()); $requestStack = $this->createRequestStack(['filterParam' => 'a.title', 'filterValue' => '*er']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $this->startQueryLog(); $query = $this->em->createQuery('SELECT a FROM Test\Fixture\Entity\Article a WHERE a.title <> \'\' AND (a.title LIKE \'summer\' OR a.title LIKE \'spring\')'); @@ -361,7 +373,8 @@ public function shouldFilterComplexDoctrineQuery2(): void $query->setHint(QuerySubscriber::HINT_FETCH_JOIN_COLLECTION, false); $requestStack = $this->createRequestStack(['filterParam' => 'a.id,a.title', 'filterValue' => '*er']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $view = $p->paginate($query, 1, 10); $items = $view->getItems(); $this->assertCount(1, $items); @@ -405,7 +418,8 @@ public function shouldFilterComplexDoctrineQuery3(): void $query->setHint(QuerySubscriber::HINT_FETCH_JOIN_COLLECTION, false); $requestStack = $this->createRequestStack(['filterParam' => 'a.title', 'filterValue' => '*er']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $this->startQueryLog(); $view = $p->paginate($query); $items = $view->getItems(); @@ -429,7 +443,8 @@ public function shouldFilterSimpleDoctrineQueryWithMultipleProperties(): void $dispatcher->addSubscriber(new PaginationSubscriber()); $dispatcher->addSubscriber(new Filtration()); $requestStack = $this->createRequestStack(['filterParam' => 'a.id,a.title', 'filterValue' => '*er']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $this->startQueryLog(); $query = $this->em->createQuery('SELECT a FROM Test\Fixture\Entity\Article a'); @@ -441,7 +456,8 @@ public function shouldFilterSimpleDoctrineQueryWithMultipleProperties(): void $this->assertEquals('winter', $items[1]->getTitle()); $requestStack = $this->createRequestStack(['filterParam' => ['a.id', 'a.title'], 'filterValue' => '*er']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $view = $p->paginate($query, 1, 10); $items = $view->getItems(); $this->assertCount(2, $items); @@ -465,7 +481,8 @@ public function shouldFilterComplexDoctrineQueryWithMultipleProperties(): void $dispatcher->addSubscriber(new PaginationSubscriber()); $dispatcher->addSubscriber(new Filtration()); $requestStack = $this->createRequestStack(['filterParam' => 'a.id,a.title', 'filterValue' => '*er']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $this->startQueryLog(); $query = $this->em->createQuery('SELECT a FROM Test\Fixture\Entity\Article a WHERE a.title <> \'\' AND (a.title LIKE \'summer\' OR a.title LIKE \'spring\')'); @@ -496,7 +513,8 @@ public function shouldValidateFiltrationParameter(): void $dispatcher->addSubscriber(new PaginationSubscriber()); $dispatcher->addSubscriber(new Filtration()); $requestStack = $this->createRequestStack(['filterParam' => '"a.title\'', 'filterValue' => 'summer']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $view = $p->paginate($query, 1, 10); $items = $view->getItems(); } @@ -517,7 +535,8 @@ public function shouldValidateFiltrationParameterWithoutAlias(): void $dispatcher->addSubscriber(new PaginationSubscriber()); $dispatcher->addSubscriber(new Filtration()); $requestStack = $this->createRequestStack(['filterParam' => 'title', 'filterValue' => 'summer']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $view = $p->paginate($query, 1, 10); $items = $view->getItems(); } @@ -538,7 +557,8 @@ public function shouldValidateFiltrationParameterExistance(): void $dispatcher->addSubscriber(new PaginationSubscriber()); $dispatcher->addSubscriber(new Filtration()); $requestStack = $this->createRequestStack(['filterParam' => 'a.nonExistantField', 'filterValue' => 'summer']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $view = $p->paginate($query, 1, 10); $items = $view->getItems(); @@ -563,7 +583,8 @@ public function shouldFilterByAnyAvailableAlias(): void $dispatcher->addSubscriber(new PaginationSubscriber()); $dispatcher->addSubscriber(new Filtration()); $requestStack = $this->createRequestStack(['filterParam' => 'test_alias', 'filterValue' => '*er']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $this->startQueryLog(); $view = $p->paginate($query, 1, 10, [PaginatorInterface::DISTINCT => false]); $items = $view->getItems(); @@ -588,6 +609,7 @@ public function shouldNotWorkWithInitialPaginatorEventDispatcher(): void $query->setHint(QuerySubscriber::HINT_FETCH_JOIN_COLLECTION, false); $requestStack = $this->createRequestStack(['filterParam' => 'a.title', 'filterValue' => 'summer']); + $accessor = new RequestArgumentAccess($requestStack); $p = $this->getPaginatorInstance($requestStack); $this->startQueryLog(); $view = $p->paginate($query, 1, 10); @@ -610,6 +632,7 @@ public function shouldNotExecuteExtraQueriesWhenCountIsZero(): void ; $requestStack = $this->createRequestStack(['filterParam' => 'a.title', 'filterValue' => 'asc']); + $accessor = new RequestArgumentAccess($requestStack); $p = $this->getPaginatorInstance($requestStack); $this->startQueryLog(); $view = $p->paginate($query, 1, 10); @@ -630,7 +653,8 @@ public function shouldFilterWithEmptyParametersAndDefaults(): void $dispatcher->addSubscriber(new PaginationSubscriber()); $dispatcher->addSubscriber(new Filtration()); $requestStack = $this->createRequestStack(['filterParam' => '', 'filterValue' => 'summer']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $this->startQueryLog(); $query = $this->em->createQuery('SELECT a FROM Test\Fixture\Entity\Article a'); @@ -669,7 +693,8 @@ public function shouldNotFilterWithEmptyParametersAndDefaults(): void $dispatcher->addSubscriber(new PaginationSubscriber()); $dispatcher->addSubscriber(new Filtration()); $requestStack = $this->createRequestStack(['filterParam' => 'a.title', 'filterValue' => '']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $this->startQueryLog(); $query = $this->em->createQuery('SELECT a FROM Test\Fixture\Entity\Article a'); @@ -679,13 +704,15 @@ public function shouldNotFilterWithEmptyParametersAndDefaults(): void $this->assertCount(4, $items); $requestStack = $this->createRequestStack(['filterParam' => '', 'filterValue' => 'summer']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $view = $p->paginate($query, 1, 10); $items = $view->getItems(); $this->assertCount(4, $items); $requestStack = $this->createRequestStack(['filterParam' => '', 'filterValue' => '']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $view = $p->paginate($query, 1, 10); $items = $view->getItems(); $this->assertCount(4, $items); @@ -707,7 +734,8 @@ public function shouldFilterCaseInsensitiveWhenAsked(): void $dispatcher = new EventDispatcher(); $dispatcher->addSubscriber(new PaginationSubscriber()); $dispatcher->addSubscriber(new Filtration()); - $p = new Paginator($dispatcher); + $accessor = new RequestArgumentAccess(new RequestStack()); + $p = new Paginator($dispatcher, $accessor); $this->startQueryLog(); $query = $this->em->createQuery('SELECT a FROM Test\Fixture\Entity\Article a'); @@ -719,7 +747,7 @@ public function shouldFilterCaseInsensitiveWhenAsked(): void $defaultFilterFields = 'a.title'; $view = $p->paginate($query, 1, 10, compact('defaultFilterFields')); $items = $view->getItems(); - $this->assertEquals(1, count($items)); + $this->assertCount(1, $items); $this->assertEquals('summer', $items[0]->getTitle()); $executed = $this->queryAnalyzer->getExecutedQueries(); diff --git a/tests/Test/Pager/Subscriber/Filtration/FiltrationSubscriberTest.php b/tests/Test/Pager/Subscriber/Filtration/FiltrationSubscriberTest.php index 91f58bf6..1ef2c212 100644 --- a/tests/Test/Pager/Subscriber/Filtration/FiltrationSubscriberTest.php +++ b/tests/Test/Pager/Subscriber/Filtration/FiltrationSubscriberTest.php @@ -2,6 +2,7 @@ namespace Test\Pager\Subscriber; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; use Knp\Component\Pager\Event\BeforeEvent; use Knp\Component\Pager\Event\Subscriber\Filtration\FiltrationSubscriber; use Symfony\Component\EventDispatcher\EventDispatcherInterface; @@ -19,8 +20,8 @@ public function shouldRegisterExpectedSubscribersOnlyOnce(): void $subscriber = new FiltrationSubscriber; - $requestStack = $this->createRequestStack([]); - $beforeEvent = new BeforeEvent($dispatcher, $requestStack->getCurrentRequest()); + $accessor = $this->createMock(ArgumentAccessInterface::class); + $beforeEvent = new BeforeEvent($dispatcher, $accessor); $subscriber->before($beforeEvent); // Subsequent calls do not add more subscribers diff --git a/tests/Test/Pager/Subscriber/Paginate/ArrayTest.php b/tests/Test/Pager/Subscriber/Paginate/ArrayTest.php index b6d950a4..88ad72ef 100644 --- a/tests/Test/Pager/Subscriber/Paginate/ArrayTest.php +++ b/tests/Test/Pager/Subscriber/Paginate/ArrayTest.php @@ -2,6 +2,7 @@ namespace Test\Pager\Subscriber\Paginate; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; use Knp\Component\Pager\Event\Subscriber\Paginate\ArraySubscriber; use Knp\Component\Pager\Pagination\PaginationInterface; use Knp\Component\Pager\Paginator; @@ -19,7 +20,8 @@ public function shouldPaginateAnArray(): void $dispatcher = new EventDispatcher; $dispatcher->addSubscriber(new ArraySubscriber); $dispatcher->addSubscriber(new MockPaginationSubscriber); // pagination view - $p = new Paginator($dispatcher); + $accessor = $this->createMock(ArgumentAccessInterface::class); + $p = new Paginator($dispatcher, $accessor); $items = ['first', 'second']; $view = $p->paginate($items, 1, 10); @@ -39,7 +41,8 @@ public function shouldSlicePaginateAnArray(): void $dispatcher = new EventDispatcher; $dispatcher->addSubscriber(new ArraySubscriber); $dispatcher->addSubscriber(new MockPaginationSubscriber); // pagination view - $p = new Paginator($dispatcher); + $accessor = $this->createMock(ArgumentAccessInterface::class); + $p = new Paginator($dispatcher, $accessor); $items = \range('a', 'u'); $view = $p->paginate($items, 2, 10); diff --git a/tests/Test/Pager/Subscriber/Paginate/Callback/CallbackTest.php b/tests/Test/Pager/Subscriber/Paginate/Callback/CallbackTest.php index ae5d5326..98708506 100644 --- a/tests/Test/Pager/Subscriber/Paginate/Callback/CallbackTest.php +++ b/tests/Test/Pager/Subscriber/Paginate/Callback/CallbackTest.php @@ -1,5 +1,6 @@ addSubscriber(new CallbackSubscriber); $dispatcher->addSubscriber(new MockPaginationSubscriber); // pagination view - return new Paginator($dispatcher); + $accessor = $this->createMock(ArgumentAccessInterface::class); + + return new Paginator($dispatcher, $accessor); } private function givenCallbackPagination(): CallbackPagination diff --git a/tests/Test/Pager/Subscriber/Paginate/Doctrine/CollectionTest.php b/tests/Test/Pager/Subscriber/Paginate/Doctrine/CollectionTest.php index 9d3b2592..5920fe97 100644 --- a/tests/Test/Pager/Subscriber/Paginate/Doctrine/CollectionTest.php +++ b/tests/Test/Pager/Subscriber/Paginate/Doctrine/CollectionTest.php @@ -3,6 +3,7 @@ namespace Test\Pager\Subscriber\Paginate\Doctrine; use Doctrine\Common\Collections\ArrayCollection; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; use Knp\Component\Pager\Event\Subscriber\Paginate\Doctrine\CollectionSubscriber; use Knp\Component\Pager\Pagination\PaginationInterface; use Knp\Component\Pager\Paginator; @@ -20,7 +21,8 @@ public function shouldPaginateCollection(): void $dispatcher = new EventDispatcher; $dispatcher->addSubscriber(new CollectionSubscriber); $dispatcher->addSubscriber(new MockPaginationSubscriber); // pagination view - $p = new Paginator($dispatcher); + $accessor = $this->createMock(ArgumentAccessInterface::class); + $p = new Paginator($dispatcher, $accessor); $items = new ArrayCollection(['first', 'second']); $view = $p->paginate($items, 1, 10); @@ -39,7 +41,8 @@ public function shouldLoopOverPagination(): void $dispatcher = new EventDispatcher; $dispatcher->addSubscriber(new CollectionSubscriber); $dispatcher->addSubscriber(new MockPaginationSubscriber); // pagination view - $p = new Paginator($dispatcher); + $accessor = $this->createMock(ArgumentAccessInterface::class); + $p = new Paginator($dispatcher, $accessor); $items = new ArrayCollection(['first', 'second']); $view = $p->paginate($items, 1, 10); @@ -63,7 +66,8 @@ public function shouldSlicePaginateAnArray(): void $dispatcher = new EventDispatcher; $dispatcher->addSubscriber(new CollectionSubscriber); $dispatcher->addSubscriber(new MockPaginationSubscriber); // pagination view - $p = new Paginator($dispatcher); + $accessor = $this->createMock(ArgumentAccessInterface::class); + $p = new Paginator($dispatcher, $accessor); $items = new ArrayCollection(\range('a', 'u')); $view = $p->paginate($items, 2, 10); diff --git a/tests/Test/Pager/Subscriber/Paginate/Doctrine/ODM/PHPCR/QuerySubscriberTest.php b/tests/Test/Pager/Subscriber/Paginate/Doctrine/ODM/PHPCR/QuerySubscriberTest.php index 878b364d..5b24eb50 100644 --- a/tests/Test/Pager/Subscriber/Paginate/Doctrine/ODM/PHPCR/QuerySubscriberTest.php +++ b/tests/Test/Pager/Subscriber/Paginate/Doctrine/ODM/PHPCR/QuerySubscriberTest.php @@ -2,6 +2,7 @@ namespace Test\Pager\Subscriber\Paginate\Doctrine\ODM\PHPCR; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; use Knp\Component\Pager\Event\Subscriber\Paginate\Doctrine\ODM\PHPCR\QuerySubscriber; use Knp\Component\Pager\Pagination\SlidingPagination; use Knp\Component\Pager\Paginator; @@ -22,7 +23,8 @@ public function shouldPaginateSimpleDoctrinePHPCRQuery(): void $dispatcher = new EventDispatcher(); $dispatcher->addSubscriber(new QuerySubscriber()); $dispatcher->addSubscriber(new PaginationSubscriber()); // pagination view - $p = new Paginator($dispatcher); + $accessor = $this->createMock(ArgumentAccessInterface::class); + $p = new Paginator($dispatcher, $accessor); $query = $this->dm->createQueryBuilder()->fromDocument(Article::class, 'a')->getQuery(); diff --git a/tests/Test/Pager/Subscriber/Paginate/ElasticaTest.php b/tests/Test/Pager/Subscriber/Paginate/ElasticaTest.php index eee9fc9a..8c7bce6e 100644 --- a/tests/Test/Pager/Subscriber/Paginate/ElasticaTest.php +++ b/tests/Test/Pager/Subscriber/Paginate/ElasticaTest.php @@ -7,6 +7,7 @@ use Elastica\Result; use Elastica\ResultSet; use Elastica\SearchableInterface; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; use Knp\Component\Pager\Event\Subscriber\Paginate\ElasticaQuerySubscriber; use Knp\Component\Pager\Paginator; use Symfony\Component\EventDispatcher\EventDispatcher; @@ -20,7 +21,8 @@ public function testElasticaSubscriber(): void $dispatcher = new EventDispatcher; $dispatcher->addSubscriber(new ElasticaQuerySubscriber()); $dispatcher->addSubscriber(new MockPaginationSubscriber); // pagination view - $p = new Paginator($dispatcher); + $accessor = $this->createMock(ArgumentAccessInterface::class); + $p = new Paginator($dispatcher, $accessor); $query = Query::create(new Term([ 'name' => 'Fred', diff --git a/tests/Test/Pager/Subscriber/Paginate/PaginationSubscriberTest.php b/tests/Test/Pager/Subscriber/Paginate/PaginationSubscriberTest.php index aa8ede61..ca94d1ca 100644 --- a/tests/Test/Pager/Subscriber/Paginate/PaginationSubscriberTest.php +++ b/tests/Test/Pager/Subscriber/Paginate/PaginationSubscriberTest.php @@ -2,6 +2,7 @@ namespace Test\Pager\Subscriber\Paginate; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; use Knp\Component\Pager\Event\BeforeEvent; use Knp\Component\Pager\Event\Subscriber\Paginate\PaginationSubscriber; use Symfony\Component\EventDispatcher\EventDispatcherInterface; @@ -19,8 +20,9 @@ public function shouldRegisterExpectedSubscribersOnlyOnce(): void $subscriber = new PaginationSubscriber; - $requestStack = $this->createRequestStack([]); - $beforeEvent = new BeforeEvent($dispatcher, $requestStack->getCurrentRequest()); + $accessor = $this->createMock(ArgumentAccessInterface::class); + + $beforeEvent = new BeforeEvent($dispatcher, $accessor); $subscriber->before($beforeEvent); // Subsequent calls do not add more subscribers diff --git a/tests/Test/Pager/Subscriber/Paginate/SolariumQuerySubscriberTest.php b/tests/Test/Pager/Subscriber/Paginate/SolariumQuerySubscriberTest.php index 6da35399..ee388ad5 100644 --- a/tests/Test/Pager/Subscriber/Paginate/SolariumQuerySubscriberTest.php +++ b/tests/Test/Pager/Subscriber/Paginate/SolariumQuerySubscriberTest.php @@ -2,6 +2,7 @@ namespace Test\Pager\Subscriber\Paginate; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; use Knp\Component\Pager\Event\Subscriber\Paginate\SolariumQuerySubscriber; use Knp\Component\Pager\Paginator; use PHPUnit\Framework\TestCase; @@ -25,7 +26,8 @@ public function arrayShouldNotBeHandled(): void $dispatcher->addSubscriber(new SolariumQuerySubscriber); $dispatcher->addSubscriber(new MockPaginationSubscriber); - $p = new Paginator($dispatcher); + $accessor = $this->createMock(ArgumentAccessInterface::class); + $p = new Paginator($dispatcher, $accessor); $p->paginate($array, 1, 10); } } diff --git a/tests/Test/Pager/Subscriber/Sortable/ArraySubscriberTest.php b/tests/Test/Pager/Subscriber/Sortable/ArraySubscriberTest.php index 1e96244d..7d6af38d 100644 --- a/tests/Test/Pager/Subscriber/Sortable/ArraySubscriberTest.php +++ b/tests/Test/Pager/Subscriber/Sortable/ArraySubscriberTest.php @@ -2,6 +2,7 @@ namespace Test\Pager\Subscriber\Sortable; +use Knp\Component\Pager\ArgumentAccess\RequestArgumentAccess; use Knp\Component\Pager\Event\ItemsEvent; use Knp\Component\Pager\Event\Subscriber\Sortable\ArraySubscriber; use Knp\Component\Pager\PaginatorInterface; @@ -27,7 +28,8 @@ public function shouldSort(): void // test asc sort $requestStack = $this->createRequestStack(['sort' => '[entry][sortProperty]', 'ord' => 'asc']); - $arraySubscriber = new ArraySubscriber($requestStack->getCurrentRequest()); + $accessor = new RequestArgumentAccess($requestStack); + $arraySubscriber = new ArraySubscriber($accessor); $arraySubscriber->items($itemsEvent); $this->assertEquals(1, $array[0]['entry']['sortProperty']); @@ -35,7 +37,8 @@ public function shouldSort(): void // test desc sort $requestStack = $this->createRequestStack(['sort' => '[entry][sortProperty]', 'ord' => 'desc']); - $arraySubscriber = new ArraySubscriber($requestStack->getCurrentRequest()); + $accessor = new RequestArgumentAccess($requestStack); + $arraySubscriber = new ArraySubscriber($accessor); $arraySubscriber->items($itemsEvent); $this->assertEquals(3, $array[0]['entry']['sortProperty']); } @@ -69,7 +72,8 @@ public function shouldSortWithCustomCallback(): void // test asc sort $requestStack = $this->createRequestStack(['sort' => '.name', 'ord' => 'asc']); - $arraySubscriber = new ArraySubscriber($requestStack->getCurrentRequest()); + $accessor = new RequestArgumentAccess($requestStack); + $arraySubscriber = new ArraySubscriber($accessor); $arraySubscriber->items($itemsEvent); $this->assertEquals('cold', $array[0]['name']); @@ -77,7 +81,8 @@ public function shouldSortWithCustomCallback(): void // test desc sort $requestStack = $this->createRequestStack(['sort' => '.name', 'ord' => 'desc']); - $arraySubscriber = new ArraySubscriber($requestStack->getCurrentRequest()); + $accessor = new RequestArgumentAccess($requestStack); + $arraySubscriber = new ArraySubscriber($accessor); $arraySubscriber->items($itemsEvent); $this->assertEquals('hot', $array[0]['name']); } @@ -99,7 +104,8 @@ public function shouldSortEvenWhenTheSortPropertyIsNotAccessible(): void // test asc sort $requestStack = $this->createRequestStack(['sort' => '[entry][sortProperty]', 'ord' => 'asc']); - $arraySubscriber = new ArraySubscriber($requestStack->getCurrentRequest()); + $accessor = new RequestArgumentAccess($requestStack); + $arraySubscriber = new ArraySubscriber($accessor); $arraySubscriber->items($itemsEvent); $this->assertEquals(false, isset($array[0]['entry']['sortProperty'])); @@ -107,7 +113,8 @@ public function shouldSortEvenWhenTheSortPropertyIsNotAccessible(): void // test desc sort $requestStack = $this->createRequestStack(['sort' => '[entry][sortProperty]', 'ord' => 'desc']); - $arraySubscriber = new ArraySubscriber($requestStack->getCurrentRequest()); + $accessor = new RequestArgumentAccess($requestStack); + $arraySubscriber = new ArraySubscriber($accessor); $arraySubscriber->items($itemsEvent); $this->assertEquals(2, $array[0]['entry']['sortProperty']); } @@ -132,7 +139,8 @@ public function shouldBeKeptTheOrderWhenSortPropertyDoesNotExist(array $items): // test asc sort $requestStack = $this->createRequestStack(['sort' => 'notExistProperty', 'ord' => 'asc']); - $arraySubscriber = new ArraySubscriber($requestStack->getCurrentRequest()); + $accessor = new RequestArgumentAccess($requestStack); + $arraySubscriber = new ArraySubscriber($accessor); $arraySubscriber->items($itemsEvent); $this->assertSame($sameSortOrderItems, $items); @@ -140,7 +148,8 @@ public function shouldBeKeptTheOrderWhenSortPropertyDoesNotExist(array $items): // test desc sort $requestStack = $this->createRequestStack(['sort' => 'notExistProperty', 'ord' => 'desc']); - $arraySubscriber = new ArraySubscriber($requestStack->getCurrentRequest()); + $accessor = new RequestArgumentAccess($requestStack); + $arraySubscriber = new ArraySubscriber($accessor); $arraySubscriber->items($itemsEvent); $this->assertSame($sameSortOrderItems, $items); } diff --git a/tests/Test/Pager/Subscriber/Sortable/Doctrine/ODM/MongoDB/QueryTest.php b/tests/Test/Pager/Subscriber/Sortable/Doctrine/ODM/MongoDB/QueryTest.php index 233423bb..1795bb37 100644 --- a/tests/Test/Pager/Subscriber/Sortable/Doctrine/ODM/MongoDB/QueryTest.php +++ b/tests/Test/Pager/Subscriber/Sortable/Doctrine/ODM/MongoDB/QueryTest.php @@ -2,6 +2,7 @@ namespace Test\Pager\Subscriber\Sortable\Doctrine\ODM\MongoDB; +use Knp\Component\Pager\ArgumentAccess\RequestArgumentAccess; use Knp\Component\Pager\Event\Subscriber\Paginate\PaginationSubscriber; use Knp\Component\Pager\Event\Subscriber\Sortable\Doctrine\ODM\MongoDB\QuerySubscriber as Sortable; use Knp\Component\Pager\Paginator; @@ -22,7 +23,8 @@ public function shouldSortSimpleDoctrineQuery(): void $dispatcher->addSubscriber(new PaginationSubscriber); $dispatcher->addSubscriber(new Sortable($this->createRequestStack([])->getCurrentRequest())); $requestStack = $this->createRequestStack(['sort' => 'title', 'direction' => 'asc']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $qb = $this->dm->createQueryBuilder(Article::class); $query = $qb->getQuery(); @@ -36,7 +38,8 @@ public function shouldSortSimpleDoctrineQuery(): void $this->assertEquals('winter', $items[3]->getTitle()); $requestStack = $this->createRequestStack(['sort' => 'title', 'direction' => 'desc']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $view = $p->paginate($query, 1, 10); $items = \array_values($view->getItems()); $this->assertCount(4, $items); @@ -46,7 +49,8 @@ public function shouldSortSimpleDoctrineQuery(): void $this->assertEquals('autumn', $items[3]->getTitle()); $requestStack = $this->createRequestStack(['sort' => 'status+created_at', 'direction' => 'desc']); - $p = new Paginator($dispatcher, $requestStack); + $accessor = new RequestArgumentAccess($requestStack); + $p = new Paginator($dispatcher, $accessor); $view = $p->paginate($query); $items = \array_values($view->getItems()); $this->assertCount(4, $items); diff --git a/tests/Test/Pager/Subscriber/Sortable/Doctrine/ORM/QueryTest.php b/tests/Test/Pager/Subscriber/Sortable/Doctrine/ORM/QueryTest.php index f885193f..5ee096e8 100644 --- a/tests/Test/Pager/Subscriber/Sortable/Doctrine/ORM/QueryTest.php +++ b/tests/Test/Pager/Subscriber/Sortable/Doctrine/ORM/QueryTest.php @@ -2,6 +2,9 @@ namespace Test\Pager\Subscriber\Sortable\Doctrine\ORM; +use Doctrine\ORM\EntityManager; +use Doctrine\ORM\Tools\SchemaTool; +use Knp\Component\Pager\ArgumentAccess\RequestArgumentAccess; use Knp\Component\Pager\Event\Subscriber\Paginate\Doctrine\ORM\QuerySubscriber; use Knp\Component\Pager\Event\Subscriber\Paginate\PaginationSubscriber; use Knp\Component\Pager\Event\Subscriber\Sortable\Doctrine\ORM\QuerySubscriber as Sortable; @@ -35,12 +38,12 @@ public function shouldHandleApcQueryCache(): void 'memory' => true, ]; - $em = \Doctrine\ORM\EntityManager::create($conn, $config); - $schema = \array_map(function ($class) use ($em) { + $em = EntityManager::create($conn, $config); + $schema = \array_map(static function ($class) use ($em) { return $em->getClassMetadata($class); - }, (array)$this->getUsedEntityFixtures()); + }, $this->getUsedEntityFixtures()); - $schemaTool = new \Doctrine\ORM\Tools\SchemaTool($em); + $schemaTool = new SchemaTool($em); $schemaTool->dropSchema([]); $schemaTool->createSchema($schema); $this->populate($em); @@ -64,10 +67,11 @@ public function shouldSortSimpleDoctrineQuery(): void $this->populate($em); $requestStack = $this->createRequestStack(['sort' => 'a.title', 'direction' => 'asc']); + $accessor = new RequestArgumentAccess($requestStack); $dispatcher = new EventDispatcher; $dispatcher->addSubscriber(new PaginationSubscriber); - $dispatcher->addSubscriber(new Sortable($requestStack->getCurrentRequest())); - $p = new Paginator($dispatcher, $requestStack); + $dispatcher->addSubscriber(new Sortable($accessor)); + $p = new Paginator($dispatcher, $accessor); $this->startQueryLog(); $query = $this->em->createQuery('SELECT a FROM Test\Fixture\Entity\Article a'); @@ -96,10 +100,11 @@ public function shouldSortSimpleDoctrineQuery2(): void $this->populate($em); $requestStack = $this->createRequestStack(['sort' => 'a.title', 'direction' => 'desc']); + $accessor = new RequestArgumentAccess($requestStack); $dispatcher = new EventDispatcher; $dispatcher->addSubscriber(new PaginationSubscriber); - $dispatcher->addSubscriber(new Sortable($requestStack->getCurrentRequest())); - $p = new Paginator($dispatcher, $requestStack); + $dispatcher->addSubscriber(new Sortable($accessor)); + $p = new Paginator($dispatcher, $accessor); $this->startQueryLog(); $query = $this->em->createQuery('SELECT a FROM Test\Fixture\Entity\Article a'); @@ -211,17 +216,18 @@ public function shouldNotExecuteExtraQueriesWhenCountIsZero(): void */ public function shouldNotAcceptArrayParameter(): void { - $this->expectException(\UnexpectedValueException::class); + $this->expectException(\PHP_VERSION_ID < 80100 ? \TypeError::class : \UnexpectedValueException::class); $query = $this ->getMockSqliteEntityManager() ->createQuery('SELECT a FROM Test\Fixture\Entity\Article a') ; $requestStack = $this->createRequestStack(['sort' => ['field' => 'a.name'], 'direction' => 'asc']); + $accessor = new RequestArgumentAccess($requestStack); $dispatcher = new EventDispatcher; $dispatcher->addSubscriber(new PaginationSubscriber); - $dispatcher->addSubscriber(new Sortable($requestStack->getCurrentRequest())); - $p = new Paginator($dispatcher, $requestStack); - $view = $p->paginate($query, 1, 10); + $dispatcher->addSubscriber(new Sortable($accessor)); + $p = new Paginator($dispatcher, $accessor); + $p->paginate($query, 1, 10); } protected function getUsedEntityFixtures(): array @@ -250,7 +256,7 @@ private function populate($em): void $em->flush(); } - private function getApcEntityManager() + private function getApcEntityManager(): EntityManager { $config = new \Doctrine\ORM\Configuration(); $config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ApcCache); @@ -265,7 +271,6 @@ private function getApcEntityManager() 'memory' => true, ]; - $em = \Doctrine\ORM\EntityManager::create($conn, $config); - return $em; + return EntityManager::create($conn, $config); } } diff --git a/tests/Test/Pager/Subscriber/Sortable/SolariumQuerySubscriberTest.php b/tests/Test/Pager/Subscriber/Sortable/SolariumQuerySubscriberTest.php index bbae3a18..fe900e79 100644 --- a/tests/Test/Pager/Subscriber/Sortable/SolariumQuerySubscriberTest.php +++ b/tests/Test/Pager/Subscriber/Sortable/SolariumQuerySubscriberTest.php @@ -2,6 +2,7 @@ namespace Test\Pager\Subscriber\Sortable; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; use Knp\Component\Pager\Event\Subscriber\Sortable\SolariumQuerySubscriber; use Knp\Component\Pager\Paginator; use Symfony\Component\EventDispatcher\EventDispatcher; @@ -32,13 +33,13 @@ public function testArrayShouldNotBeHandled(): void 'nbTotalResults' => 2, ]; - $requestStack = $this->createRequestStack([]); + $accessor = $this->createMock(ArgumentAccessInterface::class); $dispatcher = new EventDispatcher(); - $dispatcher->addSubscriber(new SolariumQuerySubscriber($requestStack->getCurrentRequest())); + $dispatcher->addSubscriber(new SolariumQuerySubscriber($accessor)); $dispatcher->addSubscriber(new MockPaginationSubscriber()); - $paginator = new Paginator($dispatcher); + $paginator = new Paginator($dispatcher, $accessor); $paginator->paginate($array, 1, 10); } } diff --git a/tests/Test/Pager/Subscriber/Sortable/SortableSubscriberTest.php b/tests/Test/Pager/Subscriber/Sortable/SortableSubscriberTest.php index 8d19bdc4..72313e94 100644 --- a/tests/Test/Pager/Subscriber/Sortable/SortableSubscriberTest.php +++ b/tests/Test/Pager/Subscriber/Sortable/SortableSubscriberTest.php @@ -1,5 +1,6 @@ createRequestStack([]); - $beforeEvent = new BeforeEvent($dispatcher, $requestStack->getCurrentRequest()); + $accessor = $this->createMock(ArgumentAccessInterface::class); + $beforeEvent = new BeforeEvent($dispatcher, $accessor); $subscriber->before($beforeEvent); // Subsequent calls do not add more subscribers diff --git a/tests/Test/Tool/BaseTestCase.php b/tests/Test/Tool/BaseTestCase.php index 179e5d03..1adfc729 100644 --- a/tests/Test/Tool/BaseTestCase.php +++ b/tests/Test/Tool/BaseTestCase.php @@ -2,6 +2,8 @@ namespace Test\Tool; +use Knp\Component\Pager\ArgumentAccess\ArgumentAccessInterface; +use Knp\Component\Pager\ArgumentAccess\RequestArgumentAccess; use Knp\Component\Pager\Event\Subscriber\Paginate\PaginationSubscriber; use Knp\Component\Pager\Event\Subscriber\Sortable\SortableSubscriber; use Knp\Component\Pager\Paginator; @@ -15,10 +17,6 @@ */ abstract class BaseTestCase extends TestCase { - protected function setUp(): void - { - } - protected function getPaginatorInstance(?RequestStack $requestStack = null, ?EventDispatcher $dispatcher = null): Paginator { if (null === $dispatcher) { @@ -26,8 +24,13 @@ protected function getPaginatorInstance(?RequestStack $requestStack = null, ?Eve $dispatcher->addSubscriber(new PaginationSubscriber()); $dispatcher->addSubscriber(new SortableSubscriber()); } + if (null !== $requestStack) { + $accessor = new RequestArgumentAccess($requestStack); + } else { + $accessor = $this->createMock(ArgumentAccessInterface::class); + } - return new Paginator($dispatcher, $requestStack); + return new Paginator($dispatcher, $accessor); } protected function createRequestStack(array $params): RequestStack