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

Make paginator covariant #10002

Merged
merged 1 commit into from
Aug 30, 2022
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
7 changes: 4 additions & 3 deletions lib/Doctrine/ORM/Tools/Pagination/Paginator.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Doctrine\ORM\QueryBuilder;
use IteratorAggregate;
use ReturnTypeWillChange;
use Traversable;

use function array_key_exists;
use function array_map;
Expand All @@ -25,7 +26,7 @@
/**
* The paginator can handle various complex scenarios with DQL.
*
* @template T
* @template-covariant T
*/
class Paginator implements Countable, IteratorAggregate
{
Expand Down Expand Up @@ -124,8 +125,8 @@ public function count()
/**
* {@inheritdoc}
*
* @return ArrayIterator
* @psalm-return ArrayIterator<array-key, T>
* @return Traversable
* @psalm-return Traversable<array-key, T>
*/
#[ReturnTypeWillChange]
public function getIterator()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

declare(strict_types=1);

namespace Doctrine\StaticAnalysis\Tools\Pagination;

use Doctrine\ORM\Tools\Pagination\Paginator;

/**
* @template-covariant T of object
*/
abstract class PaginatorFactory
{
/** @var class-string<T> */
private $class;

/**
* @param class-string<T> $class
*/
final public function __construct(string $class)
{
$this->class = $class;
}

/**
* @return class-string<T>
*/
public function getClass(): string
{
return $this->class;
}

/**
* @psalm-return Paginator<T>
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This wouldn't be possible if Paginator wasn't covariant.

*/
abstract public function createPaginator(): Paginator;
}

interface Animal
{
}

class Cat implements Animal
{
}

/**
* @param Paginator<Animal> $paginator
*/
function getFirstAnimal(Paginator $paginator): ?Animal
{
foreach ($paginator as $result) {
return $result;
}

return null;
}

/**
* @param PaginatorFactory<Cat> $catPaginatorFactory
*/
function test(PaginatorFactory $catPaginatorFactory): ?Animal
{
return getFirstAnimal($catPaginatorFactory->createPaginator());
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Passing a Paginator to getFirstAnimal wouldn't be possible if Paginator wasn't covariant

}