Affilinet::getDeals()   C
last analyzed

Complexity

Conditions 10
Paths 16

Size

Total Lines 78

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 78
rs 6.6133
cc 10
nc 16
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
namespace Padosoft\AffiliateNetwork\Networks;
4
5
use Padosoft\AffiliateNetwork\Transaction;
6
use Padosoft\AffiliateNetwork\Merchant;
7
use Padosoft\AffiliateNetwork\Stat;
8
use Padosoft\AffiliateNetwork\Deal;
9
use Padosoft\AffiliateNetwork\AbstractNetwork;
10
use Padosoft\AffiliateNetwork\NetworkInterface;
11
use Padosoft\AffiliateNetwork\DealsResultset;
12
use Padosoft\AffiliateNetwork\ProductsResultset;
13
use Padosoft\AffiliateNetwork\AffilinetEx;
14
15
/**
16
 * Class Affilinet
17
 * @package Padosoft\AffiliateNetwork\Networks
18
 */
19
class Affilinet extends AbstractNetwork implements NetworkInterface
20
{
21
    /**
22
     * @var object
23
     */
24
    private $_network = null;
25
    // private $_apiClient = null;
26
    private $_username = '';
27
    private $_password = '';
28
    private $_passwordApi = '';
29
    private $_website_id = '';
30
    protected $_tracking_parameter = 'subid';   // Default value
31
32
    /**
33
     * @method __construct
34
     */
35
    public function __construct(string $username, string $passwordApi, string $idSite='')
36
    {
37
        $this->_network = new AffilinetEx;
38
        $this->_username = $username;
39
        $this->_password = $passwordApi;
40
        $this->_passwordApi = $passwordApi;
41
        $this->_website_id = $idSite;
42
        $this->login( $this->_username, $this->_password ,$idSite);
43
        // $this->_apiClient = \ApiClient::factory(PROTOCOL_JSON);
44
    }
45
46
    /**
47
     * @return bool
48
     */
49
    public function login(string $username, string $password,string $idSite=''): bool
0 ignored issues
show
Unused Code introduced by
The parameter $idSite 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...
50
    {
51
        $this->_logged = false;
0 ignored issues
show
Bug introduced by
The property _logged does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
52
        if (isNullOrEmpty( $username ) && isNullOrEmpty( $password )) {
53
54
            return false;
55
        }
56
        $this->_username = $username;
57
        $this->_password = $password;
58
        $this->_passwordApi= $password;
59
        $credentials = array();
60
        $credentials["user"] = $this->_username;
61
        $credentials["password"] = $this->_username;
62
        $credentials["apipassword"] = $this->_passwordApi;
63
        $this->_network->login($credentials);
64
        if ($this->_network->checkConnection()) {
65
            $this->_logged = true;
66
        }
67
        return $this->_logged;
68
    }
69
70
    /**
71
     * @return bool
72
     */
73
    public function checkLogin() : bool
74
    {
75
        return $this->_logged;
76
    }
77
78
    /**
79
     * @return array of Merchants
80
     */
81 View Code Duplication
    public function getMerchants(): array
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...
82
    {
83
        $arrResult = array();
84
        $merchantList = $this->_network->getMerchantList();
85
        foreach ($merchantList as $merchant) {
86
            $Merchant = Merchant::createInstance();
87
            $Merchant->merchant_ID = $merchant['cid'];
88
            $Merchant->name = $merchant['name'];
89
            // Added more info - 2018-04-20 <PN>
90
            $Merchant->url = $merchant['url'];
91
            $Merchant->status = $merchant['status'];
92
            if (!empty($merchant['launch_date'])) {
93
                $date = new \DateTime($merchant['launch_date']);
0 ignored issues
show
Unused Code introduced by
$date 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...
94
                //TODO check date format
95
                //$Merchant->launch_date = $date;
96
            }
97
            $arrResult[] = $Merchant;
98
        }
99
100
        return $arrResult;
101
    }
102
103
    /**
104
     * @param int $merchantID
105
     * @return array of Deal
106
     */
107
    public function getDeals($merchantID = NULL, int $page = 0, int $items_per_page = 10): DealsResultset
108
    {
109
        $result = DealsResultset::createInstance();
110
111
        $arrResult = array();
112
        $arrVouchers = $this->_network->getVouchers();
113
114
        foreach($arrVouchers as $obj_voucher) {
115
116
            $voucher = json_decode(json_encode($obj_voucher), true);
117
118
            if ($merchantID > 0) {
119
                if ($voucher['ProgramId'] != $merchantID) {
120
                    continue;
121
                }
122
            }
123
124
            $partnershipStatus = $voucher['PartnershipStatus'];
125
            if ($partnershipStatus == 'NoRestriction' || $partnershipStatus == 'Accepted') {
126
                // Get only approved or without restriction
127
                $Deal = Deal::createInstance();
128
                $Deal->setValues($voucher, [
129
                    'Id' => 'deal_ID',
130
                    'ProgramId' => 'merchant_ID',
131
                    'Code' => 'code',
132
                    'LastChengeDate' => 'update_date',
133
                    'StartDate' => 'start_date',
134
                    'EndDate' => 'end_date',
135
                    'Title' => 'name',
136
                    'Description' => 'description',
137
                    'IsExclusive' => 'is_exclusive',
138
                    'MinimumOrderValue' => 'minimum_order_value',
139
                ]);
140
                /*
141
                // Check voucher type (NOT USED HERE)
142
                $voucherType = $voucher['VoucherTypes']['VoucherType'];
143
                if (is_array($voucherType)) {
144
                    foreach ($voucherType as $type) {
145
                        switch ($type) {
146
                            case 'AllProducts':
147
                                break;
148
                            case 'SpecificProducts':
149
                                break;
150
                            case 'MultiBuyDiscount':
151
                                break;
152
                            case 'Free Shipping':
153
                                break;
154
                            case 'Free Product':
155
                                break;
156
                            case 'Competition':
157
                                break;
158
                        }
159
                    }
160
                }
161
                */
162
                $Deal->deal_type = \Oara\Utilities::OFFER_TYPE_VOUCHER;
163
164
                // Decode tracking url from html snippet
165
                $snippet = $voucher['IntegrationCode'];
166
                if (!empty($snippet)) {
167
                    $pos = strpos($snippet, 'http');
168
                    if ($pos !== false) {
169
                        $posQuote = strpos($snippet,'"', $pos);
170
                        if ($posQuote === false) {
171
                            $posQuote = strpos($snippet,' ', $pos);
172
                        }
173
                        if ($posQuote !== false) {
174
                            $Deal->default_track_uri = substr($snippet, $pos, $posQuote - $pos);
175
                        }
176
                    }
177
                }
178
                $arrResult[] = $Deal;
179
            }
180
        }
181
        $result->deals[]=$arrResult;
182
183
        return $result;
184
    }
185
186
    /**
187
     * @param \DateTime $dateFrom
188
     * @param \DateTime $dateTo
189
     * @param int $merchantID
0 ignored issues
show
Documentation introduced by
There is no parameter named $merchantID. Did you maybe mean $arrMerchantID?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
190
     * @return array of Transaction
191
     */
192
    public function getSales(\DateTime $dateFrom, \DateTime $dateTo, array $arrMerchantID = array()): array
193
    {
194
        $arrResult = array();
195 View Code Duplication
        if (count( $arrMerchantID ) < 1) {
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...
196
            $merchants = $this->getMerchants();
197
            foreach ($merchants as $merchant) {
198
                $arrMerchantID[$merchant->merchant_ID] = ['cid' => $merchant->merchant_ID, 'name' => $merchant->name];
199
            }
200
        }
201
        $transactionList = $this->_network->getTransactionList($arrMerchantID, $dateFrom,$dateTo);
202
        //echo "<br>merchants id array<br>".print_r($arrMerchantID);
203
        //$counter=0;
204
        foreach($transactionList as $transaction) {
205
            $myTransaction = Transaction::createInstance();
206
            try {
207
                $myTransaction->status = $transaction['status'];
208
                $myTransaction->amount = $transaction['amount'];
209
                $myTransaction->custom_ID = $transaction['custom_id'];
210
                $myTransaction->unique_ID = $transaction['unique_id'];
211
                $myTransaction->commission = $transaction['commission'];
212
                $myTransaction->currency = $transaction['currency'];
213
                if (!empty($transaction['date'])) {
214
                    $date = new \DateTime($transaction['date']);
215
                    $myTransaction->date = $date; // $date->format('Y-m-d H:i:s');
0 ignored issues
show
Documentation Bug introduced by
It seems like $date of type object<DateTime> is incompatible with the declared type string of property $date.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
216
                }
217
                $myTransaction->merchant_ID = $transaction['merchantId'];
218
                // Future use - Only few providers returns these dates values - <PN> - 2017-06-26
219
                if (isset($transaction['click_date']) && !empty($transaction['click_date'])) {
220
                    $myTransaction->click_date = new \DateTime($transaction['click_date']);
0 ignored issues
show
Documentation Bug introduced by
It seems like new \DateTime($transaction['click_date']) of type object<DateTime> is incompatible with the declared type string of property $click_date.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
221
                }
222
                if (isset($transaction['update_date']) && !empty($transaction['update_date'])) {
223
                    $myTransaction->update_date = new \DateTime($transaction['update_date']);
0 ignored issues
show
Documentation Bug introduced by
It seems like new \DateTime($transaction['update_date']) of type object<DateTime> is incompatible with the declared type string of property $update_date.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
224
                }
225
                $arrResult[] = $myTransaction;
226
            } catch (\Exception $e) {
227
                //echo "stepE ";
228
                echo "<br><br>errore transazione Affilinet, id: ".$myTransaction->unique_ID." msg: ".$e->getMessage()."<br><br>";
229
                var_dump($e->getTraceAsString());
0 ignored issues
show
Security Debugging Code introduced by
var_dump($e->getTraceAsString()); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
230
            }
231
        }
232
        return $arrResult;
233
    }
234
235
    /**
236
     * @param \DateTime $dateFrom
237
     * @param \DateTime $dateTo
238
     * @param int $merchantID
239
     * @return array of Stat
240
     */
241
    public function getStats(\DateTime $dateFrom, \DateTime $dateTo, int $merchantID = 0): array
242
    {
243
        return array();
244
        /*
245
        $this->_apiClient->setConnectId($this->_username);
246
        $this->_apiClient->setSecretKey($this->_password);
247
        $dateFromIsoEngFormat = $dateFrom->format('Y-m-d');
248
        $dateToIsoEngFormat = $dateTo->format('Y-m-d');
249
        $response = $this->_apiClient->getReportBasic($dateFromIsoEngFormat, $dateToIsoEngFormat);
250
        $arrResponse = json_decode($response, true);
251
        $reportItems = $arrResponse['reportItems'];
252
        $Stat = Stat::createInstance();
253
        $Stat->reportItems = $reportItems;
254
255
        return array($Stat);
256
        */
257
    }
258
259
    /**
260
     * @param  array $params
261
     *
262
     * @return ProductsResultset
263
     */
264
    public function getProducts(array $params = []): ProductsResultset
265
    {
266
        // TODO: Implement getProducts() method.
267
        throw new \Exception("Not implemented yet");
268
    }
269
270
    /**
271
     * Api call CommissionJunction
272
     */
273
    private function _apiCall($url)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
274
    {
275
        $ch = curl_init();
276
        curl_setopt($ch, CURLOPT_URL, $url);
277
        curl_setopt($ch, CURLOPT_POST, FALSE);
278
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
279
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
280
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
281
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: " . $this->_passwordApi));
282
        $curl_results = curl_exec($ch);
283
        curl_close($ch);
284
        return $curl_results;
285
    }
286
287
    public function getTrackingParameter()
288
    {
289
        return $this->_tracking_parameter;
290
    }
291
}
292