Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to set responseStatusCode on Response objects #891

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
14 changes: 14 additions & 0 deletions src/Concerns/ResponsableData.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@

trait ResponsableData
{
protected int $_responseStatusCode;

public function toResponse($request)
{
$contextFactory = TransformationContextFactory::create()
Expand Down Expand Up @@ -63,8 +65,20 @@ public function toResponse($request)
);
}

public function setResponseStatusCode(int $responseStatusCode): self
{
$this->_responseStatusCode = $responseStatusCode;

return $this;
}

protected function calculateResponseStatus(Request $request): int
{
$responseStatusCode = $this->_responseStatusCode ?? null;
if ($responseStatusCode !== null) {
return $responseStatusCode;
}

return $request->isMethod(Request::METHOD_POST) ? Response::HTTP_CREATED : Response::HTTP_OK;
}

Expand Down
13 changes: 13 additions & 0 deletions tests/PartialsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1647,3 +1647,16 @@ public static function allowedRequestExcept(): ?array
]);
// Not really a test with expectation, we just want to check we don't end up in an infinite loop
});

it('sets response code', function () {
// Given
$data = new SimpleData("roxanne");
// And
$data->setResponseStatusCode(404);

// When
$jsonResponse = $data->toResponse(request());

// Then
expect($jsonResponse->status())->toBe(404);
});