Conditions | 7 |
Paths | 8 |
Total Lines | 48 |
Lines | 0 |
Ratio | 0 % |
Tests | 28 |
CRAP Score | 7.0444 |
Changes | 0 |
Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.
There are several approaches to avoid long parameter lists:
1 | <?php |
||
12 | 2 | public function loadData( |
|
|
|||
13 | $table, |
||
14 | $file, |
||
15 | $local = false, |
||
16 | array $columns = [], |
||
17 | array $set = [], |
||
18 | $delimiter = ",", |
||
19 | $enclosure = '"', |
||
20 | $escape = '\\', |
||
21 | $termination = '\n', |
||
22 | $optionallyEnclosed = true |
||
23 | ) { |
||
24 | 2 | $csv = new \SplFileObject($file, 'r'); |
|
25 | 2 | $table = $this->connection->quoteIdentifier($table); |
|
26 | 2 | $columnsPart = ''; |
|
27 | 2 | if (!empty($columns)) { |
|
28 | $columns = array_map([$this->connection, 'quoteIdentifier'], $columns); |
||
29 | $columnsPart = '(' . implode(',', $columns) . ')'; |
||
30 | } |
||
31 | 2 | $valuesPart = ''; |
|
32 | 2 | $row = $csv->fgetcsv($delimiter, $enclosure, $escape); |
|
33 | 2 | $csv->rewind(); |
|
34 | 2 | if (!empty($row)) { |
|
35 | $row = array_map(function () { |
||
36 | 2 | return '?'; |
|
37 | 2 | }, $row); |
|
38 | 2 | $valuesPart = '(' . implode(',', $row) . ')'; |
|
39 | 2 | } |
|
40 | $sql = <<<MYSQL |
||
41 | 2 | INSERT INTO $table $columnsPart |
|
42 | 2 | VALUES $valuesPart |
|
43 | 2 | MYSQL; |
|
44 | 2 | $count = 0; |
|
45 | while ( |
||
46 | 2 | ($row = $csv->fgetcsv($delimiter, $enclosure, $escape)) !== null && |
|
47 | 2 | $row != [null] && |
|
48 | $row !== false |
||
49 | 2 | ) { |
|
50 | 2 | $row = array_map(function ($var) { |
|
51 | 2 | if ($var === '\N') { |
|
52 | 1 | return null; |
|
53 | } |
||
54 | 2 | return $var; |
|
55 | 2 | }, $row); |
|
56 | 2 | $count += $this->connection->executeUpdate($sql, $row); |
|
57 | 2 | } |
|
58 | 2 | return $count; |
|
59 | } |
||
60 | } |
||
61 |
A high number of parameters is generally an indication that you should consider creating a dedicated object for the parameters.
Let’s take a look at an example:
could be refactored to: