Completed
Push — master ( dfd088...490d5a )
by Derek
02:19
created

MySql   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 193
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 18
c 5
b 0
f 0
lcom 1
cbo 1
dl 0
loc 193
ccs 74
cts 74
cp 1
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A connect() 0 20 2
A disconnect() 0 12 2
B getPrimaryKeys() 0 29 3
B getRowById() 0 33 5
A tableExists() 0 16 2
A processPrimaryKeyResult() 0 18 4
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();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 14 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
41 1
            $context["exception"] = $pdo_e;
42
43 1
            $this->updateLog("error", "MySQL connection failed with the following message: {message}", $context);
44
            
45 1
            $connected = false;
46
        }
47
48 14
        return $connected;
49
    }
50
51
    /**
52
     * Destroys an existing PDO connection
53
     *
54
     * @return bool Returns true if the connection existed and was destroyed; returns false otherwise
55
     */
56 2
    public function disconnect()
57
    {
58 2
        if ($this->pdo instanceof \PDO) {
59 1
            $this->pdo = null;
60
61 1
            $disconnected = true;
62 1
        } else {
63 1
            $disconnected = false;
64
        }
65
66 2
        return $disconnected;
67
    }
68
69
    /**
70
     * Gets the column names for all primary keys for a table or returns false if no keys exist
71
     *
72
     * @param string $table The table from which keys will be retrieved
73
     *
74
     * @return array|false  Returns an array of column names representing primary keys;
75
     *                      returns false if the table has no primary keys
76
     */
77 9
    public function getPrimaryKeys($table)
78
    {
79 9
        $table_exists = $this->tableExists($table);
80
        
81 9
        if (!$table_exists) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
82
//            return false;
83 1
        }
84
85 9
        $keys_query = "SHOW KEYS FROM {$table} WHERE Key_name='PRIMARY'";
86
87 9
        $statement = $this->pdo->prepare($keys_query);
88
89
        try {
90 9
            $statement->execute();
91 9
        } catch (\PDOException $pdo_e) {
92 1
            $context = array();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 14 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
93 1
            $context["exception"] = $pdo_e;
94
95 1
            $this->updateLog("error", "Trying to get keys failed with the following message: {message}", $context);
96
97 1
            return false;
98
        }
99
100 8
        $result = $statement->fetchAll();
101
102 8
        $keys = $this->processPrimaryKeyResult($result);
103
104 8
        return $keys;
105
    }
106
107
    /**
108
     * Retrieves a row represented by a single primary key
109
     *
110
     * @param int|string $id    A unique id for a table
111
     * @param string $table     The table from which a row will be retrieved
112
     *
113
     * @return array|false      Returns an associative array representing the row corresponding with the primary key;
114
     *                          returns false if the table does not exist, if the provided id does not correspond with a
115
     *                          record, or if the table has a compound primary key
116
     */
117 5
    public function getRowById($id, $table)
118
    {
119 5
        $key = $this->getPrimaryKeys($table);
120
121 5
        if (is_string($id)) {
122 1
            $query_id = "'{$id}'";
123 1
        } else {
124 4
            $query_id = $id;
125
        }
126
127 5
        if ($key === false) {
128 1
            $row = false;
129 5
        } elseif (count($key) > 1) {
130 1
            $row = false;
131 1
        } else {
132 3
            $query = "SELECT * FROM {$table}
133 3
                        WHERE {$key} = {$query_id}";
134
135 3
            $statement = $this->pdo->prepare($query);
136
137 3
            $statement->execute();
138
139 3
            $result = $statement->fetchAll(\PDO::FETCH_ASSOC);
140
141 3
            if (empty($result)) {
142 1
                $row = false;
143 1
            } else {
144 2
                $row = $result[0];
145
            }
146
        }
147
148 5
        return $row;
149
    }
150
151
    /**
152
     * Determines whether a given table exists
153
     *
154
     * @param string $table The table that will be checked for existence
155
     * @return bool         Returns true if the table exists; returns false otherwise
156
     */
157 11
    public function tableExists($table)
158
    {
159 11
        $table_query = "SHOW TABLES LIKE '{$table}'";
160
161 11
        $statement = $this->pdo->prepare($table_query);
162
163 11
        $statement->execute();
164
165 11
        $row_count = $statement->rowCount();
166
167 11
        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...
168 2
            return false;
169
        } else {
170 9
            return true;
171
        }
172
    }
173
174
    /**
175
     * Processes the result set from a primary key query
176
     *
177
     * @see MySql::getPrimaryKeys()
178
     *
179
     * @param array $result An array representing the result of a primary key query
180
     *
181
     * @return mixed        Returns a string column name if the result set contains only one key; returns an array of
182
     *                      string column names if the result set contains a compound key; returns false if the result
183
     *                      set was empty
184
     */
185 8
    private function processPrimaryKeyResult($result)
186
    {
187 8
        $row_count = count($result);
188
189 8
        if ($row_count > 1) {
190 2
            $keys = array();
191
192 2
            foreach ($result as $row) {
193 2
                $keys[] = $row['Column_name'];
194 2
            }
195 8
        } elseif ($row_count == 1) {
196 4
            $keys = $result[0]['Column_name'];
197 4
        } else {
198 2
            $keys = false;
199
        }
200
201 8
        return $keys;
202
    }
203
}
204