Something went wrong. Try again.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374<?php
declare(strict_types=1);
namespace Wotnak\Atproto\Http;
use Psr\Http\Message\ResponseInterface;
/** * Reads a PSR-7 response body without exceeding a caller-provided limit. * * @internal */final class BoundedResponseBody {
/** * Reads the response body incrementally. */ public static function read(ResponseInterface $response, int $maxBytes): string { if ($maxBytes < 1) { throw new \InvalidArgumentException('The response body limit must be positive.'); }
$contentLength = $response->getHeaderLine('Content-Length'); if ($contentLength !== '' && \ctype_digit($contentLength) && (int) $contentLength > $maxBytes) { throw new \LengthException(\sprintf('The response body exceeds the %d-byte limit.', $maxBytes)); }
$stream = $response->getBody(); $body = ''; while (!$stream->eof()) { $remaining = $maxBytes + 1 - \strlen($body); if ($remaining <= 0) { throw new \LengthException(\sprintf('The response body exceeds the %d-byte limit.', $maxBytes)); } $chunk = $stream->read(\min(8_192, $remaining)); if ($chunk === '') { break; } $body .= $chunk; } if (\strlen($body) > $maxBytes) { throw new \LengthException(\sprintf('The response body exceeds the %d-byte limit.', $maxBytes)); } return $body; }
/** * Reads a seekable body from the beginning and restores its position. * * Returns NULL when the body cannot be inspected without consuming it or * when it exceeds the configured limit. */ public static function readPreservingPosition(ResponseInterface $response, int $maxBytes): ?string { $stream = $response->getBody(); if (!$stream->isSeekable()) { return NULL; }
$position = $stream->tell(); $stream->rewind(); try { return self::read($response, $maxBytes); } catch (\LengthException) { return NULL; } finally { $stream->seek($position); } }
}