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

ViewListener   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
lcom 1
cbo 5
dl 0
loc 43
rs 10
c 1
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B onPlainResponse() 0 24 6
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