Completed
Push — master ( b0764c...fc8584 )
by he
07:50
created

TaskQueue::done()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
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
    public function add(Task $task)
21
    {
22
        try {
23
            $message = $this->makeMessage($task);
24
            $this->channel->basic_publish($message, '', config('rabbitmq.routing_key'));
25
        } catch (AMQPRuntimeException $e) {
26
            app('log')->error('add task queue failed!', $e->getMessage());
0 ignored issues
show
Bug introduced by
$e->getMessage() of type string is incompatible with the type array expected by parameter $context of Illuminate\Log\LogManager::error(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

26
            app('log')->error('add task queue failed!', /** @scrutinizer ignore-type */ $e->getMessage());
Loading history...
27
        }
28
29
    }
30
31
    public function done()
32
    {
33
        $this->channel->close();
34
        $this->connection->close();
35
    }
36
37
    private function getConnection()
38
    {
39
        return new AMQPStreamConnection(
40
            config('rabbitmq.host'),
41
            config('rabbitmq.port'),
42
            config('rabbitmq.login'),
43
            config('rabbitmq.password'),
44
            config('rabbitmq.vhost')
45
        );
46
    }
47
48
    private function queueChannel()
49
    {
50
        $channel = $this->connection->channel();
51
        $channel->queue_declare(config('rabbitmq.queue'), false, true);
52
53
        return $channel;
54
    }
55
56
    private function makeMessage(Task $task)
57
    {
58
        $content = json_encode($task->asQueueInfo());
59
60
        $message = new AMQPMessage();
61
        $message->setBody($content);
62
63
        return $message;
64
    }
65
}
66