Directly modify the payload of the PendingRequest class in Laravel's Http client?

Viewed 953

I am trying to build a Laravel package to extend the flexibility of Laravel's Http client and I'm running into some trouble.

Quite simply, I would like to modify the payload of POST/PUT/PATCH/DELETE requests. I see that the class is Macroable, so I've added some support macros to set the correct headers but when it comes to transforming the array into a string (XML) I'm at a loss for how to intercept the the payload. Here is a sample of the code I'm writing:

/**
 * Bootstrap Illuminate\Http\Client\PendingRequest with xml methods.
 *
 */
public function registerRequestMacros(): void
{
    $rootElement = 'request';

    PendingRequest::macro('acceptXml', function () {
        return $this->accept('application/xml');
    });

    PendingRequest::macro('convertDataToXml', function () use ($rootElement) {
        // Transform the data to xml if it is an array
        $this->beforeSending(function (\Illuminate\Http\Client\Request $request, array $options) use ($rootElement) {
            if (is_array($options[$this->bodyFormat]) && !empty($options[$this->bodyFormat])) {
                $options[$this->bodyFormat] = ArrayToXml::convert($options[$this->bodyFormat], $rootElement);
            }
        });
    });

    PendingRequest::macro('asXml', function () {
        $this->convertDataToXml();
        return $this->bodyFormat('xml')->contentType('application/xml');
    });
}

You can see that I'm attempting to utilize the beforeSending() method, and at first glance it appears to be altering the array into valid XML, but when I run the actual class it doesn't change anything. Is it possible to alter the request payload without having to create my own PendingRequest class and having my package make Laravel inject my class, which extends the base class, just to alter the request payload? I really don't want to do that, if at all possible.

Is there a way to transform $this->bodyFormat into xml before the request is sent off? I know that Guzzle will respect an xml string in the request in the given format that the PendingRequest class is sending it.

0 Answers
Related