15
15
16
16
use Rekalogika \Mapper \Context \Context ;
17
17
use Rekalogika \Mapper \Exception \UnexpectedValueException ;
18
+ use Rekalogika \Mapper \IterableMapperInterface ;
18
19
use Rekalogika \Mapper \MainTransformer \MainTransformerInterface ;
19
20
use Rekalogika \Mapper \MapperInterface ;
20
21
use Rekalogika \Mapper \Util \TypeFactory ;
21
22
22
23
/**
23
24
* @internal
24
25
*/
25
- final readonly class Mapper implements MapperInterface
26
+ final readonly class Mapper implements MapperInterface, IterableMapperInterface
26
27
{
27
28
public function __construct (
28
29
private MainTransformerInterface $ transformer ,
@@ -38,12 +39,14 @@ public function map(object $source, object|string $target, ?Context $context = n
38
39
{
39
40
if (is_string ($ target )) {
40
41
$ targetClass = $ target ;
42
+
41
43
if (
42
44
!class_exists ($ targetClass )
43
45
&& !\interface_exists ($ targetClass )
44
46
) {
45
47
throw new UnexpectedValueException (sprintf ('The target class "%s" does not exist. ' , $ targetClass ));
46
48
}
49
+
47
50
$ targetType = TypeFactory::objectOfClass ($ targetClass );
48
51
$ target = null ;
49
52
} else {
@@ -71,4 +74,44 @@ public function map(object $source, object|string $target, ?Context $context = n
71
74
72
75
return $ target ;
73
76
}
77
+
78
+ /**
79
+ * @template T of object
80
+ * @param iterable<mixed> $source
81
+ * @param class-string<T> $target
82
+ * @return iterable<T>
83
+ */
84
+ public function mapIterable (
85
+ iterable $ source ,
86
+ string $ target ,
87
+ ?Context $ context = null
88
+ ): iterable {
89
+ $ targetClass = $ target ;
90
+
91
+ if (
92
+ !class_exists ($ targetClass )
93
+ && !\interface_exists ($ targetClass )
94
+ ) {
95
+ throw new UnexpectedValueException (sprintf ('The target class "%s" does not exist. ' , $ targetClass ));
96
+ }
97
+
98
+ $ targetType = TypeFactory::objectOfClass ($ targetClass );
99
+
100
+ /** @var mixed $item */
101
+ foreach ($ source as $ item ) {
102
+ $ result = $ this ->transformer ->transform (
103
+ source: $ item ,
104
+ target: null ,
105
+ sourceType: null ,
106
+ targetTypes: [$ targetType ],
107
+ context: $ context ?? Context::create (),
108
+ );
109
+
110
+ if (!is_object ($ result ) || !is_a ($ result , $ target )) {
111
+ throw new UnexpectedValueException (sprintf ('The mapper did not return the variable of expected class, expecting "%s", returned "%s". ' , $ targetClass , get_debug_type ($ target )));
112
+ }
113
+
114
+ yield $ result ;
115
+ }
116
+ }
74
117
}
0 commit comments