Skip to content

Enable parent JSON data with classMap #212

@startailcoon

Description

@startailcoon

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;
            }
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions