Completed
Push — master ( f94c4d...339dcc )
by Daniel
03:14
created

Handler::handle()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 1 Features 2
Metric Value
c 5
b 1
f 2
dl 0
loc 22
rs 9.2
cc 3
eloc 17
nc 3
nop 2
1
<?php
2
3
namespace Cmobi\RabbitmqBundle\Rpc;
4
5
use Cmobi\RabbitmqBundle\Rpc\Controller\RpcControllerResolver;
6
use Cmobi\RabbitmqBundle\Rpc\Exception\InvalidBodyAMQPMessageException;
7
use Cmobi\RabbitmqBundle\Rpc\Exception\JsonRpcInternalErrorException;
8
use Cmobi\RabbitmqBundle\Rpc\Request\RpcRequestCollectionInterface;
9
use Cmobi\RabbitmqBundle\Rpc\Response\JsonRpcResponse;
10
use Cmobi\RabbitmqBundle\Rpc\Response\JsonRpcResponseCollection;
11
use Cmobi\RabbitmqBundle\Rpc\Response\RpcResponseCollectionInterface;
12
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
13
14
class Handler
15
{
16
    use ContainerAwareTrait;
17
18
    private $resolver;
19
20
    public function __construct()
21
    {
22
        $this->resolver = new RpcControllerResolver();
23
    }
24
25
    public function handle(RpcRequestCollectionInterface $requests, RpcResponseCollectionInterface $responses)
26
    {
27
        foreach ($requests as $request) {
0 ignored issues
show
Bug introduced by
The expression $requests of type object<Cmobi\RabbitmqBun...estCollectionInterface> is not traversable.
Loading history...
28
            $controller = $this->getResolver()->getController($request);
29
            $arguments = $this->getResolver()->getArguments($request, $controller);
30
            $response = call_user_func_array($controller, $arguments);
31
32
            if (!is_array($response)) {
33
                $previous = new InvalidBodyAMQPMessageException('Invalid Body: Content should be array.');
34
                $exception = new JsonRpcInternalErrorException($previous);
35
                $error = new JsonRpcResponse([], $exception);
36
                $error->setId($request->id);
37
                $error->setMethod($request->method);
38
                $responses->add($error);
39
            } else {
40
                $response = new JsonRpcResponse($response);
41
                $response->setId($request->id);
42
                $response->setMethod($request->method);
43
                $responses->add($response);
44
            }
45
        }
46
    }
47
48
    /**
49
     * @return RpcControllerResolver
50
     */
51
    public function getResolver()
52
    {
53
        return $this->resolver;
54
    }
55
56
    /**
57
     * @return \Symfony\Component\DependencyInjection\ContainerInterface
58
     */
59
    public function getContainer()
60
    {
61
        return $this->container;
62
    }
63
}