Completed
Push — master ( a98764...852cbb )
by diego
25s
created

InsertUpdateTable   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 212
Duplicated Lines 4.72 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 27
lcom 1
cbo 5
dl 10
loc 212
ccs 0
cts 81
cp 0
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A start() 0 13 3
B processEntry() 0 26 5
A getRecords() 0 18 2
B insertRecord() 5 22 4
B updateRecord() 5 23 4
A duplicateArray() 0 14 4
A saltPassword() 0 13 3
A isValidMd5() 0 4 1
A end() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
namespace HDNET\Importr\Service\Targets;
3
4
use HDNET\Importr\Domain\Model\Strategy;
5
use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;
6
use HDNET\Importr\Utility;
7
8
/**
9
 * Imports records from a .CSV file into the target table which you
10
 * can specify on the target section in your strategy.
11
 * If a record does not exist in the table, it will be inserted,
12
 * otherwise it will be just updated. No duplicates are created.
13
 *
14
 * complete example (strategy target):
15
 *
16
 * HDNET\Importr\Service\Targets\InsertUpdateTable:
17
 *   target_table: fe_users
18
 *   exclude_from_update:
19
 *     0: password
20
 *     1: first_name
21
 *     2: zip
22
 *   pid: 324
23
 *   identifier: username
24
 *   salt_password: 1
25
 *   mapping:
26
 *     0: username
27
 *     1: password
28
 *     2: usergroup
29
 *     3: name
30
 *     4: first_name
31
 *     5: address
32
 *     6: telephone
33
 *     7: email
34
 *     8: zip
35
 *     9: city
36
 *     10: company
37
 *
38
 * Example CSV:
39
 *
40
 * username;password;usergroup;name;first_name;address;telephone;email;zip;city;company
41
 * EduardFekete;PW123;3;Fekete;Eduard; Example 21; +049123456789;[email protected];91550;Feuchtwangen;MB Connect Line GmbH
42
 * HansVader;PW1234;3;Vader;Hans; Example 22; +049123456710;[email protected];99900;Universe;Hollywood Studios
43
 *
44
 * ------------------------------------------------------------------------------------------------
45
 *
46
 *   exclude_from_update:    the elements specified in this array, are never being updated
47
 *
48
 *   salt_password:          if set to 1 then passwords are being salted before they are stored in the database
49
 *
50
 * ------------------------------------------------------------------------------------------------
51
 * @author Eduard Fekete
52
 */
