I've setup Silex to receive webhooks from, for example, Github. In this case Github sends all the pull requests to a specific Silex API endpoint. According to the Github best practices (https://developer.github.com/v3/guides/best-practices-for-integrators/#favor-asynchronous-work-over-synchronous):
GitHub expects that integrations respond within 10 seconds of receiving the webhook payload. If your service takes longer than that to complete, then GitHub terminates the connection and the payload is lost.
We should send an answer directly to Github, and process the POST request later.
I've setup my code like this:
$app->post('/github/receive/pullreq', function (\Symfony\Component\HttpFoundation\Request $request) use ($app) {
$body = $request->request->all();
$app->after(function() use ($body) {
$listener = new \Api\Github\Events\PullRequestEvent();
$dispatcher = new \Symfony\Component\EventDispatcher\EventDispatcher();
$dispatcher->addListener('github.pullrequest.made', array($listener, 'sendTestMail'));
$dispatcher->dispatch('github.pullrequest.made');
});
return new \Symfony\Component\HttpFoundation\Response('PR Received', 201);
});
And the listener class like this:
class PullRequestEvent extends Event
{
public function sendTestMail()
{
sleep(60);
// the message
$msg = "First line of text\nSecond line of text";
// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);
// send email
mail("myemail@gmail.com","My subject",$msg);
}
}
I want to send the 201 response to Github first, and then execute the sendTestMail
function. Is this possible with Silex events? If yes, how should I set this up?