88use ReflectionException ;
99use Tempest \Container \Container ;
1010use Tempest \Mapper \Exceptions \CannotMapDataException ;
11+ use Tempest \Mapper \Mappers \ArrayToJsonMapper ;
12+ use Tempest \Mapper \Mappers \JsonToArrayMapper ;
13+ use Tempest \Mapper \Mappers \ObjectToArrayMapper ;
14+ use Tempest \Mapper \Mappers \ObjectToJsonMapper ;
1115use Tempest \Reflection \FunctionReflector ;
1216
1317/** @template ClassType */
@@ -22,8 +26,7 @@ final class ObjectFactory
2226 public function __construct (
2327 private readonly MapperConfig $ config ,
2428 private readonly Container $ container ,
25- ) {
26- }
29+ ) {}
2730
2831 /**
2932 * @template T of object
@@ -68,7 +71,7 @@ public function from(mixed $data): mixed
6871
6972 /**
7073 * @template T of object
71- * @param T|class-string<T> $to
74+ * @param T|class-string<T>|string $to
7275 * @return T|T[]|mixed
7376 */
7477 public function to (mixed $ to ): mixed
@@ -80,9 +83,33 @@ public function to(mixed $to): mixed
8083 );
8184 }
8285
86+ public function toArray (): array
87+ {
88+ if (is_object ($ this ->from )) {
89+ return $ this ->with (ObjectToArrayMapper::class);
90+ } elseif (is_array ($ this ->from )) {
91+ return $ this ->from ;
92+ } elseif (is_string ($ this ->from ) && json_validate ($ this ->from )) {
93+ return $ this ->with (JsonToArrayMapper::class);
94+ } else {
95+ throw new CannotMapDataException ($ this ->from , 'array ' );
96+ }
97+ }
98+
99+ public function toJson (): string
100+ {
101+ if (is_object ($ this ->from )) {
102+ return $ this ->with (ObjectToJsonMapper::class);
103+ } elseif (is_array ($ this ->from )) {
104+ return $ this ->with (ArrayToJsonMapper::class);
105+ } else {
106+ throw new CannotMapDataException ($ this ->from , 'json ' );
107+ }
108+ }
109+
83110 /**
84111 * @template T of object
85- * @param T|class-string<T> $to
112+ * @param T|class-string<T>|string $to
86113 * @return T|mixed
87114 */
88115 public function map (mixed $ from , mixed $ to ): mixed
@@ -131,7 +158,8 @@ private function mapObject(
131158 mixed $ from ,
132159 mixed $ to ,
133160 bool $ isCollection ,
134- ): mixed {
161+ ): mixed
162+ {
135163 if ($ isCollection && is_array ($ from )) {
136164 return array_map (
137165 fn (mixed $ item ) => $ this ->mapObject (
0 commit comments