Completed
Push — master ( 771dac...0da1fc )
by
unknown
04:16
created

CommissionJunction::getMerchants()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 16
nc 4
nop 0
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
    public function getMerchants(): array
94
    {
95
        $arrResult = array();
96
        $merchantList = $this->_network->getMerchantList();
97
        foreach ($merchantList as $merchant) {
98
            if ($merchant['status'] == 'Setup') {
99
                // Ignore setup programs not yet active
100
                continue;
101
            }
102
            $Merchant = Merchant::createInstance();
103
            $Merchant->merchant_ID = $merchant['cid'];
104
            $Merchant->name = $merchant['name'];
105
            // Added more info - 2018-04-23 <PN>
106
            $Merchant->url = $merchant['url'];
107
            if ($merchant['status'] == 'Active') {
108
                $Merchant->status = $merchant['relationship_status'];
109
            }
110
            else {
111
                $Merchant->status = $merchant['status'];
112
            }
113
            $arrResult[] = $Merchant;
114
        }
115
116
        return $arrResult;
117
    }
118
119
    /**
120
     * @param null | int $merchantID
121
     * @param int $page
122
     * @param int $records_per_page
123
     * @return DealsResultset array of Deal
124
     */
125
    public function getDeals($merchantID = NULL, int $page = 1, int $records_per_page = 100): DealsResultset
