diff --git a/src/Model/ApiResourceBase.php b/src/Model/ApiResourceBase.php index a339b10..1aa5f20 100644 --- a/src/Model/ApiResourceBase.php +++ b/src/Model/ApiResourceBase.php @@ -303,9 +303,11 @@ public function runOperation(string $op, string $method = 'POST', array $body = if (! $this->operationAvailable($op, true)) { throw new OperationUnavailableException("Operation not available: {$op}"); } + // Send an empty JSON object rather than no body, for POST and PATCH requests. + $encoded = $body ? \json_encode($body) : (in_array(strtoupper($method), ['POST', 'PATCH'], true) ? '{}' : null); $request = new Request($method, $this->getLink("#{$op}"), [ 'Content-Type' => 'application/json', - ], $body ? \json_encode($body) : null); + ], $encoded); $data = $this->send($request, $this->client); return new Result($data, $this->baseUrl, $this->client, static::class); diff --git a/tests/ResourceTest.php b/tests/ResourceTest.php index df58f5f..85c5b67 100644 --- a/tests/ResourceTest.php +++ b/tests/ResourceTest.php @@ -4,6 +4,12 @@ namespace Platformsh\Client\Tests; +use GuzzleHttp\Client; +use GuzzleHttp\Handler\MockHandler; +use GuzzleHttp\HandlerStack; +use GuzzleHttp\Middleware; +use GuzzleHttp\Psr7\Response; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Platformsh\Client\Model\ApiResourceBase; @@ -95,4 +101,52 @@ public function testInvalidPropertiesBlockUpdate() 'testProperty' => 2, ]); } + + public static function operationBodyProvider(): array + { + return [ + 'POST without a body' => ['POST', [], '{}'], + 'POST with a body' => ['post', [ + 'foo' => 'bar', + ], '{"foo":"bar"}'], + 'lowercase POST' => ['post', [], '{}'], + 'PATCH without a body' => ['PATCH', [], '{}'], + 'PUT without a body' => ['PUT', [], ''], + 'GET' => ['GET', [], ''], + 'lowercase GET' => ['get', [], ''], + 'GET with a body' => ['GET', [ + 'foo' => 'bar', + ], '{"foo":"bar"}'], + 'DELETE' => ['DELETE', [], ''], + ]; + } + + /** + * Test the request body sent by Resource::runOperation(). + */ + #[DataProvider('operationBodyProvider')] + public function testRunOperationBody(string $method, array $body, string $expected): void + { + $history = []; + $stack = HandlerStack::create(new MockHandler([new Response(200)])); + $stack->push(Middleware::history($history)); + $resource = new MockApiResource([ + '_links' => [ + 'self' => [ + 'href' => 'https://example.com/resources/test-id', + ], + '#operate' => [ + 'href' => '/resources/test-id/operate', + ], + ], + ], 'https://example.com/', new Client([ + 'handler' => $stack, + ])); + + $resource->runOperation('operate', $method, $body); + + $this->assertCount(1, $history); + $this->assertSame(strtoupper($method), $history[0]['request']->getMethod()); + $this->assertSame($expected, (string) $history[0]['request']->getBody()); + } }