66namespace tuyakhov \jsonapi ;
77
88use yii \base \Component ;
9+ use yii \base \InvalidValueException ;
910use yii \base \Model ;
1011use yii \data \DataProviderInterface ;
1112use yii \data \Pagination ;
@@ -86,16 +87,14 @@ public function serialize($data)
8687 * @param ResourceInterface $model
8788 * @return array
8889 */
89- protected function serializeModel ($ model )
90+ protected function serializeModel (ResourceInterface $ model )
9091 {
9192 $ fields = $ this ->getRequestedFields ();
9293
9394 $ attributes = isset ($ fields [$ model ->getType ()]) ? $ fields [$ model ->getType ()] : [];
94- $ data = [
95- 'id ' => $ model ->getId (),
96- 'type ' => $ model ->getType (),
95+ $ data = array_merge ($ this ->serializeIdentifier ($ model ), [
9796 'attributes ' => $ model ->getResourceAttributes ($ attributes ),
98- ];
97+ ]) ;
9998
10099 $ relationships = $ model ->getResourceRelationships ();
101100 if (!empty ($ relationships )) {
@@ -104,11 +103,11 @@ protected function serializeModel($model)
104103 if (is_array ($ items )) {
105104 foreach ($ items as $ item ) {
106105 if ($ item instanceof ResourceIdentifierInterface) {
107- $ relationship [] = [ ' id ' => $ item -> getId (), ' type ' => $ item-> getType ()] ;
106+ $ relationship [] = $ this -> serializeIdentifier ( $ item) ;
108107 }
109108 }
110109 } elseif ($ items instanceof ResourceIdentifierInterface) {
111- $ relationship = [ ' id ' => $ items -> getId (), ' type ' => $ items-> getType ()] ;
110+ $ relationship = $ this -> serializeIdentifier ( $ items) ;
112111 }
113112
114113 if (!empty ($ relationship )) {
@@ -134,7 +133,7 @@ protected function serializeModel($model)
134133 * @param ResourceInterface $resource
135134 * @return array
136135 */
137- protected function serializeResource ($ resource )
136+ protected function serializeResource (ResourceInterface $ resource )
138137 {
139138 if ($ this ->request ->getIsHead ()) {
140139 return null ;
@@ -150,6 +149,26 @@ protected function serializeResource($resource)
150149 }
151150 }
152151
152+ /**
153+ * Serialize resource identifier object and make type juggling
154+ * @link http://jsonapi.org/format/#document-resource-object-identification
155+ * @param ResourceIdentifierInterface $identifier
156+ * @return array
157+ */
158+ protected function serializeIdentifier (ResourceIdentifierInterface $ identifier )
159+ {
160+ $ result = [];
161+ foreach (['id ' , 'type ' ] as $ key ) {
162+ $ getter = 'get ' . ucfirst ($ key );
163+ $ value = $ identifier ->$ getter ();
164+ if ($ value === null || is_array ($ value ) || (is_object ($ value ) && !method_exists ($ value , '__toString ' ))) {
165+ throw new InvalidValueException ("The value {$ key } of resource object " . get_class ($ identifier ) . ' MUST be a string. ' );
166+ }
167+ $ result [$ key ] = (string ) $ value ;
168+ }
169+ return $ result ;
170+ }
171+
153172 /**
154173 * @param ResourceInterface $resource
155174 * @return array
0 commit comments