From 8a22641ce04cfa3497a3db340d1c39cafc3e0be3 Mon Sep 17 00:00:00 2001 From: MartkCz Date: Wed, 30 Dec 2020 13:58:38 +0100 Subject: [PATCH] FetchByIdentifiers --- src/FetchByIdentifiers.php | 43 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/FetchByIdentifiers.php diff --git a/src/FetchByIdentifiers.php b/src/FetchByIdentifiers.php new file mode 100644 index 0000000..beca289 --- /dev/null +++ b/src/FetchByIdentifiers.php @@ -0,0 +1,43 @@ +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] + ); + } + +}