From c494851dac8771dcd612e11ffc3de8201b601e22 Mon Sep 17 00:00:00 2001 From: Brian Stoop Date: Thu, 25 Apr 2024 18:36:22 +0200 Subject: [PATCH] Requests: Add "multiple.request.before_request_multiple" hook --- docs/hooks.md | 7 +++++++ src/Requests.php | 4 ++++ tests/RequestsTest.php | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+) diff --git a/docs/hooks.md b/docs/hooks.md index f8414e4ad..9b33b2200 100644 --- a/docs/hooks.md +++ b/docs/hooks.md @@ -53,6 +53,13 @@ Available Hooks Parameters: `WpOrg\Requests\Response &$return`, `array &$req_headers`, `array &$req_data`, `array &$options` +* **`multiple.request.before_request_multiple`** + + Alter the request before it is sent to the transport. + + Parameters: `string &$url`, `array &$headers`, `array|null &$data`, + `string &$type`, `array &$options, string|int $id` + * **`multiple.request.complete`** Alter the response for an individual request in a multi-request. diff --git a/src/Requests.php b/src/Requests.php index 6d97fddce..754745d3d 100644 --- a/src/Requests.php +++ b/src/Requests.php @@ -586,6 +586,10 @@ public static function request_multiple($requests, $options = []) { $request['options']['hooks']->register('multiple.request.complete', $request['options']['complete']); } } + + if (!empty($options['hooks'])) { + $options['hooks']->dispatch('multiple.request.before_request_multiple', [$request['url'], $request['headers'], $request['data'], $request['type'], $request['options'], $id]); + } } unset($request); diff --git a/tests/RequestsTest.php b/tests/RequestsTest.php index c24bc39f1..856c3d514 100644 --- a/tests/RequestsTest.php +++ b/tests/RequestsTest.php @@ -153,6 +153,43 @@ public function testRequestMultipleInvalidOptions($input) { Requests::request_multiple([], $input); } + public function testRequestMultipleTriggersBeforeRequestMultipleCallback() { + $mock = $this->getMockBuilder(stdClass::class)->setMethods(['before_request_multiple'])->getMock(); + $mock->expects($this->exactly(2))->method('before_request_multiple'); + $hooks = new Hooks(); + $hooks->register('multiple.request.before_request_multiple', [ $mock, 'before_request_multiple' ]); + + $transport = new TransportMock(); + + $options = [ + 'hooks' => $hooks, + 'transport' => $transport, + ]; + + $requests = [ + 'test' => [ + 'url' => 'http://example.com/', + 'options' => [ + 'mock.code' => 200, + 'mock.chunked' => false, + 'mock.body' => 'Test Body', + 'mock.raw_headers' => '', + ], + ], + 'test2' => [ + 'url' => 'http://example.com/', + 'options' => [ + 'mock.code' => 200, + 'mock.chunked' => false, + 'mock.body' => 'Test Body', + 'mock.raw_headers' => '', + ], + ], + ]; + + Requests::request_multiple($requests, $options); + } + /** * Data Provider. *