Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
68.00% |
17 / 25 |
|
50.00% |
1 / 2 |
CRAP | |
0.00% |
0 / 1 |
| PsrReponseFactory | |
68.00% |
17 / 25 |
|
50.00% |
1 / 2 |
10.10 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| createStream | |
66.67% |
16 / 24 |
|
0.00% |
0 / 1 |
8.81 | |||
| 1 | <?php |
| 2 | namespace Apie\Common\StreamFactory; |
| 3 | |
| 4 | use Apie\Core\Actions\ActionResponse; |
| 5 | use Apie\Core\FileStorage\StoredFile; |
| 6 | use Apie\Serializer\EncoderHashmap; |
| 7 | use Nyholm\Psr7\Factory\Psr17Factory; |
| 8 | use Psr\Http\Message\ResponseInterface; |
| 9 | use Psr\Http\Message\ServerRequestInterface; |
| 10 | use Psr\Http\Message\StreamInterface; |
| 11 | use Psr\Http\Message\UploadedFileInterface; |
| 12 | |
| 13 | class PsrReponseFactory implements StreamFactoryInterface |
| 14 | { |
| 15 | public function __construct( |
| 16 | private readonly EncoderHashmap $encoderHashmap |
| 17 | ) { |
| 18 | } |
| 19 | |
| 20 | public function createStream( |
| 21 | ServerRequestInterface $request, |
| 22 | ActionResponse $output |
| 23 | ): ?ResponseInterface { |
| 24 | if ($output->result instanceof ResponseInterface) { |
| 25 | return $output->result; |
| 26 | } |
| 27 | if ($output->result instanceof StreamInterface) { |
| 28 | $contentType = $this->encoderHashmap->getAcceptedContentTypeForRequest($request, 'application/octet-stream'); |
| 29 | $statusCode = $output->getStatusCode(); |
| 30 | if ($statusCode >= 300) { |
| 31 | $contentType = 'application/octet-stream'; |
| 32 | } |
| 33 | $psr17Factory = new Psr17Factory(); |
| 34 | return $psr17Factory->createResponse($statusCode) |
| 35 | ->withAddedHeader('Content-Type', $contentType) |
| 36 | ->withBody($output->result); |
| 37 | } |
| 38 | if ($output->result instanceof UploadedFileInterface) { |
| 39 | $stream = $output->result->getStream(); |
| 40 | $contentType = $output->result->getClientMediaType(); |
| 41 | if ($output->result instanceof StoredFile) { |
| 42 | $contentType = $output->result->getServerMimeType(); |
| 43 | } |
| 44 | $contentType ??= 'application/octet-stream'; |
| 45 | |
| 46 | if ($stream->isSeekable()) { |
| 47 | $stream->rewind(); |
| 48 | } |
| 49 | |
| 50 | $psr17Factory = new Psr17Factory(); |
| 51 | return $psr17Factory->createResponse($output->getStatusCode()) |
| 52 | ->withAddedHeader('Content-Type', $contentType) |
| 53 | ->withBody($stream); |
| 54 | } |
| 55 | |
| 56 | return null; |
| 57 | } |
| 58 | } |