Factory::createCreditCardFromArray()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 0
cts 8
cp 0
rs 9.8333
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 6
1
<?php
2
namespace MrPrompt\Centercob;
3
4
use DateTime;
5
use MrPrompt\ShipmentCommon\Base\Bank;
6
use MrPrompt\ShipmentCommon\Base\Email;
7
use MrPrompt\ShipmentCommon\Base\Phone;
8
use MrPrompt\ShipmentCommon\Base\Billet;
9
use MrPrompt\ShipmentCommon\Base\Charge;
10
use MrPrompt\ShipmentCommon\Base\Holder;
11
use MrPrompt\ShipmentCommon\Base\Parcel;
12
use MrPrompt\ShipmentCommon\Base\Person;
13
use MrPrompt\ShipmentCommon\Base\Seller;
14
use MrPrompt\ShipmentCommon\Base\Address;
15
use MrPrompt\ShipmentCommon\Base\Parcels;
16
use MrPrompt\ShipmentCommon\Base\Customer;
17
use MrPrompt\ShipmentCommon\Base\Document;
18
use MrPrompt\ShipmentCommon\Base\Sequence;
19
use MrPrompt\ShipmentCommon\Base\Purchaser;
20
use MrPrompt\ShipmentCommon\Base\CreditCard;
21
use MrPrompt\ShipmentCommon\Base\Occurrence;
22
use MrPrompt\ShipmentCommon\Base\BankAccount;
23
use MrPrompt\Centercob\Shipment\Partial\Detail;
24
use MrPrompt\ShipmentCommon\Base\Authorization;
25
use MrPrompt\ShipmentCommon\Base\ConsumerUnity;
26
27
/**
28
 * Common base factory
29
 *
30
 * @author Thiago Paes <[email protected]>
31
 */
32
abstract class Factory
33
{
34
    /**
35
     * @param array $campos
36
     * @return Document
37
     */
38
    public static function createDocumentFromArray(array $campos = [])
39
    {
40
        $document = new Document();
41
        $document->setType(strlen($campos['documento']) === 11 ? Document::CPF : Document::CNPJ);
42
        $document->setNumber((int) $campos['documento']);
43
44
        return $document;
45
    }
46
47
    /**
48
     * @param array $campos
49
     * @return Customer
50
     */
51
    public static function createCustomerFromArray(array $campos = [])
52
    {
53
        $customer = new Customer();
54
        $customer->setCode($campos['cliente']);
55
        $customer->setIdentityNumber($campos['identificador']);
56
57
        return $customer;
58
    }
59
60
    /**
61
     * @param array $campos
62
     * @return Charge
63
     */
64
    public static function createChargeFromArray(array $campos = [])
65
    {
66
        $charge = new Charge();
67
        $charge->setCharging($campos['cobranca']);
68
        $charge->setOccurrence(self::createOccurrenceFromArray($campos));
69
70
        return $charge;
71
    }
72
73
    /**
74
     * @param array $campos
75
     * @return ConsumerUnity
76
     */
77
    public static function createConsumerUnityFromArray(array $campos = [])
78
    {
79
        $consumerUnity  = new ConsumerUnity();
80
81
        if (array_key_exists('energia', $campos)) {
82
            $leitura    = DateTime::createFromFormat('dmY', $campos['energia']['leitura']);
83
            $vencimento = DateTime::createFromFormat('dmY', $campos['energia']['vencimento']);
84
85
            $consumerUnity->setRead($leitura);
0 ignored issues
show
Security Bug introduced by
It seems like $leitura defined by \DateTime::createFromFor...['energia']['leitura']) on line 82 can also be of type false; however, MrPrompt\ShipmentCommon\...onsumerUnity::setRead() does only seem to accept object<DateTime>, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
86
            $consumerUnity->setMaturity($vencimento);
0 ignored issues
show
Security Bug introduced by
It seems like $vencimento defined by \DateTime::createFromFor...nergia']['vencimento']) on line 83 can also be of type false; however, MrPrompt\ShipmentCommon\...merUnity::setMaturity() does only seem to accept object<DateTime>, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
87
            $consumerUnity->setNumber($campos['energia']['numero']);
88
            $consumerUnity->setCode($campos['energia']['concessionaria']);
89
        }
90
91
        return $consumerUnity;
92
    }
93
94
    /**
95
     * @param array $campos
96
     * @return Occurrence
97
     */
98
    public static function createOccurrenceFromArray(array $campos = [])
99
    {
100
        $occurrence = new Occurrence();
101
102
        if (array_key_exists('ocorrencia', $campos)) {
103
            $occurrence->setType($campos['ocorrencia']);
104
        }
105
106
        return $occurrence;
107
    }
108
109
    /**
110
     * @param int $number
111
     * @param int $type
112
     * @return Phone
113
     */
