Completed
Push — master ( c6f3bd...788fbc )
by
unknown
02:44
created

Belboon::getStats()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 3
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
/**
15
 * Class Belboon
16
 * @package Padosoft\AffiliateNetwork\Networks
17
 */
18
class Belboon extends AbstractNetwork implements NetworkInterface
19
{
20
    /**
21
     * @var object
22
     */
23
    private $_network = null;
24
    private $_apiClient = null;
25
    private $_password = '';
26
    private $_idSite = '';
27
    protected $_tracking_parameter    = '/ subid1';
28
29
    /**
30
     * @method __construct
31
     */
32 View Code Duplication
    public function __construct(string $username, string $password,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...
33
    {
34
        $this->_network = new \Padosoft\AffiliateNetwork\BelboonEx;
35
        $this->_username = $username;
0 ignored issues
show
Bug introduced by
The property _username does not seem to exist. Did you mean username?

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...
36
        $this->_password = $password;
37
        $this->login( $this->_username, $this->_password, $idSite );
0 ignored issues
show
Bug introduced by
The property _username does not seem to exist. Did you mean username?

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...
38
        $this->_apiClient = null;
39
    }
40
41
    public function login(string $username, string $password, string $idSite=''): bool{
42
        $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...
43
        if (isNullOrEmpty( $password )) {
44
45
            return false;
46
        }
47
        $this->_username = $username;
0 ignored issues
show
Bug introduced by
The property _username does not seem to exist. Did you mean username?

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...
48
        $this->_password = $password;
49
        $this->_idSite = $idSite;
50
        $credentials = array();
51
        $credentials["user"] = $this->_username;
0 ignored issues
show
Bug introduced by
The property _username does not seem to exist. Did you mean username?

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...
52
        $credentials["apipassword"] = $this->_password;
53
        $credentials['id_site'] = $idSite;
54
        if ($this->_network->login($credentials)) {
55
            $this->_logged = true;
56
        }
57
        return $this->_logged;
58
    }
59
60
    /**
61
     * @return bool
62
     */
63
    public function checkLogin() : bool
64
    {
65
        return $this->_logged;
66
    }
67
68
    /**
69
     * @return array of Merchants
70
     */
71 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...
72
    {
73
        if (!$this->checkLogin()) {
74
            return array();
75
        }
76
        $arrResult = array();
77
        $merchantList = $this->_network->getMerchantList();
78
        foreach($merchantList as $merchant) {
79
            $Merchant = Merchant::createInstance();
80
            $Merchant->merchant_ID = $merchant['cid'];
81
            $Merchant->name = $merchant['name'];
82
            $arrResult[] = $Merchant;
83
        }
84
85
        return $arrResult;
86
    }
87
88
    /**
89
     * @param int $merchantID
90
     * @return array of Deal
91
     */
92
    public function getDeals($merchantID=NULL,int $page=0,int $items_per_page=10 ): DealsResultset
93
    {
94
        $result = DealsResultset::createInstance();
95
96
        if (!isset($_ENV['BELBOON_API_VOUCHER_KEY'])) {
97
            throw new \Exception("Belboon api key not defined");
98
        }
99
        $apiKey = $_ENV['BELBOON_API_VOUCHER_KEY'];
100
101
        $arrResult = array();
102
103
104
        $vouchers = array();
105
106
        try {
107
            $params = array(
108
                new \Oara\Curl\Parameter('key', $apiKey),
109
                new \Oara\Curl\Parameter('platformid', $this->_idSite),
110
                new \Oara\Curl\Parameter('status', 'all'),
111
                new \Oara\Curl\Parameter('format', 'csv'),
112
            );
113
114
            $credentials = [];
115
            $exportClient = new \Oara\Curl\Access($credentials);
116
117
118
            $urls[] = new \Oara\Curl\Request('https://ui.belboon.com/export/vouchercodes/?', $params);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$urls was never initialized. Although not strictly required by PHP, it is generally a good practice to add $urls = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
119
            $result = $exportClient->get($urls);
120
            if ($result === false || !is_array($result))
121
            {
122
                throw new \Exception("Belboon getVouchers - http error");
123
            } else {
124
                $vouchers = \str_getcsv($result[0], "\n");
125
            }
126
        } catch (\Exception $e) {
127
            echo "Belboon getVouchers error:".$e->getMessage()."\n ";
128
            throw new \Exception($e);
129
        }
130
131
        foreach($vouchers as $obj_voucher) {
132
133
            $voucher = str_getcsv($obj_voucher, ';', '"');
134
135
            $promotionId = $voucher[2];
136
            if (!is_numeric($promotionId)) {
137
                continue;
138
            }
139
            $advertiser = $voucher[2];
0 ignored issues
show
Unused Code introduced by
$advertiser 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...
140
            $advertiserId = $voucher[2];
141
            $type = $voucher[4];
0 ignored issues
show
Unused Code introduced by
$type 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...
142
            $code = $voucher[5];
143
            $description = $voucher[9];
144
            $starts = $voucher[7];
145
            $ends = $voucher[8];
146
            $deeplink_tracking = $voucher[10];
147
            $exclusive = $voucher[0];
148
149
            if ($merchantID > 0) {
150
                if ($advertiserId != $merchantID) {
151
                    continue;
152
                }
153
            }
154
155
            $Deal = Deal::createInstance();
156
            $Deal->deal_ID = $promotionId;
0 ignored issues
show
Documentation Bug introduced by
It seems like $promotionId can also be of type double or string. However, the property $deal_ID is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
157
            $Deal->merchant_ID = $advertiserId;
158
            $Deal->code = $code;
159
            $Deal->description = $description;
160
            $Deal->start_date = $Deal->convertDate($starts);
0 ignored issues
show
Documentation Bug introduced by
It seems like $Deal->convertDate($starts) can also be of type false. However, the property $start_date is declared as type object<DateTime>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
161
            $Deal->end_date = $Deal->convertDate($ends);
0 ignored issues
show
Documentation Bug introduced by
It seems like $Deal->convertDate($ends) can also be of type false. However, the property $end_date is declared as type object<DateTime>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
162
            $Deal->default_track_uri = $deeplink_tracking;
163
            $Deal->is_exclusive = $exclusive;
164
            $Deal->deal_type = \Oara\Utilities::OFFER_TYPE_VOUCHER;
165
            $arrResult[] = $Deal;
166
        }
167
        $result->deals[]=$arrResult;
168
169
        return $result;
170
    }
171
172
    /**
173
     * @param \DateTime $dateFrom
174
     * @param \DateTime $dateTo
175
     * @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...
176
     * @return array of Transaction
177
     */
178
    public function getSales(\DateTime $dateFrom, \DateTime $dateTo, array $arrMerchantID = array()) : array
179
    {
180
        $arrResult = array();
181
        try {
182 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...
183
                $merchants = $this->getMerchants();
184
                foreach ($merchants as $merchant) {
185
                    $arrMerchantID[$merchant->merchant_ID] = ['cid' => $merchant->merchant_ID, 'name' => $merchant->name];
186
                }
187
            }
188
             $transactionList = $this->_network->getTransactionList($arrMerchantID, $dateFrom, $dateTo);
189
190
            foreach($transactionList as $transaction) {
191
                $myTransaction = Transaction::createInstance();
192
                try {
193
                    $myTransaction->merchant_ID = $transaction['merchantId'];
194
                    $myTransaction->title ='';
195
                    $myTransaction->currency ='EUR';
196 View Code Duplication
                    if (!empty($transaction['date'])) {
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...
197
                        $date = new \DateTime($transaction['date']);
198
                        $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...
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...
199
                    }
200 View Code Duplication
                    if (!empty($transaction['lastchangedate'])) {
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...
201
                        $date = new \DateTime($transaction['lastchangedate']);
202
                        $myTransaction->update_date = $date;
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 $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...
203
                    }
204
                    $myTransaction->unique_ID = $transaction['unique_id'];
205
                    $myTransaction->custom_ID = array_key_exists('custom_id', $transaction) ? $transaction['custom_id'] : '';
206
                    $myTransaction->status = $transaction['status'];
207
                    $myTransaction->amount = $transaction['amount'];
208
                    $myTransaction->commission = $transaction['commission'];
209
                    $myTransaction->approved = false;
210
                    if ($transaction['status'] == \Oara\Utilities::STATUS_CONFIRMED){
211
                        $myTransaction->approved = true;
212
                    }
213
                    $arrResult[] = $myTransaction;
214
                } catch (\Exception $e) {
215
                    echo "<br><br>errore transazione Belboon, id: ".$myTransaction->unique_ID." msg: ".$e->getMessage()."<br><br>";
216
                    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...
217
                }
218
            }
219
        } catch (\Exception $e) {
220
            echo "<br><br>errore generico transazione Belboon: ".$e->getMessage()."<br><br>";
221
            var_dump($e->getTraceAsString());
222
            throw new \Exception($e);
223
        }
224
225
        return $arrResult;
226
    }
227
228
    /**
229
     * @param \DateTime $dateFrom
230
     * @param \DateTime $dateTo
231
     * @param int $merchantID
232
     * @return array of Stat
233
     */
234
    public function getStats(\DateTime $dateFrom, \DateTime $dateTo, int $merchantID = 0) : array
235
    {
236
        return array();
237
        /*
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...
238
        $this->_apiClient->setConnectId($this->_username);
239
        $this->_apiClient->setSecretKey($this->_password);
240
        $dateFromIsoEngFormat = $dateFrom->format('Y-m-d');
241
        $dateToIsoEngFormat = $dateTo->format('Y-m-d');
242
        $response = $this->_apiClient->getReportBasic($dateFromIsoEngFormat, $dateToIsoEngFormat);
243
        $arrResponse = json_decode($response, true);
244
        $reportItems = $arrResponse['reportItems'];
245
        $Stat = Stat::createInstance();
246
        $Stat->reportItems = $reportItems;
247
248
        return array($Stat);
249
        */
250
    }
251
252
253
    /**
254
     * @param  array $params
255
     *
256
     * @return ProductsResultset
257
     */
258
    public function getProducts(array $params = []): ProductsResultset
259
    {
260
        // TODO: Implement getProducts() method.
261
        throw new \Exception("Not implemented yet");
262
    }
263
264
    public function getTrackingParameter(){
265
        return $this->_tracking_parameter;
266
    }
267
}
268