Passed
Pull Request — master (#75)
by
unknown
13:07
created

RenderDataStream::addHeaders()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 6
rs 10
cc 2
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Middleware;
6
7
use App\Stream\Data\Converter;
8
use App\Stream\DataStream;
9
use App\Stream\GeneratorStream;
10
use App\Stream\Value\DataResponseProvider;
11
use Psr\Container\ContainerInterface;
12
use Psr\Http\Message\ResponseInterface;
13
use Psr\Http\Message\ServerRequestInterface;
14
use Psr\Http\Message\StreamFactoryInterface;
15
use Psr\Http\Message\StreamInterface;
16
use Psr\Http\Server\MiddlewareInterface;
17
use Psr\Http\Server\RequestHandlerInterface;
18
19
final class RenderDataStream implements MiddlewareInterface
20
{
21
    private array $converters = [];
22
    private ContainerInterface $container;
23
    private StreamFactoryInterface $streamFactory;
24
25
    public function __construct(ContainerInterface $container, StreamFactoryInterface $streamFactory)
26
    {
27
        $this->container = $container;
28
        $this->streamFactory = $streamFactory;
29
    }
30
31
    public function defineConverter(string $className, string $format, string $mime = null, bool $deferred = false): self
32
    {
33
        if (!is_subclass_of($className, Converter::class, true)) {
34
            throw new \InvalidArgumentException('Converter class should implement ' . Converter::class);
35
        }
36
        $this->converters[$format] = [$className, $mime, $deferred];
37
        return $this;
38
    }
39
40
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
41
    {
42
        $response = $handler->handle($request);
43
        $stream = $response->getBody();
44
        if (!$stream instanceof DataStream) {
45
            return $response;
46
        }
47
48
        $data = $stream->getData();
49
50
        $format = $this->getRelevantFormat($data->getFormat(), $request);
51
        [$className, $mime, $deferred] = $this->converters[$format];
52
53
        /** @var Converter $converter */
54
        $converter = $this->container->get($className);
55
56
        $response = $response->withBody(
57
            $deferred
58
                ? new GeneratorStream((fn() => yield $this->convertData($data, $converter))())
59
                : $this->convertData($data, $converter)
60
        );
61
62
        if ($mime !== null) {
63
            $response = $response->withHeader('Content-Type', $mime);
64
        }
65
        if ($data->getCode() !== null) {
66
            $response = $response->withStatus($data->getCode());
67
        }
68
        return $this->addHeaders($response, $data->getHeaders());
69
    }
70
71
    private function addHeaders(ResponseInterface $response, array $headers): ResponseInterface
72
    {
73
        foreach ($headers as $header => $value) {
74
            $response = $response->withHeader($header, $value);
75
        }
76
        return $response;
77
    }
78
    private function convertData(DataResponseProvider $data, Converter $converter): StreamInterface
79
    {
80
        $result = $converter->convert($data->getData(), $data->getParams());
81
        return $this->streamFactory->createStream($result);
82
    }
83
    private function getRelevantFormat(?string $format, ServerRequestInterface $request): string
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

83
    private function getRelevantFormat(?string $format, /** @scrutinizer ignore-unused */ ServerRequestInterface $request): string

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
84
    {
85
        if ($format !== null) {
86
            if (!array_key_exists($format, $this->converters)) {
87
                throw new \RuntimeException('Undefined format ' . $format);
88
            }
89
            return $format;
90
        }
91
        # todo: get type from header
92
93
        return array_key_first($this->converters);
94
    }
95
}
96