diff --git a/flight/net/Request.php b/flight/net/Request.php index aceda0b..8a40a50 100644 --- a/flight/net/Request.php +++ b/flight/net/Request.php @@ -129,10 +129,23 @@ final class Request */ public string $host; + /** + * Stream path for where to pull the request body from + * + * @var string + */ + private string $stream_path = 'php://input'; + + /** + * @var string Raw HTTP request body + */ + public string $body = ''; + /** * Constructor. * * @param array $config Request configuration + * @param string */ public function __construct($config = array()) { @@ -196,7 +209,7 @@ final class Request // Check for JSON input if (0 === strpos($this->type, 'application/json')) { - $body = self::getBody(); + $body = $this->getBody(); if ('' !== $body && null !== $body) { $data = json_decode($body, true); if (is_array($data)) { @@ -213,20 +226,22 @@ final class Request * * @return string Raw HTTP request body */ - public static function getBody(): ?string + public function getBody(): ?string { - static $body; + $body = $this->body; - if (null !== $body) { + if ('' !== $body) { return $body; } $method = self::getMethod(); if ('POST' === $method || 'PUT' === $method || 'DELETE' === $method || 'PATCH' === $method) { - $body = file_get_contents('php://input'); + $body = file_get_contents($this->stream_path); } + $this->body = $body; + return $body; } diff --git a/tests/RequestTest.php b/tests/RequestTest.php index a2e4eec..aea65ee 100644 --- a/tests/RequestTest.php +++ b/tests/RequestTest.php @@ -165,4 +165,32 @@ class RequestTest extends PHPUnit\Framework\TestCase ]); $this->assertEquals('/flightphp', $request->url); } + + public function testInitNoUrl() { + $request = new Request([ + 'url' => '', + 'base' => '/vagrant/public', + 'type' => '' + ]); + $this->assertEquals('/', $request->url); + } + + public function testInitWithJsonBody() { + // create dummy file to pull request body from + $tmpfile = tmpfile(); + $stream_path = stream_get_meta_data($tmpfile)['uri']; + file_put_contents($stream_path, '{"foo":"bar"}'); + $_SERVER['REQUEST_METHOD'] = 'POST'; + $request = new Request([ + 'url' => '/something/fancy', + 'base' => '/vagrant/public', + 'type' => 'application/json', + 'length' => 13, + 'data' => new Collection(), + 'query' => new Collection(), + 'stream_path' => $stream_path + ]); + $this->assertEquals([ 'foo' => 'bar' ], $request->data->getData()); + $this->assertEquals('{"foo":"bar"}', $request->getBody()); + } } diff --git a/tests/RouterTest.php b/tests/RouterTest.php index db02757..b6b8a6a 100644 --- a/tests/RouterTest.php +++ b/tests/RouterTest.php @@ -105,6 +105,16 @@ class RouterTest extends PHPUnit\Framework\TestCase $this->check('OK'); } + // Simple path with trailing slash + // Simple path + public function testPathRouteTrailingSlash() + { + $this->router->map('/path/', [$this, 'ok']); + $this->request->url = '/path'; + + $this->check('OK'); + } + // POST route public function testPostRoute() {