Completed
Push — master ( 22389a...db1425 )
by
unknown
14:01
created

CommissionJunction::getDeals()   F

Complexity

Conditions 15
Paths 648

Size

Total Lines 77
Code Lines 54

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 77
rs 2.5974
c 0
b 0
f 0
cc 15
eloc 54
nc 648
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
14
// require "../vendor/fubralimited/php-oara/Oara/Network/Publisher/CommissionJunction/Zapi/ApiClient.php";
15
16
/**
17
 * Class CommissionJunction
18
 * @package Padosoft\AffiliateNetwork\Networks
19
 */
20
class CommissionJunction extends AbstractNetwork implements NetworkInterface
21
{
22
    /**
23
     * @var object
24
     */
25
    private $_network = null;
26
    // private $_apiClient = null;
0 ignored issues
show
Unused Code Comprehensibility introduced by
45% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
27
    private $_username = '';
28
    private $_password = '';
29
    private $_passwordApi = '';
30
    private $_website_id = '';
31
    protected $_tracking_parameter = 'sid';
32
33
    /**
34
     * @method __construct
35
     */
36 View Code Duplication
    public function __construct(string $username, string $passwordApi, string $idSite='')
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...
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...
37
    {
38
        $this->_network = new \Oara\Network\Publisher\CommissionJunction;
39
        $this->_username = $username;
40
        $this->_password = $passwordApi;
41
        $this->_passwordApi = $passwordApi;
42
        $idSite = $this->_website_id;
43
44
        if (trim($idSite)!=''){
45
            $this->addAllowedSite($idSite);
46
        }
47
48
        $this->login( $this->_username, $this->_password ,$this->_website_id);
49
    }
50
51
    /**
52
     * @return bool
53
     */
54
    public function login(string $username, string $password,string $idSite=''): bool
55
    {
56
        $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...
57
        if (isNullOrEmpty( $username ) && isNullOrEmpty( $password )) {
58
            return false;
59
        }
60
        $this->_username = $username;
61
        $this->_password = $password;
62
        $this->_passwordApi= $password;
63
        $this->_website_id = $idSite;
64
        $credentials = array();
65
        $credentials["user"] = $this->_username;
66
        $credentials["password"] = $this->_username;
67
        $credentials["apipassword"] = $this->_passwordApi;
68
        $credentials["id_site"] = $idSite;
69
70
        if (trim($idSite)!=''){
71
            $this->addAllowedSite($idSite);
72
        }
73
74
        $this->_network->login($credentials);
75
        if ($this->_network->checkConnection()) {
76
            $this->_logged = true;
77
        }
78
79
        return $this->_logged;
80
    }
81
82
    /**
83
     * @return bool
84
     */
85
    public function checkLogin() : bool
86
    {
87
        return $this->_logged;
88
    }
89
90
    /**
91
     * @return array of Merchants
92
     */
93 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...
94
    {
95
        $arrResult = array();
96
        $merchantList = $this->_network->getMerchantList();
97
        foreach ($merchantList as $merchant) {
98
            $Merchant = Merchant::createInstance();
99
            $Merchant->merchant_ID = $merchant['cid'];
100
            $Merchant->name = $merchant['name'];
101
            $arrResult[] = $Merchant;
102
        }
103
104
        return $arrResult;
105
    }
106
107
    /**
108
     * @param null | int $merchantID
109
     * @param int $page
110
     * @param int $records_per_page
111
     * @return DealsResultset array of Deal
112
     */
113
    public function getDeals($merchantID = NULL, int $page = 1, int $records_per_page = 100): DealsResultset
114
    {
115
        if (empty($page)){
116
            $page = 1;
117
        }
118
        if (empty($records_per_page)){
119
            $records_per_page = 100;
120
        }
121
        if (empty($merchantID)){
122
            $merchantID  = 'joined';
123
        }
124
        $arrResult = new DealsResultset();
125
        $arrResult->items = $records_per_page;
126
127
        while ((int) $arrResult->items >= (int) $records_per_page){
128
129
            try {
130
                //<JC> 2017-10-23  (valid keys are: advertiser-ids, category, event-name, keywords, language, link-type, page-number, promotion-end-date, promotion-start-date, promotion-type, records-per-page, website-id)
131
                $response = $this->_apiCall(
132
                    'https://link-search.api.cj.com/v2/link-search?website-id=' . $this->_website_id .
133
                    '&advertiser-ids=' . $merchantID .
134
                    '&records-per-page=' . $records_per_page .
135
                    '&page-number=' . $page .
136
                    '&promotion-type=coupon'
137
                );
138
139
                if ($response===false || \preg_match("/error/", $response)) {
140
                    return $arrResult;
141
                }
142
143
                $arrResponse = xml2array($response);
144
145
                if (!is_array($arrResponse) || count($arrResponse) <= 0) {
146
                    return $arrResult;
147
                }
148
                if (!isset($arrResponse['cj-api']['links'])){
149
                    return $arrResult;
150
                }
151
                $arrResult->page=$arrResponse['cj-api']['links_attr']['page-number'];
152
                $arrResult->items=$arrResponse['cj-api']['links_attr']['records-returned'];
153
                $arrResult->total=$arrResponse['cj-api']['links_attr']['total-matched'];
154
                ($arrResult->total > 0) ? $arrResult->num_pages = (int)ceil($arrResult->total / $records_per_page) : $arrResult->num_pages = 0;
0 ignored issues
show
Bug introduced by
The property num_pages does not seem to exist in Padosoft\AffiliateNetwork\DealsResultset.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
155
                $a_links = $arrResponse['cj-api']['links']['link'];
156
157
                foreach ($a_links as $link) {
158
                    $Deal = Deal::createInstance();
159
                    $Deal->deal_ID = $link['link-id'];
160
                    $Deal->name = $link['link-name'];
161
                    $Deal->language = $link['language'];
162
                    $Deal->description = $link['description'];
163
                    $Deal->note = $link['description'];
0 ignored issues
show
Bug introduced by
The property note does not seem to exist in Padosoft\AffiliateNetwork\Deal.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
164
                    $Deal->merchant_ID = $link['advertiser-id'];
165
                    $Deal->merchant_name = $link['advertiser-name'];
166
                    $Deal->default_track_uri = $link['clickUrl'];
167
                    $Deal->description = $link['description'];
168
                    $Deal->title = $link['link-name'];
0 ignored issues
show
Bug introduced by
The property title does not seem to exist in Padosoft\AffiliateNetwork\Deal.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
169
                    if (!empty($link['promotion-start-date'])) {
170
                        $startDate = new \DateTime($link['promotion-start-date']);
171
                        $Deal->start_date = $startDate;
172
                    }
173
                    if (!empty($link['promotion-end-date'])) {
174
                        $endDate = new \DateTime($link['promotion-end-date']);
175
                        $Deal->end_date = $endDate;
176
                    }
177
                    $Deal->code = $link['coupon-code'];
178
                    $Deal->deal_type = \Oara\Utilities::OFFER_TYPE_VOUCHER;
179
                    $arrResult->deals[0][] = $Deal;
180
                }
181
                $page++;
182
            }
183
            catch (\Exception $e){
184
                return $arrResult;
185
            }
186
        }
187
188
        return $arrResult;
189
    }
190
191
    /**
192
     * @param \DateTime $dateFrom
193
     * @param \DateTime $dateTo
194
     * @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...
195
     * @return array of Transaction
196
     */
197
    public function getSales(\DateTime $dateFrom, \DateTime $dateTo, array $arrMerchantID = array()): array
198
    {
199
        $arrResult = array();
200
        // User passed $arrMerchantID, don't fill it with active merchants only - 2017-10-12 <PN>
201
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
202
        if (count( $arrMerchantID ) < 1) {
203
            $merchants = $this->getMerchants();
204
            foreach ($merchants as $merchant) {
205
                $arrMerchantID[$merchant->merchant_ID] = ['cid' => $merchant->merchant_ID, 'name' => $merchant->name];
206
            }
207
        }
208
        */
209
        $transactionList = $this->_network->getTransactionList($arrMerchantID, $dateFrom,$dateTo);
210
        //echo "<br>merchants id array<br>".print_r($arrMerchantID);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
211
        //$counter=0;
212
        foreach($transactionList as $transaction) {
213
            $Transaction = Transaction::createInstance();
214
            $Transaction->status = $transaction['status'];
215
            $Transaction->amount = $transaction['amount'];
216
            $Transaction->custom_ID = $transaction['custom_id'];
217
            $Transaction->unique_ID = $transaction['unique_id'];
218
            $Transaction->transaction_ID = $transaction['order-id'];
219
            $Transaction->commission = $transaction['commission'];
220
            if (!empty($transaction['date'])) {
221
                $date = new \DateTime($transaction['date']);
222
                $Transaction->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...
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
223
            }
224
            $Transaction->merchant_ID = $transaction['merchantId'];
225
            //original	Displays either a '1' indicating an original transaction or a '0' indicating a non-original or correction transaction.
226
            //considero transazioni valide solo quelle di tipo original come viene fatto dal report consultabile sul sito web di c.j.
227
            if ($transaction['original'] == 'true') {
228
                $arrResult[] = $Transaction;
229
                //$counter++;
230
            }
231
            /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
69% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
232
            echo "custom_id ".$transaction['custom_id']." unique_id ".$transaction['unique_id']." aid ".$transaction['aid']." commission-id ".$transaction['commission-id'].
233
            " order-id ".$transaction['order-id']." original ".$transaction['original']."<br>";
234
            */
235
236
        }
237
        //echo "<br>num transazioni: ".$counter;
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
238
        return $arrResult;
239
    }
240
241
    /**
242
     * @param \DateTime $dateFrom
243
     * @param \DateTime $dateTo
244
     * @param int $merchantID
245
     * @return array of Stat
246
     */
247
    public function getStats(\DateTime $dateFrom, \DateTime $dateTo, int $merchantID = 0): array
248
    {
249
        return array();
250
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
251
        $this->_apiClient->setConnectId($this->_username);
252
        $this->_apiClient->setSecretKey($this->_password);
253
        $dateFromIsoEngFormat = $dateFrom->format('Y-m-d');
254
        $dateToIsoEngFormat = $dateTo->format('Y-m-d');
255
        $response = $this->_apiClient->getReportBasic($dateFromIsoEngFormat, $dateToIsoEngFormat);
256
        $arrResponse = json_decode($response, true);
257
        $reportItems = $arrResponse['reportItems'];
258
        $Stat = Stat::createInstance();
259
        $Stat->reportItems = $reportItems;
260
261
        return array($Stat);
262
        */
263
    }
264
265
    /**
266
     * @param  array $params
267
     *
268
     * @return ProductsResultset
269
     */
270
    public function getProducts(array $params = []): ProductsResultset
271
    {
272
        // TODO: Implement getProducts() method.
273
        throw new \Exception("Not implemented yet");
274
    }
275
276
    /**
277
     * Api call CommissionJunction
278
     */
279 View Code Duplication
    private function _apiCall($url)
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...
280
    {
281
        $ch = curl_init();
282
        curl_setopt($ch, CURLOPT_URL, $url);
283
        curl_setopt($ch, CURLOPT_POST, FALSE);
284
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
285
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
286
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
287
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: " . $this->_passwordApi));
288
        $curl_results = curl_exec($ch);
289
        curl_close($ch);
290
        return $curl_results;
291
    }
292
293
    public function getTrackingParameter()
294
    {
295
        return $this->_tracking_parameter;
296
    }
297
298
    public function addAllowedSite($idSite){
299
        if (trim($idSite)!=''){
300
            $this->_network->addAllowedSite($idSite);
301
        }
302
    }
303
304
}
305