Issues (13)

src/Connections/Connect.php (1 issue)

Severity
1
<?php
2
3
namespace WillRy\RabbitRun\Connections;
4
5
use PhpAmqpLib\Channel\AMQPChannel;
6
use PhpAmqpLib\Connection\AMQPStreamConnection;
7
8
/**
9
 * Class Connect Singleton Pattern
10
 */
11
class Connect
12
{
13
    /**
14
     * @const array
15
     */
16
    private static $opt = [];
17
18
    /** @var AMQPStreamConnection */
19
    private static $instance;
20
21
    /** @var AMQPChannel */
22
    private static $channel;
23
24
    /**
25
     * Connect constructor. Private singleton
26
     */
27
    private function __construct()
28
    {
29
    }
30
31
    /**
32
     * Connect clone. Private singleton
33
     */
34
    private function __clone()
35
    {
36
    }
37
38
    public static function getInstance()
39
    {
40
        if (empty(self::$instance) || (!empty(self::$instance) && !self::$instance->isConnected())) {
41
            self::$instance = new AMQPStreamConnection(
42
                self::$opt["host"],
43
                self::$opt["port"],
44
                self::$opt["user"],
45
                self::$opt["pass"]
46
            );
47
        }
48
49
        return self::$instance;
50
    }
51
52
    public static function getChannel()
53
    {
54
        if (empty(self::$channel) || (!empty(self::$channel) && !self::$channel->is_open())) {
55
            try {
56
                self::$channel = self::getInstance()->channel();
57
            } catch (\Exception $exception) {
58
                die('Connection error RabbitMQ' . $exception->getMessage());
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
59
            }
60
        }
61
62
        return self::$channel;
63
    }
64
65
    public static function closeInstance()
66
    {
67
        if (!empty(self::$instance) && self::$instance->isConnected()) {
68
            self::$instance->close();
69
        }
70
    }
71
72
    public static function closeChannel()
73
    {
74
        if (!empty(self::$channel) && self::$channel->is_open()) {
75
            self::$channel->close();
76
        }
77
    }
78
79
    public static function config($host, $port, $user, $pass, $vhost)
80
    {
81
        self::$opt = [
82
            'host' => $host,
83
            'port' => $port,
84
            'user' => $user,
85
            'pass' => $pass,
86
            'vhost' => $vhost,
87
        ];
88
    }
89
}
90