Skip to content

Commit

Permalink
Adds Request::getPsrRequest() (#725)
Browse files Browse the repository at this point in the history
* Adds `Request::getPsrRequest()`

* test: Add test for `getPsrRequest()` method in HttpServerRequest

---------

Co-authored-by: Deeka Wong <[email protected]>
  • Loading branch information
huangdijia and huangdijia authored Oct 17, 2024
1 parent 1e539fb commit 3cfd616
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ public function getHttpHost(): string;

public function getPort(): int;

public function getPsrRequest(): ?ServerRequestInterface;

public function getScheme(): string;

public function isSecure(): bool;
Expand Down
6 changes: 6 additions & 0 deletions src/macros/src/RequestMixin.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Carbon\Carbon;
use Hyperf\Collection\Arr;
use Hyperf\Context\Context;
use Hyperf\Context\RequestContext;
use Hyperf\HttpMessage\Server\Request as ServerRequest;
use Hyperf\HttpServer\Request;
use Hyperf\Stringable\Str;
Expand Down Expand Up @@ -170,6 +171,11 @@ public function getHttpHost()
return fn () => $this->getHost() . ':' . $this->getPort();
}

public function getPsrRequest()
{
return fn () => RequestContext::getOrNull();
}

public function getPort()
{
return function () {
Expand Down
15 changes: 12 additions & 3 deletions tests/Macros/HttpServerRequestTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
expect($request->isEmptyString('id'))->toBeFalse();
});

test('test get host', function () {
test('test getHost', function () {
$request = new Request();

$host = 'foo.com';
Expand Down Expand Up @@ -75,7 +75,7 @@
expect($request->getHost())->toBe($host);
});

test('test get port', function () {
test('test getPort', function () {
$request = new Request();

$port = 80;
Expand Down Expand Up @@ -113,7 +113,7 @@
expect($request->getPort())->toBe($port);
});

test('test get scheme', function () {
test('test getScheme', function () {
$request = new Request();

$psrRequest = m::mock(ServerRequestPlusInterface::class, function ($mock) {
Expand Down Expand Up @@ -168,3 +168,12 @@
expect($request->getMethod())->toBe('POST');
expect($request->getUri()->getPath())->toBe('/foo');
});

test('test getPsrRequest', function () {
$request = new Request();
expect($request->getPsrRequest())->toBeNull();

$psrRequest = Request::fake();
Context::set(ServerRequestInterface::class, $psrRequest);
expect($request->getPsrRequest())->toBe($psrRequest);
});

0 comments on commit 3cfd616

Please sign in to comment.