TaskQueue   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 25
c 1
b 0
f 1
dl 0
loc 54
rs 10
wmc 7

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getConnection() 0 8 1
A makeMessage() 0 8 1
A done() 0 4 1
A queueChannel() 0 6 1
A add() 0 7 2
1
<?php
2
3
namespace App\Task;
4
5
use PhpAmqpLib\Connection\AMQPStreamConnection;
6
use PhpAmqpLib\Exception\AMQPRuntimeException;
7
use PhpAmqpLib\Message\AMQPMessage;
8
9
class TaskQueue
10
{
11
    private $connection;
12
    private $channel;
13
14
    public function __construct()
15
    {
16
        $this->connection = $this->getConnection();
17
        $this->channel = $this->queueChannel();
18
    }
19
20
    private function getConnection()
21
    {
22
        return new AMQPStreamConnection(
23
            config('rabbitmq.host'),
24
            config('rabbitmq.port'),
25
            config('rabbitmq.login'),
26
            config('rabbitmq.password'),
27
            config('rabbitmq.vhost')
28
        );
29
    }
30
31
    private function queueChannel()
32
    {
33
        $channel = $this->connection->channel();
34
        $channel->queue_declare(config('rabbitmq.queue'), false, true);
35
36
        return $channel;
37
    }
38
39
    public function add(Task $task)
40
    {
41
        try {
42
            $message = $this->makeMessage($task);
43
            $this->channel->basic_publish($message, '', config('rabbitmq.routing_key'));
44
        } catch (AMQPRuntimeException $e) {
45
            app('log')->error('add task queue failed!', ['message' => $e->getMessage()]);
46
        }
47
    }
48
49
    private function makeMessage(Task $task)
50
    {
51
        $content = json_encode($task->asQueueInfo());
52
53
        $message = new AMQPMessage();
54
        $message->setBody($content);
55
56
        return $message;
57
    }
58
59
    public function done()
60
    {
61
        $this->channel->close();
62
        $this->connection->close();
63
    }
64
}
65