Completed
Push — master ( af423c...f81b31 )
by Adeola
02:40
created

DataBaseQuery::create()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 3.0146

Importance

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