126
    {
127
        if (empty($page)){
128
            $page = 1;
129
        }
130
        if (empty($records_per_page)){
131
            $records_per_page = 100;
132
        }
133
        if (empty($merchantID)){
134
            $merchantID  = 'joined';
135
        }
136
        $arrResult = new DealsResultset();
137
        $arrResult->items = $records_per_page;
138
139
        while ((int) $arrResult->items >= (int) $records_per_page){
140
141
            try {
142
                //<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)
143
                $response = $this->_apiCall(
144
                    'https://link-search.api.cj.com/v2/link-search?website-id=' . $this->_website_id .
145
                    '&advertiser-ids=' . $merchantID .
146
                    '&records-per-page=' . $records_per_page .
147
                    '&page-number=' . $page .
148
                    '&promotion-type=coupon'
149
                );
150
151
                if ($response===false || \preg_match("/error/", $response)) {
152
                    return $arrResult;
153
                }
154
155
                $arrResponse = xml2array($response);
156
157
                if (!is_array($arrResponse) || count($arrResponse) <= 0) {
158
                    return $arrResult;
159
                }
160
                if (!isset($arrResponse['cj-api']['links'])){
161
                    return $arrResult;
162
                }
163
                $arrResult->page=$arrResponse['cj-api']['links_attr']['page-number'];
164
                $arrResult->items=$arrResponse['cj-api']['links_attr']['records-returned'];
165
                $arrResult->total=$arrResponse['cj-api']['links_attr']['total-matched'];
166
                ($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...
167
                $a_links = $arrResponse['cj-api']['links']['link'];
168
169
                foreach ($a_links as $link) {
170
                    $Deal = Deal::createInstance();
171
                    $Deal->deal_ID = $link['link-id'];
172
                    $Deal->name = $link['link-name'];
173
                    $Deal->language = $link['language'];
174
                    $Deal->description = $link['description'];
175
                    $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...
176
                    $Deal->merchant_ID = $link['advertiser-id'];
177
                    $Deal->merchant_name = $link['advertiser-name'];
178
                    $Deal->default_track_uri = $link['clickUrl'];
179
                    $Deal->description = $link['description'];
180
                    $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...
181
                    if (!empty($link['promotion-start-date'])) {
182
                        $startDate = new \DateTime($link['promotion-start-date']);
183
                        $Deal->start_date = $startDate;
184
                    }
185
                    if (!empty($link['promotion-end-date'])) {
186
                        $endDate = new \DateTime($link['promotion-end-date']);
187
                        $Deal->end_date = $endDate;
188
                    }
189
                    $Deal->code = $link['coupon-code'];
190
                    $Deal->deal_type = \Oara\Utilities::OFFER_TYPE_VOUCHER;
191
                    $arrResult->deals[0][] = $Deal;
192
                }
193
                $page++;
194
            }
195
            catch (\Exception $e){
196
                return $arrResult;
197
            }
198
        }
199
200
        return $arrResult;
201
    }
202
203
    /**
204
     * @param \DateTime $dateFrom
205
     * @param \DateTime $dateTo
206
     * @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...
207
     * @return array of Transaction
208
     */
209
    public function getSales(\DateTime $dateFrom, \DateTime $dateTo, array $arrMerchantID = array()): array
210
    {
211
        $arrResult = array();
212
        // User passed $arrMerchantID, don't fill it with active merchants only - 2017-10-12 <PN>
213
        /*
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...
214
        if (count( $arrMerchantID ) < 1) {
215
            $merchants = $this->getMerchants();
216
            foreach ($merchants as $merchant) {
217
                $arrMerchantID[$merchant->merchant_ID] = ['cid' => $merchant->merchant_ID, 'name' => $merchant->name];
218
            }
219
        }
220
        */
221
        $transactionList = $this->_network->getTransactionList($arrMerchantID, $dateFrom,$dateTo);
222
        //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...
223
        //$counter=0;
224
        foreach($transactionList as $transaction) {
225
            $Transaction = Transaction::createInstance();
226
            $Transaction->status = $transaction['status'];
227
            $Transaction->amount = $transaction['amount'];
228
            $Transaction->custom_ID = $transaction['custom_id'];
229
            $Transaction->unique_ID = $transaction['unique_id'];
230
            $Transaction->transaction_ID = $transaction['order-id'];
231
            $Transaction->commission = $transaction['commission'];
232
            if (!empty($transaction['date'])) {
233
                $date = new \DateTime($transaction['date']);
234
                $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...
235
            }
236
            $Transaction->merchant_ID = $transaction['merchantId'];
237
            //original	Displays either a '1' indicating an original transaction or a '0' indicating a non-original or correction transaction.
238
            // considero transazioni valide solo quelle di tipo original come viene fatto dal report consultabile sul sito web di c.j.
239
            // Don't check for 'original' to get DECLINED transactions - 2017-12-13 <PN>
240
            // if ($transaction['original'] == 'true') {
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
241
                $arrResult[] = $Transaction;
242
            // }
243
            /*
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...
244
            echo "custom_id ".$transaction['custom_id']." unique_id ".$transaction['unique_id']." aid ".$transaction['aid']." commission-id ".$transaction['commission-id'].
245
            " order-id ".$transaction['order-id']." original ".$transaction['original']."<br>";
246
            */
247
248
        }
249
        //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...
250
        return $arrResult;
251
    }
252
253
    /**
254
     * @param \DateTime $dateFrom
255
     * @param \DateTime $dateTo
256
     * @param int $merchantID
257
     * @return array of Stat
258
     */
259
    public function getStats(\DateTime $dateFrom, \DateTime $dateTo, int $merchantID = 0): array
260
    {
261
        return array();
262
        /*
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...
263
        $this->_apiClient->setConnectId($this->_username);
264
        $this->_apiClient->setSecretKey($this->_password);
265
        $dateFromIsoEngFormat = $dateFrom->format('Y-m-d');
266
        $dateToIsoEngFormat = $dateTo->format('Y-m-d');
267
        $response = $this->_apiClient->getReportBasic($dateFromIsoEngFormat, $dateToIsoEngFormat);
268
        $arrResponse = json_decode($response, true);
269
        $reportItems = $arrResponse['reportItems'];
270
        $Stat = Stat::createInstance();
271
        $Stat->reportItems = $reportItems;
272
273
        return array($Stat);
274
        */
275
    }
276
277
    /**
278
     * @param  array $params
279
     *
280
     * @return ProductsResultset
281
     */
282
    public function getProducts(array $params = []): ProductsResultset
283
    {
284
        // TODO: Implement getProducts() method.
285
        throw new \Exception("Not implemented yet");
286
    }
287
288
    /**
289
     * Api call CommissionJunction
290
     */
291 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...
292
    {
293
        $ch = curl_init();
294
        curl_setopt($ch, CURLOPT_URL, $url);
295
        curl_setopt($ch, CURLOPT_POST, FALSE);
296
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
297
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
298
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
299
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: " . $this->_passwordApi));
300
        $curl_results = curl_exec($ch);
301
        curl_close($ch);
302
        return $curl_results;
303
    }
304
305
    public function getTrackingParameter()
306
    {
307
        return $this->_tracking_parameter;
308
    }
309
310
    public function addAllowedSite($idSite){
311
        if (trim($idSite)!=''){
312
            $this->_network->addAllowedSite($idSite);
313
        }
314
    }
315
316
}
317