Passed
Pull Request — master (#233)
by Alexander
05:18 queued 57s
created

WebResponseFormatter   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 24
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 24
rs 10
c 0
b 0
f 0
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A process() 0 12 4
1
<?php
2
3
namespace Yiisoft\Yii\Web\Middleware;
4
5
use Psr\Http\Message\ResponseInterface;
6
use Psr\Http\Message\ServerRequestInterface;
7
use Psr\Http\Server\MiddlewareInterface;
8
use Psr\Http\Server\RequestHandlerInterface;
9
use Yiisoft\Yii\Web\Formatter\ResponseFormatterInterface;
10
use Yiisoft\Yii\Web\WebResponse;
11
12
class WebResponseFormatter implements MiddlewareInterface
13
{
14
    private ResponseFormatterInterface $responseFormatter;
15
16
    private bool $forceRender;
17
18
    public function __construct(ResponseFormatterInterface $responseFormatter, bool $forceRender = false)
19
    {
20
        $this->responseFormatter = $responseFormatter;
21
        $this->forceRender = $forceRender;
22
    }
23
24
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
25
    {
26
        $response = $handler->handle($request);
27
        if ($response instanceof WebResponse && !$response->hasResponseFormatter()) {
28
            if ($this->forceRender) {
29
                $response = $this->responseFormatter->format($response);
30
            } else {
31
                $response = $response->withResponseFormatter($this->responseFormatter);
32
            }
33
        }
34
35
        return $response;
36
    }
37
}
38