Passed
Push — master ( 0d66f5...cc4d3c )
by George
03:27
created

PostgresqlStore::storeCsvRows()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 32
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 32
ccs 0
cts 21
cp 0
rs 8.5806
cc 4
eloc 18
nc 5
nop 0
crap 20
1
<?php
2
namespace JsonTable\Store;
3
4
use \JsonTable\Base;
5
6
/**
7
 * Postgresql store.
8
 *
9
 * @package JSON table
10
 */
11
class PostgresqlStore extends AbstractStore
12
{
13
    /**
14
     * @var string  The name of the table to store the data into.
15
     */
16
    private $tableName;
17
18
    /**
19
     * @var string  The name of the primary key column in the table the data is being stored in.
20
     */
21
    private $primaryKey;
22
23
    /**
24
     * @var array      Data type and format metadata for each column being inserted.
25
     *                 The Key is the CSV column position in the file and value is an array of:
26
     *                     "pdo_type" - The PDO data type
27
     *                     "type" - The schema data type
28
     *                     "format" - The schema format.
29
     */
30
    private $column_metadata = [];
31
32
    /**
33
     * @var string  The CSV list of columns to be inserted into.
34
     */
35
    private $columnList;
36
37
    /**
38
     * @var string  The parameters to be used in the insert statement.
39
     */
40
    private $insertParameters;
41
42
    /**
43
     * @var int The current CSV row being stored.
44
     */
45
    private $currentCsvRow;
46
47
    /**
48
     * @var int The position of the current CSV row row in the CSV file.
49
     */
50
    private $rowNumber;
51
52
    /**
53
     * @var int The position of the current CSV field in the current row.
54
     */
55
    private $fieldNumber;
56
57
58
    /**
59
     * @static
60
     *
61
     * @var array Mappings of JSON table types to PDO param types.
62
     */
63
    private static $pdo_type_mappings = [
64
        'any' => \PDO::PARAM_STR,
65
        'array' => \PDO::PARAM_STR,
66
        'boolean' => \PDO::PARAM_BOOL,
67
        'date' => \PDO::PARAM_STR,
68
        'datetime' => \PDO::PARAM_STR,
69
        'time' => \PDO::PARAM_STR,
70
        'integer' => \PDO::PARAM_INT,
71
        'null' => \PDO::PARAM_NULL,
72
        'number' => \PDO::PARAM_STR,
73
        'string' => \PDO::PARAM_STR
74
    ];
75
76
77
    /**
78
     * Store the data.
79
     *
80
     * @param   string  $tableName  The name of the table to save the data in. With optional schema prefix.
81
     * @param   string  $primaryKey The name of the primary key on the table. [optional] The default is "id".
82
     *                                  The primary key does not need to be listed in the CSV if it has
83
     *                                  a serial associated with it.
84
     *
85
     * @return  boolean true
86
     */
87
    public function store($tableName, $primaryKey = 'id')
88
    {
89
        $this->tableName = (string) $tableName;
90
        $this->primaryKey = (string) $primaryKey;
91
        Base::openFile();
92
        $this->setColumns();
93
        $this->setColumnsMetadata();
94
        $this->setInsertParameters();
95
        Base::rewindFilePointerToFirstData();
96
        $this->rowNumber = 1;
97
        $this->storeCsvRows();
98
99
        return true;
100
    }
101
102
103
    /**
104
     * Get the PDO type, schema type & schema format for each column in the CSV file.
105
     *
106
     * @return boolean true on success
107
     */
108
    private function setColumnsMetadata()
109
    {
110
        foreach (Base::$headerColumns as $li_csv_field_position => $ls_csv_column_name) {
111
            $la_metadata = [];
112
            $li_csv_field_position += 1;
113
114
            $li_schema_key = $this->getSchemaKeyFromName($ls_csv_column_name);
115
            $lo_schema_field = self::$schemaJson->fields[$li_schema_key];
116
117
            $la_metadata['type'] = $this->getColumnType($lo_schema_field);
118
            $la_metadata['pdo_type'] = self::$pdo_type_mappings[$la_metadata['type']];
119
            $la_metadata['format'] = $this->getColumnFormat($lo_schema_field);
120
121
            $this->column_metadata[$li_csv_field_position] = $la_metadata;
122
        }
123
124
        return true;
125
    }
126
127
128
    /**
129
     * Set the columns that will be inserted into.
130
     * The columns include the "csv_row" field to store the CSV row
131
     * number to help make error messages more useful.
132
     *
133
     * @return  void
134
     */
135
    private function setColumns()
136
    {
137
        $this->columnList = implode(', ', Base::$headerColumns);
138
        $this->columnList .= ', csv_row';
139
    }
140
141
142
    /**
143
     * Set the insert parameters string.
144
     *
145
     * @return  void
146
     */
147
    private function setInsertParameters()
148
    {
149
        $this->insertParameters = implode(', ', array_fill(0, count(Base::$headerColumns), '?'));
150
        $this->insertParameters .= ', ?';
151
    }
152
153
154
    /**
155
     * Store each of the CSV rows.
156
     *
157
     * @return  void
158
     *
159
     * @throws  \Exception if the row couldn't be inserted into the database.
160
     */
161
    private function storeCsvRows()
162
    {
163
        while ($this->currentCsvRow = Base::loopThroughFileRows()) {
0 ignored issues
show
Documentation Bug introduced by
It seems like \JsonTable\Base::loopThroughFileRows() of type array or boolean is incompatible with the declared type integer of property $currentCsvRow.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
164
            $insertSql = "INSERT INTO $this->tableName (
165
                                  $this->columnList
166
                              )
167
                              VALUES (
168
                                  $this->insertParameters
169
                              )
170
                              RETURNING
171
                                $this->primaryKey AS key";
172
173
            $statement = self::$pdoConnection->prepare($insertSql);
174
            $this->fieldNumber = 1;
175
176
            foreach ($this->currentCsvRow as &$fieldValue) {
1 ignored issue
show
Bug introduced by
The expression $this->currentCsvRow of type array|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
177
                $columnMetadata = $this->column_metadata[$this->fieldNumber];
178
                $fieldValue = $this->updateFieldValue($columnMetadata, $fieldValue);
179
                $statement->bindParam($this->fieldNumber++, $fieldValue, $columnMetadata['pdo_type']);
180
            }
181
182
            $statement->bindParam($this->fieldNumber, $this->rowNumber, \PDO::PARAM_INT);
183
            $la_result = $statement->execute();
184
185
            if (false === $la_result) {
186
                throw new \Exception("Could not insert row $this->rowNumber into the database.");
187
            }
188
189
            $this->insertedIds[] = $statement->fetch(\PDO::FETCH_ASSOC);
190
            $this->rowNumber++;
191
        }
192
    }
193
194
195
    /**
196
     * Do any data manipulation required on the specified column's value.
197
     *
198
     * @param array     $columnMetadata The metadata about the column.
199
     * @param string    $fieldValue     The value to update.
200
     *
201
     * @return  string  The updated field value.
202
     */
203
    private function updateFieldValue($columnMetadata, $fieldValue)
204
    {
205
        if ('date' === $columnMetadata['type'] && 'default' !== $columnMetadata['format']) {
206
            $fieldValue = self::isoDateFromFormat($columnMetadata['format'], $fieldValue);
207
        }
208
209
        if ('boolean' === $columnMetadata['type']) {
210
            $fieldValue = self::booleanFromFilterBooleans($fieldValue);
211
        }
212
213
        if ('' === $fieldValue || '\N' === $fieldValue) {
214
            $fieldValue = null;
215
        }
216
217
        return $fieldValue;
218
    }
219
}
220