Hello!
I am trying to make a "bbcode" that retrieves information from an API endpoint and adds the returned custom HTML on a post. The idea is to have a specific keyword, let's say: {{ContentAPI|1234}} which connects to a service such as: example.com/api/1234. The service would then return HTML code for that 1234 id and I want to show it on a post.
Originally, I thought I could add a Replace to the Formatter like this:
(new Extend\Formatter)
->configure(function (Configurator $config) {
$config->Preg->replace(
'/{{CustomAPI\|(?<id>[-0-9]+)}}/',
getAPIContent("$1"),
);
})
That didn't work since this is cached and the $1 is not passed to the function.
Then, I tried with a render function
->render(function($renderer, $context, string $xml){
$xml= preg_replace_callback('/{{CustomAPI\|(.+?)\}}/s',
function ($matches){
$endpoint = 'https://www.example.com/'.$matches[1];
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', $endpoint);
$data = json_decode($response->getBody(), true);
return preg_replace('/<!--(.*)-->/Uis', '', $data["content"]); //delete comments
},
$xml);
This works partially, but there are two issues:
- There are some cases in which all the HTML tags are stripped from this, so I end up with only the plain text. Not always though! It seems like it depends on the HTML content, sometimes I get the full HTML code rendered. I don't know why the HTML are deleted in some cases...
- This will actually make an API call every time a post is loaded which causes unnecessary calls, and also does not save the content on the post so it won't appear when searching in the forum.
So... does anyone know a nice way to retrieve the API content on the Formatter, saving it to the post, and rendering nicely with any custom HTML that may be coming from the API content?
Thanks!