Trying to trim() body after request completed using getEmitter::on()

55 views
Skip to first unread message

Matt

unread,
Jun 6, 2014, 3:52:37 PM6/6/14
to guz...@googlegroups.com
I have an API that is returning XML with a leading carriage return (ASCII 13), so when I run the Response::xml() method I am getting an exception.  Using trim() on the getBody() will fix this so I've been trying to accomplish this using a 'complete' listener on the request.  I've tried both intercept() and setBody(), but I'm not having any luck.  Any help/links would be greatly appreciated.

The approach I'm currently using:

$request = $this->client->createRequest([...]);

$request->getEmitter()->on('complete', function(CompleteEvent $e)
{
    if ($body = $e->getResponse()->getBody())
    {
        try {
            // This is where I am stuck
            $e->intercept(trim($body));  // Fail.
        } catch(/Exception $e)
        {
            // etc.
        }
    }
});

Dowling, Michael

unread,
Jun 6, 2014, 3:54:41 PM6/6/14
to guz...@googlegroups.com
Don’t intercept the request. Simply call setBody() on the response object with the updated body as a GuzzleHttp\Stream\StreamInterface instance.

--Michael

--
You received this message because you are subscribed to the Google Groups "Guzzle - PHP HTTP client and REST client framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to guzzle+un...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Message has been deleted

Matt

unread,
Jun 6, 2014, 6:50:16 PM6/6/14
to guz...@googlegroups.com
Michael,
Thanks for the quick reply.  I obviously needed a lunch break... I was totally missing that GuzzleHttp\Stream\Stream implements GuzzleHttp\Stream\MetadataStreamInterface which extends GuzzleHttp\Stream\StreamInterface, so this works (maybe this will help others trying to get this implemented):

$request = $this->client->createRequest('POST', $yourUrl, ['body' => $yourPostArray]);

$request->getEmitter()->on('complete', function(CompleteEvent $e)
{
  if ($body = $e->getResponse()->getBody())
  {
    // This fn() allows us to easily instantiate \GuzzleHttp\Stream\Stream
    // which also returns an instance of \GuzzleHttp\Stream\StreamInterface
    $trimmedBody = Stream\create(trim($body));

    try {
      $e->getResponse()->setBody($trimmedBody);
    } catch(\Exception $e)
    {
      // Handle your exception
    }
  }
});
Reply all
Reply to author
Forward
0 new messages