114
    public static function createPhone($number, $type = Phone::TELEPHONE)
115
    {
116
        $phone = new Phone();
117
        $phone->setNumber($number);
118
        $phone->setType($type);
119
120
        return $phone;
121
    }
122
123
    /**
124
     * @param array $campos
125
     * @return Person
126
     */
127
    public static function createPersonFromArray(array $campos = [])
128
    {
129
        $person = new Person();
130
        $person->setName($campos['nome']);
131
        $person->setCellPhone(self::createPhone($campos['celular'], Phone::CELLPHONE));
132
        $person->setHomePhone(self::createPhone($campos['telefone1'], Phone::TELEPHONE));
133
        $person->setHomePhoneSecondary(self::createPhone($campos['telefone2'], Phone::TELEPHONE));
134
        $person->setDocument(self::createDocumentFromArray($campos['comprador']));
135
        $person->setEmail($campos['email']);
136
        $person->setFatherName($campos['pai']);
137
        $person->setMotherName($campos['mae']);
138
139
        return $person;
140
    }
141
142
    /**
143
     * @param array $campos
144
     * @return Holder
145
     */
146
    public static function createHolderFromArray(array $campos = [])
147
    {
148
        $person = new Holder();
149
150
        if (array_key_exists('titular', $campos)) {
151
            $person->setName($campos['titular']['nome']);
152
            $person->setCellPhone($campos['titular']['celular']);
153
            $person->setDocument(self::createDocumentFromArray($campos['titular']));
154
            $person->setEmail($campos['titular']['email']);
155
            $person->setFatherName($campos['titular']['pai']);
156
            $person->setMotherName($campos['titular']['mae']);
157
        }
158
159
        return $person;
160
    }
161
162
    /**
163
     * @param array $campos
164
     * @return Address
165
     */
166
    public static function createAddressFromArray(array $campos = [])
167
    {
168
        $address = new Address();
169
        $address->setNumber($campos['numero']);
170
        $address->setAddress($campos['logradouro']);
171
        $address->setComplement($campos['complemento']);
172
        $address->setDistrict($campos['bairro']);
173
        $address->setPostalCode($campos['cep']);
174
        $address->setCity($campos['cidade']);
175
        $address->setState($campos['uf']);
176
177
        return $address;
178
    }
179
180
    /**
181
     * @param array $campos
182
     * @return BankAccount
183
     */
184
    public static function createBankAccountFromArray(array $campos = [])
185
    {
186
        $holder     = new Holder();
187
        $bank       = new Bank();
188
        $account    = new BankAccount($bank, $holder);
189
190
        if (array_key_exists('banco', $campos)) {
191
            $bank->setAgency($campos['banco']['agencia']);
192
            $bank->setDigit($campos['banco']['digito']);
193
            $bank->setCode($campos['banco']['codigo']);
194
195
            $account->setDigit($campos['banco']['conta']['digito']);
196
            $account->setNumber($campos['banco']['conta']['numero']);
197
            $account->setOperation($campos['banco']['conta']['operacao']);
198
199
            if (array_key_exists('seguro', $campos['banco']['conta'])) {
200
                $account->setSecurity($campos['banco']['conta']['seguro']);
201
            }
202
203
            if (array_key_exists('titular', $campos['banco']['conta'])) {
204
                $account->setHolder(self::createHolderFromArray($campos['banco']['conta']['titular']));
205
            }
206
        }
207
208
        return $account;
209
    }
210
211
    /**
212
     * @param array $campos
213
     * @return Purchaser
214
     */
215
    public static function createPurchaserFromArray(array $campos = [])
216
    {
217
        $purchaser  = new Purchaser();
218
219
        if (array_key_exists('comprador', $campos)) {
220
            $document   = self::createDocumentFromArray($campos['comprador']);
221
            $address    = self::createAddressFromArray($campos['comprador']['endereco']);
222
            $birth      = DateTime::createFromFormat('dmY', $campos['comprador']['nascimento']);
223
224
            $purchaser->setName($campos['comprador']['nome']);
225
            $purchaser->setCellPhone(self::createPhone($campos['comprador']['celular'], Phone::CELLPHONE));
226
            $purchaser->setHomePhone(self::createPhone($campos['comprador']['telefone1'], Phone::TELEPHONE));
227
            $purchaser->setHomePhoneSecondary(self::createPhone($campos['comprador']['telefone2'], Phone::TELEPHONE));
228
            $purchaser->setDocument($document);
229
            $purchaser->setEmail(self::createEmail($campos['comprador']['email']));
230
            $purchaser->setBirth($birth);
0 ignored issues
show
Security Bug introduced by
It seems like $birth defined by \DateTime::createFromFor...prador']['nascimento']) on line 222 can also be of type false; however, MrPrompt\ShipmentCommon\Base\Person::setBirth() does only seem to accept object<DateTime>, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
231
            $purchaser->setAddress($address);
232
            $purchaser->setPerson($campos['comprador']['pessoa']);
233
        }
234
235
        return $purchaser;
236
    }
