Completed
Push — master ( 727909...673a73 )
by Derek
02:38
created

MySql::quoteQueryStringVariable()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.4285
cc 2
eloc 6
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Subreality\Dilmun\Enki;
4
5
use Subreality\Dilmun\LoggedClassTrait;
6
7
/**
8
 * Class MySql
9
 * @package Subreality\Dilmun\Enki
10
 */
11
class MySql implements EnkiInterface
12
{
13
    use LoggedClassTrait;
14
15
    /**
16
     * @var \PDO
17
     */
18
    private $pdo;
19
20
    /**
21
     * Provides a MySQL connection interface that catches a PDOException on failure.
22
     *
23
     * @param string $host  The host name for the MySQL connection
24
     * @param string $user  The username for the MySQL connection
25
     * @param string $pass  The password for the MySQL connection
26
     * @param string $name  The database name for the MySQL connection
27
     *
28
     * @return bool         Returns true if the connection was successful; returns false otherwise
29
     */
30 14
    public function connect($host, $user, $pass, $name)
31
    {
32 14
        $dsn = "mysql:host={$host};dbname={$name}";
33
34
        try {
35 14
            $this->pdo = new \PDO($dsn, $user, $pass);
36 13
            $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
37
38 13
            $connected = true;
39 14
        } catch (\PDOException $pdo_e) {
40 1
            $context = array();
41
42 1
            $context["exception"] = $pdo_e;
43
44 1
            $this->updateLog("error", "MySQL connection failed with the following message: {message}", $context);
45
            
46 1
            $connected = false;
47
        }
48
49 14
        return $connected;
50
    }
51
52
    /**
53
     * Destroys an existing PDO connection
54
     *
55
     * @return bool Returns true if the connection existed and was destroyed; returns false otherwise
56
     */
57 2
    public function disconnect()
58
    {
59 2
        if ($this->pdo instanceof \PDO) {
60 1
            $this->pdo = null;
61
62 1
            $disconnected = true;
63 1
        } else {
64 1
            $disconnected = false;
65
        }
66
67 2
        return $disconnected;
68
    }
69
70
    /**
71
     * Gets the column names for all primary keys for a table or returns false if no keys exist
72
     *
73
     * @param string $table The table from which keys will be retrieved
74
     *
75
     * @return array|false  Returns an array of column names representing primary keys;
76
     *                      returns false if the table has no primary keys
77
     */
78 9
    public function getPrimaryKeys($table)
79
    {
80 9
        $keys_query = "SHOW KEYS FROM {$table} WHERE Key_name='PRIMARY'";
81
82 9
        $statement = $this->pdo->prepare($keys_query);
83
84
        try {
85 9
            $statement->execute();
86 9
        } catch (\PDOException $pdo_e) {
87 1
            $context = array();
88
89 1
            $context["exception"] = $pdo_e;
90
91 1
            $this->updateLog("error", "Trying to get keys failed with the following message: {message}", $context);
92
93 1
            return false;
94
        }
95
96 8
        $result = $statement->fetchAll();
97
98 8
        $keys = $this->processPrimaryKeyResult($result);
99
100 8
        return $keys;
101
    }
102
103
    /**
104
     * Retrieves a row represented by a single primary key
105
     *
106
     * @param int|string $id    A unique id for a table
107
     * @param string $table     The table from which a row will be retrieved
108
     *
109
     * @return array|false      Returns an associative array representing the row corresponding with the primary key;
110
     *                          returns false if the table does not exist, if the provided id does not correspond with a
111
     *                          record, or if the table has a compound primary key
112
     */
113 5
    public function getRowById($id, $table)
114
    {
115 5
        $id  = $this->quoteQueryStringVariable($id);
116 5
        $key = $this->getPrimaryKeys($table);
117
118 5
        if ($key === false || count($key) > 1) {
119 2
            $row = false;
120 2
        } else {
121 3
            $query = "SELECT * FROM {$table}
122 3
                        WHERE {$key} = {$id}";
123
124 3
            $statement = $this->pdo->prepare($query);
125
126 3
            $statement->execute();
127
128 3
            $result = $statement->fetchAll(\PDO::FETCH_ASSOC);
129
130 3
            if (empty($result)) {
131 1
                $row = false;
132 1
            } else {
133 2
                $row = $result[0];
134
            }
135
        }
136
137 5
        return $row;
138
    }
139
140
    /**
141
     * Determines whether a given table exists
142
     *
143
     * @param string $table The table that will be checked for existence
144
     * @return bool         Returns true if the table exists; returns false otherwise
145
     */
146 2
    public function tableExists($table)
147
    {
148 2
        $table_query = "SHOW TABLES LIKE '{$table}'";
149
150 2
        $statement = $this->pdo->prepare($table_query);
151
152 2
        $statement->execute();
153
154 2
        $row_count = $statement->rowCount();
155
156 2
        if ($row_count == 0) {
0 ignored issues
show
Coding Style introduced by
The if-else statement can be simplified to return !($row_count == 0);.
Loading history...
157 1
            return false;
158
        } else {
159 1
            return true;
160
        }
161
    }
162
163
    /**
164
     * Processes the result set from a primary key query
165
     *
166
     * @see MySql::getPrimaryKeys()
167
     *
168
     * @param array $result An array representing the result of a primary key query
169
     *
170
     * @return mixed        Returns a string column name if the result set contains only one key; returns an array of
171
     *                      string column names if the result set contains a compound key; returns false if the result
172
     *                      set was empty
173
     */
174 8
    private function processPrimaryKeyResult($result)
175
    {
176 8
        $row_count = count($result);
177
178 8
        if ($row_count > 1) {
179 2
            $keys = array();
180
181 2
            foreach ($result as $row) {
182 2
                $keys[] = $row['Column_name'];
183 2
            }
184 8
        } elseif ($row_count == 1) {
185 4
            $keys = $result[0]['Column_name'];
186 4
        } else {
187 2
            $keys = false;
188
        }
189
190 8
        return $keys;
191
    }
192
193
    /**
194
     * Prepares a variable for a query string by surrounding it with single quotes if it's a string
195
     *
196
     * @param mixed $var    The variable to be assessed for quoting
197
     *
198
     * @return mixed        Returns the single-quoted variable if the variable is a string; returns the variable
199
     *                      otherwise
200
     */
201 5
    private function quoteQueryStringVariable($var)
202
    {
203 5
        if (is_string($var)) {
204 1
            $query_var = "'{$var}'";
205 1
        } else {
206 4
            $query_var = $var;
207
        }
208
209 5
        return $query_var;
210
    }
211
}
212