Skip to main content

HTTP responses

Http\AvatarResponder turns a GeneratedAvatar into an HTTP response. It is kept separate from GeneratedAvatar so the avatar object stays free of transport concerns.

The responder is Laravel-aware: when Illuminate\Http\Response exists it returns an Illuminate response; otherwise it sends headers and writes the body to the output buffer directly.

use Renfordt\AvatarSmithy\Http\AvatarResponder;

$avatar = Avatar::for($user)
->try('gravatar')
->fallbackTo('initials')
->generate();

return (new AvatarResponder($avatar))->toResponse();

Methods

toResponse(): mixed

Sends the avatar with its content type and a 200 status. Returns an Illuminate\Http\Response under Laravel, or null after writing to the output buffer otherwise.

download(string $filename): mixed

Sends the avatar as an attachment with a Content-Disposition header. The filename is sanitized against header injection: path components and ASCII control characters (including CR/LF) are stripped, and an RFC 5987 filename* form is emitted alongside the ASCII fallback so UTF-8 filenames are preserved.

return (new AvatarResponder($avatar->toPng()))->download('avatar.png');

stream(int $chunkSize = 8192, bool $sendHeaders = true): void

Writes the content to the output buffer in chunks, flushing after each. Chunking controls flush cadence; the full content is already in memory, so this does not reduce memory use.

Laravel example

use Renfordt\AvatarSmithy\Avatar;
use Renfordt\AvatarSmithy\Http\AvatarResponder;

Route::get('/avatar/{user}', function (User $user) {
$avatar = Avatar::for($user)
->try('gravatar')
->fallbackTo('initials')
->size(400)
->generate();

return (new AvatarResponder($avatar))->toResponse();
});
<img src="{{ route('avatar', $user) }}" alt="{{ $user->name }}">

PSR-7 frameworks

For a PSR-7 response, build one from the avatar's content and content type using your framework's PSR-17 factory:

$response = $responseFactory
->createResponse(200)
->withHeader('Content-Type', $avatar->getContentType());

$response->getBody()->write($avatar->getContent());