Passed
Pull Request — master (#75)
by
unknown
10:45
created

RenderDataStream::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Middleware;
6
7
use App\Stream\Data\Converter;
8
use App\Stream\Data\PrintRConverter;
9
use App\Stream\DataStream;
10
use Psr\Container\ContainerInterface;
11
use Psr\Http\Message\ResponseInterface;
12
use Psr\Http\Message\ServerRequestInterface;
13
use Psr\Http\Server\MiddlewareInterface;
14
use Psr\Http\Server\RequestHandlerInterface;
15
16
final class RenderDataStream implements MiddlewareInterface
17
{
18
    private ContainerInterface $container;
19
20
    public function __construct(ContainerInterface $container)
21
    {
22
        $this->container = $container;
23
    }
24
25
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
26
    {
27
        $response = $handler->handle($request);
28
        $stream = $response->getBody();
29
        if (!$stream instanceof DataStream) {
30
            return $response;
31
        }
32
        $converterClass = $stream->getConverter();
33
        if ($converterClass === null) {
34
            # todo: get most relevant format from header
35
            $converterClass = PrintRConverter::class;
36
        }
37
38
        /** @var Converter $converter */
39
        $converter = $this->container->get($converterClass);
40
        $stream->render($converter);
41
42
        return $response->withHeader('Content-Type', $converter::getFormat());
43
    }
44
}
45