Completed
Push — master ( 71eabe...c88c98 )
by Andrew
03:38
created

Database::select()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 2
eloc 4
nc 2
nop 3
1
<?php
2
3
namespace PotatoORM;
4
5
use PDO;
6
use Dotenv\Dotenv;
7
8
/**
9
* Class that assists in data persistence and retrieval
10
*/
11
class Database
12
{
13
    private $dsn;
14
    private $database_handler;
15
    private $statement;
16
17
    /**
18
     * Sets the DSN for the database and creates a connection
19
     */
20
    public function __construct()
21
    {
22
        $this->setDSN();
23
24
        //set options
25
        $options = [
26
            PDO::ATTR_PERSISTENT   => true,
27
            PDO::ATTR_ERRMODE      => PDO::ERRMODE_EXCEPTION
28
        ];
29
30
        //create a new pdo instance
31
        $this->database_handler = new PDO(
32
            $this->dsn,
33
            getenv("USERNAME"),
34
            getenv("PASSWORD"),
35
            $options
36
        );
37
    }
38
39
    /**
40
    * Sets the DSN as set in the environment variable file
41
    */
42
    private function setDSN()
43
    {
44
        $env = new Dotenv(__DIR__ . "/../");
45
        $env->load();
46
        
47
        $this->dsn = getenv("DATABASE_TYPE")
48
            . ":host=" . getenv("HOST")
49
            . ";dbname=" . getenv("DATABASE_NAME")
50
            . ";port=" . getenv("PORT");
51
    }
52
53
    /**
54
    * Prepares the statement
55
    *
56
    * @param string $query  The SQL query to be prepared
57
    */
58
    public function prepare($query)
59
    {
60
        $this->statement = $this->database_handler->prepare($query);
61
    }
62
63
    /**
64
    * Binds the values of the parameters in the statement    *
65
    * @param mixed $param  The parameter that the value will be bound to
66
    * @param mixed $value  The value to be bound to the parameter
67
    * @param $type   The PDO SQL data type of the value being bound to the parameter
68
    */
69
    public function bind($param, $value, $type = null)
70
    {
71
        if (is_null($type)) {
72
            if (is_int($value)) {
73
                $type = PDO::PARAM_INT;
74
            } elseif (is_bool($value)) {
75
                $type = PDO::PARAM_BOOL;
76
            } elseif (is_null($value)) {
77
                $type = PDO::PARAM_NULL;
78
            } else {
79
                $type = PDO::PARAM_STR;
80
            }
81
        }
82
83
        $this->statement->bindValue($param, $value, $type);
84
    }
85
86
    /**
87
    * Executes the SQL statement
88
    */
89
    public function execute()
90
    {
91
        $this->statement->execute();
92
    }
93
94
    /**
95
     * Prepares a select query to be executed by the execute() method
96
     * @param string $table  The name of the table to query
97
     * @param $where  The condition to be used when querying
98
     */
99
    public function select($table, $where = "", $fields = "*")
100
    {
101
        $query = "SELECT $fields FROM $table"
102
            . ($where ? " WHERE $where " : "");
103
104
        $this->prepare($query);
105
    }
106
107
    /**
108
     * Inserts a new record in the database and returns the last inserted ID
109
     * @param string $table  The name of the table to insert the record into
110
     * @param array $data    The information to insert
111
     * @return int
112
     */
113
    public function insert($table, $data)
114
    {
115
        $field_names = implode(",", array_keys($data));
116
        $field_values = ":" . implode(", :", array_keys($data));
117
118
        $query = "INSERT INTO $table ($field_names) VALUES ($field_values)";
119
120
        $this->prepare($query);
121
122
        foreach ($data as $key => $value) {
123
            $this->bind(":$key", $value);
124
        }
125
126
        $this->execute();
127
128
        return $this->database_handler->lastInsertId();
129
    }
130
131
    /**
132
     * Updates a record in the database
133
     * @param string $table  The table to update
134
     * @param array $data    The updated information in the form of an array
135
     * @param $where  The condition that needs to be true in order to update
136
     */
137
    public function update($table, array $data, $where = "")
138
    {
139
        $field_details = null;
140
141
        foreach ($data as $key => $value) {
142
            $field_details .= "$key = :$key,";
143
        }
144
        $field_details = rtrim($field_details, ",");
145
146
        $query = "UPDATE $table SET $field_details "
147
            . ($where ? " WHERE $where " : "");
148
149
        $this->prepare($query);
150
151
        foreach ($data as $key => $value) {
152
            $this->bind(":$key", $value);
153
        }
154
155
        $this->execute();
156
    }
157
158
    /**
159
     * Deletes a record or records from the database
160
     * @param string $table  The table to delete the record(s) from
161
     * @param $where  The condition that needs to be true in order to delete
162
     * @param int $limit
163
     */
164
    public function delete($table, $where = "", $limit = 1)
165
    {
166
        if (!empty(trim($where))) {
167
            $statement = "DELETE FROM $table WHERE $where LIMIT $limit";
168
        } else {
169
            $statement = "DELETE FROM $table";
170
        }
171
172
        $this->prepare($statement);
173
        $this->execute();
174
    }
175
176
    /**
177
     * Retrieves all records from the corresponding table in the
178
     * database and returns them as an array of objects
179
     * @return array
180
     */
181
    public function objectSet($entityClass)
182
    {
183
        $this->execute();
184
        $this->statement->setFetchMode(PDO::FETCH_CLASS, $entityClass);
185
        return $this->statement->fetchAll();
186
    }
187
188
    /**
189
     * Retrieves a record from the database based on its ID
190
     * and returns it in the form of the corresponding object
191
     * @return object
192
     */
193
    public function singleObject($entityClass)
194
    {
195
        $this->execute();
196
        $this->statement->setFetchMode(PDO::FETCH_CLASS, $entityClass);
197
        return $this->statement->fetch();
198
    }
199
}
200