Completed
Pull Request — master (#10)
by
unknown
02:49
created

InsertUpdateTable::getConfiguration()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 8
Ratio 88.89 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 8
loc 9
ccs 0
cts 5
cp 0
rs 9.6666
c 0
b 0
f 0
cc 3
eloc 5
nc 2
nop 0
crap 12
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 52 and the first side effect is on line 248.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
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
  *   model: TYPO3\CMS\Extbase\Domain\Model\FrontendUser
18
  *   repository: TYPO3\CMS\Extbase\Domain\Repository\FrontendUserRepository
19
  *   target_table: fe_users
20
  *   exclude_from_update:
21
  *     0: password
22
  *     1: first_name
23
  *     2: zip
24
  *   pid: 324
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;BestPwEU1234;3;Fekete;Eduard; Mystreet 21; +049123456789;[email protected];91550;Feuchtwangen;MB Connect Line GmbH
42
  * HansVader;SecondBestPwEU1234;3;Vader;Hans; Hisstreet 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
  * ------------------------------------------------------------------------------------------------
49
  * @author Eduard Fekete
50
  */
51
52
class InsertUpdateTable extends AbstractTarget implements TargetInterface
53
{
54
    /**
55
     * @var array
56
     */
57
    protected $table_records;
58
59
    /**
60
     * @var array
61
     */
62
    protected $configuration;
63
64
    /**
65
     * @var string
66
     */
67
    protected $firstTime = "1";
68
69
    /**
70
     * @var Strategy
71
     */
72
    protected $strategy;
73
74
    /**
75
     * @return array
76
     */
77 View Code Duplication
    public function getConfiguration()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
78
    {
79
        $configuration = parent::getConfiguration();
80
        if (!isset($configuration['pid']) || !is_numeric($configuration['pid'])) {
81
            $configuration['pid'] = 0;
82
        }
83
84
        return $configuration;
85
    }
86
87
    /**
88
     * @param \HDNET\Importr\Domain\Model\Strategy $strategy
89
     *
90
     * @return void
91
     */
92
    public function start(Strategy $strategy)
93
    {
94
        $this->strategy = $strategy;
95
    }
96
97
    /**
98
     * Process every entry in the .csv
99
     *
100
     * @param array $entry
101
     *
102
     * @return int|void
103
     */
104
    public function processEntry(array $entry)
105
    {
106
        $record_exists    = false;
107
        $entry_username   = $entry['0'];
108
109
        $this->configuration    = $this->getConfiguration();
110
111
        if ($this->firstTime == "1") {
112
            $this->firstTime = 0;
0 ignored issues
show
Documentation Bug introduced by
The property $firstTime was declared of type string, but 0 is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
113
            $this->getRecords("*");
114
        }
115
116
        foreach ($this->table_records as $record){
117
            if ($record['deleted'] == 0){
118
                if ($record['username'] == $entry_username){
119
                    $record_exists = true;
120
                    break;
121
                }
122
            }
123
            else {
124
                continue;
125
            }
126
        }
127
128
        if ($record_exists){
129
            $this->updateRecord($entry);
130
            return TargetInterface::RESULT_UPDATE;
131
        }
132
        else { 
133
            $this->insertRecord($entry);
134
            return TargetInterface::RESULT_INSERT;
135
        }
136
    }
137
138
    /**
139
     *
140
     * Fetch all records from the target table, where the PID equals the PID specified in the target section of the strategy 
141
     *
142
     * @return void
143
     */
144
    public function getRecords($selectFields)
0 ignored issues
show
Coding Style introduced by
getRecords uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
145
    {
146
        $fromTable        = $this->configuration['target_table'];
147
        $whereStatement   = "pid = '".$this->configuration['pid']."'";
148
149
        $GLOBALS['TYPO3_DB']->store_lastBuiltQuery = 1;
150
151
        $this->table_records = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows
152
        (
153
            $selectFields,
154
            $fromTable,
155
            $whereStatement
156
        );
157
    }
158
159
    /**
160
     * Insert record into the target table which you have specified in the target section of the strategy 
161
     *
162
     * @param array $entry
163
     *
164
     * @return void
165
     */
166
    public function insertRecord(array $entry)
0 ignored issues
show
Coding Style introduced by
insertRecord uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
167
    {
168
        $field_values       = array();
169
        $into_table         = $this->configuration['target_table'];
170
171
        foreach ($this->configuration["mapping"] as $key => $value){
172
            $field_values[$value] = $entry[$key];
173
        }
174
175
        $field_values['pid']      = $this->configuration['pid'];
176
        $field_values['tstamp']   = time();
177
        $field_values['crdate']   = time();
178
              
179
        $GLOBALS['TYPO3_DB']->exec_INSERTquery( $into_table, $field_values);
180
        $GLOBALS['TYPO3_DB']->sql_insert_id();
181
    }
182
183
     /**
184
     * Update a record in the target table which you have specified in the target section of the strategy (don't update the password)
185
     *
186
     * @param array $entry
187
     *
188
     * @return void
189
     */
190
    public function updateRecord(array $entry)
0 ignored issues
show
Coding Style introduced by
updateRecord uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
191
    {
192
        $into_table       = $this->configuration['target_table'];
193
        $whereStatement   = "pid = '".$this->configuration['pid']."' AND username = '".$entry[0]."'";
194
                           
195
        $field_values     = array();
0 ignored issues
show
Unused Code introduced by
$field_values 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...
196
        $tmp_arr          = array();
197
198
        foreach ($this->configuration["mapping"] as $key => $value){
199
            $tmp_arr[$value] = $entry[$key];
200
        }
201
202
        $field_values = $this->duplicateArray($tmp_arr,$this->configuration['exclude_from_update']);
203
        $field_values['tstamp'] = time();
204
        
205
        $res = $GLOBALS['TYPO3_DB']->exec_UPDATEquery( $into_table , $whereStatement , $field_values );
0 ignored issues
show
Unused Code introduced by
$res 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...
206
        $cnt = $GLOBALS['TYPO3_DB']->sql_affected_rows();
0 ignored issues
show
Unused Code introduced by
$cnt 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...
207
    }
208
209
    /**
210
    * This function creates a duplicate of a associative array and optionally removes
211
    * any entries which are also elements of a second array
212
    *
213
    * @param array $arr
214
    * @param array $exclude_arr
215
    *
216
    * @return array
217
    */
218
    public function duplicateArray(array $arr, array $exclude_arr = null)
219
    {
220
        $exclude = false;
221
222
        if ($exclude_arr != null) {
223
            $exclude_max = count($exclude_arr);
224
            if (count($exclude_arr) > 0){
225
                $exclude = true;
226
            }
227
228
            foreach ($arr as $parentkey => $parentvalue)
229
            {
230
                $chk = $exclude_max;
0 ignored issues
show
Unused Code introduced by
$chk 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...
231
232
                if ($exclude) {
233
                    foreach ($exclude_arr as $key => $value) {
234
                        if ($value == $parentkey){
235
                            unset($arr[$parentkey]);
236
                        }
237
                    }
238
                }
239
            }
240
        }
241
242
        return $arr;
243
    }
244
245
    public function end()
246
    {
247
    }
248
};
249