237
238
    /**
239
     * @param $address
240
     * @return Email
241
     */
242
    public static function createEmail($address)
243
    {
244
        return new Email($address, true);
245
    }
246
247
    /**
248
     * @param array $campos
249
     * @return CreditCard
250
     */
251
    public static function createCreditCardFromArray(array $campos = [])
252
    {
253
        $creditCard = new CreditCard();
254
255
        if (array_key_exists('cartao', $campos)) {
256
            $creditCard->setSecurityNumber($campos['cartao']['seguranca']);
257
            $creditCard->setValidate(DateTime::createFromFormat('mY', $campos['cartao']['validade']));
0 ignored issues
show
Security Bug introduced by
It seems like \DateTime::createFromFor...['cartao']['validade']) targeting DateTime::createFromFormat() can also be of type false; however, MrPrompt\ShipmentCommon\...editCard::setValidate() does only seem to accept object<DateTime>, did you maybe forget to handle an error condition?
Loading history...
258
            $creditCard->setNumber($campos['cartao']['numero']);
259
            $creditCard->setFlag($campos['cartao']['bandeira']);
260
        }
261
262
        return $creditCard;
263
    }
264
265
    /**
266
     * @param array $campos
267
     * @return \SplFixedArray
268
     */
269
    public static function createParcelsFromArray(array $campos = [])
270
    {
271
        $parcels = new Parcels(count($campos['parcelas']));
272
        $key     = 1;
273
274
        foreach ($campos['parcelas'] as $parcela) {
275
            $parcelOne   = new Parcel();
276
            $parcelOne->setMaturity(DateTime::createFromFormat('dmY', $parcela['vencimento']));
0 ignored issues
show
Security Bug introduced by
It seems like \DateTime::createFromFor...$parcela['vencimento']) targeting DateTime::createFromFormat() can also be of type false; however, MrPrompt\ShipmentCommon\Base\Parcel::setMaturity() does only seem to accept object<DateTime>, did you maybe forget to handle an error condition?
Loading history...
277
            $parcelOne->setKey($key);
278
            $parcelOne->setPrice($parcela['valor']);
279
            $parcelOne->setQuantity($parcela['quantidade']);
280
281
            $parcels->addParcel($parcelOne);
282
283
            $key++;
284
        }
285
286
        return $parcels;
287
    }
288
289
    /**
290
     * @param array $campos
291
     * @return Seller
292
     */
293
    public static function createSellerFromArray(array $campos = [])
294
    {
295
        $seller = new Seller();
296
297
        if (array_key_exists('vendedor', $campos)) {
298
            $seller = new Seller();
299
            $seller->setCode($campos['vendedor']['codigo']);
300
            $seller->setName($campos['vendedor']['nome']);
301
            $seller->setDocument(static::createDocumentFromArray($campos['vendedor']));
302
            $seller->setAddress(static::createAddressFromArray($campos['vendedor']['endereco']));
303
        }
304
305
        return $seller;
306
    }
307
308
    /**
309
     * @param array $campos
310
     * @return Authorization
311
     */
312
    public static function createAuthorizationFromArray(array $campos = [])
313
    {
314
        $authorization = new Authorization();
315
316
        if (array_key_exists('autorizacao', $campos)) {
317
            $authorization->setNumber($campos['autorizacao']);
318
        }
319
320
        return $authorization;
321
    }
322
323
    /**
324
     * @param array $campos
325
     * @return Billet
326
     */
327
    public static function createBilletFromArray(array $campos = [])
328
    {
329
        $billet = new Billet();
330
331
        if (array_key_exists('boleto', $campos)) {
332
            $billet->setBankAccount(self::createBankAccountFromArray($campos['boleto']));
333
            $billet->setNumber($campos['boleto']['documento']);
334
        }
335
336
        return $billet;
337
    }
338
339
    /**
340
     * Create a cart item object
341
     *
342
     * @param array $campos
343
     * @return Detail
344
     */
345
    public static function createDetailFromArray(array $campos = [])
346
    {
347
        $customer       = self::createCustomerFromArray($campos);
348
        $charge         = self::createChargeFromArray($campos);
349
        $purchaser      = self::createPurchaserFromArray($campos);
350
        $parcels        = self::createParcelsFromArray($campos);
351
        $creditCard     = self::createCreditCardFromArray($campos);
352
        $consumerUnity  = self::createConsumerUnityFromArray($campos);
353
        $bankAccount    = self::createBankAccountFromArray($campos);
354
        $seller         = self::createSellerFromArray($campos);
355
        $authorization  = self::createAuthorizationFromArray($campos);
356
        $sequence       = new Sequence();
357
358
        /* @var $detail \Centercob\Gateway\Shipment\Partial\Detail */
359
        $detail = new Detail(
360
            $customer,
361
            $charge,
362
            $seller,
363
            $purchaser,
364
            $parcels,
365
            $authorization,
366
            $creditCard,
367
            $bankAccount,
368
            $consumerUnity,
369
            $sequence
370
        );
371
372
        return $detail;
373
    }
