Db::__wakeup()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 2 Features 1
Metric Value
cc 1
eloc 5
c 6
b 2
f 1
nc 1
nop 0
dl 0
loc 7
rs 9.4285
1
<?php
2
namespace Sovereign\Lib;
3
4
use League\Container\Container;
5
use Monolog\Logger;
6
7
/**
8
 * Class Db
9
 * @package Sovereign\Lib
10
 */
11
class Db
12
{
13
    /**
14
     * @var Config
15
     */
16
    protected $config;
17
    /**
18
     * @var Logger
19
     */
20
    protected $log;
21
    /**
22
     * @var \PDO
23
     */
24
    private $pdo;
25
    /**
26
     * @var Container
27
     */
28
    private $container;
29
30
    /**
31
     * Db constructor.
32
     * @param Config $config
33
     * @param Logger $log
34
     * @param Container $container
35
     */
36
    public function __construct(Config $config, Logger $log, Container $container)
37
    {
38
        $this->log = $log;
39
        $this->config = $config;
40
        $this->pdo = $this->connect();
41
        $this->container = $container;
42
    }
43
44
    /**
45
     * @return array
46
     * Upon sleeping (which is needed for pthreads to work with pdo) we just return an empty array, which is the default for all the query functions anyway
47
     * It doesn't really matter what we return tho, since once the thread wakes up, the __wakeup function is ran
48
     */
49
    public function __sleep()
50
    {
51
        return array();
52
    }
53
54
    /**
55
     * This is for the pthreads compatibility - for some reason the DB just goes tits up when using pthreads
56
     * and PDO.. Hence the __wakeup() call, that restarts the database.
57
     * No numbers on it, but it more than likely adds quite a bit of latency.
58
     */
59
    public function __wakeup()
60
    {
61
        $this->container = getContainer();
62
        $this->log = $this->container->get('log');
63
        $this->config = $this->container->get('config');
64
        $this->pdo = $this->connect();
65
    }
66
67
    /**
68
     * @return \PDO
69
     */
70
    private function connect()
71
    {
72
        $dsn = "mysql:dbname={$this->config->get("dbName", "db")};host={$this->config->get("dbHost", "db")}";
73
        try {
74
            $pdo = new \PDO($dsn, $this->config->get("dbUser", "db"), $this->config->get("dbPass", "db"), array(
75
                \PDO::ATTR_PERSISTENT => false,
76
                \PDO::ATTR_EMULATE_PREPARES => true,
77
                \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
78
                \PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
79
                \PDO::MYSQL_ATTR_INIT_COMMAND => "SET time_zone = '+00:00',NAMES utf8;"
80
            ));
81
        } catch (\Exception $e) {
82
            $this->log->addCritical("Unable to connect to database: ", [$e->getMessage()]);
83
            die();
0 ignored issues
show
Coding Style Compatibility introduced by
The method connect() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
84
        }
85
86
        return $pdo;
87
    }
88
89
    /**
90
     * @param String $query
91
     * @param array $parameters
92
     * @return array
93
     */
94
    public function queryRow(String $query, $parameters = array())
95
    {
96
        $result = $this->query($query, $parameters);
97
98
        if (count($result) >= 1) {
99
            return $result[0];
100
101
    }
102
        return array();
103
    }
104
105
    /**
106
     * @param String $query
107
     * @param array $parameters
108
     * @return array
109
     */
110
    public function query(String $query, $parameters = array())
111
    {
112
        try {
113
            $stmt = $this->pdo->prepare($query);
114
            $stmt->execute($parameters);
115
116
            if ($stmt->errorCode() != 0) {
117
                return array();
118
            }
119
120
            $result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
121
122
            $stmt->closeCursor();
123
124
            return $result;
125
        } catch (\Exception $e) {
126
            $this->log->addError("There was an error during a query: ", [$e->getMessage()]);
127
            try {
128
                $this->pdo = $this->connect();
129
            } catch (\Exception $e2) {
130
                $this->log->addCritical("Couldn't reconnect to the database: " . $e->getMessage());
131
                die(1);
0 ignored issues
show
Coding Style Compatibility introduced by
The method query() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
132
            }
133
        }
134
        return array();
135
    }
136
137
    /**
138
     * @param String $query
139
     * @param String $field
140
     * @param array $parameters
141
     * @return string
142
     */
143
    public function queryField(String $query, String $field, $parameters = array())
144
    {
145
        $result = $this->query($query, $parameters);
146
147
        if (count($result) == 0) {
148
            return "";
149
        }
150
151
        $resultRow = $result[0];
152
        return $resultRow[$field];
153
    }
154
155
    /**
156
     * @param String $query
157
     * @param array $parameters
158
     * @return int|null|string
159
     */
160
    public function execute(String $query, $parameters = array())
161
    {
162
        try {
163
            $this->pdo->beginTransaction();
164
165
            $stmt = $this->pdo->prepare($query);
166
            $stmt->execute($parameters);
167
168
            if ($stmt->errorCode() != 0) {
169
                $this->pdo->rollBack();
170
                return 0;
171
            }
172
173
            $returnID = $this->pdo->lastInsertId();
174
            $this->pdo->commit();
175
            $stmt->closeCursor();
176
177
            return $returnID;
178
        } catch (\Exception $e) {
179
            $this->log->addError("There was an error during a query: ", [$e->getMessage()]);
180
            try {
181
                $this->pdo = $this->connect();
182
            } catch (\Exception $e2) {
183
                $this->log->addCritical("Couldn't reconnect to the database: " . $e->getMessage());
184
                die(1);
0 ignored issues
show
Coding Style Compatibility introduced by
The method execute() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
185
            }
186
        }
187
        return null;
188
    }
189
}
190