Test Failed
Pull Request — master (#11)
by Pavel
23:42
created

ViewListener::onPlainResponse()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 24
rs 8.5125
c 1
b 0
f 0
cc 6
eloc 12
nc 4
nop 1
1
<?php
2
3
namespace Bankiru\Api\JsonRpc\Listener;
4
5
use Bankiru\Api\JsonRpc\NormalizerInterface;
6
use Bankiru\Api\JsonRpc\Specification\JsonRpcResponse;
7
use Bankiru\Api\JsonRpc\Specification\RichJsonRpcRequest;
8
use Bankiru\Api\Rpc\Event\ViewEvent;
9
use ScayTrase\Api\JsonRpc\JsonRpcResponseInterface;
10
11
final class ViewListener
12
{
13
    /**
14
     * @var NormalizerInterface
15
     */
16
    private $normalizer;
17
18
    /**
19
     * ViewListener constructor.
20
     *
21
     * @param NormalizerInterface $normalizer
22
     */
23
    public function __construct(NormalizerInterface $normalizer)
24
    {
25
        $this->normalizer = $normalizer;
26
    }
27
28
    public function onPlainResponse(ViewEvent $event)
29
    {
30
        $request  = $event->getRequest();
31
        $response = $event->getResponse();
32
33
        // No need to perform JSON-RPC serialization here
34
        if (!$request instanceof RichJsonRpcRequest || $request->isNotification()) {
35
            return;
36
        }
37
38
        // Response is already properly formatted
39
        if ($response instanceof JsonRpcResponseInterface) {
40
            return;
41
        }
42
43
        $content = $event->getResponse();
44
        if (!is_scalar($content) && null !== $content) {
45
            $content = $this->normalizer->normalize($content, $request->getAttributes()->get('_context'));
46
        }
47
48
        $response = new JsonRpcResponse($request->getId(), $content);
49
50
        $event->setResponse($response);
51
    }
52
53
}
54