Completed
Pull Request — master (#11)
by Elisha-Wigwe Chijioke
03:32
created

PotatoQuery::storeIn()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 5 Features 1
Metric Value
c 7
b 5
f 1
dl 0
loc 12
rs 9.4285
cc 2
eloc 9
nc 2
nop 2
1
<?php
2
3
namespace Elchroy\PotatoORM;
4
5
use Elchroy\PotatoORMExceptions\FaultyExecutionException;
6
use Elchroy\PotatoORMExceptions\FaultyOrNoTableException;
7
use Elchroy\PotatoORMExceptions\NoRecordException;
8
use PDO;
9
use PDOException;
10
11
class PotatoQuery
12
{
13
    /**
14
     * [$connection The connection to be used to communicate with the database. To be instantiated during construction.].
15
     *
16
     * @var [type] PDO Connection.
17
     */
18
    public $connection;
19
20
    /**
21
     * Setup the connection to aid all queries.
22
     *
23
     * @param PotatoConnector|null $connector [description]
24
     */
25
    public function __construct(PotatoConnector $connector = null)
26
    {
27
        $connector = $connector == null ? new PotatoConnector() : $connector;
28
        $this->connection = $connector->connection;
29
    }
30
31
    /**
32
     * Get all records from the specified database table.
33
     *
34
     * @param string $table   The table name
35
     * @param string $columns The columns to be gotten from the database table
36
     *
37
     * @return array An array of objects, each representing a record fetched from the database table.
38
     */
39
    public function getFrom($table, $columns = '*')
40
    {
41
        $sql = "SELECT $columns FROM $table";
42
        $statement = $this->connection->prepare($sql);
43
        $statement == false ? $this->throwFaultyOrNoTableException($table) : '';
44
        $execution = $this->tryExecuting($statement);
0 ignored issues
show
Documentation introduced by
$statement is of type object<PDOStatement>, but the function expects a object<Elchroy\PotatoORM\PDOStatemetn>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Unused Code introduced by
$execution is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
45
        $result = $statement->fetchAll(PDO::FETCH_CLASS);
46
        $result == false ? $this->throwNoRecordException($table) : '';
47
48
        return $result;
49
    }
50
51
    /**
52
     * Get only one record from the datbase table, given the id of the record to be retrieved.
53
     *
54
     * @param string $table The database table name
55
     * @param int    $id    The id of the recored to be fethced.
56
     *
57
     * @return model object        The record fetched form the database table as an object
58
     */
59
    public function getOne($table, $id)
60
    {
61
        $sql = "SELECT * FROM $table WHERE id = :id ";
62
        $statement = $this->connection->prepare($sql);
63
        $statement == false ? $this->throwFaultyOrNoTableException($table) : '';
64
        $statement->bindParam(':id', $id);
65
        $execution = $this->tryExecuting($statement);
0 ignored issues
show
Documentation introduced by
$statement is of type object<PDOStatement>, but the function expects a object<Elchroy\PotatoORM\PDOStatemetn>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Unused Code introduced by
$execution is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
66
        $result = $statement->fetchObject($table);
67
        $result == false ? $this->throwNoRecordException($table, $id) : '';
68
69
        return $result;
70
    }
71
72
    /**
73
     * Store a new recored inside athe database table.
74
     *
75
     * @param string $table The table into which it is required to add a new record
76
     * @param string $data  An aray of the columns to be used for inseting into the database
77
     *
78
     * @return bool The result of the query execution. True if successful. False otherwise.
79
     */
80
    public function storeIn($table, $data)
81
    {
82
        $columnsString = $this->getColumns($data);
0 ignored issues
show
Documentation introduced by
$data is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
83
        $count = (int) count($data);
84
        $sql = "INSERT INTO $table $columnsString VALUES (".$this->putQuesMarks($count).')';
85
        $statement = $this->connection->prepare($sql);
86
        $statement == false ? $this->throwFaultyOrNoTableException($table) : '';
87
        $this->setBindForInsert($statement, array_values($data));
88
        $execution = $this->tryExecuting($statement);
0 ignored issues
show
Documentation introduced by
$statement is of type object<PDOStatement>, but the function expects a object<Elchroy\PotatoORM\PDOStatemetn>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
89
90
        return $execution;
91
    }
92
93
    /**
94
     * Try executoing a query given the statment.
95
     *
96
     * @param PDOStatemetn $statement The PDO statment to be executed.
97
     *
98
     * @return bool The result of executing a query. True for success, false for failure
99
     */
100
    public function tryExecuting($statement)
101
    {
102
        try {
103
            $execution = $statement->execute();
104
        } catch (PDOException $e) {
105
            $message = $e->getMessage();
106
            $this->throwFaultyExecutionException($message);
107
        }
108
109
        return $execution;
110
    }
111
112
    /**
113
     * Throw an exception when there is a problem with execution of a statement.
114
     *
115
     * @param string $message The message to be related in the event of this exception
116
     *
117
     * @return [type] [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
118
     */
119
    public function throwFaultyExecutionException($message)
120
    {
121
        throw new FaultyExecutionException($message);
122
    }
123
124
    /**
125
     * The columns to be inserted into the SQL query.
126
     *
127
     * @param array $data An array of the columns to be used for inserting int ot he database.
128
     *
129
     * @return string A string made up of the columns for insert query enclode in parentheses
130
     */
131
    public function getColumns(array $data)
132
    {
133
        return '('.implode(', ', array_keys($data)).')';
134
    }
135
136
    /**
137
     * Bind parameters to the placeholders in the SQL queries. This is to avoid sql injection.
138
     *
139
     * @param [type]  $statement The PDOStatement to be used to the binding.
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
140
     * @param [array] $values    The result of binding parameters to an SQL query.
0 ignored issues
show
Documentation introduced by
The doc-type [array] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
141
     */
142
    public function setBindForInsert($statement, $values)
143
    {
144
        $count = count($values);
145
        for ($i = 1; $i <= $count; $i++) {
146
            $statement->bindParam(($i), $values[$i - 1]);
147
        }
148
    }
149
150
    /**
151
     * Delete a record form a database table.
152
     *
153
     * @param [string] $table The table to be deleted from
0 ignored issues
show
Documentation introduced by
The doc-type [string] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
154
     * @param [int]    $id    the ID of the record to be deleted
0 ignored issues
show
Documentation introduced by
The doc-type [int] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
155
     *
156
     * @return [type] The result of the deletion execution.
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
157
     */
158
    public function deleteFrom($table, $id)
159
    {
160
        $sql = "DELETE FROM $table WHERE id = :id ";
161
        $statement = $this->connection->prepare($sql);
162
        $statement == false ? $this->throwFaultyOrNoTableException($table) : '';
163
        $statement->bindParam(':id', $id);
164
        $execution = $this->tryExecuting($statement);
0 ignored issues
show
Documentation introduced by
$statement is of type object<PDOStatement>, but the function expects a object<Elchroy\PotatoORM\PDOStatemetn>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
165
166
        return $execution;
167
    }
168
169
    /**
170
     * Update records in the datbase table.
171
     *
172
     * @param string  $table The table who record ois to be updated
173
     * @param [array] $data  [The update data in an array]
0 ignored issues
show
Documentation introduced by
The doc-type [array] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
174
     *
175
     * @return [bool] [The result of executing an SQL update query. TRUE OR FALSE]
0 ignored issues
show
Documentation introduced by
The doc-type [bool] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
176
     */
177
    public function updateAt($table, $data)
178
    {
179
        $id = (int) $data['id']; // store the id in a variable.
180
        unset($data['id']);
181
        $upd = (string) $this->makeModify(array_keys($data)); // genertate the columns for the update statement.
182
        $sql = "UPDATE {$table} SET ".$upd.' WHERE id = :id_val';
183
        $statement = $this->connection->prepare($sql);
184
        $statement == false ? $this->throwFaultyOrNoTableException($table) : '';
185
        $this->setBindForUpdate($statement, $data);
186
        $statement->bindValue(':id_val', $id);
187
        $execution = $this->tryExecuting($statement);
0 ignored issues
show
Documentation introduced by
$statement is of type object<PDOStatement>, but the function expects a object<Elchroy\PotatoORM\PDOStatemetn>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
188
189
        return $execution;
190
    }
191
192
    /**
193
     * Bind parameters to the placeholders in the SQL queries. This is to avoid sql injection.
194
     *
195
     * @param [type]  $statement The PDOStatement to be used to the binding.
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
196
     * @param [array] $values    The result of binding parameters to an SQL query.
0 ignored issues
show
Documentation introduced by
The doc-type [array] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
Bug introduced by
There is no parameter named $values. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
197
     */
198
    public function setBindForUpdate($statement, array $data)
199
    {
200
        $count = count($data);
0 ignored issues
show
Unused Code introduced by
$count is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
201
        foreach ($data as $key => $value) {
202
            $statement->bindValue(":$key".'_val', $value);
203
        }
204
    }
205
206
    /**
207
     * [makeModify Modify the query string to enable the binding for update.
208
     *
209
     * @param array $columns [The columns to be updated]
210
     *
211
     * @return [string] [The string of the columns to be updated and their corresponidng value_tags/ placeholders] E.g name = :name_val
0 ignored issues
show
Documentation introduced by
The doc-type [string] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
212
     */
213
    public function makeModify(array $columns)
214
    {
215
        $count = count($columns);
0 ignored issues
show
Unused Code introduced by
$count is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
216
        $updateString = ''; // Start with an empty string
217
        foreach ($columns as $column) {
218
            $updateString .= $column.' = '.':'.$column.'_val, ';
219
        }
220
221
        return $updateString = trim($updateString, ', ');
0 ignored issues
show
Unused Code introduced by
$updateString is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
222
    }
223
224
    /**
225
     * [putQuesMarks Prepare a set of question-marks to comple an insert query SQL string. THis enables queryh binding.
226
     *
227
     * @param int $count The numbe rof column to be inserted
228
     *
229
     * @return string A string with the number of  question marks needed for a complete insert query. E.g "?, ?"
230
     */
231
    public function putQuesMarks($count)
232
    {
233
        $str = '';
234
        for ($i = 0; $i < $count; $i++) {
235
            $str .= '?, ';
236
        }
237
238
        return $str = trim($str, ', '); // remove the last comma.
0 ignored issues
show
Unused Code introduced by
$str is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
239
    }
240
241
    /**
242
     * [throwFaultyOrNoTableException Throw an exception if the table does not exist.
243
     *
244
     * @param string $table The table that foes not exist.
245
     *
246
     * @return [type] An exception with a custom message displayed when the databse table does not exist.
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
247
     */
248
    public function throwFaultyOrNoTableException($table)
249
    {
250
        $message = "There seems to be a problem. Please confirm if the '$table' table exists in the database.";
251
        throw new FaultyOrNoTableException($message);
252
    }
253
254
    /**
255
     * [throwNoRecordException Throw an Exception if there is no record found in the database table.]
256
     * This may mean that the table is empty ot that the record with the given ID is not foung.
257
     *
258
     * @param [string] $table [The table that is empty or does not have the record with the given ID.]
0 ignored issues
show
Documentation introduced by
The doc-type [string] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
259
     * @param [int]    $id    [The ID of the record that does not exist in the databse table]
0 ignored issues
show
Documentation introduced by
The doc-type [int] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
260
     *
261
     * @return [type] [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
262
     */
263
    public function throwNoRecordException($table, $id = null)
264
    {
265
        $message = is_null($id) ? "The table ($table) is empty." : "Record $id : Not found found in this table ($table).";
266
        throw new NoRecordException($message);
267
    }
268
}
269