Api::setPayer()   F
last analyzed

Complexity

Conditions 16
Paths 16385

Size

Total Lines 35
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 1 Features 0
Metric Value
c 4
b 1
f 0
dl 0
loc 35
rs 2.7326
cc 16
eloc 22
nc 16385
nop 1

How to fix   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 namespace SOSTheBlack\Moip;
2
3
use App;
4
use SimpleXmlElement;
5
6
/**
7
 * Library to help PHP users of Moip's API
8
 *
9
 * @author Herberth Amaral
10
 * @author Wesley Willians
11
 * @author Alê Borba
12
 * @author Vagner Fiuza Vieira
13
 * @author Paulo Cesar
14
 * @version 1.*
15
 * @license <a href="http://www.opensource.org/licenses/bsd-license.php">BSD License</a>
16
 */
17
18
/**
19
 * Moip's API abstraction class
20
 *
21
 * Class to use for all abstraction of Moip's API
22
 * @package Moip
23
 */
24
class Api extends MoipAbstract {
25
26
	/**
27
	 * Encoding of the page
28
	 *
29
	 * @var string
30
	 */
31
	public $encoding = 'UTF-8';
32
    /**
33
     * Associative array with two keys. 'key'=>'your_key','token'=>'your_token'
34
     *
35
     * @var array
36
     */
37
    protected $credential;
38
    /**
39
     * Define the payment's reason
40
     *
41
     * @var string
42
     */
43
    protected $reason;
44
    /**
45
     * The application's environment
46
     *
47
     * @var SOSTheBlack\Moip\Environment
48
     */
49
    protected $environment = null;
50
    /**
51
     * Transaction's unique ID
52
     *
53
     * @var string
54
     */
55
    protected $uniqueID;
56
    /**
57
     * Associative array of payment's way
58
     *
59
     * @var array
60
     */
61
    protected $payment_ways = array('billet' => 'BoletoBancario',
62
        'financing' => 'FinanciamentoBancario',
63
        'debit' => 'DebitoBancario',
64
        'creditCard' => 'CartaoCredito',
65
        'debitCard' => 'CartaoDebito');
66
    /**
67
     * Associative array of payment's institutions
68
     *
69
     * @var array
70
     */
71
    protected $institution = array('moip' => 'MoIP',
72
        'visa' => 'Visa',
73
        'american_express' => 'AmericanExpress',
74
        'mastercard' => 'Mastercard',
75
        'diners' => 'Diners',
76
        'banco_brasil' => 'BancoDoBrasil',
77
        'bradesco' => 'Bradesco',
78
        'itau' => 'Itau',
79
        'real' => 'BancoReal',
80
        'unibanco' => 'Unibanco',
81
        'aura' => 'Aura',
82
        'hipercard' => 'Hipercard',
83
        'paggo' => 'Paggo', //oi paggo
84
        'banrisul' => 'Banrisul'
85
    );
86
    /**
87
     * Associative array of delivery's type
88
     *
89
     * @var array
90
     */
91
    protected $delivery_type = array('proprio' => 'Proprio', 'correios' => 'Correios');
92
    /**
93
     * Associative array with type of delivery's time
94
     *
95
     * @var array
96
     */
97
    protected $delivery_type_time = array('corridos' => 'Corridos', 'uteis' => 'Uteis');
98
    /**
99
     * Payment method
100
     *
101
     * @var array
102
     */
103
    protected $payment_method;
104
    /**
105
     * Arguments of payment method
106
     *
107
     * @var array
108
     */
109
    protected $payment_method_args;
110
    /**
111
     * Payment's type
112
     *
113
     * @var string
114
     */
115
    protected $payment_type;
116
    /**
117
     * Associative array with payer's information
118
     *
119
     * @var array
120
     */
121
    protected $payer;
122
    /**
123
     * Server's answer
124
     *
125
     * @var \SOSTheBlack\Moip\Response
126
     */
127
    public $answer;
128
    /**
129
     * The transaction's value
130
     *
131
     * @var float
132
     */
133
    protected $value;
134
    /**
135
     * Simple XML object
136
     *
137
     * @var SimpleXMLElement
138
     */
139
    protected $xml;
140
    /**
141
     * Simple XML object
142
     *
143
     * @var object
144
     */
145
    public $errors;
146
	/**
147
	 * @var array
148
	 */
149
	protected $payment_way = array();
150
	/**
151
	 * @var float
152
	 */
153
	protected $adds;
154
	/**
155
	 * @var float
156
	 */
157
	protected $deduction;
158
    /**
159
     * Method construct
160
     *
161
     * @access public
162
     */
163
    public function __construct() {
164
        $this->setEnvironment();
165
166
        if (!$this->payment_type) {
167
            $this->payment_type = 'Basic';
168
        }
169
170
        $this->initXMLObject();
171
    }
172
173
	private function convert_encoding($text, $post = false)
174
	{
175
		if ($post)
176
		{
177
			return mb_convert_encoding($text, 'UTF-8');
178
		}
179
		else
180
		{
181
			/* No need to convert if its already in utf-8 */
182
			if ($this->encoding === 'UTF-8')
183
			{
184
				return $text;
185
			}
186
			return mb_convert_encoding($text, $this->encoding, 'UTF-8');
187
		}
188
	}
189
190
    /**
191
     * Method initXMLObject()
192
     *
193
     * Start a new XML structure for the requests
194
     *
195
     * @return void
196
     * @access private
197
     */
198
    private function initXMLObject() {
199
        $this->xml = new SimpleXmlElement('<?xml version="1.0" encoding="utf-8" ?><EnviarInstrucao></EnviarInstrucao>');
0 ignored issues
show
Documentation Bug introduced by
It seems like new \SimpleXmlElement('<...ao></EnviarInstrucao>') of type object<SimpleXMLElement> is incompatible with the declared type object<SOSTheBlack\Moip\SimpleXMLElement> of property $xml.

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...
200
        $this->xml->addChild('InstrucaoUnica');
201
    }
202
203
    /**
204
     * Method setPaymentType()
205
     *
206
     * Define the payment's type between 'Basic' or 'Identification'
207
     *
208
     * @param string $tipo Can be 'Basic' or 'Identification'
209
     * @return Api
210
     * @access public
211
     */
212
    public function setPaymentType($tipo) {
213
        if ($tipo == 'Basic' || $tipo == 'Identification') {
214
            $this->payment_type = $tipo;
215
        } else {
216
            $this->setError("Error: The variable type must contain values 'Basic' or 'Identification'");
217
        }
218
219
        return $this;
220
    }
221
222
    /**
223
     * Method setCredential()
224
     *
225
     * Set the credentials(key,token) required for the API authentication.
226
     *
227
     * @param array $credential Array with the credentials token and key
228
     * @return Api
229
     * @access public
230
     */
231
    public function setCredential($credential) {
232
        if (!isset($credential['token']) or
233
                !isset($credential['key']) or
234
                strlen($credential['token']) != 32 or
235
                strlen($credential['key']) != 40)
236
            $this->setError("Error: credential invalid");
237
238
        $this->credential = $credential;
239
        return $this;
240
    }
241
242
    /**
243
     * Method \SOSTheBlack\Moip\Environment setEnvironment()
244
     *
245
     * Define the environment for the API utilization.
246
     *
247
     * @param bool $testing If true, will use the sandbox environment
248
	 * @return Api
249
     */
250
    public function setEnvironment($testing = false) {
251
		if (empty($this->environment))
252
		{
253
			$this->environment = App::make('\SOSTheBlack\Moip\Environment');
254
		}
255
256
        if ($testing) {
257
            $this->environment->name = "Sandbox";
258
            $this->environment->base_url = "https://desenvolvedor.moip.com.br/sandbox";
259
        } else {
260
            $this->environment->name = "Produção";
261
            $this->environment->base_url = "https://www.moip.com.br";
262
        }
263
264
        return $this;
265
    }
266
267
    /**
268
     * Method validate()
269
     *
270
     * Make the data validation
271
	 *
272
     * @param string $validateType Identification or Basic, defaults to Basic
273
     * @return Api
274
     * @access public
275
     */
276
    public function validate($validateType = "Basic") {
277
278
        $this->setPaymentType($validateType);
279
280
        if (!isset($this->credential) or
281
                !isset($this->reason) or
282
                !isset($this->uniqueID))
283
            $this->setError("[setCredential], [setReason] and [setUniqueID] are required");
284
285
        $payer = $this->payer;
286
287
        if ($this->payment_type == 'Identification') {
288
			$varNotSeted = '';
289
290
            $dataValidate = array('name',
291
                'email',
292
                'payerId',
293
                'billingAddress');
294
295
            $dataValidateAddress = array('address',
296
                'number',
297
                'complement',
298
                'neighborhood',
299
                'city',
300
                'state',
301
                'country',
302
                'zipCode',
303
                'phone');
304
305
            foreach ($dataValidate as $key) {
306
                if (!isset($payer[$key])) {
307
                    $varNotSeted .= ' [' . $key . '] ';
308
                }
309
            }
310
311
            foreach ($dataValidateAddress as $key) {
312
                if (!isset($payer['billingAddress'][$key])) {
313
                    $varNotSeted .= ' [' . $key . '] ';
314
                }
315
            }
316
317
            if ($varNotSeted !== '') {
318
                $this->setError('Error: The following data required were not informed: ' . $varNotSeted . '.');
319
			}
320
        }
321
        return $this;
322
    }
323
324
    /**
325
     * Method setUniqueID()
326
     *
327
     * Set the unique ID for the transaction
328
     *
329
     * @param int $id Unique ID for each transaction
330
     * @return Api
331
     * @access public
332
     */
333
    public function setUniqueID($id) {
334
        $this->uniqueID = $id;
0 ignored issues
show
Documentation Bug introduced by
The property $uniqueID was declared of type string, but $id is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
335
        $this->xml->InstrucaoUnica->addChild('IdProprio', $this->uniqueID);
336
        return $this;
337
    }
338
339
    /**
340
     * Method setReason()
341
     *
342
     * Set the short description of transaction. eg. Order Number.
343
     *
344
     * @param string $reason The reason fo transaction
345
     * @return Api
346
     * @access public
347
     */
348
    public function setReason($reason) {
349
        $this->reason = $reason;
350
        $this->xml->InstrucaoUnica->addChild('Razao', $this->reason);
351
        
352
        return $this;
353
    }
354
355
    /**
356
     * Method addPaymentWay()
357
     *
358
     * Add a payment's method
359
     *
360
     * @param string $way The payment method. Options: 'billet','financing','debit','creditCard','debitCard'.
361
     * @return Api
362
     * @access public
363
     */
364
    public function addPaymentWay($way) {
365
        if (!isset($this->payment_ways[$way]))
366
            $this->setError("Error: Payment method unavailable");
367
        else
368
            $this->payment_way[] = $way;
369
370
371
        $instrucao = $this->xml->InstrucaoUnica;
372
373
374
        $formas = (!isset($instrucao->FormasPagamento)) ? $instrucao->addChild('FormasPagamento') : $instrucao->FormasPagamento;
375
376
        if (!empty($this->payment_way)) 
377
            $formas->addChild('FormaPagamento', $this->payment_ways[$way]);
378
379
        return $this;
380
    }
381
382
    /**
383
     * Method billetConf()
384
     *
385
     * Add a payment's method
386
     *
387
     * @param int $expiration expiration in days or dateTime.
388
     * @param boolean $workingDays expiration should be counted in working days?
389
     * @param array $instructions Additional payment instructions can be array of message or a message in string
390
     * @param string $uriLogo URL of the image to be displayed on docket (75x40)
391
     * @return Api
392
     * @access public
393
     */
394
    public function setBilletConf($expiration, $workingDays=false, $instructions = null, $uriLogo = null) {
395
396
        if (!isset($this->xml->InstrucaoUnica->Boleto)) {
397
            $this->xml->InstrucaoUnica->addChild('Boleto');
398
            if (is_numeric($expiration)) {
399
                $this->xml->InstrucaoUnica->Boleto->addChild('DiasExpiracao', $expiration);
0 ignored issues
show
Bug introduced by
The method addChild cannot be called on $this->xml->InstrucaoUnica->Boleto (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
400
401
                if ($workingDays)
402
                    $this->xml->InstrucaoUnica->Boleto->DiasExpiracao->addAttribute('Tipo', 'Uteis');
403
                else
404
                    $this->xml->InstrucaoUnica->Boleto->DiasExpiracao->addAttribute('Tipo', 'Corridos');
405
            }else {
406
                $this->xml->InstrucaoUnica->Boleto->addChild('DataVencimento', $expiration);
0 ignored issues
show
Bug introduced by
The method addChild cannot be called on $this->xml->InstrucaoUnica->Boleto (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
407
            }
408
409
            if (isset($instructions)) {
410
                if (is_array($instructions)) {
411
                    $numeroInstrucoes = 1;
412
                    foreach ($instructions as $instrucaostr) {
413
                        $this->xml->InstrucaoUnica->Boleto->addChild('Instrucao' . $numeroInstrucoes, $instrucaostr);
0 ignored issues
show
Bug introduced by
The method addChild cannot be called on $this->xml->InstrucaoUnica->Boleto (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
414
                        $numeroInstrucoes++;
415
                    }
416
                } else {
417
                    $this->xml->InstrucaoUnica->Boleto->addChild('Instrucao1', $instructions);
0 ignored issues
show
Bug introduced by
The method addChild cannot be called on $this->xml->InstrucaoUnica->Boleto (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
418
                }
419
            }
420
421
            if (isset($uriLogo))
422
                $this->xml->InstrucaoUnica->Boleto->addChild('URLLogo', $uriLogo);
0 ignored issues
show
Bug introduced by
The method addChild cannot be called on $this->xml->InstrucaoUnica->Boleto (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
423
        }
424
425
        return $this;
426
    }
427
428
    /**
429
     * Method setPayer()
430
     *
431
     * Set contacts informations for the payer.
432
     *
433
     * @param string $payer Contact information for the payer.
434
     * @return Api
435
     * @access public
436
     */
437
    public function setPayer($payer) {
438
        $this->payer = $payer;
0 ignored issues
show
Documentation Bug introduced by
It seems like $payer of type string is incompatible with the declared type array of property $payer.

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...
439
440
        if (!empty($this->payer)) {
441
            $p = $this->payer;
442
            $this->xml->InstrucaoUnica->addChild('Pagador');
443
            (isset($p['name'])) ? $this->xml->InstrucaoUnica->Pagador->addChild('Nome', $this->payer['name']) : null;
444
            (isset($p['email'])) ? $this->xml->InstrucaoUnica->Pagador->addChild('Email', $this->payer['email']) : null;
445
            (isset($p['payerId'])) ? $this->xml->InstrucaoUnica->Pagador->addChild('IdPagador', $this->payer['payerId']) : null;
446
            (isset($p['identity'])) ? $this->xml->InstrucaoUnica->Pagador->addChild('Identidade', $this->payer['identity']) : null;
447
            (isset($p['phone'])) ? $this->xml->InstrucaoUnica->Pagador->addChild('TelefoneCelular', $this->payer['phone']) : null;
448
449
            $p = $this->payer['billingAddress'];
450
            $this->xml->InstrucaoUnica->Pagador->addChild('EnderecoCobranca');
451
            (isset($p['address'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Logradouro', $this->payer['billingAddress']['address']) : null;
452
453
            (isset($p['number'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Numero', $this->payer['billingAddress']['number']) : null;
454
455
            (isset($p['complement'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Complemento', $this->payer['billingAddress']['complement']) : null;
456
457
            (isset($p['neighborhood'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Bairro', $this->payer['billingAddress']['neighborhood']) : null;
458
459
            (isset($p['city'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Cidade', $this->payer['billingAddress']['city']) : null;
460
461
            (isset($p['state'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Estado', $this->payer['billingAddress']['state']) : null;
462
463
            (isset($p['country'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('Pais', $this->payer['billingAddress']['country']) : null;
464
465
            (isset($p['zipCode'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('CEP', $this->payer['billingAddress']['zipCode']) : null;
466
467
            (isset($p['phone'])) ? $this->xml->InstrucaoUnica->Pagador->EnderecoCobranca->addChild('TelefoneFixo', $this->payer['billingAddress']['phone']) : null;
468
        }
469
470
        return $this;
471
    }
472
473
    /**
474
     * Method setValue()
475
     *
476
     * Set the transaction's value
477
     *
478
     * @param float $value The transaction's value
479
     * @return Api
480
     * @access public
481
     */
482
    public function setValue($value) {
483
        $this->value = $value;
484
485
        if (empty($this->value))
486
            $this->setError('Error: The transaction amount must be specified.');
487
488
        $this->xml->InstrucaoUnica->addChild('Valores')
489
                ->addChild('Valor', $this->value)
490
                ->addAttribute('moeda', 'BRL');
491
492
        return $this;
493
    }
494
495
    /**
496
     * Method setAdds()
497
     *
498
     * Adds a value on payment. Can be used for collecting fines, shipping and other
499
     *
500
     * @param float $value The value to add.
501
     * @return Api
502
     * @access public
503
     */
504 View Code Duplication
    public function setAdds($value) {
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...
505
        $this->adds = $value;
506
507
        if (isset($this->adds)) {
508
            $this->xml->InstrucaoUnica->Valores->addChild('Acrescimo', $this->adds)
509
                    ->addAttribute('moeda', 'BRL');
510
        }
511
512
        return $this;
513
    }
514
515
    /**
516
     * Method setDeduct()
517
     *
518
     * Deducts a payment amount. It is mainly used for discounts.
519
     *
520
     * @param float $value The value to deduct
521
     * @return Api
522
     * @access public
523
     */
524 View Code Duplication
    public function setDeduct($value) {
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...
525
        $this->deduction = $value;
526
527
        if (isset($this->deduction)) {
528
            $this->xml->InstrucaoUnica->Valores->addChild('Deducao', $this->deduction)
529
                    ->addAttribute('moeda', 'BRL');
530
        }
531
532
        return $this;
533
    }
534
535
    /**
536
     * Method addMessage()
537
     *
538
     * Add a message in the instruction to be displayed to the payer.
539
     *
540
     * @param string $msg Message to be displayed.
541
     * @return Api
542
     * @access public
543
     */
544 View Code Duplication
    public function addMessage($msg) {
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...
545
        if (!isset($this->xml->InstrucaoUnica->Mensagens)) {
546
            $this->xml->InstrucaoUnica->addChild('Mensagens');
547
        }
548
549
        $this->xml->InstrucaoUnica->Mensagens->addChild('Mensagem', $msg);
550
        return $this;
551
    }
552
553
    /**
554
     * Method setReturnURL()
555
     *
556
     * Set the return URL, which redirects the client after payment.
557
     *
558
     * @param string $url Return URL
559
	 * @return Api
560
     * @access public
561
     */
562
    public function setReturnURL($url) {
563
        if (!isset($this->xml->InstrucaoUnica->URLRetorno)) {
564
            $this->xml->InstrucaoUnica->addChild('URLRetorno', $url);
565
        }
566
		return $this;
567
    }
568
569
    /**
570
     * Method setNotificationURL()
571
     *
572
     * Set the notification URL, which sends information about changes in payment status
573
     *
574
     * @param string $url Notification URL
575
     * @access public
576
     */
577
    public function setNotificationURL($url) {
578
        if (!isset($this->xml->InstrucaoUnica->URLNotificacao)) {
579
            $this->xml->InstrucaoUnica->addChild('URLNotificacao', $url);
580
        }
581
    }
582
583
    /**
584
     * Method setError()
585
     *
586
     * Set Erroe alert
587
     *
588
     * @param String $error Error alert
589
     * @return Api
590
     * @access public
591
     */
592
    public function setError($error) {
593
        $this->errors = $error;
0 ignored issues
show
Documentation Bug introduced by
It seems like $error of type string is incompatible with the declared type object of property $errors.

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...
594
595
        return $this;
596
    }
597
598
    /**
599
     * Method addComission()
600
     *
601
     * Allows to specify commissions on the payment, like fixed values or percent.
602
     *
603
     * @param string $reason reason for commissioning
604
     * @param string $receiver login Moip the secondary receiver
605
     * @param number $value value of the division of payment
606
     * @param boolean $percentageValue percentage value should be
607
     * @param boolean $ratePayer this secondary recipient will pay the fee Moip
608
	 * @return Api
609
     * @access public
610
     */
611
    public function addComission($reason, $receiver, $value, $percentageValue=false, $ratePayer=false) {
612
613
        if (!isset($this->xml->InstrucaoUnica->Comissoes))
614
            $this->xml->InstrucaoUnica->addChild('Comissoes');
615
616
        if (is_numeric($value)) {
617
618
            $split = $this->xml->InstrucaoUnica->Comissoes->addChild('Comissionamento');
619
            $split->addChild('Comissionado')->addChild('LoginMoIP', $receiver);
620
            $split->addChild('Razao', $reason);
621
622
            if ($percentageValue == false)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
623
                $split->addChild('ValorFixo', $value);
624
            if ($percentageValue == true)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
625
                $split->addChild('ValorPercentual', $value);
626
            if ($ratePayer == true)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
627
                $this->xml->InstrucaoUnica->Comissoes->addChild('PagadorTaxa')->addChild('LoginMoIP', $receiver);
628
        }else {
629
            $this->setError('Error: Value must be numeric.');
630
        }
631
632
        return $this;
633
    }
634
635
    /**
636
     * Method addParcel()
637
     *
638
     * Allows to add a order to parceling.
639
     *
640
     * @param int $min The minimum number of parcels.
641
     * @param int $max The maximum number of parcels.
642
     * @param float $rate The percentual value of rates
643
     * @param boolean $transfer "true" defines the amount of interest charged by MoIP installment to be paid by the payer
644
     * @return Api
645
     * @access public
646
     */
647
    public function addParcel($min, $max, $rate=null, $transfer=false, $receipt=false) {
648
        if (!isset($this->xml->InstrucaoUnica->Parcelamentos)) {
649
            $this->xml->InstrucaoUnica->addChild('Parcelamentos');
650
        }
651
652
        $parcela = $this->xml->InstrucaoUnica->Parcelamentos->addChild('Parcelamento');
653 View Code Duplication
        if (is_numeric($min) && $min <= 12)
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...
654
            $parcela->addChild('MinimoParcelas', $min);
655
        else
656
            $this->setError('Error: Minimum parcel can not be greater than 12.');
657
658 View Code Duplication
        if (is_numeric($max) && $max <= 12)
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...
659
            $parcela->addChild('MaximoParcelas', $max);
660
        else
661
            $this->setError('Error: Maximum amount can not be greater than 12.');
662
663
        $parcela->addChild('Recebimento', $this->receipt($receipt));
664
665
        if ($transfer === false) {
666
            if (isset($rate)) {
667
                if (is_numeric($rate))
668
                    $parcela->addChild('Juros', $rate);
669
                else
670
                    $this->setError('Error: Rate must be numeric');
671
            }
672
        }else {
673
            if (is_bool($transfer))
674
                $parcela->addChild('Repassar', $transfer);
675
            else
676
                $this->setError('Error: Transfer must be boolean');
677
        }
678
679
        return $this;
680
    }
681
682
    /**
683
     * @param boolean $receipt
684
     */
685
    private function receipt($receipt)
686
    {
687
        return $receipt === false ? 'AVista' : 'Parcelado';
688
    }
689
690
    /**
691
     * Method setReceiving()
692
     *
693
     * Allows to add a order to parceling.
694
     *
695
     * @param string $receiver login Moip the secondary receiver
696
     * @return Api
697
     * @access public
698
     */
699
    public function setReceiver($receiver) {
700
        if (!isset($this->xml->InstrucaoUnica->Recebedor)) {
701
            $this->xml->InstrucaoUnica->addChild('Recebedor')
702
                    ->addChild('LoginMoIP', $receiver);
703
        }
704
705
        return $this;
706
    }
707
708
    /**
709
     * Method getXML()
710
     *
711
     * Returns the XML that is generated. Useful for debugging.
712
     *
713
     * @return string
714
     * @access public
715
     */
716
    public function getXML() {
717
718
        if ($this->payment_type == "Identification")
719
            $this->xml->InstrucaoUnica->addAttribute('TipoValidacao', 'Transparente');        
720
721
        $return = $this->convert_encoding($this->xml->asXML(), true);
722
        return str_ireplace("\n", "", $return);
723
    }
724
725
    /**
726
     * Method send()
727
     *
728
     * Send the request to the server
729
     *
730
     * @param object $client The server's connection
731
     * @return type|null
732
     * @access public
733
     */
734
    public function send($client=null) {
735
        $this->validate();
736
737
        if ($client == null)
738
            $client = App::make('\SOSTheBlack\Moip\Client');
739
740
        $url = $this->environment->base_url . '/ws/alpha/EnviarInstrucao/Unica';
741
742
        return $this->answer = $client->curlPost($this->credential['token'] . ':' . $this->credential['key'],
743
                $this->getXML(),
744
                $url, $this->errors);
745
    }
746
747
    /**
748
     * Method getAnswer()
749
     *
750
     * Gets the server's answer
751
     * @param boolean $return_xml_as_string Return the answer XMl string
752
     * @return MoipResponse|string
753
     * @access public
754
     */
755
    public function getAnswer($return_xml_as_string = false) {
756
        if ($this->answer->response == true) {
757
            if ($return_xml_as_string) {
758
                return $this->answer->xml;
759
            }
760
761
            $xml = new SimpleXmlElement($this->answer->xml);
762
763
            return App::make('\SOSTheBlack\Moip\Response',[[
764
                'response' => $xml->Resposta->Status == 'Sucesso' ? true : false,
765
                'error' => $xml->Resposta->Status == 'Falha' ? $this->convert_encoding((string)$xml->Resposta->Erro) : false,
766
                'token' => (string) $xml->Resposta->Token,
767
                'payment_url' => $xml->Resposta->Status == 'Sucesso' ? (string) $this->environment->base_url . "/Instrucao.do?token=" . (string) $xml->Resposta->Token : false,
768
            ]]);
769
        } else {
770
            return $this->answer->error;
771
        }
772
    }
773
774
    /**
775
     * Method verifyParcelValues()
776
     *
777
     * Get all informations about the parcelling of user defined by $login_moip
778
     *
779
     * @param string $login The client's login for Moip services
780
     * @param int $maxParcel The total parcels
781
     * @param float $rate The rate's percents of the parcelling.
782
     * @param float $simulatedValue The value for simulation
783
     * @return array
784
     * @access public
785
     */
786
    public function queryParcel($login, $maxParcel, $rate, $simulatedValue) {
787
        if (!isset($this->credential))
788
            $this->setError("You must specify the credentials (token / key) and enriroment");
789
790
791
        $client = App::make('\SOSTheBlack\Moip\Client');
792
793
        $url = $this->environment->base_url . "/ws/alpha/ChecarValoresParcelamento/$login/$maxParcel/$rate/$simulatedValue";
794
        $credential = $this->credential['token'] . ':' . $this->credential['key'];
795
        $answer = $client->curlGet($credential, $url, $this->errors);
796
797
        if ($answer->response) {
798
            $xml = new SimpleXmlElement($answer->xml);
799
800
            if ($xml->Resposta->Status == "Sucesso")
801
                $response = true;
802
            else
803
                $response = false;
804
805
            $return = array('response' => $response,
806
                'installment' => array());
807
808
            $i = 1;
809
            foreach ($xml->Resposta->ValorDaParcela as $parcela) {
810
                $attrib = $parcela->attributes();
811
                $return['installment']["$i"] = array('total' => (string) $attrib['Total'], 'rate' => (string) $attrib['Juros'], 'value' => (string) $attrib['Valor']);
812
                $i++;
813
            }
814
            return $return;
815
        }
816
817
		return $answer;
818
    }
819
820
}
821