Completed
Push — master ( 395fb2...b0764c )
by he
10:48 queued 10s
created

TaskQueue::makeMessage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 4
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 8
rs 10
1
<?php
2
3
namespace App\Task;
4
5
use PhpAmqpLib\Connection\AMQPStreamConnection;
6
use PhpAmqpLib\Message\AMQPMessage;
7
8
class TaskQueue
9
{
10
    private $connection;
11
    private $channel;
12
13
    public function __construct()
14
    {
15
        $this->connection = $this->getConnection();
16
        $this->channel = $this->queueChannel();
17
    }
18
19
    public function add(Task $task)
20
    {
21
        $message = $this->makeMessage($task);
22
        $this->channel->basic_publish($message, '', config('rabbitmq.routing_key'));
23
    }
24
25
    public function close()
26
    {
27
        $this->channel->close();
28
        $this->connection->close();
29
    }
30
31
    private function getConnection()
32
    {
33
        return new AMQPStreamConnection(
34
            config('rabbitmq.host'),
35
            config('rabbitmq.port'),
36
            config('rabbitmq.login'),
37
            config('rabbitmq.password'),
38
            config('rabbitmq.vhost')
39
        );
40
    }
41
42
    private function queueChannel()
43
    {
44
        $channel = $this->connection->channel();
45
        $channel->queue_declare(config('rabbitmq.queue'), false, true);
46
47
        return $channel;
48
    }
49
50
    private function makeMessage(Task $task)
51
    {
52
        $content = json_encode($task->asQueueInfo());
53
54
        $message = new AMQPMessage();
55
        $message->setBody($content);
56
57
        return $message;
58
    }
59
}
60