Completed
Push — master ( fd261f...f30db2 )
by Adeola
02:28
created

DataBaseQuery::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.1481

Importance

Changes 6
Bugs 1 Features 0
Metric Value
c 6
b 1
f 0
dl 0
loc 9
ccs 4
cts 6
cp 0.6667
rs 9.6666
cc 2
eloc 5
nc 2
nop 1
crap 2.1481
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 39
    public function __construct($dbConn = null)
35
    {
36 39
        if (is_null($dbConn)) {
37
            $this->dataBaseConnection = new DataBaseConnection(); 
38
        } else {
39 39
             $dbConn = $this->dataBaseConnection;
0 ignored issues
show
Unused Code introduced by
$dbConn 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...
40
        }   
41
        //$this->dataBaseConnection = $dataBaseConnection;
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
42 39
    }
43
44
    /**
45
     * This method create or insert new users to the table.
46
     *
47
     * @param $associativeArray
48
     * @param $tableName
49
     *
50
     * @return array
51
     */
52 9
    public function create($associativeArray, $tableName, $dbConn = null)
53
    {
54 9
        if (is_null($dbConn)) {
55
            $dbConn = $this->dataBaseConnection;
56
        }
57 9
        $tableFields = [];
58 9
        $tableValues = [];
59
60 9
        foreach ($associativeArray as $key => $val) {
61 9
            $tableFields[] = $key;
62 9
            $tableValues[] = $val;
63 6
        }
64 9
        $unexpectedArray = array_diff($tableFields, $this->getColumnNames($tableName, $dbConn));
65
        
66 9
        if (count($unexpectedArray) < 1) {
67 3
            $sql = 'INSERT INTO '.$tableName;
68 3
            $sql .= '('.$this->splitTableField($tableFields).') ';
69 3
            $sql .= 'VALUES ('.$this->formatTableValues($tableValues).')';
70 3
            $statement = $dbConn->exec($sql);
71
            //var_dump($sql);
72 3
            return $statement;
73
        }
74
75 6
        throw new FieldUndefinedException('Oops, please input the following field: NAME, SEX, OCCUPATION, ORGANISATION AND YEAR');
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 12
    public static function read($id, $tableName, $dbConn = null)
87
    {
88 12
        if (is_null($dbConn)) {
89
            $dbConn = new DataBaseConnection();
90
        }
91
92 12
        $tableData = [];
93 12
        $sql = $id ? 'SELECT * FROM '.$tableName.' WHERE id = '.$id : 'SELECT * FROM '.$tableName;
94 12
        $statement = $dbConn->prepare($sql);
95 12
        $statement->execute();
96 12
        $results = $statement->fetchAll(PDO::FETCH_ASSOC);
97
98 12
        foreach ($results as $result) {
99 9
            array_push($tableData, $result);
100 8
        }
101
102 12
        if (count($tableData) < 1) {
103 3
            throw new IdNotFoundException('Oops, the id '.$id.' is not in the database, try another id');
104
        }
105
106 9
        return $tableData;
107
    }
108
109
    /**
110
     * This method delete the table name of the id being passed to it.
111
     *
112
     * @param $update Params
113
     * @param $associativeArray
114
     * @param $tableName
115
     *
116
     * @return bool
117
     */
118 6
    public function update($updateParams, $associativeArray, $tableName, $dbConn = null)
119
    {
120 6
        if (is_null($dbConn)) {
121
            $dbConn = $this->dataBaseConnection;
122
        }
123 6
        $sql = '';
0 ignored issues
show
Unused Code introduced by
$sql 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...
124 6
        $updateSql = "UPDATE `$tableName` SET ";
125
126 6
        unset($associativeArray['id']);
127
128 6
        foreach ($associativeArray as $key => $val) {
129 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...
130 4
        }
131
132 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...
133
134 6
        if (count($unexpectedArray) < 1) {
135 3
            $updateSql .= $this->updateArraySql($associativeArray);
136
137 3
            foreach ($updateParams as $field => $value) {
138 3
                $updateSql .= " WHERE $field = $value";
139 2
            }
140
141 3
            $statement = $dbConn->exec($updateSql);
142
143 3
            return $statement ?: false;
144
        }
145
146 3
        throw new FieldUndefinedException('Oops, please input the following field: NAME, SEX, OCCUPATION, ORGANISATION AND YEAR');
147
    }
148
149
    /**
150
     * This method delete the table name of the id passed to it.
151
     *
152
     * @param $id
153
     * @param $tableName
154
     *
155
     * @return bool
156
     */
157 6
    public static function delete($id, $tableName, $dbConn = null)
158
    {
159 6
        if (is_null($dbConn)) {
160
            $dbConn = new DataBaseConnection();
161
        }
162 6
        $sql = 'DELETE FROM '.$tableName.' WHERE id = '.$id;
163 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...
164
165 6
        return true;
166
    }
167
168
    /**
169
     * This method returns a string form an array by making us of the implode function.
170
     *
171
     * @param $tableField
172
     *
173
     * @return string
174
     */
175 3
    public function splitTableField($tableField)
176
    {
177 3
        $splitTableField = implode(',', $tableField);
178 3
        return $splitTableField;
179
    }
180
181
    /**
182
     * This method returns a string formed fron an array, It format the array.
183
     *
184
     * @param $tableValues
185
     *
186
     * @return string
187
     */
188 3
    public function formatTableValues($tableValues)
189
    {
190 3
        $formattedValues = [];
191
192 3
        foreach ($tableValues as $key => $value) {
193 3
            $formattedValues[] = "'".$value."'";
194 2
        }
195
196 3
        $ValueSql = implode(',', $formattedValues);
197
198 3
        return $ValueSql;
199
    }
200
201
    /**
202
     * This method returns a string formed from an array.
203
     *
204
     * @param $array
205
     *
206
     * @return string
207
     */
208 3
    public function updateArraySql($array)
209
    {
210 3
        $updatedValues = [];
211
212 3
        foreach ($array as $key => $val) {
213 3
            $updatedValues[] = "`$key` = '$val'";
214 2
        }
215
216 3
        $valueSql = implode(',', $updatedValues);
217
218 3
        return $valueSql;
219
    }
220
221
    /**
222
     * This method returns column fields of a particular table.
223
     *
224
     * @param $table
225
     *
226
     * @return array
227
     */
228 18
    public function getColumnNames($table, $dbConn = null)
229
    {
230 18
        if (is_null($dbConn)) {
231
            $dbConn = new DataBaseConnection();
232
        }
233 18
        $tableFields = [];
234
235 18
        $sql = 'SHOW COLUMNS FROM '.$table;
236 18
        $stmt = $dbConn->prepare($sql);
237 18
        $stmt->bindValue(':table', $table, PDO::PARAM_STR);
238 18
        $stmt->execute();
239 18
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
240
241 18
        foreach ($results as $result) {
242 18
            array_push($tableFields, $result['Field']);
243 12
        }
244
245 18
        return $tableFields;
246
    }
247
}
248