Issues (17)

src/Factory.php (4 issues)

Labels
Severity
1
<?php
2
namespace MrPrompt\Celesc;
3
4
use DateTime;
5
use MrPrompt\ShipmentCommon\Base\Address;
6
use MrPrompt\ShipmentCommon\Base\Authorization;
7
use MrPrompt\ShipmentCommon\Base\Bank;
8
use MrPrompt\ShipmentCommon\Base\BankAccount;
9
use MrPrompt\ShipmentCommon\Base\Billet;
10
use MrPrompt\ShipmentCommon\Base\Charge;
11
use MrPrompt\ShipmentCommon\Base\ConsumerUnity;
12
use MrPrompt\ShipmentCommon\Base\Customer;
13
use MrPrompt\ShipmentCommon\Base\Document;
14
use MrPrompt\ShipmentCommon\Base\Email;
15
use MrPrompt\ShipmentCommon\Base\Holder;
16
use MrPrompt\ShipmentCommon\Base\Occurrence;
17
use MrPrompt\ShipmentCommon\Base\Parcel;
18
use MrPrompt\ShipmentCommon\Base\Parcels;
19
use MrPrompt\ShipmentCommon\Base\Person;
20
use MrPrompt\ShipmentCommon\Base\Phone;
21
use MrPrompt\ShipmentCommon\Base\Purchaser;
22
use MrPrompt\ShipmentCommon\Base\Seller;
23
use MrPrompt\ShipmentCommon\Base\Sequence;
24
use MrPrompt\Celesc\Shipment\Partial\Detail;
25
26
/**
27
 * Common base factory
28
 *
29
 * @author Thiago Paes <[email protected]>
30
 */
31
abstract class Factory
32
{
33
    /**
34
     * @param array $campos
35
     * @return Document
36
     */
37
    public static function createDocumentFromArray(array $campos = [])
38
    {
39
        $document = new Document();
40
        $document->setType(strlen($campos['documento']) === 11 ? Document::CPF : Document::CNPJ);
41
        $document->setNumber($campos['documento']);
42
43
        return $document;
44
    }
45
46
    /**
47
     * @param array $campos
48
     * @return Customer
49
     */
50
    public static function createCustomerFromArray(array $campos = [])
51
    {
52
        $customer = new Customer();
53
        $customer->setCode((int) $campos['codigo']);
54
        $customer->setIdentityNumber($campos['documento']);
55
        $customer->setName($campos['nome']);
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);
86
            $consumerUnity->setMaturity($vencimento);
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);
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 \SplFixedArray
250
     */
251
    public static function createParcelsFromArray(array $campos = [])
252
    {
253
        $parcels = new Parcels(count($campos['parcelas']));
254
        $key     = 1;
255
256
        foreach ($campos['parcelas'] as $parcela) {
257
            $parcelOne   = new Parcel();
258
            $parcelOne->setMaturity(DateTime::createFromFormat('dmY', $parcela['vencimento']));
259
            $parcelOne->setKey($key);
260
            $parcelOne->setPrice($parcela['valor']);
261
            $parcelOne->setQuantity($parcela['quantidade']);
262
263
            $parcels->addParcel($parcelOne);
264
265
            $key++;
266
        }
267
268
        return $parcels;
269
    }
270
271
    /**
272
     * @param array $campos
273
     * @return Seller
274
     */
275
    public static function createSellerFromArray(array $campos = [])
276
    {
277
        $seller = new Seller();
278
279
        if (array_key_exists('vendedor', $campos)) {
280
            $seller = new Seller();
281
            $seller->setCode((int) $campos['vendedor']['codigo']);
282
            $seller->setName($campos['vendedor']['nome']);
283
            $seller->setDocument(static::createDocumentFromArray($campos['vendedor']));
284
            $seller->setAddress(static::createAddressFromArray($campos['vendedor']['endereco']));
285
        }
286
287
        return $seller;
288
    }
289
290
    /**
291
     * @param array $campos
292
     * @return Authorization
293
     */
294
    public static function createAuthorizationFromArray(array $campos = [])
295
    {
296
        $authorization = new Authorization();
297
298
        if (array_key_exists('autorizacao', $campos)) {
299
            $authorization->setNumber($campos['autorizacao']);
300
        }
301
302
        return $authorization;
303
    }
304
305
    /**
306
     * @param array $campos
307
     * @return Billet
308
     */
309
    public static function createBilletFromArray(array $campos = [])
310
    {
311
        $billet = new Billet();
312
313
        if (array_key_exists('boleto', $campos)) {
314
            $billet->setBankAccount(self::createBankAccountFromArray($campos['boleto']));
315
            $billet->setNumber($campos['boleto']['documento']);
316
        }
317
318
        return $billet;
319
    }
320
321
    /**
322
     * Create a cart item object
323
     *
324
     * @param array $campos
325
     * @return Detail
326
     */
327
    public static function createDetailFromArray(array $campos = [])
328
    {
329
        $purchaser      = self::createPurchaserFromArray($campos);
330
        $parcels        = self::createParcelsFromArray($campos);
331
        $consumerUnity  = self::createConsumerUnityFromArray($campos);
332
        $seller         = self::createSellerFromArray($campos);
333
        $authorization  = self::createAuthorizationFromArray($campos);
334
        $sequence       = new Sequence();
335
336
        /* @var $detail \MrPrompt\Celesc\Shipment\Partial\Detail */
337
        $detail = new Detail(
338
            $seller,
339
            $purchaser,
340
            $parcels,
341
            $authorization,
342
            $consumerUnity,
343
            $sequence
344
        );
345
346
        return $detail;
347
    }
