Completed
Push — master ( 826672...47aefb )
by
unknown
02:03
created

TradeDoublerEx::getTransactionList()   D

Complexity

Conditions 18
Paths 288

Size

Total Lines 67
Code Lines 41

Duplication

Lines 47
Ratio 70.15 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
dl 47
loc 67
rs 4.3141
c 3
b 1
f 0
cc 18
eloc 41
nc 288
nop 3

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Copyright (c) Padosoft.com 2017.
4
 */
5
namespace Padosoft\AffiliateNetwork;
6
7
use Oara\Network\Publisher\TradeDoubler as TradeDoublerOara;
8
9
class TradeDoublerEx extends TradeDoublerOara
10
{
11
    public function getTransactionList($merchantList = null, \DateTime $dStartDate = null, \DateTime $dEndDate = null)
0 ignored issues
show
Coding Style introduced by
getTransactionList uses the super-global variable $_ENV 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...
12
    {
13
        $updateTransactions = Array();
0 ignored issues
show
Unused Code introduced by
$updateTransactions 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...
14
        $totalTransactions = Array();
15
16
        if (isset($_ENV['TRADEDOUBLER_CURRENCY'])) {
17
            $currency = $_ENV['TRADEDOUBLER_CURRENCY'];
18
        }
19
        else {
20
            $currency = 'EUR';
21
        }
22
23
        // Get updated transactions in date range
24
        $updatedTransactions = self::getTransactionListByDateType($merchantList, $dStartDate, $dEndDate, true, $currency);
25
        // Get new transactions in date range
26
        $insertedTransactions= self::getTransactionListByDateType($merchantList, $dStartDate, $dEndDate, false, $currency);
27
28
        $parsedIDs=[];
0 ignored issues
show
Unused Code introduced by
$parsedIDs 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...
29 View Code Duplication
        foreach ($insertedTransactions as $transaction){
0 ignored issues
show
Duplication introduced by
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...
30
            if (array_key_exists('unique_id', $transaction)){
31
                $found=false;
32
                for ($i=0;$i<count($totalTransactions);$i++){
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
33
                    // Check also event_id to obtain a real unique key - <PN> - 2017-07-03
34
                    if ($totalTransactions[$i]['unique_id']==$transaction['unique_id'] && $totalTransactions[$i]['event_id']==$transaction['event_id']){
35
                        if ($totalTransactions[$i]['commission']<=0){
36
                            $totalTransactions[$i] = $transaction;
37
                            $found=true;
38
                            break;
39
                        }
40
                        if ($totalTransactions[$i]['status']==\Oara\Utilities::STATUS_DECLINED){
41
                            $totalTransactions[$i] = $transaction;
42
                            $found=true;
43
                            break;
44
                        }
45
                    }
46
                }
47
                if (!$found){
48
                    $totalTransactions[] = $transaction;
49
                }
50
            }
51
        }
52 View Code Duplication
        foreach ($updatedTransactions as $transaction){
0 ignored issues
show
Duplication introduced by
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...
53
            if (array_key_exists('unique_id',$transaction)){
54
                $found=false;
55
                for ($i=0;$i<count($totalTransactions);$i++){
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
56
                    // Check also event_id to obtain a real unique key - <PN> - 2017-07-03
57
                    if ($totalTransactions[$i]['unique_id']==$transaction['unique_id'] && $totalTransactions[$i]['event_id']==$transaction['event_id']){
58
                        if ($totalTransactions[$i]['commission']<=0){
59
                            $totalTransactions[$i]=$transaction;
60
                            $found=true;
61
                            break;
62
                        }
63
                        if ($totalTransactions[$i]['status']==\Oara\Utilities::STATUS_DECLINED){
64
                            $totalTransactions[$i]=$transaction;
65
                            $found=true;
66
                            break;
67
                        }
68
69
                    }
70
                }
71
                if (!$found){
72
                    $totalTransactions[]=$transaction;
73
                }
74
            }
75
        }
76
        return $totalTransactions;
77
    }
78
79
    public function getTransactionListByDateType($merchantList = null, \DateTime $dStartDate = null, \DateTime $dEndDate = null, bool $byDateUpdated = false, $currency = null)
0 ignored issues
show
Unused Code introduced by
The parameter $merchantList is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
80
    {
81
        $transactions = Array();
82
83
        $valuesFormExport = array(new \Oara\Curl\Parameter('reportName', 'aAffiliateEventBreakdownReport'),
84
            new \Oara\Curl\Parameter('columns', 'programId'),
85
            new \Oara\Curl\Parameter('columns', 'timeOfVisit'),
86
            new \Oara\Curl\Parameter('columns', 'timeOfEvent'),
87
            new \Oara\Curl\Parameter('columns', 'timeInSession'),
88
            new \Oara\Curl\Parameter('columns', 'lastModified'),
89
            new \Oara\Curl\Parameter('columns', 'epi1'),
90
            new \Oara\Curl\Parameter('columns', 'eventName'),
91
            new \Oara\Curl\Parameter('columns', 'pendingStatus'),
92
            new \Oara\Curl\Parameter('columns', 'siteName'),
93
            new \Oara\Curl\Parameter('columns', 'graphicalElementName'),
94
            new \Oara\Curl\Parameter('columns', 'graphicalElementId'),
95
            new \Oara\Curl\Parameter('columns', 'productName'),
96
            new \Oara\Curl\Parameter('columns', 'productNrOf'),
97
            new \Oara\Curl\Parameter('columns', 'productValue'),
98
            new \Oara\Curl\Parameter('columns', 'affiliateCommission'),
99
            new \Oara\Curl\Parameter('columns', 'link'),
100
            new \Oara\Curl\Parameter('columns', 'leadNR'),
101
            new \Oara\Curl\Parameter('columns', 'orderNR'),
102
            new \Oara\Curl\Parameter('columns', 'pendingReason'),
103
            new \Oara\Curl\Parameter('columns', 'orderValue'),
104
            new \Oara\Curl\Parameter('columns', 'eventId'),           // Added <PN> 2017-07-03
105
            new \Oara\Curl\Parameter('isPostBack', ''),
106
            new \Oara\Curl\Parameter('metric1.lastOperator', '/'),
107
            new \Oara\Curl\Parameter('interval', ''),
108
            new \Oara\Curl\Parameter('favoriteDescription', ''),
109
            new \Oara\Curl\Parameter('event_id', '0'),
110
            new \Oara\Curl\Parameter('pending_status', '1'),
111
            new \Oara\Curl\Parameter('run_as_organization_id', ''),
112
            new \Oara\Curl\Parameter('minRelativeIntervalStartTime', '0'),
113
            new \Oara\Curl\Parameter('includeWarningColumn', 'true'),
114
            new \Oara\Curl\Parameter('metric1.summaryType', 'NONE'),
115
            new \Oara\Curl\Parameter('metric1.operator1', '/'),
116
            new \Oara\Curl\Parameter('latestDayToExecute', '0'),
117
            new \Oara\Curl\Parameter('showAdvanced', 'true'),
118
            new \Oara\Curl\Parameter('currencyId', $currency),              // Added <PN> 2018-03-26
119
            new \Oara\Curl\Parameter('breakdownOption', '1'),
120
            new \Oara\Curl\Parameter('metric1.midFactor', ''),
121
            new \Oara\Curl\Parameter('reportTitleTextKey', 'REPORT3_SERVICE_REPORTS_AAFFILIATEEVENTBREAKDOWNREPORT_TITLE'),
122
            new \Oara\Curl\Parameter('setColumns', 'true'),
123
            new \Oara\Curl\Parameter('metric1.columnName1', 'orderValue'),
124
            new \Oara\Curl\Parameter('metric1.columnName2', 'orderValue'),
125
            new \Oara\Curl\Parameter('reportPrograms', ''),
126
            new \Oara\Curl\Parameter('metric1.midOperator', '/'),
127
            new \Oara\Curl\Parameter('dateSelectionType', $byDateUpdated ? '2' : '1'),    // Retrieve transactions by Date Event (default = 1) or by Date Last Updated (2)
128
            new \Oara\Curl\Parameter('favoriteName', ''),
129
            new \Oara\Curl\Parameter('affiliateId', ''),
130
            new \Oara\Curl\Parameter('dateType', '1'),
131
            new \Oara\Curl\Parameter('period', 'custom_period'),
132
            new \Oara\Curl\Parameter('tabMenuName', ''),
133
            new \Oara\Curl\Parameter('maxIntervalSize', '0'),
134
            new \Oara\Curl\Parameter('favoriteId', ''),
135
            new \Oara\Curl\Parameter('sortBy', 'timeOfEvent'),
136
            new \Oara\Curl\Parameter('metric1.name', ''),
137
            new \Oara\Curl\Parameter('customKeyMetricCount', '0'),
138
            new \Oara\Curl\Parameter('metric1.factor', ''),
139
            new \Oara\Curl\Parameter('showFavorite', 'false'),
140
            new \Oara\Curl\Parameter('separator', ','),
141
            new \Oara\Curl\Parameter('format', 'CSV')
142
        );
143
        $valuesFormExport[] = new \Oara\Curl\Parameter('startDate', self::formatDate($dStartDate));
144
        $valuesFormExport[] = new \Oara\Curl\Parameter('endDate', self::formatDate($dEndDate));
145
        $urls = array();
146
        $urls[] = new \Oara\Curl\Request('http://publisher.tradedoubler.com/pan/aReport3Internal.action?', $valuesFormExport);
147
        $exportReport = $this->_client->get($urls);
148
149
        $exportReport[0] = self::checkReportError($exportReport[0], $urls[0]);
150
        $exportData = \str_getcsv($exportReport[0], "\r\n");
151
        $num = \count($exportData);
152
        for ($i = 2; $i < $num - 1; $i++) {
153
154
            try {
155
                $transactionExportArray = \str_getcsv($exportData[$i], ",");
156
157
                if (!isset($transactionExportArray[2])) {
158
                    throw new \Exception('Problem getting transaction\n\n');
159
                }
160
                if (\count($this->_sitesAllowed) == 0 || \in_array($transactionExportArray[13], $this->_sitesAllowed)) {
161
162
                    if (!empty(trim($transactionExportArray[7] . $transactionExportArray[8]))) {
163
                        // Skip rows without a unique_id
164
                        $transaction = Array();
165
                        $transaction['merchantId'] = $transactionExportArray[2];
166
                        $transactionDate = self::toDate(\substr($transactionExportArray[4], 0, -6));
167
                        if ($transactionDate === false) {
168
                            // Bad date ... skip
169
                            $transaction['date'] = '';
170
                        }
171
                        else {
172
                            $transaction['date'] = $transactionDate->format("Y-m-d H:i:s");
173
                        }
174
                        if ($transactionExportArray[8] != '') {
175
                            $transaction['unique_id'] = \substr($transactionExportArray[8], 0, 200);
176
                        } else
177
                            if ($transactionExportArray[7] != '') {
178
                                $transaction['unique_id'] = \substr($transactionExportArray[7], 0, 200);
179
                            } else {
180
                                throw new \Exception("No Identifier");
181
                            }
182
183
184
                        if ($transactionExportArray[9] != '') {
185
                            $transaction['custom_id'] = $transactionExportArray[9];
186
                        }
187
188
                        $transaction['status'] = \Oara\Utilities::STATUS_PENDING;
189 View Code Duplication
                        if ($transactionExportArray[12] == 'A') {
0 ignored issues
show
Duplication introduced by
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...
190
                            $transaction['status'] = \Oara\Utilities::STATUS_CONFIRMED;
191
                        } else
192
                            if ($transactionExportArray[12] == 'P') {
193
                                $transaction['status'] = \Oara\Utilities::STATUS_PENDING;
194
                            } else
195
                                if ($transactionExportArray[12] == 'D') {
196
                                    $transaction['status'] = \Oara\Utilities::STATUS_DECLINED;
197
                                }
198
199
                        if ($transactionExportArray[20] != '') {
200
                            $transaction['amount'] = \Oara\Utilities::parseDouble($transactionExportArray[20]);
201
                        } else {
202
                            $transaction['amount'] = \Oara\Utilities::parseDouble($transactionExportArray[21]);
203
                        }
204
205
                        $transaction['commission'] = \Oara\Utilities::parseDouble($transactionExportArray[21]);
206
                        $transaction['event_id'] = $transactionExportArray[11];
207
                        $transaction['currency'] = $currency;
208
                        $transactions[] = $transaction;
209
                    }
210
                }
211
            }
212
            catch (\Exception $e) {
213
                echo PHP_EOL."TradeDoublerEx - getTransactionList err: ".$e->getMessage().PHP_EOL;
214
            }
215
        }
216
        return $transactions;
217
    }
218
}