Passed
Push — master ( cc4d3c...8a136e )
by George
04:18
created

PostgresqlStore::setColumnsMetadata()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 2

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 18
ccs 12
cts 12
cp 1
rs 9.4285
cc 2
eloc 11
nc 2
nop 0
crap 2
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 array 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 2
    public function store($tableName, $primaryKey = 'id')
88
    {
89 2
        $this->tableName = (string) $tableName;
90 2
        $this->primaryKey = (string) $primaryKey;
91 2
        Base::openFile();
92 2
        $this->setColumns();
93 2
        $this->setColumnsMetadata();
94 2
        $this->setInsertParameters();
95 2
        Base::rewindFilePointerToFirstData();
96 2
        $this->rowNumber = 1;
97 2
        $this->storeCsvRows();
98
99 1
        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 2
    private function setColumnsMetadata()
109
    {
110 2
        foreach (Base::$headerColumns as $li_csv_field_position => $ls_csv_column_name) {
111 2
            $la_metadata = [];
112 2
            $li_csv_field_position += 1;
113
114 2
            $li_schema_key = $this->getSchemaKeyFromName($ls_csv_column_name);
115 2
            $lo_schema_field = self::$schemaJson->fields[$li_schema_key];
116
117 2
            $la_metadata['type'] = $this->getColumnType($lo_schema_field);
118 2
            $la_metadata['pdo_type'] = self::$pdo_type_mappings[$la_metadata['type']];
119 2
            $la_metadata['format'] = $this->getColumnFormat($lo_schema_field);
120
121 2
            $this->column_metadata[$li_csv_field_position] = $la_metadata;
122 2
        }
123
124 2
        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 2
    private function setColumns()
136
    {
137 2
        $this->columnList = implode(', ', Base::$headerColumns);
138 2
        $this->columnList .= ', csv_row';
139 2
    }
140
141
142
    /**
143
     * Set the insert parameters string.
144
     *
145
     * @return  void
146
     */
147 2
    private function setInsertParameters()
148
    {
149 2
        $this->insertParameters = implode(', ', array_fill(0, count(Base::$headerColumns), '?'));
150 2
        $this->insertParameters .= ', ?';
151 2
    }
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 2
    private function storeCsvRows()
162
    {
163 2
        while ($csvRow = Base::loopThroughFileRows()) {
164 2
            $this->currentCsvRow = $csvRow;
1 ignored issue
show
Documentation Bug introduced by
It seems like $csvRow can also be of type boolean. However, the property $currentCsvRow is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
165
            
166 2
            $insertSql = "INSERT INTO $this->tableName (
167 2
                                  $this->columnList
168
                              )
169
                              VALUES (
170 2
                                  $this->insertParameters
171
                              )
172
                              RETURNING
173 2
                                $this->primaryKey AS key";
174
175 2
            $statement = self::$pdoConnection->prepare($insertSql);
176 2
            $this->fieldNumber = 1;
177
178 2
            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...
179 2
                $columnMetadata = $this->column_metadata[$this->fieldNumber];
180 2
                $fieldValue = $this->updateFieldValue($columnMetadata, $fieldValue);
181 2
                $statement->bindParam($this->fieldNumber++, $fieldValue, $columnMetadata['pdo_type']);
182 2
            }
183
184 2
            $statement->bindParam($this->fieldNumber, $this->rowNumber, \PDO::PARAM_INT);
185 2
            $la_result = $statement->execute();
186
187 2
            if (false === $la_result) {
188 1
                throw new \Exception("Could not insert row $this->rowNumber into the database.");
189
            }
190
191 1
            $this->insertedIds[] = $statement->fetch(\PDO::FETCH_ASSOC);
192 1
            $this->rowNumber++;
193 1
        }
194 1
    }
195
196
197
    /**
198
     * Do any data manipulation required on the specified column's value.
199
     *
200
     * @param array     $columnMetadata The metadata about the column.
201
     * @param string    $fieldValue     The value to update.
202
     *
203
     * @return  string  The updated field value.
204
     */
205 2
    private function updateFieldValue($columnMetadata, $fieldValue)
206
    {
207 2
        if ('date' === $columnMetadata['type'] && 'default' !== $columnMetadata['format']) {
208
            $fieldValue = self::isoDateFromFormat($columnMetadata['format'], $fieldValue);
209
        }
210
211 2
        if ('boolean' === $columnMetadata['type']) {
212 2
            $fieldValue = self::booleanFromFilterBooleans($fieldValue);
213 2
        }
214
215 2
        if ('' === $fieldValue || '\N' === $fieldValue) {
216 2
            $fieldValue = null;
217 2
        }
218
219 2
        return $fieldValue;
220
    }
221
222
223
    /**
224
     * Get the returned primary key of any rows that have been stored.
225
     *
226
     * @return  array   The primary keys.
227
     */
228 1
    public function getInsertedIds()
229
    {
230 1
        return $this->insertedIds;
231
    }
232
}
233