Search code examples
phplaraveldata-processing

Converting data to string


I need to convert data, like this:

{
    "action": "PushEvent",
    "commits_count": 5,
    "repository": {"name":"example-repo"}
}

To a string, like this: User pushed 5 commits to example-repo

The problem is, I have very high amount of action types to support. What would be the best solution to this problem and where should I put the code (Laravel)?


Solution

  • I think json_decode is the way to go, example:

    $source = '{
        "action": "PushEvent",
        "commits_count": 5,
        "repository": {"name":"example-repo"}
    }';
    
    $actions = ['PushEvent' => 'pushed'];
    
    $result = json_decode($source, true);
    
    var_dump(sprintf('User %s %d commits to %s', $actions[$result['action']], $result['commits_count'], $result['repository']['name']));