File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments