Completed
Push — master ( ba5607...5fa440 )
by Adeola
02:28
created

DataBaseQuery::update()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 26
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 4

Importance

Changes 10
Bugs 1 Features 0
Metric Value
c 10
b 1
f 0
dl 0
loc 26
ccs 15
cts 15
cp 1
rs 8.5806
cc 4
eloc 13
nc 6
nop 4
crap 4
1
<?php
2
3
/**
4
 * Class DataBase:
5
 * This class performs the basic CRUD operations which compose of
6
 * various methods such as create, read, update, and delete.
7
 * This class class query the database to achieve its function.
8
 *
9
 * @author: Raimi Ademola <[email protected]>
10
 * @copyright: 2016 Andela
11
 */
12
namespace Demo;
13
14
use PDO;
15
16
/**
17
 * This is a constructor; a default method  that will be called automatically during class instantiation.
18
 */
19
class DataBaseQuery
20
{
21
    protected $tableName;
22
    protected $splitTableField;
23
    protected $formatTableValues;
24
    protected $dataBaseConnection;
25
26
    /**
27
     * This method create or insert new users to the table.
28
     *
29
     * @param $associativeArray
30
     * @param $tableName
31
     *
32
     * @return array
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
33
     */
34 63
    public function __construct($dbConn = null)
35
    {
36 63
        if (is_null($dbConn)) {
37
            $this->dbConnection = new DataBaseConnection();
0 ignored issues
show
Bug introduced by
The property dbConnection does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
38
        } else {
39 63
            $this->dbConnection = $dbConn;
40
        }
41 63
    }
42
43
    /**
44
     * This method create or insert new users to the table.
45
     *
46
     * @param $associativeArray
47
     * @param $tableName
48
     *
49
     * @return array
50
     */
51 6
    public function create($associativeArray, $tableName, $dbConn = null)
52
    {
53 6
        $tableFields = [];
54 6
        $tableValues = [];
55
56 6
        foreach ($associativeArray as $key => $val) {
57 6
            $tableFields[] = $key;
58 6
            $tableValues[] = $val;
59 4
        }
60
61
        
62
63 6
        $unexpectedArray = array_diff($tableFields, $this->getColumnNames($tableName, $dbConn));
64
65 6
        if (count($unexpectedArray) < 1) {
66 3
            $sql = 'INSERT INTO '.$tableName;
67 3
            $sql .= '('.$this->splitTableField($tableFields).') ';
68 3
            $sql .= 'VALUES ('.$this->formatTableValues($tableValues).')';
69
70 3
            $bool = $this->dbConnection->exec($sql);
71
72 3
            return $bool;
73
        }
74
75 3
        throw new FieldUndefinedException('Oops, '.$this->splitTableField($unexpectedArray).' is not defined as a field');
76
    }
77
78
    /**
79
     * This method read the data in the table name of the id being passed to it.
80
     *
81
     * @param $id
82
     * @param $tableName
83
     *
84
     * @return array
85
     */
86 9
    public static function read($id, $tableName, $dbConn = null)
87
    {
88 9
        if (is_null($dbConn)) {
89
            $dbConn = new DataBaseConnection();
90
        }
91
92 9
        $sql = $id ? 'SELECT * FROM '.$tableName.' WHERE id = '.$id : 'SELECT * FROM '.$tableName;
93 9
        $statement = $dbConn->prepare($sql);
94 9
        $statement->execute();
95
    
96 9
        $results = $statement->fetchAll(PDO::FETCH_ASSOC);
97
98 9
        if (count($results) < 1) {
99 3
            throw new IdNotFoundException('Oops, the id '.$id.' is not in the database, try another id');
100
        }
101
102 6
        return $results;
103
    }
104
105
    /**
106
     * This method delete the table name of the id being passed to it.
107
     *
108
     * @param $update Params
109
     * @param $associativeArrayToUpdate
110
     * @param $tableName
111
     *
112
     * @return bool
113
     */
114 6
    public function update($updateParams, $associativeArrayToUpdate, $tableName, $dbConn = null)
115
    {
116 6
        $updateSql = "UPDATE `$tableName` SET ";
117
118 6
        unset($associativeArrayToUpdate['id']);
119
120 6
        foreach ($associativeArrayToUpdate as $key => $val) {
121 6
            $tableFields[] = $key;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$tableFields was never initialized. Although not strictly required by PHP, it is generally a good practice to add $tableFields = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
122 4
        }
123
124 6
        $unexpectedArray = array_diff($tableFields, $this->getColumnNames($tableName, $dbConn));
0 ignored issues
show
Bug introduced by
The variable $tableFields does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
125
126 6
        if (count($unexpectedArray) < 1) {
127 3
            $updateSql .= $this->updateArraySql($associativeArrayToUpdate);
128
            
129 3
            foreach ($updateParams as $field => $value) {
130 3
                $updateSql .= " WHERE $field = $value";
131 2
            }
132
133 3
            $statement = $this->dbConnection->exec($updateSql);
134
            
135 3
            return $statement;
136
        }
137
138 3
        throw new FieldUndefinedException('Oops, '.$this->splitTableField($unexpectedArray).' is not defined as a field');
139
    }
140
141
    /**
142
     * This method delete the table name of the id passed to it.
143
     *
144
     * @param $id
145
     * @param $tableName
146
     *
147
     * @return bool
148
     */
149 9
    public static function delete($id, $tableName, $dbConn = null)
150
    {
151 9
        if (is_null($dbConn)) {
152
            $dbConn = new DataBaseConnection();
153
        }
154
155 9
        $sql = 'SELECT * FROM '.$tableName.' WHERE id = '.$id;
156 9
        $statement = $dbConn->prepare($sql);
157 9
        $statement->execute();
158 9
        $results = $statement->fetchAll(PDO::FETCH_ASSOC);
159
160 9
        if (count($results) < 1) {
161 3
            throw new IdNotFoundException('Oops, the id '.$id.' is not in the database, try another id');
162
        }
163
164 6
        $sql = 'DELETE FROM '.$tableName.' WHERE id = '.$id;
165 6
        $statement = $dbConn->exec($sql);
0 ignored issues
show
Unused Code introduced by
$statement 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...
166
167 6
        return true;
168
    }
169
170
    /**
171
     * This method returns a string form an array by making us of the implode function.
172
     *
173
     * @param $tableField
174
     *
175
     * @return string
176
     */
177 15
    public function splitTableField($tableField)
178
    {
179 15
        $splitTableField = implode(', ', $tableField);
180
181 15
        return $splitTableField;
182
    }
183
184
    /**
185
     * This method returns a string formed fron an array, It format the array.
186
     *
187
     * @param $tableValues
188
     *
189
     * @return string
190
     */
191 3
    public function formatTableValues($tableValues)
192
    {
193 3
        $formattedValues = [];
194
195 3
        foreach ($tableValues as $key => $value) {
196 3
            $formattedValues[] = "'".$value."'";
197 2
        }
198
199 3
        $ValueSql = implode(',', $formattedValues);
200
201 3
        return $ValueSql;
202
    }
203
204
    /**
205
     * This method returns a string formed from an array.
206
     *
207
     * @param $array
208
     *
209
     * @return string
210
     */
211 6
    public function updateArraySql($array)
212
    {
213 6
        $updatedValues = [];
214
215 6
        foreach ($array as $key => $val) {
216 6
            $updatedValues[] = "`$key` = '$val'";
217 4
        }
218
219 6
        $valueSql = implode(',', $updatedValues);
220
221 6
        return $valueSql;
222
    }
223
224
    /**
225
     * This method returns column fields of a particular table.
226
     *
227
     * @param $table
228
     *
229
     * @return array
230
     */
231 15
    public function getColumnNames($table, $dbConn = null)
0 ignored issues
show
Unused Code introduced by
The parameter $dbConn is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
232
    {
233 15
        $tableFields = [];
234
235 15
        $sql = 'SHOW COLUMNS FROM '.$table;
236 15
        $stmt = $this->dbConnection->prepare($sql);
237 15
        $stmt->bindValue(':table', $table, PDO::PARAM_STR);
238 15
        $stmt->execute();
239 15
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
240
241 15
        foreach ($results as $result) {
242 15
            array_push($tableFields, $result['Field']);
243 10
        }
244
245 15
        return $tableFields;
246
    }
247
}
248