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

InsertUpdateTable::duplicateArray()   C

Complexity

Conditions 7
Paths 15

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 0
cts 13
cp 0
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 13
nc 15
nop 2
crap 56
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 50 and the first side effect is on line 240.

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 can specify on the target section in your strategy.
10
  * If a record does not exist in the table, it will be inserted, otherwise it will be just updated. No duplicates are created.
11
  *
12
  * complete example (strategy target):
13
  *
14
  * HDNET\Importr\Service\Targets\InsertUpdateTable:
15
  *   model: TYPO3\CMS\Extbase\Domain\Model\FrontendUser
16
  *   repository: TYPO3\CMS\Extbase\Domain\Repository\FrontendUserRepository
17
  *   target_table: fe_users
18
  *   exclude_from_update:
19
  *     0: password
20
  *     1: first_name
21
  *     2: zip
22
  *   pid: 324
23
  *   mapping:
24
  *     0: username
25
  *     1: password
26
  *     2: usergroup
27
  *     3: name
28
  *     4: first_name
29
  *     5: address
30
  *     6: telephone
31
  *     7: email
32
  *     8: zip
33
  *     9: city
34
  *     10: company
35
  *     
36
  * Example CSV:
37
  *
38
  * username;password;usergroup;name;first_name;address;telephone;email;zip;city;company
39
  * EduardFekete;BestPwEU1234;3;Fekete;Eduard; Mystreet 21; +049123456789;[email protected];91550;Feuchtwangen;MB Connect Line GmbH
40
  * HansVader;SecondBestPwEU1234;3;Vader;Hans; Hisstreet 22; +049123456710;[email protected];99900;Universe;Hollywood Studios
41
  *
42
  * ------------------------------------------------------------------------------------------------
43
  *
44
  *   exclude_from_update:    the elements specified in this array, are never being updated
45
  *
46
  * ------------------------------------------------------------------------------------------------
47
  * @author Eduard Fekete
48
  */
49
   
50
class InsertUpdateTable extends AbstractTarget implements TargetInterface
51
{
52
    /**
53
     * @var array
54
     */
55
    protected $table_records;
56
    
57
    /**
58
     * @var array
59
     */
60
    protected $configuration;
61
    
62
    /**
63
     * @var string
64
     */
65
    protected $firstTime = "1";
66
    
67
    /**
68
     * @var Strategy
69
     */
70
    protected $strategy;
71
72
    /**
73
     * @return array
74
     */
75 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...
76
    {
77
        $configuration = parent::getConfiguration();
78
        if (!isset($configuration['pid']) || !is_numeric($configuration['pid']))
79
            $configuration['pid'] = 0;
80
81
        return $configuration;
82
    }
83
84
    /**
85
     * @param \HDNET\Importr\Domain\Model\Strategy $strategy
86
     *
87
     * @return void
88
     */
89
    public function start(Strategy $strategy)
90
    {
91
        $this->strategy = $strategy;
92
    }
93
    
94
    /**
95
     * Process every entry in the .csv
96
     *
97
     * @param array $entry
98
     *
99
     * @return int|void
100
     */
101
    public function processEntry(array $entry)
102
    {
103
        $record_exists    = false;
104
        $entry_username   = $entry['0'];
105
      
106
        $this->configuration    = $this->getConfiguration();
107
      
108
        if ($this->firstTime == "1") {
109
            $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...
110
            $this->getRecords("*");
111
        }
112
113
        foreach($this->table_records as $record) {         
114
            if ($record['deleted'] == 0) {         
115
                if ($record['username'] == $entry_username) {
116
                    $record_exists = true;
117
                    break;
118
                }
119
            }
120
            else {
121
                continue;
122
            }
123
        }
124
      
125
        if ($record_exists) {       
126
            $this->updateRecord($entry);      
127
            return TargetInterface::RESULT_UPDATE;
128
        }
129
        else { 
130
            $this->insertRecord($entry);
131
            return TargetInterface::RESULT_INSERT;
132
        }
133
    }
134
    
135
    /**
136
     *
137
     * Fetch all records from the target table, where the PID equals the PID specified in the target section of the strategy 
138
     *
139
     * @return void
140
     */
141
    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...
142
    {               
143
        $fromTable        = $this->configuration['target_table'];
144
        $whereStatement   = "pid = '".$this->configuration['pid']."'";
145
146
        $GLOBALS['TYPO3_DB']->store_lastBuiltQuery = 1;
147
      
148
        $this->table_records = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows
149
        (
150
            $selectFields,
151
            $fromTable,
152
            $whereStatement
153
        );
154
    }
155
    
156
    /**
157
     * Insert record into the target table which you have specified in the target section of the strategy 
158
     *
159
     * @param array $entry
160
     *
161
     * @return void
162
     */
163
    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...
164
    {           
165
        $field_values       = array();
166
        $into_table         = $this->configuration['target_table'];
167
      
168
        foreach($this->configuration["mapping"] as $key => $value)  
169
            $field_values[$value] = $entry[$key];
170
      
171
        $field_values['pid']      = $this->configuration['pid'];
172
        $field_values['tstamp']   = time();
173
        $field_values['crdate']   = time();
174
              
175
        $GLOBALS['TYPO3_DB']->exec_INSERTquery( $into_table, $field_values);
176
        $GLOBALS['TYPO3_DB']->sql_insert_id();
177
    }
178
    
179
     /**
180
     * Update a record in the target table which you have specified in the target section of the strategy (don't update the password)
181
     *
182
     * @param array $entry
183
     *
184
     * @return void
185
     */
186
    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...
187
    {
188
        $into_table       = $this->configuration['target_table']; 
189
        $whereStatement   = "pid = '".$this->configuration['pid']."' AND username = '".$entry[0]."'";
190
                           
191
        $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...
192
        $tmp_arr                = array();
193
      
194
        foreach($this->configuration["mapping"] as $key => $value)      
195
            $tmp_arr[$value] = $entry[$key];
196
          
197
        $field_values = $this->duplicateArray($tmp_arr, $this->configuration['exclude_from_update']);
198
        $field_values['tstamp'] = time();
199
        
200
        $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...
201
        $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...
202
    }
203
    
204
    /**
205
    * This function creates a duplicate of a associative array and optionally removes any entries which are also elements of a second array
206
    *
207
    * @param array $arr
208
    * @param array $exclude_arr
209
    *
210
    * @return array
211
    */
212
    public function duplicateArray(array $arr, array $exclude_arr = null)
213
    {       
214
        $exclude = false;
215
        
216
        if ($exclude_arr != null) {
217
            $exclude_max = count($exclude_arr);
218
            if (count($exclude_arr) > 0)
219
                $exclude = true;
220
        }
221
        
222
        foreach($arr as $parentkey => $parentvalue)
223
        {
224
            $chk = $exclude_max;
0 ignored issues
show
Bug introduced by
The variable $exclude_max does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
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...
225
226
            if ($exclude) {
227
                foreach($exclude_arr as $key => $value) {
0 ignored issues
show
Bug introduced by
The expression $exclude_arr 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...
228
                    if ($value == $parentkey)
229
                        unset($arr[$parentkey]);
230
                }
231
            }
232
        }
233
234
        return $arr;
235
    }
236
237
    public function end()
238
    {
239
    }
240
};