Completed
Push — master ( f26c6c...1e867a )
by Adeola
02:38
created

DataBaseQuery::create()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 3

Importance

Changes 12
Bugs 3 Features 1
Metric Value
c 12
b 3
f 1
dl 0
loc 26
ccs 15
cts 15
cp 1
rs 8.8571
cc 3
eloc 14
nc 4
nop 3
crap 3
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 60
    public function __construct($dbConn = null)
35
    {
36 60
        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 60
            $this->dbConnection = $dbConn;
40
        }
41 60
    }
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
            $statement = $this->dbConnection->exec($sql);
71
72 3
            return $statement;
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 9
        $results = $statement->fetchAll(PDO::FETCH_ASSOC);
96
97 9
        if (count($results) < 1) {
98 3
            throw new IdNotFoundException('Oops, the id '.$id.' is not in the database, try another id');
99
        }
100
101 6
        return $results;
102
    }
103
104
    /**
105
     * This method delete the table name of the id being passed to it.
106
     *
107
     * @param $update Params
108
     * @param $associativeArray
109
     * @param $tableName
110
     *
111
     * @return bool
112
     */
113 6
    public function update($updateParams, $associativeArray, $tableName, $dbConn = null)
114
    {
115 6
        $updateSql = "UPDATE `$tableName` SET ";
116
117 6
        unset($associativeArray['id']);
118
119 6
        foreach ($associativeArray as $key => $val) {
120 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...
121 4
        }
122
123 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...
124
125 6
        if (count($unexpectedArray) < 1) {
126 3
            $updateSql .= $this->updateArraySql($associativeArray);
127
128 3
            foreach ($updateParams as $field => $value) {
129 3
                $updateSql .= " WHERE $field = $value";
130 2
            }
131
132 3
            $statement = $this->dbConnection->exec($updateSql);
133
134 3
            return $statement ?: false;
135
        }
136
137 3
        throw new FieldUndefinedException('Oops, '.$this->splitTableField($unexpectedArray).' is not defined as a field');
138
    }
139
140
    /**
141
     * This method delete the table name of the id passed to it.
142
     *
143
     * @param $id
144
     * @param $tableName
145
     *
146
     * @return bool
147
     */
148 6
    public static function delete($id, $tableName, $dbConn = null)
149
    {
150 6
        if (is_null($dbConn)) {
151
            $dbConn = new DataBaseConnection();
152
        }
153
154 6
        $sql = $id ? 'SELECT * FROM '.$tableName.' WHERE id = '.$id : 'SELECT * FROM '.$tableName;
155 6
        $statement = $dbConn->prepare($sql);
156 6
        $statement->execute();
157 6
        $results = $statement->fetchAll(PDO::FETCH_ASSOC);
158
159 6
        if (count($results) < 1) {
160
            throw new IdNotFoundException('Oops, the id '.$id.' is not in the database, try another id');
161
        }
162
163 6
        $sql = 'DELETE FROM '.$tableName.' WHERE id = '.$id;
164 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...
165
166 6
        return true;
167
    }
168
169
    /**
170
     * This method returns a string form an array by making us of the implode function.
171
     *
172
     * @param $tableField
173
     *
174
     * @return string
175
     */
176 15
    public function splitTableField($tableField)
177
    {
178 15
        $splitTableField = implode(', ', $tableField);
179
180 15
        return $splitTableField;
181
    }
182
183
    /**
184
     * This method returns a string formed fron an array, It format the array.
185
     *
186
     * @param $tableValues
187
     *
188
     * @return string
189
     */
190 3
    public function formatTableValues($tableValues)
191
    {
192 3
        $formattedValues = [];
193
194 3
        foreach ($tableValues as $key => $value) {
195 3
            $formattedValues[] = "'".$value."'";
196 2
        }
197
198 3
        $ValueSql = implode(',', $formattedValues);
199
200 3
        return $ValueSql;
201
    }
202
203
    /**
204
     * This method returns a string formed from an array.
205
     *
206
     * @param $array
207
     *
208
     * @return string
209
     */
210 6
    public function updateArraySql($array)
211
    {
212 6
        $updatedValues = [];
213
214 6
        foreach ($array as $key => $val) {
215 6
            $updatedValues[] = "`$key` = '$val'";
216 4
        }
217
218 6
        $valueSql = implode(',', $updatedValues);
219
220 6
        return $valueSql;
221
    }
222
223
    /**
224
     * This method returns column fields of a particular table.
225
     *
226
     * @param $table
227
     *
228
     * @return array
229
     */
230 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...
231
    {
232 15
        $tableFields = [];
233
234 15
        $sql = 'SHOW COLUMNS FROM '.$table;
235 15
        $stmt = $this->dbConnection->prepare($sql);
236 15
        $stmt->bindValue(':table', $table, PDO::PARAM_STR);
237 15
        $stmt->execute();
238 15
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
239
240 15
        foreach ($results as $result) {
241 15
            array_push($tableFields, $result['Field']);
242 10
        }
243
244 15
        return $tableFields;
245
    }
246
}
247