Completed
Push — master ( bfb363...ace2c0 )
by Daniel
03:56
created

RpcClient::getConnectionManager()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace Cmobi\RabbitmqBundle\Transport\Rpc;
4
5
use Cmobi\RabbitmqBundle\Connection\CmobiAMQPChannel;
6
use Cmobi\RabbitmqBundle\Connection\CmobiAMQPConnection;
7
use Cmobi\RabbitmqBundle\Connection\ConnectionManager;
8
use Cmobi\RabbitmqBundle\Queue\CmobiAMQPMessage;
9
use Cmobi\RabbitmqBundle\Queue\QueueProducerInterface;
10
use Cmobi\RabbitmqBundle\Transport\Exception\QueueNotFoundException;
11
use PhpAmqpLib\Message\AMQPMessage;
12
use Ramsey\Uuid\Uuid;
13
14
class RpcClient implements QueueProducerInterface
15
{
16
    private $connectionName;
17
    private $connectionManager;
18
    private $fromName;
19
    private $queueName;
20
    private $response;
21
    private $logOutput;
22
    private $correlationId;
23
    private $callbackQueue;
24
25
    public function __construct($queueName, ConnectionManager $manager, $fromName, $connectionName = 'default')
26
    {
27
        $this->connectionName = $connectionName;
28
        $this->queueName = $queueName;
29
        $this->fromName = $fromName;
30
        $this->connectionManager = $manager;
31
        $this->logOutput = fopen('php://stdout', 'a+');
32
        //$this->connection = $this->connectionManager->getConnection();
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
33
    }
34
35
    /**
36
     * @param AMQPMessage $rep
37
     */
38
    public function onResponse(AMQPMessage $rep)
39
    {
40
        if ($rep->get('correlation_id') === $this->correlationId) {
41
            $this->response = $rep->getBody();
42
        }
43
    }
44
45
    /**
46
     * @param $data
47
     * @param int $expire
48
     * @param int $priority
49
     * @throws QueueNotFoundException
50
     * @throws \Cmobi\RabbitmqBundle\Connection\Exception\NotFoundAMQPConnectionFactoryException
51
     */
52
    public function publish($data, $expire = self::DEFAULT_TTL, $priority = self::PRIORITY_LOW)
53
    {
54
        $this->response = null;
55
        $connection = $this->connectionManager->getConnection($this->connectionName);
56
        $channel = $connection->channel();
57
58
        if (! $this->queueHasExists($channel)) {
59
            throw new QueueNotFoundException("Queue $this->queueName not declared.");
60
        }
61
        $this->correlationId = $this->generateCorrelationId();
62
        $queueBag = new RpcQueueBag(
63
            sprintf(
64
                'callback_to_%s_from_%s_%s',
65
                $this->getQueueName(),
66
                $this->getFromName(),
67
                Uuid::uuid4()->toString()
68
                . microtime()
69
            )
70
        );
71
        $queueBag->setArguments([
72
            'x-expires' => ['I', $expire],
73
        ]);
74
        list($callbackQueue) = $channel->queueDeclare($queueBag->getQueueDeclare());
75
        $this->callbackQueue = $callbackQueue;
76
        $consumeQueueBag = new RpcQueueBag($callbackQueue);
77
78
        $channel->basicConsume(
79
            $consumeQueueBag->getQueueConsume(),
80
            [$this, 'onResponse']
81
        );
82
        $msg = new CmobiAMQPMessage(
83
            (string) $data,
84
            [
85
                'correlation_id' => $this->correlationId,
86
                'reply_to' => $this->callbackQueue,
87
                'priority' => $priority,
88
            ]
89
        );
90
        $channel->basic_publish($msg, '', $this->getQueueName());
91
92
        while (! $this->response) {
93
            $channel->wait(null, 0, ($expire / 1000));
0 ignored issues
show
Documentation introduced by
0 is of type integer, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
94
        }
95
        $channel->close();
96
        $connection->close();
97
    }
98
99
    /**
100
     * @return bool
101
     */
102
    /**
103
     * @param CmobiAMQPChannel $channel
104
     * @return bool
105
     */
106
    public function queueHasExists(CmobiAMQPChannel $channel)
107
    {
108
        try {
109
            $channel->queue_declare($this->queueName, true);
110
        } catch (\Exception $e) {
111
            return false;
112
        }
113
114
        return true;
115
    }
116
117
    /**
118
     * @return string
119
     */
120
    public function getQueueName()
121
    {
122
        return $this->queueName;
123
    }
124
125
    /**
126
     * @return string
127
     */
128
    public function getFromName()
129
    {
130
        return $this->fromName;
131
    }
132
133
    /**
134
     * @todo unecessary method set, its only exists to run tests whitout stay jailed in infinite while waiting response.
135
     *
136
     * @param $content
137
     */
138
    public function setResponse($content)
139
    {
140
        $this->response = $content;
141
    }
142
143
    /**
144
     * @return string
145
     */
146
    public function getResponse()
147
    {
148
        return $this->response;
149
    }
150
151
    /** @return string */
152
    public function generateCorrelationId()
153
    {
154
        return uniqid($this->getQueueName()) . Uuid::uuid4()->toString() . microtime();
155
    }
156
157
    /**
158
     * @return string
159
     */
160
    public function getCurrentCorrelationId()
161
    {
162
        return $this->correlationId;
163
    }
164
165
    /**
166
     * @return string
167
     */
168
    public function getExchange()
169
    {
170
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type declared by the interface Cmobi\RabbitmqBundle\Que...rInterface::getExchange of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
171
    }
172
173
    /**
174
     * @return string
175
     */
176
    public function getExchangeType()
177
    {
178
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type declared by the interface Cmobi\RabbitmqBundle\Que...erface::getExchangeType of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
179
    }
180
181
    /**
182
     * @return ConnectionManager
183
     */
184
    public function getConnectionManager()
185
    {
186
        return $this->connectionManager;
187
    }
188
}
189