Skip to content

Commit

Permalink
FetchByIdentifiers
Browse files Browse the repository at this point in the history
  • Loading branch information
MartkCz committed Dec 30, 2020
1 parent 7035fe6 commit 8a22641
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/FetchByIdentifiers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php declare(strict_types = 1);

namespace Utilitte\Doctrine;

use Doctrine\ORM\EntityManagerInterface;
use LogicException;
use Utilitte\Php\ArraySort;

final class FetchByIdentifiers
{

private EntityManagerInterface $em;

public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}

public function fetch(string $entity, array $ids): array
{
$metadata = $this->em->getClassMetadata($entity);
$identifiers = $metadata->getIdentifierFieldNames();
if (count($identifiers) !== 1) {
throw new LogicException(sprintf('%s entity must have one identifier', $entity));
}
$column = $identifiers[0];

$result = $this->em->createQueryBuilder()
->select('e')
->from($entity, 'e')
->where(sprintf('e.%s IN(:ids)', $column))
->setParameter('ids', $ids)
->getQuery()
->getResult();

return ArraySort::byGivenValues(
$ids,
$result,
fn (object $entity) => $metadata->getIdentifierValues($entity)[$column]
);
}

}

0 comments on commit 8a22641

Please sign in to comment.