@@ -88,9 +88,7 @@ public function normalize($object, $format = null, array $context = [])
88
88
return $ this ->handleCircularReference ($ object );
89
89
}
90
90
91
- if (!$ resource = $ this ->guessResource ($ object , $ context )) {
92
- throw new InvalidArgumentException ('A resource object must be passed in the context. ' );
93
- }
91
+ $ resource = $ this ->guessResource ($ object , $ context );
94
92
95
93
$ data = [];
96
94
if (!isset ($ context ['has_json_ld_context ' ])) {
@@ -160,11 +158,15 @@ public function normalize($object, $format = null, array $context = [])
160
158
if ('id ' !== $ attribute ) {
161
159
$ attributeValue = $ this ->propertyAccessor ->getValue ($ object , $ attribute );
162
160
163
- if (null !== $ attributeValue && !is_scalar ($ attributeValue )) {
164
- $ attributeValue = $ this ->serializer ->normalize ($ attributeValue , $ format , $ context );
161
+ if ($ details ['type ' ]) {
162
+ $ attributeContext = $ context ;
163
+ $ attributeContext ['resource ' ] = $ this ->resources ->getResourceForEntity ($ details ['type ' ]);
164
+ $ data [$ attribute ] = $ this ->serializer ->normalize ($ attributeValue , $ format , $ attributeContext );
165
+
166
+ continue ;
165
167
}
166
168
167
- $ data [$ attribute ] = $ attributeValue ;
169
+ $ data [$ attribute ] = $ this -> serializer -> normalize ( $ attributeValue, ' json ' , $ context ) ;
168
170
}
169
171
}
170
172
@@ -214,21 +216,35 @@ public function denormalize($data, $class, $format = null, array $context = [])
214
216
/**
215
217
* Guesses the associated resource.
216
218
*
217
- * @param mixed $object
219
+ * @param mixed $type
218
220
* @param array $context
219
221
*
220
222
* @return \Dunglas\JsonLdApiBundle\Resource|null
223
+ *
224
+ * @throws InvalidArgumentException
221
225
*/
222
- private function guessResource ($ object , array $ context )
226
+ private function guessResource ($ type , array $ context )
223
227
{
224
228
if (isset ($ context ['resource ' ])) {
225
229
return $ context ['resource ' ];
226
230
}
227
231
228
- if (is_object ($ object )) {
229
- return $ this ->resources ->getResourceForEntity (get_class ($ object ));
232
+ if (is_object ($ type )) {
233
+ $ type = get_class ($ type );
234
+ }
235
+
236
+ if (is_string ($ type )) {
237
+ if ($ resource = $ this ->resources ->getResourceForEntity ($ type )) {
238
+ return $ resource ;
239
+ }
240
+
241
+ throw new InvalidArgumentException (
242
+ sprintf ('Cannot find a resource object for type "%s". Add a "resource" key in the context. ' , $ type )
243
+ );
230
244
}
231
245
232
- return ;
246
+ throw new InvalidArgumentException (
247
+ sprintf ('Cannot find a resource object for type "%s". Add a "resource" key in the context. ' , gettype ($ type ))
248
+ );
233
249
}
234
250
}
0 commit comments