Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
20 / 20 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
| ChainedStreamFactory | |
100.00% |
20 / 20 |
|
100.00% |
3 / 3 |
5 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| create | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
1 | |||
| createStream | |
100.00% |
12 / 12 |
|
100.00% |
1 / 1 |
3 | |||
| 1 | <?php |
| 2 | namespace Apie\Common\StreamFactory; |
| 3 | |
| 4 | use Apie\Core\Actions\ActionResponse; |
| 5 | use Apie\Serializer\EncoderHashmap; |
| 6 | use Nyholm\Psr7\Factory\Psr17Factory; |
| 7 | use Psr\Http\Message\ResponseInterface; |
| 8 | use Psr\Http\Message\ServerRequestInterface; |
| 9 | |
| 10 | class ChainedStreamFactory implements StreamFactoryInterface |
| 11 | { |
| 12 | /** |
| 13 | * @var array<int, StreamFactoryInterface> $factories |
| 14 | */ |
| 15 | private array $factories; |
| 16 | |
| 17 | public function __construct( |
| 18 | private readonly EncoderHashmap $encoderHashmap, |
| 19 | StreamFactoryInterface... $factories |
| 20 | ) { |
| 21 | $this->factories = $factories; |
| 22 | } |
| 23 | |
| 24 | /** |
| 25 | * @param iterable<int, StreamFactoryInterface> $additionalFactories |
| 26 | */ |
| 27 | public static function create( |
| 28 | ?EncoderHashmap $encoderHashmap = null, |
| 29 | iterable $additionalFactories = [] |
| 30 | ): self { |
| 31 | $encoderHashmap ??= EncoderHashmap::create(); |
| 32 | return new self( |
| 33 | $encoderHashmap, |
| 34 | new EmptyResponseOn204Factory(), |
| 35 | new PsrReponseFactory($encoderHashmap), |
| 36 | ...$additionalFactories |
| 37 | ); |
| 38 | } |
| 39 | |
| 40 | public function createStream( |
| 41 | ServerRequestInterface $request, |
| 42 | ActionResponse $output |
| 43 | ): ResponseInterface { |
| 44 | foreach ($this->factories as $factory) { |
| 45 | $result = $factory->createStream($request, $output); |
| 46 | if ($result) { |
| 47 | return $result; |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | $contentType = $this->encoderHashmap->getAcceptedContentTypeForRequest($request); |
| 52 | $encoder = $this->encoderHashmap[$contentType]; |
| 53 | |
| 54 | $psr17Factory = new Psr17Factory(); |
| 55 | $nativeData = $output->getResultAsNativeData(); |
| 56 | $stream = $psr17Factory->createStream($encoder->encode($nativeData)); |
| 57 | |
| 58 | return $response = $psr17Factory->createResponse($output->getStatusCode()) |
| 59 | ->withBody($stream) |
| 60 | ->withHeader('Content-Type', $contentType); |
| 61 | } |
| 62 | } |