Completed
Pull Request — master (#2)
by Opeyemi
12:49
created

Connection::updateRecord()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 29
Code Lines 17

Duplication

Lines 8
Ratio 27.59 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 8
loc 29
rs 8.439
cc 6
eloc 17
nc 6
nop 3
1
<?php
2
3
namespace Opeyemiabiodun\PotatoORM\Connections;
4
5
use Dotenv\Dotenv;
6
use Exception;
7
use RuntimeException;
8
9
abstract class Connection
10
{
11
    /**
12
     * $_database The database name.
13
     * @var string
14
     */
15
    protected $_database;
16
17
    /**
18
     * $_host The host name.
19
     * @var string
20
     */
21
    protected $_host;
22
23
    /**
24
     * $_password The password to the database server.
25
     * @var string
26
     */
27
    protected $_password;
28
29
    /**
30
     * $_pdo The PDO instance of the connection.
31
     * @var PDO
32
     */
33
    protected $_pdo;
34
35
    /**
36
     *  $_port The port number to the database server.
37
     * @var string
38
     */
39
    protected $_port;
40
41
    /**
42
     * The username to the database server.
43
     * @var string
44
     */
45
    protected $_username;
46
47
    /**
48
     * The Connection constructor
49
     */
50
    public function __construct()
51
    {
52
        $this->connect();
53
    }
54
55
    /**
56
     * The method called in the constructor.
57
     * @return void
58
     */
59
    abstract protected function connect();
60
61
    /**
62
     * Returns the Connection's PDO.
63
     * @return PDO  PHP Data Objects
64
     */
65
    public function getPdo()
66
    {
67
        return $this->_pdo;
68
    }
69
70
    /**
71
     * Loads variables in the .env file.
72
     * @return void
73
     */
74
    protected function loadDbEnv()
75
    {
76
        $dotenv = new Dotenv(__DIR__.'/../..');
77
        $dotenv->required(['DB_HOST', 'DB_DATABASE', 'DB_USERNAME', 'DB_PASSWORD'])->notEmpty();
78
        $dotenv->required(['DB_PORT']);
79
        $dotenv->load();
80
81
        $this->_host = getenv('DB_HOST');
82
        $this->_database = getenv('DB_DATABASE');
83
        $this->_username = getenv('DB_USERNAME');
84
        $this->_password = getenv('DB_PASSWORD');
85
        if (isset(getenv('DB_PORT'))) {
86
            $this->_port = getenv('DB_PORT');            
87
        }
88
    }
89
90
    /**
91
     * Loads variables in the .env file and handles exceptions.
92
     * @return void
93
     */
94
    protected function useDbEnv()
95
    {
96
        try {
97
            $this->loadDbEnv();
98
        } catch (RuntimeException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
99
        } catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
100
        }
101
    }
102
103
    /**
104
     * Creates a record in the database.
105
     * @param  string   $table  The table where the a new record is made.
106
     * @param  array    $record The record to be made in the database.
107
     * @return bool
108
     */
109
    public function createRecord($table, $record)
110
    {
111
        if (gettype($table) !== 'string') {
112
            throw new Exception("Error Processing Request", 1);            
113
        } 
114
115
        if (gettype($record) !== 'array') {
116
            throw new Exception("Error Processing Request", 1);            
117
        } 
118
119
        $count = count($record);
120
121
        $sql = "INSERT INTO {$table} (";
122 View Code Duplication
        foreach ($record as $key => $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
123
            if ($count > 1) {
124
                $sql = $sql."{$key}, ";
125
            } else {
126
                $sql = $sql."{$key}) ";
127
            }
128
            $count--;
129
        }
130
131
        $count = count($record);
132
133
        $sql .= "VALUES (";
134 View Code Duplication
        foreach ($record as $key => $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
135
            if ($count > 1) {
136
                $sql = $sql."{$value}, ";
137
            } else {
138
                $sql = $sql."{$value}) ";
139
            }
140
            $count--;
141
        }
142
143
        return $this->getPdo()->prepare($sql)->execute();
144
    }
145
146
    /**
147
     * Remove a record in the database.
148
     * @param  string $table The table where the record is removed in the database.
149
     * @param  string $pk    The primary key value of the record.
150
     * @return bool          Returns boolean true if the record was successfully deleted or else it returns false.
151
     */
152 View Code Duplication
    public function deleteRecord($table, $pk)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
153
    {
154
        if (gettype($table) !== 'string') {
155
            throw new Exception("Error Processing Request", 1);            
156
        } 
157
158
        if (gettype($pk) !== 'string') {
159
            throw new Exception("Error Processing Request", 1);            
160
        } 
161
162
        return $this->getPdo()->prepare("DELETE FROM {$table}
163
                                            WHERE {$this->getPrimaryKey($table)}={$pk}")->execute();
164
    }
165
166
    /**
167
     * Returns a particular record in a table.
168
     * @param  string $table The table of the record. 
169
     * @param  string $pk    The primary key value of the record.
170
     * @return array         An array containing the particular record.
171
     */
172 View Code Duplication
    public function findRecord($table, $pk)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
173
    {
174
        if (gettype($table) !== 'string') {
175
            throw new Exception("Error Processing Request", 1);            
176
        } 
177
178
        if (gettype($pk) !== 'string') {
179
            throw new Exception("Error Processing Request", 1);            
180
        }
181
182
        return $this->getPdo()->query("SELECT * FROM {$table}
183
                                        WHERE {$this->getPrimaryKey($table)}={$pk}")->fetchAll();
184
    }
185
186
    /**
187
     * Returns all the records in a table.
188
     * @param  string $table The table inspected for all its records.
189
     * @return array         All the records in the table.        
190
     */
191
    public function getAllRecords($table)
192
    {
193
        if (gettype($table) !== 'string') {
194
            throw new Exception("Error Processing Request", 1);            
195
        } 
196
197
        return $this->getPdo()->query("SELECT * FROM {$table}")->fetchAll();
198
    }
199
200
    /**
201
     * Returns the columns of a table.
202
     * @param  string $table The table inspected for its columns.
203
     * @return array         The columns of the table.        
204
     */
205
    abstract public function getColumns($table);
206
207
    /**
208
     * Returns the primary key of a table.
209
     * @param  string $table The table inspected for its primary key.
210
     * @return string        The primary key of the table.
211
     */
212
    abstract public function getPrimaryKey($table);
213
214
    /**
215
     * Update a record in the database.
216
     * @param  string $table  The table where the record update is being made.
217
     * @param  string $pk     The primary key value of the record to be updated.
218
     * @param  array  $record The updates to be made to the record in the database.
219
     * @return bool           Returns boolean true if the record was successfully updated or else it returns false.
220
     */
221
    public function updateRecord($table, $pk, $record)
222
    {        
223
        if (gettype($table) !== 'string') {
224
            throw new Exception("Error Processing Request", 1);            
225
        } 
226
227
        if (gettype($pk) !== 'string') {
228
            throw new Exception("Error Processing Request", 1);            
229
        }
230
        
231
        if (gettype($record) !== 'array') {
232
            throw new Exception("Error Processing Request", 1);            
233
        } 
234
235
        $count = count($record);
236
237
        $sql = "UPDATE {$table} SET ";
238 View Code Duplication
        foreach ($record as $key => $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
239
            if ($count > 1) {
240
                $sql = $sql."{$key}={$value}, ";
241
            } else {
242
                $sql = $sql."{$key}={$value} ";
243
            }
244
            $count--;
245
        }
246
        $sql .= "WHERE {$this->getPrimaryKey($table)}={$pk}";
247
248
        return $this->getPdo()->prepare($sql)->execute();
249
    }
250
}
251