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
13 changes: 12 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,16 @@ All notable changes to this package are in this file. The format follows

## [Unreleased]

## [1.2.0] - 2026-11-22

### Changed

- `new Response()` throws a `ValueError` for an array with keys as a body. Such a body went out as
a stream of its values without the keys; for JSON, pass `json_encode($data)`.
- More messages name the way out: a handler that returns a string or an array, `tick()` or
`close()` called from a handler, and the forms of the headers of `Request` and `Response`. A
handler's wrong value is now "returned", a streamed body's wrong chunk "yielded".

## [1.1.1] - 2026-11-22

### Changed
Expand Down Expand Up @@ -51,7 +61,8 @@ response with the FrankenPHP binary, in the form that Chrome receives, and the p
`net/http`. The README states the scope and each deliberate difference. The 0.x releases were
private.

[Unreleased]: https://github.com/sorge-it/http-server/compare/v1.1.1...HEAD
[Unreleased]: https://github.com/sorge-it/http-server/compare/v1.2.0...HEAD
[1.2.0]: https://github.com/sorge-it/http-server/compare/v1.1.1...v1.2.0
[1.1.1]: https://github.com/sorge-it/http-server/compare/v1.1.0...v1.1.1
[1.1.0]: https://github.com/sorge-it/http-server/compare/v1.0.0...v1.1.0
[1.0.0]: https://github.com/sorge-it/http-server/releases/tag/v1.0.0
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -714,7 +714,7 @@ class lives in the namespace `SorgeIt\HttpServer\Internal` and can change in any
| `Body::read(int $length): string` | at most `$length` bytes; see [The request body](#the-request-body) | `ValueError` for a length below 1; `LogicException` when called while the handler runs, from a fiber other than the server's, such as one you started. Once the handler has returned, a read returns `''` |
| `Body::error(): ?string` | null, or the first read error | none |
| `(string) $request->body` | the rest of the body as one string, after the whole body has arrived; check `error()` afterwards. Cast it before you pass it to a function such as `json_decode()`: under `strict_types`, a function that accepts a string rejects the object | `LogicException` as for `read()` |
| `new Response(int $status = 200, array $headers = [], string\|iterable $body = '', ?string $file = null, bool $deleteFile = false)` | a response. `$headers` maps a name to a string or a list of strings. `$body` is a string, or an iterable of strings that the server streams as they come. `$file` sends a file instead of a body. A redirect needs its status, such as `new Response(303, ['Location' => '/done'])`; status 0 sets none, and then a `Location` gives 302, as in PHP. A status outside 100 to 999 becomes 500 | `ValueError` for a header value that is not a string, an integer header key, or a body and a file together |
| `new Response(int $status = 200, array $headers = [], string\|iterable $body = '', ?string $file = null, bool $deleteFile = false)` | a response. `$headers` maps a name to a string or a list of strings. `$body` is a string, or an iterable of strings that the server streams as they come. `$file` sends a file instead of a body. A redirect needs its status, such as `new Response(303, ['Location' => '/done'])`; status 0 sets none, and then a `Location` gives 302, as in PHP. A status outside 100 to 999 becomes 500 | `ValueError` for a header value that is not a string, an integer header key, an array with keys as a body, or a body and a file together |
| `Response::$status`, `$headers`, `$body`, `$file`, `$deleteFile` | the constructor arguments, as public readonly properties, for a test that checks a handler's response | none |
| `new Limits(?int $maxHead = null, ?int $maxBody = null, ?float $idleTimeout = null, ?float $headerTimeout = null)` | the limits and timeouts; name the arguments, such as `new Limits(maxBody: 1024)`. Null selects the default, 0 turns a limit off. Defaults: `maxHead` 16 KiB, `maxBody` none, `idleTimeout` 120 s, `headerTimeout` 10 s; see [Limits and timeouts](#limits-and-timeouts) | `ValueError` for a negative value, or a timeout that is not finite or above 1e8 s |
| `ClosedWithErrors::$errors` | the list of `Throwable`s that no `onError` received; the first is also the previous exception | none |
Expand Down
9 changes: 7 additions & 2 deletions src/Internal/Answer.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,12 @@ private function __construct(public string $head, public array $parts, public bo
public static function check(mixed $response): Response
{
if (! $response instanceof Response) {
throw new UnexpectedValueException('The handler gave '.get_debug_type($response).', not a '.Response::class.'. '.($response === null ? 'Return a Response from every path of the handler.' : 'A handler for a framework converts its response; see "Works with Symfony, Laravel and PSR-15" in the README of sorge-it/http-server.'));
throw new UnexpectedValueException('The handler returned '.get_debug_type($response).', not a '.Response::class.'. '.match (true) {
$response === null => 'Return a Response from every path of the handler.',
is_string($response) => 'Wrap it: new Response(200, [], $body).',
is_array($response) => 'For JSON, return new Response(200, [\'Content-Type\' => \'application/json\'], json_encode($data)).',
default => 'A handler for a framework converts its response; see "Works with Symfony, Laravel and PSR-15" in the README of sorge-it/http-server.',
});
}

if ($response->file !== null && (! is_file($response->file) || ! is_readable($response->file))) {
Expand Down Expand Up @@ -287,7 +292,7 @@ private static function body(iterable $chunks, bool $sent, bool $counted, bool $
private static function chunk(mixed $chunk): string
{
if (! is_string($chunk)) {
throw new UnexpectedValueException('The body gave '.get_debug_type($chunk).', not a string. A streamed body yields strings; for JSON, pass json_encode($data) as the body.');
throw new UnexpectedValueException('The streamed body yielded '.get_debug_type($chunk).', not a string. Yield strings; for JSON, pass json_encode($data) as the body.');
}

return $chunk;
Expand Down
2 changes: 1 addition & 1 deletion src/Internal/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ public function close(): array
// handler suspended itself waits for no read, so it is dropped.
if ($fiber instanceof Fiber && $request instanceof Request && $fiber->isSuspended() && $this->parser->waits()) {
$length = (int) $request->header('Content-Length');
$errors[] = [new LogicException(sprintf('The server closed before the body was complete, with %d of %d bytes read', $length - $this->parser->left(), $length)), $request];
$errors[] = [new LogicException(sprintf('The server closed before the body was complete, with %d of %d bytes read.', $length - $this->parser->left(), $length)), $request];
$this->parser->end('read tcp '.$this->local.'->'.$this->remote.': '.Go::NET_CLOSING);
$fiber->resume();

Expand Down
4 changes: 2 additions & 2 deletions src/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,11 @@ private function fault(array $headers): ?string
$name = (string) $name;

if ($name !== strtolower($name)) {
return 'has the name '.addcslashes($name, "\0..\37\177..\377").', which is not lowercase';
return 'has the name '.addcslashes($name, "\0..\37\177..\377").", which is not lowercase; map each lowercase name to a list of values, such as ['content-type' => ['text/plain']]";
}

if (! is_array($values) || ! array_is_list($values)) {
return 'has values of '.addcslashes($name, "\0..\37\177..\377").' that are not a list';
return 'has values of '.addcslashes($name, "\0..\37\177..\377")." that are not a list; map each lowercase name to a list of values, such as ['content-type' => ['text/plain']]";
}
}

Expand Down
7 changes: 6 additions & 1 deletion src/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ public function __construct(
if ($body !== '' && $file !== null) {
throw new ValueError(sprintf('%s::__construct(): Argument #3 ($body) must be empty when Argument #4 ($file) is given', self::class));
}

// A streamed body would send the values without the keys, as `yesAda` for JSON data.
if (is_array($body) && ! array_is_list($body)) {
throw new ValueError(sprintf('%s::__construct(): Argument #3 ($body) must be a list of strings, not an array with keys; for JSON, pass json_encode($data)', self::class));
}
}

/**
Expand All @@ -50,7 +55,7 @@ private function fault(array $headers): ?string
{
foreach ($headers as $name => $values) {
if (is_int($name)) {
return 'has the key '.$name.', which is not a header name';
return 'has the key '.$name.", which is not a header name; map each name to its value, such as ['X-Foo' => 'bar']";
}

// Not `(array)`: it makes an object the list of its properties.
Expand Down
4 changes: 2 additions & 2 deletions src/Server.php
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ public function tick(float $seconds): void
}

if ($this->busy()) {
throw new LogicException('tick() is already running, or close() resumes a handler. A tick now would answer later requests before the one in progress.');
throw new LogicException('tick() is already running, or close() resumes a handler. A tick now would answer later requests before the one in progress. Return from the handler, and call tick() and close() from the test.');
}

$this->ticking = true;
Expand All @@ -234,7 +234,7 @@ public function tick(float $seconds): void
public function close(): void
{
if ($this->busy()) {
throw new LogicException('close() was called during tick(), or from a handler that close() resumes. A close now would end the request in progress.');
throw new LogicException('close() was called during tick(), or from a handler that close() resumes. A close now would end the request in progress. Return from the handler, and call tick() and close() from the test.');
}

$this->closing = true;
Expand Down
2 changes: 1 addition & 1 deletion tests/Files/FilesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ function lockedFile(string $content): string

expect(feof($client))->toBeTrue()
->and($errors)->toBe([
'LogicException: The server closed before the body was complete, with 3 of 10 bytes read',
'LogicException: The server closed before the body was complete, with 3 of 10 bytes read.',
'RuntimeException: read abc',
]);
} finally {
Expand Down
2 changes: 1 addition & 1 deletion tests/FrankenPhp/FrankenPhpTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ function frankenPhpCases(): array
[$answer, $errors] = withDisplayErrors('0', static fn (): array => failed(static fn (): Response => new Response(body: new ArrayIterator([1])), "GET / HTTP/1.1\r\nHost: a\r\nConnection: close\r\n\r\n"));

expect($answer)->toStartWith("HTTP/1.1 500 Internal Server Error\r\n")->toContain("\r\nContent-Length: 0\r\n")
->and($errors)->toBe(['UnexpectedValueException: The body gave int, not a string. A streamed body yields strings; for JSON, pass json_encode($data) as the body.']);
->and($errors)->toBe(['UnexpectedValueException: The streamed body yielded int, not a string. Yield strings; for JSON, pass json_encode($data) as the body.']);
});

it('gives onError each throwable PHP turns into output, once, and answers the next request', function (string $target, string $start): void {
Expand Down
16 changes: 8 additions & 8 deletions tests/Handler/BodyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@
expect($seen)->toBeArray()
->and($seen[0] ?? null)->toBe('')
->and($seen[1] ?? null)->toMatch('/^read tcp \S+->\S+: use of closed network connection$/')
->and($errors)->toBe(['LogicException: The server closed before the body was complete, with 0 of 5 bytes read']);
->and($errors)->toBe(['LogicException: The server closed before the body was complete, with 0 of 5 bytes read.']);
} finally {
fclose($client);
}
Expand All @@ -145,7 +145,7 @@
$server->close();

expect($calls)->toBe([
['LogicException: The server closed before the body was complete, with 3 of 10 bytes read', '/upload?x=1', [[], []]],
['LogicException: The server closed before the body was complete, with 3 of 10 bytes read.', '/upload?x=1', [[], []]],
['RuntimeException: read abc', '/upload?x=1', [[], []]],
])
->and(converse($server, $client))->toBe("\n<closed>");
Expand All @@ -162,8 +162,8 @@
try {
expect(converse($server, $client, "PUT /upload?x=1 HTTP/1.1\r\nHost: a\r\nContent-Length: 10\r\n\r\nabc"))->toBe('')
->and(closedWithErrors($server))->toBe([
['LogicException: The server closed before the body was complete, with 3 of 10 bytes read', 'RuntimeException: read abc'],
'The server closed with 2 errors that no onError callback received; ClosedWithErrors::$errors lists each one. Fix the handler, or let each request finish before close(). To fail the test at the error instead of at close(), pass onError: static fn (Throwable $e): never => throw $e; a test that expects the error passes an onError that records it. The first, from PUT /upload?x=1: The server closed before the body was complete, with 3 of 10 bytes read',
['LogicException: The server closed before the body was complete, with 3 of 10 bytes read.', 'RuntimeException: read abc'],
'The server closed with 2 errors that no onError callback received; ClosedWithErrors::$errors lists each one. Fix the handler, or let each request finish before close(). To fail the test at the error instead of at close(), pass onError: static fn (Throwable $e): never => throw $e; a test that expects the error passes an onError that records it. The first, from PUT /upload?x=1: The server closed before the body was complete, with 3 of 10 bytes read.',
true,
])
->and($server->streams())->toBe([[], []])
Expand All @@ -182,8 +182,8 @@
try {
expect(converse($server, $client, "POST /early HTTP/1.1\r\nHost: a\r\nContent-Length: 10\r\n\r\nabc"))->toBe('')
->and(closedWithErrors($server))->toBe([
['LogicException: The server closed before the body was complete, with 3 of 10 bytes read'],
'The server closed with 1 error that no onError callback received; ClosedWithErrors::$errors lists each one. Fix the handler, or let each request finish before close(). To fail the test at the error instead of at close(), pass onError: static fn (Throwable $e): never => throw $e; a test that expects the error passes an onError that records it. The first, from POST /early: The server closed before the body was complete, with 3 of 10 bytes read',
['LogicException: The server closed before the body was complete, with 3 of 10 bytes read.'],
'The server closed with 1 error that no onError callback received; ClosedWithErrors::$errors lists each one. Fix the handler, or let each request finish before close(). To fail the test at the error instead of at close(), pass onError: static fn (Throwable $e): never => throw $e; a test that expects the error passes an onError that records it. The first, from POST /early: The server closed before the body was complete, with 3 of 10 bytes read.',
true,
]);
} finally {
Expand All @@ -210,8 +210,8 @@
try {
expect(converse($server, $client, "PUT /upload HTTP/1.1\r\nHost: a\r\nContent-Length: 10\r\n\r\nabc"))->toBe('')
->and(closedWithErrors($server))->toBe([
['LogicException: The server closed before the body was complete, with 3 of 10 bytes read'],
'The server closed with 1 error that no onError callback received; ClosedWithErrors::$errors lists each one. Fix the handler, or let each request finish before close(). To fail the test at the error instead of at close(), pass onError: static fn (Throwable $e): never => throw $e; a test that expects the error passes an onError that records it. The first, from PUT /upload: The server closed before the body was complete, with 3 of 10 bytes read',
['LogicException: The server closed before the body was complete, with 3 of 10 bytes read.'],
'The server closed with 1 error that no onError callback received; ClosedWithErrors::$errors lists each one. Fix the handler, or let each request finish before close(). To fail the test at the error instead of at close(), pass onError: static fn (Throwable $e): never => throw $e; a test that expects the error passes an onError that records it. The first, from PUT /upload: The server closed before the body was complete, with 3 of 10 bytes read.',
true,
])
->and($caught)->toStartWith('LogicException: '.$message);
Expand Down
Loading
Loading