Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added XML support #7

Open
wants to merge 1 commit into
base: craft3
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions src/twigextensions/FetchTwigExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,23 @@ public function getFunctions()
];
}

public function fetch($client, $method, $destination, $request = [], $parseJson = true)
public function fetch($client, $method, $destination, $request = [], $format = 'json')
{
$client = new \GuzzleHttp\Client($client);

try {

$response = $client->request($method, $destination, $request);

if ($parseJson) {
if ($format == 'json') {
$body = json_decode($response->getBody(), true);
} elseif ($format == 'xml') {
$xmlbody = simplexml_load_string($response->getBody(), null, LIBXML_NOCDATA);

$json = json_encode($xmlbody);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The $json variable is unnecessary here. Put json_encode($xmlbody) on the next line instead where $json is.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apologies, had no idea you replied.

I tried you suggestion and the body key had a string of the JSON object returned. So the XML needs encoding to JSON then decoding.
I suppose it could go $body = json_decode(json_encode($xmlbody), true); ?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I think that snippet is what Patrik is suggesting. A bit DRYer I guess, but I personally prefer it as you have it for readability... (If I'm misunderstanding your point @patrikalienus feel free to correct me)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeh, it was more for readability. It was a bit rushed too at the time, so wasn't thinking to save a few lines. I guess where there isn't much in it, then @patrikalienus suggestion is still valid.

$body = json_decode($json, true);
} else {
$body = (string)$response->getBody();
$body = (string)$response->getBody();
}

return [
Expand All @@ -59,7 +64,8 @@ public function fetch($client, $method, $destination, $request = [], $parseJson
'error' => true,
'reason' => $e->getMessage()
];

}
}
}

}