jsonmapper icon indicating copy to clipboard operation
jsonmapper copied to clipboard

Enable parent JSON data with classMap

Open startailcoon opened this issue 1 year ago • 1 comments

Today the classMap function does not pass on the parent json array. This makes it impossible to make a change due to a specific value in the parent.

A feature update was declined in #209. Due to this I'm make a Issue ticke to describe the requested feature for implementation

Case

We have a JSON with the following data

"contracts":
 "0":
  "version": "2"
  "type": "vote"
  "action": "A"
  "body":
   "version": "1"
   "body_data": "some_data"

The single point here is the "type" in the JSON data. Based on this value, which can be a number of different actions, we wish to process the body data with a specific data class.

Expected feature

The ability to read the parent data, something like the following. The parent data is passed and possible to read from the ClassMap function, here named determineClass. Based on parent->type we process the data and return the correct class.

$jm = new JsonMapper();
$jm->classMap[ContractBody::class] = function($class, $jvalue, $parent_json) {
    return ContractBody::determineClass($class, $jvalue, $parent_json);
};

class ContractBody { 
    public static function determineClass($class, $json, $parent_json) {
        if($parent_json->version <= 2) {
                
            if($parent_json->type == "")           return;
            if(is_string($json))             return 'string';

            switch(strtoupper($parent_json->type)) {
               case "VOTE":
                    if($parent_json->version == 1)    return 'ContractVoteLegacy';
                    if($parent_json->version == 2)    return 'ContractVote';
                    break;
            }
        }
    }
}

startailcoon avatar Jul 22 '23 10:07 startailcoon

In #209 I requested that the full ancestor stack shall be passed as array, instead of only the direct parent value. Patches need to implement that requirement.

cweiske avatar Aug 01 '23 08:08 cweiske