Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/selectable/indexby #100

Merged
merged 2 commits into from
Jun 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
* feat(`PageableInterface`): add `$start` parameter to `getPages()` method to
ease batch resuming.
* refactor: move common indexBy logic to separate package
* feat(`SelectableAdapter`): add `indexBy` parameter

# 0.11.2

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"require": {
"php": "^8.2",
"doctrine/collections": "^2.2",
"rekalogika/rekapager-adapter-common": "self.version",
"rekalogika/rekapager-keyset-pagination": "^0.11.2",
"rekalogika/rekapager-offset-pagination": "^0.11.2"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Collections\Order;
use Doctrine\Common\Collections\Selectable;
use Rekalogika\Rekapager\Adapter\Common\IndexResolver;
use Rekalogika\Rekapager\Doctrine\Collections\Exception\UnsupportedCollectionItemException;
use Rekalogika\Rekapager\Doctrine\Collections\Exception\UnsupportedCriteriaException;
use Rekalogika\Rekapager\Doctrine\Collections\Internal\SelectableKeysetItem;
Expand All @@ -41,6 +42,7 @@ final class SelectableAdapter implements
public function __construct(
private readonly Selectable $collection,
?Criteria $criteria = null,
private readonly string|null $indexBy = null,
) {
$criteria ??= Criteria::create();
$orderings = $criteria->orderings();
Expand Down Expand Up @@ -79,7 +81,25 @@ public function getOffsetItems(int $offset, int $limit): array
->setMaxResults($limit);

try {
return $this->collection->matching($criteria)->toArray();
// @todo: does not preserve keys due to a longstanding Doctrine bug
// https://github.com/doctrine/orm/issues/4693
// workaround: use indexBy
$items = $this->collection->matching($criteria)->toArray();

if ($this->indexBy !== null && array_is_list($items)) {
$newItems = [];

/** @var T $item */
foreach ($items as $item) {
$key = IndexResolver::resolveIndex($item, $this->indexBy);
$newItems[$key] = $item;
}

/** @var array<TKey,T> */
$items = $newItems;
}

return $items;
} catch (\TypeError $e) {
if (preg_match('|ClosureExpressionVisitor::getObjectFieldValue\(\): Argument \#1 \(\$object\) must be of type object\|array, (\S+) given|', $e->getMessage(), $matches)) {
throw new UnsupportedCollectionItemException($matches[1], $e);
Expand Down Expand Up @@ -271,7 +291,23 @@ public function getKeysetItems(
$criteria = $this->getCriteria($offset, $limit, $boundaryValues, $boundaryType);

try {
// @todo: does not preserve keys due to a longstanding Doctrine bug
// https://github.com/doctrine/orm/issues/4693
// workaround: use indexBy
$items = $this->collection->matching($criteria)->toArray();

if ($this->indexBy !== null && array_is_list($items)) {
$newItems = [];

/** @var T $item */
foreach ($items as $item) {
$key = IndexResolver::resolveIndex($item, $this->indexBy);
$newItems[$key] = $item;
}

/** @var array<TKey,T> */
$items = $newItems;
}
} catch (\TypeError $e) {
if (preg_match('|ClosureExpressionVisitor::getObjectFieldValue\(\): Argument \#1 \(\$object\) must be of type object\|array, (\S+) given|', $e->getMessage(), $matches)) {
throw new UnsupportedCollectionItemException($matches[1], $e);
Expand All @@ -281,7 +317,7 @@ public function getKeysetItems(
}

if ($boundaryType === BoundaryType::Upper) {
$items = array_reverse($items);
$items = array_reverse($items, true);
}

$properties = array_keys($this->criteria->orderings());
Expand Down
2 changes: 1 addition & 1 deletion tests/src/App/Entity/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class User
/**
* @var Collection<array-key,Post>
*/
#[ORM\OneToMany(targetEntity: Post::class, mappedBy: 'user', fetch: 'EXTRA_LAZY')]
#[ORM\OneToMany(targetEntity: Post::class, mappedBy: 'user', fetch: 'EXTRA_LAZY', indexBy: 'id')]
private Collection $posts;

public function __construct()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ public function generatePageable(
$adapter = new SelectableAdapter(
collection: $selectable,
criteria: $criteria,
indexBy: 'id',
);

$pageable = new KeysetPageable(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,11 @@ public function generatePageable(
'id' => Order::Ascending
]);

$adapter = new SelectableAdapter($selectable, $criteria);
$adapter = new SelectableAdapter(
collection: $selectable,
criteria: $criteria,
indexBy: 'id',
);

$pageable = new KeysetPageable(
adapter: $adapter,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,11 @@ public function generatePageable(
'id' => Order::Ascending
]);

$adapter = new SelectableAdapter($selectable, $criteria);
$adapter = new SelectableAdapter(
collection: $selectable,
criteria: $criteria,
indexBy: 'id',
);

$pageable = new OffsetPageable(
adapter: $adapter,
Expand Down
85 changes: 85 additions & 0 deletions tests/src/IntegrationTests/Index/SelectableAdapterIndexByTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php

declare(strict_types=1);

/*
* This file is part of rekalogika/rekapager package.
*
* (c) Priyadi Iman Nurcahyo <https://rekalogika.dev>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/

namespace Rekalogika\Rekapager\Tests\IntegrationTests\Index;

use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Collections\Order;
use Rekalogika\Rekapager\Adapter\Common\Exception\IncompatibleIndexTypeException;
use Rekalogika\Rekapager\Doctrine\Collections\SelectableAdapter;
use Rekalogika\Rekapager\Keyset\KeysetPageable;
use Rekalogika\Rekapager\Tests\App\Entity\Post;
use Rekalogika\Rekapager\Tests\App\Repository\PostRepository;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class SelectableAdapterIndexByTest extends KernelTestCase
{
protected function getSelectable(): PostRepository
{
return self::getContainer()->get(PostRepository::class);
}

public function testIndexBy(): void
{
$criteria = Criteria::create()
->where(Criteria::expr()->eq('setName', 'large'))
->orderBy([
'date' => Order::Descending,
'title' => Order::Ascending,
'id' => Order::Ascending
]);

$adapter = new SelectableAdapter(
collection: $this->getSelectable(),
criteria: $criteria,
indexBy: 'id'
);

$pageable = new KeysetPageable(
adapter: $adapter,
itemsPerPage: 1000,
);

/** @var Post $post */
foreach ($pageable->getFirstPage() as $key => $post) {
static::assertInstanceOf(Post::class, $post);
static::assertEquals($key, $post->getId());
}
}

public function testInvalidIndexBy(): void
{
$criteria = Criteria::create()
->where(Criteria::expr()->eq('setName', 'large'))
->orderBy([
'date' => Order::Descending,
'title' => Order::Ascending,
'id' => Order::Ascending
]);

$adapter = new SelectableAdapter(
collection: $this->getSelectable(),
criteria: $criteria,
indexBy: 'foo'
);

$pageable = new KeysetPageable(
adapter: $adapter,
itemsPerPage: 1000,
);

$this->expectException(IncompatibleIndexTypeException::class);

iterator_to_array($pageable->getFirstPage());
}
}