@@ -6,32 +6,41 @@ object ComposeLogic {
66
77 val OPERATORS = Array (" <=" , " <" , " >=" , " >" , " ==" , " !=" , " or" , " and" , " xor" )
88
9- implicit def composeLogicReads [T ](implicit fmt : Reads [T ]): Reads [ComposeLogic [T ]] = new Reads [ComposeLogic [T ]] {
9+ private [core] def parse [T ](jsonLogic : JsObject , jsonLogicData : JsObject )(implicit fmt : Reads [T ]): ComposeLogic [T ] = {
10+ // check for operator field
11+ val fields = jsonLogic.fields
1012
11- override def reads (json : JsValue ): JsResult [ComposeLogic [T ]] = {
12- // check for operator field
13- val fields = json.asInstanceOf [JsObject ].fields
13+ // check for compose logic operator field
14+ if (fields.length > 1 ) throw new Error (" JSON object is supposed to have only one operator field." )
15+ val operator = fields.head._1
16+ if (! OPERATORS .contains(operator)) throw new Error (s " Invalid parsed operator: $operator" )
1417
15- // check for compose logic operator field
16- if (fields.length > 1 ) throw new Error (" JSON object is supposed to have only one operator field." )
17- val operator = fields.head._1
18- if (! ComposeLogic .OPERATORS .contains(operator)) throw new Error (s " Invalid parsed operator: $operator" )
18+ // if operator is compose logic
19+ ComposeLogic [T ](operator, readArrayOfConditions[T ]((jsonLogic \ operator).get, jsonLogicData)(fmt))
20+ }
1921
20- // if operator is compose logic
21- JsSuccess (ComposeLogic [T ](operator, readArrayOfConditions((json \ operator).get)))
22- }
22+ private [core] def readArrayOfConditions [T ](json : JsValue , jsonLogicData : JsObject )(implicit fmt : Reads [T ]): Array [JsonLogicCore [_]] = {
23+ val jsArray = json.asInstanceOf [JsArray ]
24+ jsArray
25+ .value
26+ .map(jsValue => {
27+ JsonLogicCore .parse[T ](jsValue.asInstanceOf [JsObject ], jsonLogicData)(fmt)
28+ })
29+ .toArray
30+ }
2331
24- def readArrayOfConditions (json : JsValue ): Array [JsonLogicCore [_]] = {
25- val jsArray = json.asInstanceOf [JsArray ]
26- jsArray
27- .value
28- .map(jsValue => {
29- JsonLogicCore .jsonLogicCoreReads[T ].reads(jsValue).get
30- })
31- .toArray
32- }
32+ implicit def composeLogicReads [T ](implicit fmt : Reads [T ]): Reads [ComposeLogic [T ]] = new Reads [ComposeLogic [T ]] {
33+
34+ override def reads (json : JsValue ): JsResult [ComposeLogic [T ]] = {
35+ // split json in two components jsonLogic and jsonLogicData
36+ val jsonLogic = (json \ 0 ).getOrElse(JsObject .empty).asInstanceOf [JsObject ]
37+ val jsonLogicData = (json \ 1 ).getOrElse(JsObject .empty).asInstanceOf [JsObject ]
3338
39+ // apply reading with distinguished components: logic and data
40+ JsSuccess (parse[T ](jsonLogic, jsonLogicData)(fmt))
41+ }
3442 }
43+
3544}
3645
3746case class ComposeLogic [T ](operator : String , conditions : Array [JsonLogicCore [_]]) extends JsonLogicCore [T ](operator)
0 commit comments