Reputation: 35
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)?
Upvotes: 0
Views: 79
Reputation: 1786
YOu can try something like this
<?php
function convert_multi_array($glue, $arr) {
foreach ($arr as $key => $value) {
if (@is_array($value))
{
$arr[$key] = convert_multi_array ($glue, $arr[$key]);
}
}
return implode($glue, $arr);
}
$json_data = <<<END_OF_JSON
{
"action": "PushEvent",
"commits_count": 5,
"repository": {"name":"example-repo"}
}
END_OF_JSON;
$array_data = json_decode($json_data, true);
$string_data = convert_multi_array(',', $array_data);
echo "<pre>";
print_r($json_data);
print_r($array_data);
echo($string_data);
die();
Upvotes: 0
Reputation: 6544
I think you best put it into the Activity
model (or a trait, if you want to keep the model clean). For the method itself, you won't have much other options than implementing each action individually. Maybe you can combine multiple actions when you use switch-case
, but the hardest part will probably be translating the action into a verb.
Alternatively, you could also put it into a blade component. This would make sense if you plan on having your notifications look nice, e.g. if you look at the following HTML
<span class="activity">
<span class="activity-user">User</span> pushed
<span class="activity-count">5</span> commits to
<span class="activity-repository">
<a href="/path/to/example-repo">example-repo</a>
</span>.
</span>
you'll notice that you can't just create the same afterwards if you compile your activity into a plain text sentence.
Upvotes: 1
Reputation: 1250
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']));
Upvotes: 1