53
class InsertUpdateTable extends DbRecord implements TargetInterface
54
{
55
    /**
56
     * @var int
57
     */
58
    protected $identifierField;
59
60
    /**
61
     * @param Strategy $strategy
62
     */
63
    public function start(Strategy $strategy)
64
    {
65
        parent::start($strategy);
66
        if (!isset($this->getConfiguration()['identifier'])) {
67
            throw new \RuntimeException('Identifier field is missing!');
68
        }
69
        $identifier = $this->getConfiguration()['identifier'];
70
        $identifierField = array_search($identifier, $this->getConfiguration()['mapping']);
71
        if ($identifierField === false) {
72
            throw new \RuntimeException('Identifier field not found in mapping.');
73
        }
74
        $this->identifierField = $identifierField;
75
    }
76
77
    /**
78
     * Process every entry in the .csv
79
     *
80
     * @param array $entry
81
     *
82
     * @return int|void
83
     */
84
    public function processEntry(array $entry)
85
    {
86
        $record_exists = false;
87
        $entry_identifier = $entry[$this->identifierField];
88
        $records = $this->getRecords("*");
89
        $fieldName = $this->getConfiguration()['mapping'][$this->identifierField];
90
91
        foreach ($records as $record) {
0 ignored issues
show
Bug introduced by Tim Spiekerkötter
The expression $records of type array|null 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...
92
            if ($record['deleted'] == 0) {
93
                if ($record[$fieldName] == $entry_identifier) {
94
                    $record_exists = true;
95
                    break;
96
                }
97
            } else {
98
                continue;
99
            }
100
        }
101
102
        if ($record_exists) {
103
            $this->updateRecord($entry);
104
            return TargetInterface::RESULT_UPDATE;
105
        }
106
107
        $this->insertRecord($entry);
108
        return TargetInterface::RESULT_INSERT;
109
    }
110
111
    /**
112
     *
113
     * Fetch all records from the target table, where the PID equals the PID specified
114
     * in the target section of the strategy
115
     *
116
     * @param $selectFields
117
     * @return array
118
     */
119
    protected function getRecords($selectFields)
120
    {
121
        static $records = [];
122
        if ($records) {
0 ignored issues
show
Bug Best Practice introduced by Tim Spiekerkötter
The expression $records of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
123
            return $records;
124
        }
125
126
        $fromTable = $this->getConfiguration()['target_table'];
127
        $whereStatement = "pid = '" . $this->getConfiguration()['pid'] . "'";
128
129
        $records = Utility::getDatabaseConnection()->exec_SELECTgetRows(
130
            $selectFields,
131
            $fromTable,
132
            $whereStatement
133
        );
134
135
        return $records;
136
    }
137
138
    /**
139
     * Insert record into the target table which you have specified in the target section of the strategy
140
     *
141
     * @param array $entry
142
     *
143
     * @return void
144
     */
145
    protected function insertRecord(array $entry)
146
    {
147
        $field_values = [];
148
        $into_table = $this->getConfiguration()['target_table'];
149
150
        foreach ($this->getConfiguration()["mapping"] as $key => $value) {
151
            $field_values[$value] = $entry[$key];
152
        }
153
        
154 View Code Duplication
        if ($this->getConfiguration()["salt_password"] == 1) {
0 ignored issues
show
Duplication introduced by Eduard Fekete
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
155
            if (array_key_exists("password", $field_values)) {
156
                $field_values["password"] = $this->saltPassword($field_values["password"]);
157
            }
158
        }
159
160
        $field_values['pid'] = $this->getConfiguration()['pid'];
161
        $time = time();
162
        $field_values['tstamp'] = $time;
163
        $field_values['crdate'] = $time;
164
        
165
        Utility::getDatabaseConnection()->exec_INSERTquery($into_table, $field_values);
166
    }
167
168
    /**
169
     * Update a record in the target table which you have specified in the
170
     * target section of the strategy (don't update the password)
171
     *
172
     * @param array $entry
173
     *
174
     * @return void
175
     */
176
    protected function updateRecord(array $entry)
177
    {
178
        $into_table = $this->getConfiguration()['target_table'];
179
        $fieldName = $this->getConfiguration()['mapping'][$this->identifierField];
180
        $whereStatement = "pid = '" . $this->getConfiguration()['pid'] . "' AND " . $fieldName . " = '" . $entry[$this->identifierField] . "'";
181
182
        $tmp_arr = [];
183
184
        foreach ($this->getConfiguration()["mapping"] as $key => $value) {
185
            $tmp_arr[$value] = $entry[$key];
186
        }
187
        
188 View Code Duplication
        if ($this->getConfiguration()["salt_password"] == 1) {
0 ignored issues
show
Duplication introduced by Eduard Fekete
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
189
            if (array_key_exists("password", $tmp_arr)) {
190
                $tmp_arr["password"] = $this->saltPassword($tmp_arr["password"]);
191
            }
192
        }
193
        
194
        $field_values = $this->duplicateArray($tmp_arr, $this->getConfiguration()['exclude_from_update']);
195
        $field_values['tstamp'] = time();
196
197
        Utility::getDatabaseConnection()->exec_UPDATEquery($into_table, $whereStatement, $field_values);
198
    }
199
200
    /**
201
     * This function creates a duplicate of a associative array and optionally removes
202
     * any entries which are also elements of a second array
203
     *
204
     * @param array $arr
205
     * @param array $exclude_arr
206
     *
207
     * @return array
208
     */
209
    protected function duplicateArray(array $arr, array $exclude_arr = null)
210
    {
211
        if (!is_array($exclude_arr)) {
212
            return $arr;
213
        }
214
215
        foreach ($arr as $key => $_) {
216
            if (in_array($key, $exclude_arr)) {
217
                unset($arr[$key]);
218
            }
219
        }
220
221
        return $arr;
222
    }
223
    
224
    /**
225
    * This function takes a password as argument, salts it and returns the new password.
226
    *
227
    * @param string $password
228
    *
229
    * @return string
230
    */
231
    protected function saltPassword($password)
232
    {
233
        if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('saltedpasswords')) {
234
            $saltedpasswordsInstance = \TYPO3\CMS\Saltedpasswords\Salt\SaltFactory::getSaltingInstance(null, 'FE');
235
            $password = $saltedpasswordsInstance->getHashedPassword($password);
236
237
            if ($this->isValidMd5($password)) {
238
                $password = 'M' . $password;
239
            }
240
        }
241
242
        return $password;
243
    }
244
    
245
    /**
246
    * This function checks if a password is in md5 format.
247
    *
248
    * @param string $md5
249
    *
250
    * @return int
251
    */
252
    protected function isValidMd5($md5 = '')
253
    {
254
        return preg_match('/^[a-f0-9]{32}$/', $md5);
255
    }
256
257
    /**
258
     *
259
     */
260
    public function end()
261
    {
262
        parent::end();
263
    }
264
}
265