Skip to content

Commit 8a22641

Browse files
committed
FetchByIdentifiers
1 parent 7035fe6 commit 8a22641

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/FetchByIdentifiers.php

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Utilitte\Doctrine;
4+
5+
use Doctrine\ORM\EntityManagerInterface;
6+
use LogicException;
7+
use Utilitte\Php\ArraySort;
8+
9+
final class FetchByIdentifiers
10+
{
11+
12+
private EntityManagerInterface $em;
13+
14+
public function __construct(EntityManagerInterface $em)
15+
{
16+
$this->em = $em;
17+
}
18+
19+
public function fetch(string $entity, array $ids): array
20+
{
21+
$metadata = $this->em->getClassMetadata($entity);
22+
$identifiers = $metadata->getIdentifierFieldNames();
23+
if (count($identifiers) !== 1) {
24+
throw new LogicException(sprintf('%s entity must have one identifier', $entity));
25+
}
26+
$column = $identifiers[0];
27+
28+
$result = $this->em->createQueryBuilder()
29+
->select('e')
30+
->from($entity, 'e')
31+
->where(sprintf('e.%s IN(:ids)', $column))
32+
->setParameter('ids', $ids)
33+
->getQuery()
34+
->getResult();
35+
36+
return ArraySort::byGivenValues(
37+
$ids,
38+
$result,
39+
fn (object $entity) => $metadata->getIdentifierValues($entity)[$column]
40+
);
41+
}
42+
43+
}

0 commit comments

Comments
 (0)