348
349
    /**
350
     * @param Detail $item
351
     * @return array
352
     */
353
    public static function createArrayFromDetail(Detail $item)
354
    {
355
        $result = [
356
            'cliente'           => $item->getCustomer()->getCode(),
0 ignored issues
show
The method getCustomer() does not exist on MrPrompt\Celesc\Shipment\Partial\Detail. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

356
            'cliente'           => $item->/** @scrutinizer ignore-call */ getCustomer()->getCode(),

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
357
            'vendedor'          => $item->getSeller()->getCode(),
358
            'cobranca'          => $item->getCharge()->getCharging(),
0 ignored issues
show
The method getCharge() does not exist on MrPrompt\Celesc\Shipment\Partial\Detail. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

358
            'cobranca'          => $item->/** @scrutinizer ignore-call */ getCharge()->getCharging(),

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
359
            'ocorrencia'        => $item->getCharge()->getOccurrence()->getReturn(),
360
            'descricao'         => $item->getCharge()->getOccurrence()->getDescription(),
361
            'identificador'     => $item->getCharge(),
362
            'autorizacao'       => $item->getAuthorization()->getNumber(),
363
            'comprador'         => [
364
                'pessoa'        => $item->getPurchaser()->getPerson(),
365
                'nome'          => $item->getPurchaser()->getName(),
366
                'documento'     => $item->getPurchaser()->getDocument(),
367
                'nascimento'    => $item->getPurchaser()->getBirth()->format('dmY'),
368
                'email'         => $item->getPurchaser()->getEmail()->getAddress(),
369
                'telefone1'     => $item->getPurchaser()->getHomePhone()->getNumber(),
370
                'telefone2'     => $item->getPurchaser()->getHomePhone()->getNumber(),
371
                'celular'       => $item->getPurchaser()->getCellPhone()->getNumber(),
372
                'endereco'      => [
373
                    'cidade'        => $item->getPurchaser()->getAddress()->getCity(),
374
                    'uf'            => $item->getPurchaser()->getAddress()->getState(),
375
                    'cep'           => $item->getPurchaser()->getAddress()->getPostalCode(),
376
                    'logradouro'    => $item->getPurchaser()->getAddress()->getAddress(),
377
                    'numero'        => $item->getPurchaser()->getAddress()->getNumber(),
378
                    'bairro'        => $item->getPurchaser()->getAddress()->getDistrict(),
379
                    'complemento'   => $item->getPurchaser()->getAddress()->getComplement(),
380
                ],
381
            ],
382
            'parcelas'          => [],
383
        ];
384
385
        foreach ($item->getParcels() as $parcel) {
386
            $result['parcelas'][] = [
387
                'vencimento' => ($parcel->getMaturity() !== null ? $parcel->getMaturity()->format('dmY') : null),
388
                'valor'      => $parcel->getPrice(),
389
                'quantidade' => $parcel->getQuantity(),
390
            ];
391
        }
392
393
        switch ($result['cobranca']) {
394
            case Charge::CREDIT_CARD:
395
                $result['cartao'] = [
396
                    'bandeira' => $item->getCreditCard()->getFlag(),
0 ignored issues
show
The method getCreditCard() does not exist on MrPrompt\Celesc\Shipment\Partial\Detail. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

396
                    'bandeira' => $item->/** @scrutinizer ignore-call */ getCreditCard()->getFlag(),

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
397
                    'numero'   => $item->getCreditCard()->getNumber(),
398
                    'validade' => ($item->getCreditCard()->getValidate() !== null ? $item->getCreditCard()->getValidate()->format('mY') : null),
399
                    'seguranca'=> $item->getCreditCard()->getSecurityNumber(),
400
                ];
401
                break;
402
403
            case Charge::DEBIT:
404
                $result['banco'] = [
405
                    'codigo'    => $item->getBankAccount()->getBank()->getCode(),
0 ignored issues
show
The method getBankAccount() does not exist on MrPrompt\Celesc\Shipment\Partial\Detail. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

405
                    'codigo'    => $item->/** @scrutinizer ignore-call */ getBankAccount()->getBank()->getCode(),

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
406
                    'agencia'   => $item->getBankAccount()->getBank()->getAgency(),
407
                    'digito'    => $item->getBankAccount()->getBank()->getDigit(),
408
                    'conta'     => [
409
                        'numero'    => $item->getBankAccount()->getNumber(),
410
                        'digito'    => $item->getBankAccount()->getDigit(),
411
                        'operacao'  => $item->getBankAccount()->getOperation(),
412
                        'seguro'    => $item->getBankAccount()->getSecurity(),
413
                        'titular'   => $result['comprador'],
414
                    ]
415
                ];
416
                break;
417
418
            case Charge::ENERGY:
419
                $result['energia'] = [
420
                    'numero'        => $item->getConsumerUnity()->getNumber(),
421
                    'leitura'       => ($item->getConsumerUnity()->getRead() !== null ? $item->getConsumerUnity()->getRead()->format('dmy') : null),
422
                    'vencimento'    => ($item->getConsumerUnity()->getMaturity() !== null ? $item->getConsumerUnity()->getMaturity()->format('dmy') : null),
423
                    'concessionaria'=> $item->getConsumerUnity()->getCode(),
424
                ];
425
                break;
426
        }
427
428
        return $result;
429
    }
430
}