Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/Model/ApiResourceBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
54 changes: 54 additions & 0 deletions tests/ResourceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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());
}
}
Loading