374
375
    /**
376
     * @param Detail $item
377
     * @return array
378
     */
379
    public static function createArrayFromDetail(Detail $item)
380
    {
381
        $result = [
382
            'cliente'           => $item->getCustomer()->getCode(),
383
            'vendedor'          => $item->getSeller()->getCode(),
384
            'cobranca'          => $item->getCharge()->getCharging(),
385
            'ocorrencia'        => $item->getCharge()->getOccurrence()->getReturn(),
386
            'descricao'         => $item->getCharge()->getOccurrence()->getDescription(),
387
            'identificador'     => $item->getCharge(),
388
            'autorizacao'       => $item->getAuthorization()->getNumber(),
389
            'comprador'         => [
390
                'pessoa'        => $item->getPurchaser()->getPerson(),
391
                'nome'          => $item->getPurchaser()->getName(),
392
                'documento'     => $item->getPurchaser()->getDocument(),
393
                'nascimento'    => $item->getPurchaser()->getBirth()->format('dmY'),
394
                'email'         => $item->getPurchaser()->getEmail()->getAddress(),
395
                'telefone1'     => $item->getPurchaser()->getHomePhone()->getNumber(),
396
                'telefone2'     => $item->getPurchaser()->getHomePhone()->getNumber(),
397
                'celular'       => $item->getPurchaser()->getCellPhone()->getNumber(),
398
                'endereco'      => [
399
                    'cidade'        => $item->getPurchaser()->getAddress()->getCity(),
400
                    'uf'            => $item->getPurchaser()->getAddress()->getState(),
401
                    'cep'           => $item->getPurchaser()->getAddress()->getPostalCode(),
402
                    'logradouro'    => $item->getPurchaser()->getAddress()->getAddress(),
403
                    'numero'        => $item->getPurchaser()->getAddress()->getNumber(),
404
                    'bairro'        => $item->getPurchaser()->getAddress()->getDistrict(),
405
                    'complemento'   => $item->getPurchaser()->getAddress()->getComplement(),
406
                ],
407
            ],
408
            'parcelas'          => [],
409
        ];
410
411
        foreach ($item->getParcels() as $parcel) {
412
            $result['parcelas'][] = [
413
                'vencimento' => ($parcel->getMaturity() !== null ? $parcel->getMaturity()->format('dmY') : null),
414
                'valor'      => $parcel->getPrice(),
415
                'quantidade' => $parcel->getQuantity(),
416
            ];
417
        }
418
419
        switch ($result['cobranca']) {
420
            case Charge::CREDIT_CARD:
421
                $result['cartao'] = [
422
                    'bandeira' => $item->getCreditCard()->getFlag(),
423
                    'numero'   => $item->getCreditCard()->getNumber(),
424
                    'validade' => ($item->getCreditCard()->getValidate() !== null ? $item->getCreditCard()->getValidate()->format('mY') : null),
425
                    'seguranca'=> $item->getCreditCard()->getSecurityNumber(),
426
                ];
427
                break;
428
429
            case Charge::DEBIT:
430
                $result['banco'] = [
431
                    'codigo'    => $item->getBankAccount()->getBank()->getCode(),
432
                    'agencia'   => $item->getBankAccount()->getBank()->getAgency(),
433
                    'digito'    => $item->getBankAccount()->getBank()->getDigit(),
434
                    'conta'     => [
435
                        'numero'    => $item->getBankAccount()->getNumber(),
436
                        'digito'    => $item->getBankAccount()->getDigit(),
437
                        'operacao'  => $item->getBankAccount()->getOperation(),
438
                        'seguro'    => $item->getBankAccount()->getSecurity(),
439
                        'titular'   => $result['comprador'],
440
                    ]
441
                ];
442
                break;
443
444
            case Charge::ENERGY:
445
                $result['energia'] = [
446
                    'numero'        => $item->getConsumerUnity()->getNumber(),
447
                    'leitura'       => ($item->getConsumerUnity()->getRead() !== null ? $item->getConsumerUnity()->getRead()->format('dmy') : null),
448
                    'vencimento'    => ($item->getConsumerUnity()->getMaturity() !== null ? $item->getConsumerUnity()->getMaturity()->format('dmy') : null),
449
                    'concessionaria'=> $item->getConsumerUnity()->getCode(),
450
                ];
451
                break;
452
        }
453
454
        return $result;
455
    }
456
}