ModelService::getTemplateVarsWithValues()   B
last analyzed

Complexity

Conditions 6
Paths 32

Size

Total Lines 72
Code Lines 64

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 64
c 1
b 0
f 0
dl 0
loc 72
rs 8.1632
cc 6
nc 32
nop 1

How to fix   Long Method   

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
2
3
namespace ControleOnline\Service;
4
5
use Doctrine\ORM\EntityManagerInterface;
0 ignored issues
show
Bug introduced by
The type Doctrine\ORM\EntityManagerInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use ControleOnline\Entity\City;
7
use ControleOnline\Entity\People;
0 ignored issues
show
Bug introduced by
The type ControleOnline\Entity\People was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use ControleOnline\Entity\Address;
9
use ControleOnline\Entity\Contract as MyContract;
0 ignored issues
show
Bug introduced by
The type ControleOnline\Entity\Contract was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
10
use App\Library\Utils\Formatter;
0 ignored issues
show
Bug introduced by
The type App\Library\Utils\Formatter was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use ControleOnline\Entity\MyContractProduct;
0 ignored issues
show
Bug introduced by
The type ControleOnline\Entity\MyContractProduct was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
13
14
class ModelService
15
{
16
17
18
    protected $request;
19
    public function __construct(
20
        private EntityManagerInterface $manager,
21
22
    ) {}
23
24
25
    protected $daysWeek = [
26
        'monday'    => 'segunda-feira',
27
        'tuesday'   => 'terça-feira',
28
        'wednesday' => 'quarta-feira',
29
        'thursday'  => 'quinta-feira',
30
        'friday'    => 'sexta-feira',
31
        'saturday'  => 'sábado',
32
        'sunday'    => 'domingo'
33
    ];
34
35
    protected $vars = [
36
        'contract_id' => [
37
            'id',
38
            'contract_id'
39
        ],
40
        'order_id' => [
41
            'order_id',
42
            'quote_id'
43
        ],
44
        'order_price' => [
45
            'order_price'
46
        ],
47
        'order_price_text' => [
48
            'order_price_text'
49
        ],
50
        'product_cubage' => [
51
            'product_cubage'
52
        ],
53
        'product_type' => [
54
            'product_type',
55
            'car_name'
56
        ],
57
        'product_total_price' => [
58
            'product_total_price',
59
            'car_price'
60
        ],
61
        'student_name' => [
62
            'dados_aluno',
63
            'student_name',
64
            'contratante'
65
        ],
66
        'student_address' => [
67
            'endereco_aluno',
68
            'student_address',
69
            'contratante_endereco_completo'
70
        ],
71
        'student_small_address' => [
72
            'student_small_address',
73
            'contratante_endereco'
74
        ],
75
        'student_cep' => [
76
            'student_cep',
77
            'contratante_cep'
78
        ],
79
        'student_rg' => [
80
            'rg_aluno',
81
            'student_rg',
82
            'contratante_rg'
83
        ],
84
        'payer_document_type' => [
85
            'doc_aluno',
86
            'payer_document_type',
87
            'contratante_doc_type'
88
        ],
89
        'payer_document' => [
90
            'cpf_aluno',
91
            'payer_document',
92
            'contratante_cpf'
93
        ],
94
        'company_cnpj' => [
95
            'company_cnpj'
96
        ],
97
        'company_address' => [
98
            'company_address'
99
        ],
100
        'company_owners' => [
101
            'company_owners'
102
        ],
103
        'contract_place' => [
104
            'company_place',
105
            'contract_place'
106
        ],
107
        'contract_hours' => [
108
            'total_horas_contratadas',
109
            'contract_hours'
110
        ],
111
        'contract_schedule' => [
112
            'horarios_agendados',
113
            'contract_schedule'
114
        ],
115
        'contract_startdate' => [
116
            'data_inicio_contrato',
117
            'contract_startdate'
118
        ],
119
        'contract_amount' => [
120
            'valor_total_servicos',
121
            'contract_amount'
122
        ],
123
        'contract_enddate' => [
124
            'dia_vencimento',
125
            'contract_enddate'
126
        ],
127
        'contract_modality' => [
128
            'contract_modality'
129
        ],
130
        'contract_detail_services' => [
131
            'detalhe_total_servicos',
132
            'contract_detail_services'
133
        ],
134
        'origin_address' => [
135
            'origin_address'
136
        ],
137
        'origin_city' => [
138
            'origin_city'
139
        ],
140
        'origin_state' => [
141
            'origin_state'
142
        ],
143
        'destination_city' => [
144
            'destination_city'
145
        ],
146
        'destination_state' => [
147
            'destination_state'
148
        ],
149
        'origin_small_address' => [
150
            'origin_small_address'
151
        ],
152
        'origin_cep' => [
153
            'origin_cep'
154
        ],
155
        'destination_address' => [
156
            'destination_address'
157
        ],
158
        'destination_small_address' => [
159
            'destination_small_address'
160
        ],
161
        'destination_cep' => [
162
            'destination_cep'
163
        ],
164
        'company_address' => [
165
            'company_address'
166
        ],
167
        'company_cep' => [
168
            'company_cep'
169
        ],
170
        'company_small_address' => [
171
            'company_small_address'
172
        ],
173
        'today' => [
174
            'data_hoje',
175
            'today'
176
        ],
177
        'company_name' => [
178
            'company_name'
179
        ],
180
        'company_alias' => [
181
            'company_alias'
182
        ],
183
        'car_color' => [
184
            'car_color'
185
        ],
186
        'car_number' => [
187
            'car_number'
188
        ],
189
        'renavan' => [
190
            'renavan'
191
        ],
192
        'route_time' => [
193
            'route_time'
194
        ],
195
        'retrieve_address_type' => [
196
            'retrieve_address_type'
197
        ],
198
        'delivery_address_type' => [
199
            'delivery_address_type'
200
        ],
201
        'retrieve_address' => [
202
            'retrieve_address'
203
        ],
204
        'delivery_address' => [
205
            'delivery_address'
206
        ],
207
        'payment_type' => [
208
            'payment_type'
209
        ],
210
        'date' => [
211
            'date'
212
        ],
213
    ];
214
215
216
217
218
219
220
    /**
221
     * dados_aluno
222
     * endereco_aluno
223
     * rg_aluno
224
     * cpf_aluno
225
     * total_horas_contratadas
226
     * horarios_agendados
227
     * data_inicio_contrato
228
     * valor_total_servicos
229
     * dia_vencimento
230
     * data_hoje
231
     * company_place
232
     * company_cnpj
233
     * company_address
234
     * company_owners
235
     * contract_modality
236
     * detalhe_total_servicos
237
     */
238
    public function genetateFromModel(MyContract $contract): string
239
    {
240
        $values = $this->getTemplateVarsWithValues($contract);
241
        $content = preg_replace(
242
            $this->getRegex($values),
243
            array_values($values),
244
            $contract->getContractModel()->getFile()->getContent()
245
        );
246
247
        return $content;
248
    }
249
250
    protected function getRegex(array $values): array
251
    {
252
253
        $reges = array();
254
255
        foreach (array_keys($values) as $key) {
256
            $variables = $this->vars[$key];
257
258
            $reges[] = "#\{\{\\s*\\n*\\t*(" . implode("|", $variables) . ")\\t*\\n*\\s*\}\}#";
259
        }
260
261
        return $reges;
262
    }
263
264
    protected function getTemplateVarsWithValues(MyContract $myContract): array
265
    {
266
        $student   = $this->getStudentsData($myContract);
267
        $contract  = $this->getContractData($myContract);
268
        $company   = $this->getCompanyData($myContract);
269
        $orderData = $this->getOrderData($myContract);
270
271
        $orderPriceText = new \NumberFormatter("pt-BR", \NumberFormatter::SPELLOUT);
272
273
274
        date_default_timezone_set('America/Sao_Paulo');
275
276
        $data = new \DateTime('now');
277
        $formatter = new \IntlDateFormatter(
278
            'pt_BR',
279
            \IntlDateFormatter::LONG,
280
            \IntlDateFormatter::NONE,
281
            'America/Sao_Paulo',
282
            \IntlDateFormatter::GREGORIAN
283
        );
284
285
        return [
286
            'contract_id'               => $myContract->getId(),
287
            'student_name'              => $student['student_name'],
288
            'student_address'           => $student['student_address'],
289
            'student_small_address'     => $student['student_small_address'],
290
            'student_cep'               => $student['student_cep'],
291
            'student_rg'                => $student['student_rg'],
292
            'payer_document'            => Formatter::document($student['payer_document']),
293
            'payer_document_type'       => $student['payer_document_type'],
294
            'today'                     => (new \DateTime('now'))->format('d/m/Y'),
295
            'date'                      => $formatter->format($data),
296
            'company_cnpj'              => Formatter::document($company['company_cnpj']),
297
            'company_address'           => $company['company_address'],
298
            'company_cep'               => $company['company_cep'],
299
            'company_small_address'     => $company['company_small_address'],
300
            'company_owners'            => $company['company_owners'],
301
            'company_name'              => $company['company_name'],
302
            'company_alias'             => $company['company_alias'],
303
            'contract_place'            => $contract['contract_place'],
304
            'contract_hours'            => $contract['contract_hours'],
305
            'contract_schedule'         => $contract['contract_schedule'],
306
            'contract_startdate'        => $contract['contract_startdate'],
307
            'contract_amount'           => Formatter::money(floatval($contract['contract_amount'])),
308
            'contract_enddate'          => $contract['contract_enddate'],
309
            'contract_modality'         => $contract['contract_modality'],
310
            'contract_detail_services'  => $contract['contract_detail_services'],
311
            'order_id'                  => $orderData['order_id'],
312
            'order_price'               => $orderData['order_price'],
313
            'order_price_text'          => $orderPriceText->format(floatval($orderData['order_price'])),
314
            'product_cubage'            => $orderData['product_cubage'],
315
            'product_type'              => $orderData['product_type'],
316
            'product_total_price'       => $orderData['product_total_price'],
317
            'origin_address'            => $orderData['origin_address'],
318
            'origin_city'               => $orderData['origin_city'],
319
            'origin_state'              => $orderData['origin_state'],
320
            'origin_cep'                => $orderData['origin_cep'],
321
            'origin_small_address'      => $orderData['origin_small_address'],
322
            'destination_address'       => $orderData['destination_address'],
323
            'destination_city'          => $orderData['destination_city'],
324
            'destination_state'         => $orderData['destination_state'],
325
            'destination_cep'           => $orderData['destination_cep'],
326
            'destination_small_address' => $orderData['destination_small_address'],
327
            'retrieve_address_type'     => isset($orderData['other_informations']->retrieve_address_type) ? $orderData['other_informations']->retrieve_address_type : 'Base',
328
            'delivery_address_type'     => isset($orderData['other_informations']->delivery_address_type) ? $orderData['other_informations']->delivery_address_type : 'Base',
329
            'renavan'                   => isset($orderData['other_informations']->renavan) ? $orderData['other_informations']->renavan : 'Renavan não informado',
330
            'car_color'                 => isset($orderData['other_informations']->carColor) ? $orderData['other_informations']->carColor : null,
331
            'car_number'                => isset($orderData['other_informations']->carNumber) ? $orderData['other_informations']->carNumber : null,
332
            'route_time'                => $this->getRouteTime($orderData),
333
            'payment_type'              => $this->getPaymentType($orderData),
334
            'delivery_address'          => $this->getDeliveryAddress($orderData),
335
            'retrieve_address'          => $this->getRetrieveAddress($orderData),
336
337
        ];
338
    }
339
    protected function getRouteTime($orderData)
340
    {
341
        $route_time = (isset($orderData['other_informations']->route_time) && $orderData['other_informations']->route_time > 0 ? $orderData['other_informations']->route_time : 10);
342
343
        if (in_array($orderData['origin_state'], ['RR', 'AM', 'RO', 'AC']) || in_array($orderData['destination_state'], ['RR', 'AM', 'RO', 'AC'])) {
344
            $route_time += 10;
345
        }
346
347
        return  $route_time . ' a ' . ($route_time + 5) . ' dias';
348
    }
349
350
351
352
    protected function getDeliveryAddress($orderData)
353
    {
354
        if (!isset($orderData['other_informations']->delivery_address_type)) {
355
            return $orderData['destination_city'] . ' / ' . $orderData['destination_state'];
356
        } else if ($orderData['other_informations']->delivery_address_type == 'winch') {
357
            return $orderData['destination_address'] . ' - ' . $orderData['destination_city'] . ' / ' . $orderData['destination_state'];
358
        } else {
359
            return $orderData['destination_city'] . ' / ' . $orderData['destination_state'] . ' (Ponto de Encontro) ';
360
        }
361
    }
362
363
    protected function getRetrieveAddress($orderData)
364
    {
365
        if (!isset($orderData['other_informations']->retrieve_address_type)) {
366
            return $orderData['origin_city'] . ' / ' . $orderData['origin_state'];
367
        } else if ($orderData['other_informations']->retrieve_address_type == 'winch') {
368
            return $orderData['origin_address'] . ' - ' . $orderData['origin_city'] . ' / ' . $orderData['origin_state'];
369
        } else {
370
            return $orderData['origin_city'] . ' / ' . $orderData['origin_state'] . ' (Ponto de Encontro) ';
371
        }
372
    }
373
374
    protected function getPaymentType($orderData)
375
    {
376
        if ($orderData['other_informations'] && isset($orderData['other_informations']->paymentType)) {
377
            switch ($orderData['other_informations']->paymentType) {
378
                case '5':
379
                    return '
380
                    24 horas úteis (não considerados sábados, domingos e feriados) antes da retirada
381
                    do veículo, para que sejam realizados os procedimentos administrativos de liberação.
382
                    ';
383
                    break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
384
                case '4':
385
                    return '
386
387
                    50% do valor na assinatura do contrato e os outros 50%, 24 horas úteis
388
                    (não considerados sábados, domingos e feriados) antes da retirada do veículo,
389
                    para que sejam realizados os procedimentos administrativos de liberação.
390
391
                        ';
392
                    break;
393
                case '3':
394
                    return '
395
396
                    na assinatura do contrato, via Cartão de Crédito, COM OS ACRÉSCIMOS DAS TAXAS
397
                    RELATIVAS AO CARTÃO. Para esta modalidade de pagamento, o veículo será liberado
398
                    após 24 horas úteis (não considerados sábados, domingos e feriados) da
399
                    confirmação da chegada, para que sejam realizados os procedimentos
400
                    administrativos de liberação
401
402
                    ';
403
                    break;
404
                case '2':
405
                    return '
406
407
                    60% do valor na assinatura do contrato e os outros 40%, 24 horas úteis
408
                    (não considerados sábados, domingos e feriados) antes da retirada do veículo,
409
                    para que sejam realizados os procedimentos administrativos de liberação.
410
411
412
                    ';
413
                    break;
414
                case '1':
415
                    return '
416
417
                    à vista. Para esta modalidade de pagamento, o veículo será liberado
418
                    após 24 horas úteis (não considerados sábados, domingos e feriados)
419
                    da confirmação da chegada, para que sejam realizados os procedimentos
420
                    administrativos de liberação.
421
422
                    ';
423
                    break;
424
                default:
425
                    return '
426
                    na
427
                    assinatura do contrato, via Transferência Bancaria/Boleto ou
428
                    Cartão de Crédito
429
                    ';
430
                    break;
431
            }
432
        } else {
433
            return ' na
434
            assinatura do contrato, via Transferência Bancaria/Boleto ou
435
            Cartão de Crédito
436
           ';
437
        }
438
    }
439
440
    protected function getOrderData(MyContract $myContract): array
0 ignored issues
show
Unused Code introduced by
The parameter $myContract is not used and could be removed. ( Ignorable by Annotation )

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

440
    protected function getOrderData(/** @scrutinizer ignore-unused */ MyContract $myContract): array

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
441
    {
442
443
        return [];
444
        $data = [
0 ignored issues
show
Unused Code introduced by
$data = array('order_id'... '[destination_state]') is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
445
            'order_id'                  => '[order_id]',
446
            'order_price'               => '[order_price]',
447
            'product_cubage'            => '[product_cubage]',
448
            'product_type'              => '[product_type]',
449
            'product_total_price'       => '[product_total_price]',
450
            'origin_address'            => '[origin_address]',
451
            'origin_cep'                => '[origin_cep]',
452
            'origin_small_address'      => '[origin_small_address]',
453
            'destination_address'       => '[destination_address]',
454
            'destination_cep'           => '[destination_cep]',
455
            'destination_small_address' => '[destination_small_address]',
456
            'other_informations'        => '[other_informations]',
457
            'origin_city'               => '[origin_city]',
458
            'origin_state'              => '[origin_state]',
459
            'destination_city'          => '[destination_city]',
460
            'destination_state'         => '[destination_state]',
461
        ];
462
463
        $orderRepo = $this->manager->getRepository(SalesOrder::class);
0 ignored issues
show
Bug introduced by
The type ControleOnline\Service\SalesOrder was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
464
465
        /**
466
         * @var SalesOrder $order
467
         */
468
        $order = $orderRepo->findOneBy([
469
            'contract' => $myContract->getId(),
470
            'orderType'  => 'sale'
471
        ]);
472
473
474
475
        if (!empty($order)) {
476
            $data['order_id']            = $order->getId();
477
            $data['order_price']         = number_format($order->getPrice(), 2, ',', '.');
478
            $data['product_cubage']      = $order->getCubage();
479
            $data['product_type']        = $order->getProductType();
480
            $data['product_total_price'] = number_format($order->getInvoiceTotal(), 2, ',', '.');
481
            $data['other_informations'] = $order->getOtherInformations(true);
482
            $origin = $order->getAddressOrigin();
483
            if (empty($origin)) {
484
                $origin = $order->getQuote()->getCityOrigin();
485
            }
486
487
            $adresO =             $this->getAddress($origin);
488
            if ($adresO) {
489
                $resOrigin = $this->getAddressVars('origin', $adresO);
490
                $data["origin_address"]       = $resOrigin["origin_address"];
491
                $data["origin_cep"]           = $resOrigin["origin_cep"];
492
                $data["origin_small_address"] = $resOrigin["origin_small_address"];
493
                $data["origin_city"] = $resOrigin["origin_city"];
494
                $data["origin_state"] = $resOrigin["origin_state"];
495
            } else {
496
                $data["origin_city"] = $order->getQuotes()->first()->getCityOrigin()->getCity();
497
                $data["origin_state"] = $order->getQuotes()->first()->getCityOrigin()->getState()->getUf();
498
            }
499
            $destination = $order->getAddressDestination();
500
            if (empty($destination)) {
501
                $destination = $order->getQuote()->getCityDestination();
502
            }
503
504
            $adresD =             $this->getAddress($destination);
505
            if ($adresD) {
506
                $resDestination = $this->getAddressVars('destination', $adresD);
507
                $data["destination_address"]       = $resDestination["destination_address"];
508
                $data["destination_cep"]           = $resDestination["destination_cep"];
509
                $data["destination_small_address"] = $resDestination["destination_small_address"];
510
                $data["destination_city"] = $resDestination["destination_city"];
511
                $data["destination_state"] = $resDestination["destination_state"];
512
            } else {
513
                $data["destination_city"] = $order->getQuotes()->first()->getCityDestination()->getCity();
514
                $data["destination_state"] = $order->getQuotes()->first()->getCityDestination()->getState()->getUf();
515
            }
516
        }
517
518
        return $data;
519
    }
520
521
    protected function getAddressVars(string $prefix, array $address): array
522
    {
523
        $data = [
524
            $prefix . '_address'       => '[_address]',
525
            $prefix . '_cep'           => '[_cep]',
526
            $prefix . '_small_address' => '[_small_address]',
527
        ];
528
529
        if ($address !== null) {
0 ignored issues
show
introduced by
The condition $address !== null is always true.
Loading history...
530
            $resAddress = [];
531
532
            $resAddress[] = sprintf('%s %s', $address['street'], $address['number']);
533
            $resAddress[] = $address['complement'];
534
            $resAddress[] = $address['district'];
535
            $resAddress[] = sprintf('%s - %s', $address['city'], $address['state']);
536
537
            $data[$prefix . '_small_address'] = array_filter($resAddress, 'strlen');
538
            $data[$prefix . '_small_address'] = implode(', ', $data[$prefix . '_small_address']);
0 ignored issues
show
Bug introduced by
$data[$prefix . '_small_address'] of type string is incompatible with the type array expected by parameter $pieces of implode(). ( Ignorable by Annotation )

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

538
            $data[$prefix . '_small_address'] = implode(', ', /** @scrutinizer ignore-type */ $data[$prefix . '_small_address']);
Loading history...
539
540
            $resAddress[] = sprintf('CEP %s', Formatter::mask('#####-###', $address['postalCode']));
541
542
            $data[$prefix . '_address'] = array_filter($resAddress, 'strlen');
543
            $data[$prefix . '_address'] = implode(', ', $data[$prefix . '_address']);
544
            $data[$prefix . '_cep']     = Formatter::mask('#####-###', $address['postalCode']);
545
            $data[$prefix . '_city'] = $address['city'];
546
            $data[$prefix . '_state'] = $address['state'];
547
        }
548
549
        return $data;
550
    }
551
552
    protected function getStudentsData(MyContract $myContract): array
553
    {
554
        $data = [
555
            'student_name'          => '[student_name]',
556
            'student_rg'            => '[student_rg]',
557
            'payer_document'        => '[payer_document]',
558
            'payer_document_type'   => '[payer_document_type]',
559
            'student_address'       => '[student_address]',
560
            'student_cep'           => '[student_cep]',
561
            'student_small_address' => '[student_small_address]',
562
        ];
563
564
        $peopleContract = $myContract->getPeoples()
565
            ->filter(function ($contractPeople) {
566
                return $contractPeople->getPeopleType() == 'Payer';
567
            });
568
        if (!$peopleContract->isEmpty()) {
569
            $contact = $this->getContactByPeople($peopleContract->first()->getPeople());
570
571
            // name
572
573
            $data['student_name'] = sprintf('%s %s', $contact['name'], $contact['alias']);
574
575
            // documents
576
577
            if (!empty($contact['documents'])) {
578
579
                if (isset($contact['documents']['CNPJ']) && !empty($contact['documents']['CNPJ'])) {
580
                    $data['payer_document'] = $contact['documents']['CNPJ'];
581
                    $data['payer_document_type'] = 'CNPJ';
582
                }
583
584
                if (isset($contact['documents']['CPF']) && !empty($contact['documents']['CPF'])) {
585
                    $data['payer_document'] = $contact['documents']['CPF'];
586
                    $data['payer_document_type'] = 'CPF';
587
                }
588
589
                if (isset($contact['documents']['R.G'])) {
590
                    $data['student_rg']  = $contact['documents']['R.G'];
591
                }
592
            }
593
594
            // address
595
596
            if ($contact['address'] !== null) {
597
                $result = $this->getAddressVars('student', $contact['address']);
598
599
                $data["student_address"]       = $result["student_address"];
600
                $data["student_cep"]           = $result["student_cep"];
601
                $data["student_small_address"] = $result["student_small_address"];
602
            }
603
        }
604
605
        return $data;
606
    }
607
608
    protected function getContractData(MyContract $myContract): array
0 ignored issues
show
Unused Code introduced by
The parameter $myContract is not used and could be removed. ( Ignorable by Annotation )

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

608
    protected function getContractData(/** @scrutinizer ignore-unused */ MyContract $myContract): array

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
609
    {
610
611
        return[];
612
        $data = [
0 ignored issues
show
Unused Code introduced by
$data = array('contract_...ract_detail_services]') is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
613
            'contract_hours'           => '[contract_hours]',
614
            'contract_schedule'        => '[contract_schedule]',
615
            'contract_startdate'       => $myContract->getStartDate()->format('d/m/Y'),
616
            'contract_enddate'         => $myContract->getEndDate() !== null ? $myContract->getEndDate()->format('d/m/Y') : '-',
617
            'contract_amount'          => $this->getContractTotalPrice($myContract),
618
            'contract_place'           => '[contract_place]',
619
            'contract_modality'        => '[contract_modality]',
620
            'contract_detail_services' => '[contract_detail_services]',
621
        ];
622
623
        // place
624
625
        $company = $myContract->getBeneficiary();
626
        if ($company !== null) {
627
            $address = $this->getPeopleAddress($company);
628
            if (is_array($address) && isset($address['city'])) {
629
                $data['contract_place'] = $address['city'];
630
            }
631
        }
632
633
        // detail services
634
635
        $items  = [];
636
        $payers = $this->getContractPeoplePayers($myContract);
637
638
        $contractProducts = $this->manager->getRepository(MyContractProduct::class)
639
            ->getContractProducts($myContract->getId());
640
641
        //// total per month
642
        $products = array_filter(
643
            $contractProducts,
644
            function ($contractProduct) {
645
                return $contractProduct['product_subtype'] == 'Package'
646
                    && $contractProduct['billing_unit'] == 'Monthly';
647
            }
648
        );
649
        $total = 0;
650
        foreach ($products as $product) {
651
            $total += (float) $product['product_price'] * (int) $product['quantity'];
652
        }
653
        $items[] = sprintf(
654
            'Mensalidade de %s aplicada para os meses que seguem o contrato '
655
                . 'tendo seu vencimento para todo dia %s.',
656
            Formatter::money($total),
657
            !empty($payers) ? $payers[0]['paymentDay'] : '00'
658
        );
659
        //// contract tax
660
        $products = array_filter(
661
            $contractProducts,
662
            function ($contractProduct) {
663
                return $contractProduct['product_type'] == 'Registration'
664
                    && $contractProduct['billing_unit'] == 'Single';
665
            }
666
        );
667
        $product = current($products);
668
        $total   = /*(float) $product['product_price'] * (int) $product['quantity']*/ 10;
669
        $parcels = /*(int) $product['parcels']*/ 0;
670
        if ($parcels > 1) {
671
            $items[] = sprintf(
672
                'Taxa administrativa: %s será '
673
                    . 'parcelada em %sx nas primeiras cobranças.',
674
                Formatter::money($total),
675
                $parcels
676
            );
677
        } else {
678
            $items[] = sprintf(
679
                'Taxa administrativa: %s será paga à vista '
680
                    . '(ou parcelada em 2x nas primeiras cobranças)',
681
                Formatter::money($total)
682
            );
683
        }
684
685
        if (!empty($items)) {
686
            $data['contract_detail_services'] = '';
687
            foreach ($items as $description) {
688
                $data['contract_detail_services'] .= '<li>' . $description . '</li>';
689
            }
690
        }
691
692
        return $data;
693
    }
694
695
    protected function getCompanyData(MyContract $myContract): array
696
    {
697
        $data = [
698
            'company_name'          => '[company_name]',
699
            'company_alias'         => '[company_alias]',
700
            'company_cnpj'          => '[company_cnpj]',
701
            'company_address'       => '[company_address]',
702
            'company_cep'           => '[company_cep]',
703
            'company_small_address' => '[company_small_address]',
704
            'company_owners'        => '[company_owners]',
705
        ];
706
707
        $company = $myContract->getBeneficiary();
708
        $contact = $this->getContactByPeople($company);
709
710
711
        $data['company_name']  = $company->getName();
712
        $data['company_alias'] = $company->getAlias();
713
714
        // get CNPJ
715
716
        if (!empty($contact['documents'])) {
717
            if (isset($contact['documents']['CNPJ'])) {
718
                $data['company_cnpj'] = $contact['documents']['CNPJ'];
719
            }
720
        }
721
722
        // get address
723
724
        if (isset($contact['address'])) {
725
            $result = $this->getAddressVars('company', $contact['address']);
0 ignored issues
show
Bug introduced by
It seems like $contact['address'] can also be of type null; however, parameter $address of ControleOnline\Service\M...rvice::getAddressVars() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

725
            $result = $this->getAddressVars('company', /** @scrutinizer ignore-type */ $contact['address']);
Loading history...
726
727
            $data["company_address"]       = $result["company_address"];
728
            $data["company_cep"]           = $result["company_cep"];
729
            $data["company_small_address"] = $result["company_small_address"];
730
        }
731
732
733
        /*
734
        // get owners
735
736
        $owners = $company->getCompany()->filter(function ($peopleLink) {
737
            return $peopleLink->getPeopleRole() == 'owner';
738
        });;
739
740
        if (!$owners->isEmpty()) {
741
            $ownersContact = [];
742
743
            foreach ($owners as $owner) {
744
                $ownerContact = $this->getContactByPeople($owner->getPeople());
745
746
                // name
747
748
                $ownerData = sprintf('%s %s', trim($ownerContact['name']), trim($ownerContact['alias']));
749
750
                // particulars
751
752
                $particulars = $this->manager->getRepository(Particulars::class)
753
                    ->getParticularsByPeopleAndContext($owner->getPeople(), 'contract_document');
754
                if (!empty($particulars)) {
755
                    $particularsValues = [];
756
757
                    foreach ($particulars as $particular) {
758
                        if ($particular['type_value'] == 'Naturalidade') {
759
                            $particularsValues[] = 'natural de ' . $particular['value'];
760
                        } else {
761
                            $particularsValues[] = $particular['value'];
762
                        }
763
                    }
764
765
                    if (!empty($particularsValues)) {
766
                        $ownerData .= ', ' . implode(', ', $particularsValues);
767
                    }
768
                }
769
770
                // documents
771
772
                if (!empty($ownerContact['documents'])) {
773
                    if (isset($ownerContact['documents']['R.G'])) {
774
                        $ownerData .= sprintf(
775
                            ', portador da cédula de identidade nº %s',
776
                            $ownerContact['documents']['R.G']
777
                        );
778
                    }
779
780
                    if (isset($ownerContact['documents']['CPF']) && !empty($ownerContact['documents']['CPF'])) {
781
                        $ownerData .= sprintf(
782
                            ', inscrito no CPF/MF %s',
783
                            Formatter::document($ownerContact['documents']['CPF'])
784
                        );
785
                    }
786
                }
787
788
                $ownersContact[] = $ownerData;
789
            }
790
791
            $lastOwner              = array_pop($ownersContact);
792
            $data['company_owners'] = implode(', ', $ownersContact) . ' e ' . $lastOwner;
793
        }
794
        */
795
796
        return $data;
797
    }
798
799
800
801
    protected function getContractTotalPrice(MyContract $myContract): float
802
    {
803
        $total = 0;
804
805
        // monthly products
806
807
        $contractProduct = $myContract->getContractProduct()
808
            ->filter(function ($contractProduct) {
809
                return $contractProduct->getProduct()->getProductSubtype() == 'Package'
810
                    && $contractProduct->getProduct()->getBillingUnit() == 'Monthly'
811
                    && $contractProduct->getPrice() > 0;
812
            });
813
814
        foreach ($contractProduct as $cproduct) {
815
            $total += $cproduct->getPrice() * $cproduct->getQuantity();
816
        }
817
818
        // contract tax
819
820
        $contractProduct = $myContract->getContractProduct()
821
            ->filter(function ($contractProduct) {
822
                return $contractProduct->getProduct()->getProductType() == 'Registration'
823
                    && $contractProduct->getProduct()->getBillingUnit() == 'Single'
824
                    && $contractProduct->getPrice() > 0;
825
            });
826
827
        foreach ($contractProduct as $cproduct) {
828
            $total += $cproduct->getPrice() * $cproduct->getQuantity();
829
        }
830
831
        return (float) $total;
832
    }
833
834
    protected function getContactByPeople(People $people): array
835
    {
836
        $documents = [];
837
        foreach ($people->getDocument() as $document) {
838
            $documents[$document->getDocumentType()->getDocumentType()] = $document->getDocument();
839
        }
840
841
        return [
842
            'id'        => $people->getId(),
843
            'name'      => $people->getName(),
844
            'alias'     => $people->getAlias(),
845
            'documents' => $documents,
846
            'address'   => $this->getPeopleAddress($people),
847
        ];
848
    }
849
850
    protected function getPeopleAddress(People $people): ?array
851
    {
852
        if (($address = $people->getAddress()->first()) === false)
853
            return null;
854
855
        return $this->getAddress($address);
856
    }
857
858
    /**
859
     * @param Address|City $address
860
     */
861
    protected function getAddress($address): ?array
862
    {
863
864
        $isAddress = true;
865
866
        $street   = null;
867
        $district = null;
868
        $city     = null;
869
        $state    = null;
870
871
        if (!empty($address)) {
872
            if ($address instanceof City) {
873
                $isAddress = false;
874
                $city      = $address;
875
                $state     = $address->getState();
876
            } else {
877
                $street   = $address->getStreet();
878
                $district = $street->getDistrict();
879
                $city     = $district->getCity();
880
                $state    = $city->getState();
881
            }
882
        } else {
883
            $isAddress = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $isAddress is dead and can be removed.
Loading history...
884
            return null;
885
        }
886
887
888
        return [
889
            'id'         => $isAddress        ? $address->getId() : '',
890
            'country'    => !empty($state)    ? $this->fixCountryName($state->getCountry()->getCountryName()) : '',
891
            'state'      => !empty($state)    ? $state->getUF() : '',
892
            'city'       => !empty($city)     ? $city->getCity() : '',
893
            'district'   => !empty($district) ? $district->getDistrict() : '',
894
            'postalCode' => !empty($street)   ? $this->fixPostalCode($street->getCep()->getCep()) : '',
895
            'street'     => !empty($street)   ? $street->getStreet() : '',
896
            'number'     => $isAddress        ? $address->getNumber() : '',
0 ignored issues
show
Bug introduced by
The method getNumber() does not exist on ControleOnline\Entity\City. ( Ignorable by Annotation )

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

896
            'number'     => $isAddress        ? $address->/** @scrutinizer ignore-call */ getNumber() : '',

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...
897
            'complement' => $isAddress        ? $address->getComplement() : '',
0 ignored issues
show
Bug introduced by
The method getComplement() does not exist on ControleOnline\Entity\City. ( Ignorable by Annotation )

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

897
            'complement' => $isAddress        ? $address->/** @scrutinizer ignore-call */ getComplement() : '',

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...
898
        ];
899
    }
900
901
    protected function fixCountryName(string $originalName): string
902
    {
903
        return strtolower($originalName) == 'brazil' ? 'Brasil' : $originalName;
904
    }
905
906
    protected function fixPostalCode(int $postalCode): string
907
    {
908
        $code = (string)$postalCode;
909
        return strlen($code) == 7 ? '0' . $code : $code;
910
    }
911
912
    protected function getContractPeoplePayers(MyContract $contract): array
913
    {
914
        $contractPeople = $contract->getPeoples()
915
            ->filter(function ($contractPeople) {
916
                return $contractPeople->getPeopleType() == 'Payer' && $contractPeople->getContractPercentage() > 0;
917
            });
918
919
        $payers = [];
920
921
        if (!$contractPeople->isEmpty()) {
922
            foreach ($contractPeople as $cpeople) {
923
                $payers[] = [
924
                    'people'     => $cpeople->getPeople(),
925
                    'percent'    => $cpeople->getContractPercentage(),
926
                    'paymentDay' => $cpeople->getPeople()->getPaymentTerm()
927
                ];
928
            }
929
        }
930
931
        return $payers;
932
    }
933
}
934