-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSantanderRemessa.php
1428 lines (1318 loc) · 44 KB
/
SantanderRemessa.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* SantanderRemessa.php (Classe Santander Remessa Padrão CNAB400)
*
* Gerador de arquivo de remessa para o banco Santander.
* Com essa classe o usuário não fica obrigado a usar um framework para poder
* gerar o arquivo de remessa do banco santander, o objetivo foi criar uma classe
* apenas, para facilitar a geração desses arquivos de remessa, supondo que o
* usuário já possua a classe para gerar o boleto. Essa classe requer os dados
* gerados pelo boleto.
*
* PHP Version >=5.6
*
* @category CNAB400
* @package Remessa
* @author Costa <[email protected]>
* @license https://www.gnu.org/licenses/gpl-3.0.txt GNU GENERAL PUBLIC LICENSE Version 3
* @version 1.0.0
* @link https://github.com/deepcell/RemessaCNAB400
* @see CNAB400, Remessa, Santander
* @since File available since Release 1.0.0
*
* @reference
* Especificação/referência: Documento do banco Santander
* Baseado no `laravel-boleto` (https://github.com/eduardokum/laravel-boleto/)
* @status Homologado pelo banco Santander.
* @file encode UTF-8
* @date 2017-12-18
* @update 2018-02-26
*
* @dependency extensao `php5-intl`
* @observation Essa classe com um pouco de alteração funciona para outros bancos.
*/
class SantanderRemessa
{
/**
* Declaracao das propriedades (property declaration).
* Campos obrigatorios do arquivo de remessa santander.
* use `$this->` para chamar a propriedade
*/
public $tamanho_linha = 400; # se for trabalhar com o layout de 240, entao setar para valor `false`.
public $camposObrigatorios = array(
'carteira',
'agencia',
'conta',
'beneficiario',
);
public $boletos = [];
public $codigoBanco = '033'; # 033 banco santander
public $iRegistros = 0;
public $aRegistros = [
self::HEADER => [],
self::DETALHE => [],
self::TRAILER => [],
];
public $atual;
public $fimLinha = "\r\n"; # padrao inicial \n
public $fimArquivo = "\r\n"; # null;
public $idremessa;
public $numeroControle; # numero controle da remessa
public $agencia = '0123';
public $agenciaDv = 7; # digito verificador da agencia
public $conta_movimento = '01234567'; # Conta movimento Beneficiário 8 posicoes
public $conta = '0123456'; # Conta cobrança Beneficiário 7 posicoes
public $contaDv;
public $carteira = 101;
public $carteiras = [101]; # se for trabalhar com outras carteiras deixe vazio essa propriedade.
public $pagador;
public $beneficiario = array(
'nome' => 'BAVARIAN ILLUMINATI LTDA - ME',
'endereco' => 'RUA PIO XI, 23',
'bairro' => 'LAPA',
'cep' => '05060001',
'uf' => 'SP',
'cidade' => 'SAO PAULO',
'documento' => '012012012000901',
'nome_documento' => '',
'endereco2' => ''
);
public $beneficiarioDocumento = '012012012000901'; # nao usar essa propriedade
public $codigoCliente;
public $total = 0; # valor total dos titulos
//-- pessoa
public $nome; # nome da pessoa/cliente
public $endereco;
public $bairro;
public $cep;
public $uf;
public $cidade;
public $documento;
public $dda = false;
public $campoNossoNumero = 0;
public $status;
public $numeroDocumento;
//-- use self:: para chamar a constante
const COD_BANCO_SANTANDER = '033';
const STATUS_REGISTRO = 1;
const STATUS_ALTERACAO = 2;
const STATUS_BAIXA = 3;
const HEADER = 'header';
const HEADER_LOTE = 'header_lote';
const DETALHE = 'detalhe';
const TRAILER_LOTE = 'trailer_lote';
const TRAILER = 'trailer';
//-- SANTANDER
const ESPECIE_DUPLICATA = '01';
const ESPECIE_NOTA_PROMISSORIA = '02';
const ESPECIE_NOTA_SEGURO = '03';
const ESPECIE_RECIBO = '05';
const ESPECIE_DUPLICATA_SERVICO = '06';
const ESPECIE_LETRA_CAMBIO = '07';
const OCORRENCIA_REMESSA = '01';
const OCORRENCIA_PEDIDO_BAIXA = '02';
const OCORRENCIA_CONCESSAO_ABATIMENTO = '04';
const OCORRENCIA_CANC_ABATIMENTO = '05';
const OCORRENCIA_ALT_VENCIMENTO = '06';
const OCORRENCIA_ALT_CONTROLE_PARTICIPANTE = '07';
const OCORRENCIA_ALT_SEUNUMERO = '08';
const OCORRENCIA_PROTESTAR = '09';
const OCORRENCIA_SUSTAR_PROTESTO = '18';
const INSTRUCAO_SEM = '00';
const INSTRUCAO_BAIXAR_APOS_VENC_15 = '02';
const INSTRUCAO_BAIXAR_APOS_VENC_30 = '03';
const INSTRUCAO_NAO_BAIXAR = '04';
const INSTRUCAO_PROTESTAR = '06';
const INSTRUCAO_NAO_PROTESTAR = '07';
const INSTRUCAO_NAO_COBRAR_MORA = '08';
/***********************************************************************************************
* @Util methods
* Reference: https://github.com/eduardokum/laravel-boleto/blob/master/src/Util.php
***********************************************************************************************/
/**
* @return string
*/
public static function dateCheck($date)
{
$tmpDate = explode('-', $date);
// checkdate(month, day, year)
return checkdate($tmpDate[1], $tmpDate[2], $tmpDate[0]);
}
/**
* @return string
*/
public static function appendStrings()
{
$strings = func_get_args();
$appended = null;
foreach ($strings as $string) {
$appended .= " $string"; // add a space in between the strings
}
return trim($appended);
}
/**
* Retorna a String em MAIUSCULO
*
* @param String $string
*
* @return String
*/
public static function upper($string)
{
return strtr(mb_strtoupper($string), "àáâãäåæçèéêëìíîïðñòóôõö÷øùüúþÿ", "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÜÚÞß");
}
/**
* Retorna a String em minusculo
*
* @param String $string
*
* @return String
*/
public static function lower($string)
{
return strtr(mb_strtolower($string), "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÜÚÞß", "àáâãäåæçèéêëìíîïðñòóôõö÷øùüúþÿ");
}
/**
* Retorna a primeira posição da String em maiusculo e o restante em minusculo.
*
* @param String $string
*
* @return String
*/
public static function upFirst($string)
{
return ucfirst(self::lower($string));
}
/**
* Retorna somente as letras da string
*
* @param String $string
*
* @return String
*/
public static function lettersOnly($string)
{
return preg_replace('/[^[:alpha:]]/', '', $string); // se precisar manter o espaco orginal (se houver) na string inclua-o aqui.
}
/**
* Retorna TUDO oque nao for letras na string
*
* @param String $string
*
* @return String
*/
public static function lettersNot($string)
{
return preg_replace('/[[:alpha:]]/', '', $string);
}
/**
* Retorna somente os digitos da string e tambem remove espacos em branco
*
* @param String $string
*
* @return String
*/
public static function numbersOnly($string)
{
return preg_replace('/[^[:digit:]]/', '', $string);
}
/**
* Retorna a string sem os digitos - remove digitos da string
*
* @param String $string
*
* @return String
*/
public static function numbersNot($string)
{
return preg_replace('/[[:digit:]]/', '', $string);
}
/**
* Retorna somente alfanumericos (remove caracteres especiais)
* Obs.: Tambem remove acentos, para limpar acentos numa string
* substituindo o caractere pelo seu correspondente sem acento
* use o metodo `normalizeChars($string)`.
*
* @param String $string
*
* @return String
*/
public static function alphanumberOnly($string)
{
return preg_replace('/[^[:alnum:]]/', '', $string);
}
/**
* Função para limpar acentos de uma string
*
* @param string $string
* @return string
*/
public static function normalizeChars($string)
{
$normalizeChars = array(
'Á' => 'A', 'À' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Å' => 'A', 'Ä' => 'A', 'Æ' => 'AE', 'Ç' => 'C',
'É' => 'E', 'È' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Í' => 'I', 'Ì' => 'I', 'Î' => 'I', 'Ï' => 'I', 'Ð' => 'Eth',
'Ñ' => 'N', 'Ó' => 'O', 'Ò' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ø' => 'O',
'Ú' => 'U', 'Ù' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ý' => 'Y', 'Ŕ' => 'R',
'á' => 'a', 'à' => 'a', 'â' => 'a', 'ã' => 'a', 'å' => 'a', 'ä' => 'a', 'æ' => 'ae', 'ç' => 'c',
'é' => 'e', 'è' => 'e', 'ê' => 'e', 'ë' => 'e', 'í' => 'i', 'ì' => 'i', 'î' => 'i', 'ï' => 'i', 'ð' => 'eth',
'ñ' => 'n', 'ó' => 'o', 'ò' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ø' => 'o',
'ú' => 'u', 'ù' => 'u', 'û' => 'u', 'ü' => 'u', 'ý' => 'y', 'ŕ' => 'r', 'ÿ' => 'y',
'ß' => 'sz', 'þ' => 'thorn',
);
return strtr($string, $normalizeChars);
}
/**
* Mostra o Valor no float Formatado
*
* @param string $number
* @param integer $decimals
* @param boolean $showThousands
* @return string
*/
public static function nFloat($number, $decimals = 2, $showThousands = false)
{
if (is_null($number) || empty($number)) {
return '';
}
$pontuacao = preg_replace('/[0-9]/', '', $number);
$locale = (mb_substr($pontuacao, -1, 1) == ',') ? "pt-BR" : "en-US";
$formater = new \NumberFormatter($locale, \NumberFormatter::DECIMAL);
if ($decimals === false) {
$decimals = 2;
preg_match_all('/[0-9][^0-9]([0-9]+)/', $number, $matches);
if (!empty($matches[1])) {
$decimals = mb_strlen(rtrim($matches[1][0], 0));
}
}
return number_format($formater->parse($number, \NumberFormatter::TYPE_DOUBLE), $decimals, '.', ($showThousands ? ',' : ''));
}
/**
* Mostra o Valor no real Formatado
*
* @param float $number
* @param boolean $fixed
* @param boolean $symbol
* @param integer $decimals
* @return string
*/
public static function nReal($number, $decimals = 2, $symbol = true, $fixed = true)
{
if (is_null($number) || empty($number)) {
return '';
}
$formater = new \NumberFormatter("pt-BR", \NumberFormatter::CURRENCY);
$formater->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, ($fixed ? $decimals : 1));
if ($decimals === false) {
$decimals = 2;
preg_match_all('/[0-9][^0-9]([0-9]+)/', $number, $matches);
if (!empty($matches[1])) {
$decimals = mb_strlen(rtrim($matches[1][0], 0));
}
}
$formater->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, $decimals);
if (!$symbol) {
$pattern = preg_replace("/[¤]/", '', $formater->getPattern());
$formater->setPattern($pattern);
} else {
// ESPAÇO DEPOIS DO SIMBOLO
$pattern = str_replace("¤", "¤ ", $formater->getPattern());
$formater->setPattern($pattern);
}
return $formater->formatCurrency($number, $formater->getTextAttribute(\NumberFormatter::CURRENCY_CODE));
}
/**
* Retorna a percentagem de um valor
*
* @param $big
* @param $percent
*
* @return string
*/
public static function percent($big, $percent)
{
if ($percent < 0.01) {
return 0;
}
return self::nFloat($big*($percent/100));
}
/**
* Função para mascarar uma string, mascara tipo $mask="###.###.###-####/##"
*
* @param string $val
* @param string $mask
*
* @return string
*/
public static function maskString($val, $mask)
{
if (empty($val)) {
return $val;
}
$maskared = '';
$k = 0;
if (is_numeric($val)) {
$val = sprintf('%0' . mb_strlen(preg_replace('/[^#]/', '', $mask)) . 's', $val);
}
for ($i = 0; $i <= mb_strlen($mask) - 1; $i++) {
if ($mask[$i] == '#') {
if (isset($val[$k])) {
$maskared .= $val[$k++];
}
} else {
if (isset($mask[$i])) {
$maskared .= $mask[$i];
}
}
}
return $maskared;
}
/**
* @param $n
* @param integer $loop
* @param $insert
*
* @return string
* Not working with long numbers (15 figures for instance)
* solution: make this number a string wraping it around double quotes
*/
public static function numberFormatGeneral($n, $loop, $insert = 0)
{
// Removo os caracteras a mais do que o pad solicitado caso a string seja maior
$n = mb_substr(self::numbersOnly($n), 0, $loop);
return str_pad($n, $loop, $insert, STR_PAD_RIGHT); // params 1=input, 2=pad length, 3=pad string, 4=pad type (STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH)
}
/**
* @param $tipo (9 numeric or X string)
* @param $valor
* @param integer $tamanho
* @param int $dec decimal size
* @param string $sFill
*
* @return string
* @throws \Exception
*/
public static function formatCnab($tipo, $valor, $tamanho, $dec = 0, $sFill = '')
{
$tipo = self::upper($tipo);
if (in_array($tipo, array('9', 9, 'N', '9L', 'NL'))) {
if ($tipo == '9L' || $tipo == 'NL') {
$valor = self::numbersOnly($valor);
}
$left = '';
$sFill = 0;
$type = 's';
$valor = ($dec > 0) ? sprintf("%.{$dec}f", $valor) : $valor;
$valor = str_replace(array(',', '.'), '', $valor);
} elseif (in_array($tipo, array('A', 'X'))) {
$left = '-';
$type = 's';
$valor = self::upper(self::normalizeChars($valor));
} else {
throw new \Exception('Tipo inválido');
}
return sprintf("%{$left}{$sFill}{$tamanho}{$type}", mb_substr($valor, 0, $tamanho));
}
/**
* @param $n
* @param int $factor
* @param int $base
* @param int $x10
* @param int $resto10
*
* @return int
*
*/
public static function modulo11($n, $factor = 2, $base = 9, $x10 = 0, $resto10 = 0)
{
$sum = 0;
for ($i = mb_strlen($n); $i > 0; $i--) {
$sum += mb_substr($n, $i - 1, 1)*$factor;
if ($factor == $base) {
$factor = 1;
}
$factor++;
}
if ($x10 == 0) {
$sum *= 10;
$digito = $sum%11;
if ($digito == 10) {
$digito = $resto10;
}
return $digito;
}
return $sum%11;
}
/**
* @param $n
*
* @return int
*/
public static function modulo10($n)
{
$chars = array_reverse(str_split($n, 1));
$odd = array_intersect_key($chars, array_fill_keys(range(1, count($chars), 2), null));
$even = array_intersect_key($chars, array_fill_keys(range(0, count($chars), 2), null));
$even = array_map(
function ($n) {
return ($n >= 5) ? 2*$n - 9 : 2*$n;
}, $even
);
$total = array_sum($odd) + array_sum($even);
return ((floor($total/10) + 1)*10 - $total)%10;
}
/**
* @param array $a
*
* @return string
* @throws \Exception
*
* Esse metodo pode ser usado para validar chaves de moeda digital, alterar preg_match nesse caso.
*/
public static function array2Controle($a)
{
if (preg_match('/[0-9]/', implode('', array_keys($a)))) {
throw new \Exception('Somente chave alfanumérica no array, para separar o controle pela chave');
}
$controle = '';
foreach ($a as $key => $value) {
$controle .= sprintf('%s%s', $key, $value);
}
if (mb_strlen($controle) > 25) {
throw new \Exception('Controle muito grande, máximo permitido de 25 caracteres');
}
return $controle;
}
/**
* @param $controle
*
* @return null|string
*/
public static function controle2array($controle)
{
$matches = '';
$matches_founded = [];
preg_match_all('/(([A-Za-zÀ-Úà-ú]+)([0-9]*))/', $controle, $matches, PREG_SET_ORDER);
if ($matches) {
foreach ($matches as $match) {
$matches_founded[$match[2]] = (int) $match[3];
}
return $matches_founded;
}
return [$controle];
}
/**
* Remove trecho do array.
*
* @param $i
* @param $f
* @param $array
*
* @return string
* @throws \Exception
*/
public static function remove($i, $f, &$array)
{
if (is_string($array)) {
$array = str_split(rtrim($array, chr(10) . chr(13) . "\n" . "\r"), 1);
}
$i--;
if ($i > 398 || $f > 400) {
throw new \Exception('$ini ou $fim ultrapassam o limite máximo de 400');
}
if ($f < $i) {
throw new \Exception('$ini é maior que o $fim');
}
$t = $f - $i;
$toSplice = $array;
if($toSplice != null)
return trim(implode('', array_splice($toSplice, $i, $t)));
else
return;
}
/**
* Função para add valor a linha nas posições informadas.
*
* @param $line
* @param integer $i
* @param integer $f
* @param $value
*
* @return array
* @throws \Exception
*/
public static function adiciona(&$line, $i, $f, $value)
{
$i--;
if ($i > 398 || $f > 400) {
throw new \Exception('$ini ou $fim ultrapassam o limite máximo de 400');
}
if ($f < $i) {
throw new \Exception('$ini é maior que o $fim');
}
$t = $f - $i;
if (mb_strlen($value) > $t) {
throw new \Exception(sprintf('String $valor maior que o tamanho definido em $ini e $fim: $valor=%s e tamanho é de: %s', mb_strlen($value), $t));
}
$value = sprintf("%{$t}s", $value);
$value = preg_split('//u', $value, -1, PREG_SPLIT_NO_EMPTY);
return array_splice($line, $i, $t, $value);
}
/**
* Validação para o tipo de cnab 240
*
* @param $content
* @return bool
*/
public static function isCnab240($content)
{
$content = is_array($content) ? $content[0] : $content;
$content = Encoding::toUTF8($content);
return mb_strlen(rtrim($content, "\r\n")) == 240 ? true : false;
}
/**
* Validação para o tipo de cnab 400
*
* @param $content
* @return bool
*/
public static function isCnab400($content)
{
$content = is_array($content) ? $content[0] : $content;
$content = Encoding::toUTF8($content);
return mb_strlen(rtrim($content, "\r\n")) == 400 ? true : false;
}
/**
* Valida se o header é de um arquivo retorno valido, 240 ou 400 posicoes
*
* @param $header
*
* @return bool
*/
public static function isHeaderRetorno($header)
{
if (!self::isCnab240($header) && !self::isCnab400($header)) {
return false;
}
if (self::isCnab400($header) && mb_substr($header, 0, 9) != '02RETORNO') {
return false;
}
if (self::isCnab240($header) && mb_substr($header, 142, 1) != '2') {
return false;
}
return true;
}
/***********************************************************************************************
* @CNAB REMESSA abstract methods
* Reference: https://github.com/eduardokum/laravel-boleto/blob/master/src/Cnab/Remessa/AbstractRemessa.php
***********************************************************************************************/
/**
* Retorna o Nosso Número calculado.
*
* @return string
*/
public function getNossoNumero()
{
if (empty($this->campoNossoNumero)) {
return $this->campoNossoNumero += 1;
}
return $this->campoNossoNumero;
}
/**
* Gera o Nosso Número.
*
* @return string
*/
public function gerarNossoNumero()
{
// nao usado
}
/**
* Retorna o código do banco
*
* @return string
*/
public function getCodigoBanco()
{
return $this->codigoBanco;
}
/**
* @return mixed
*/
public function getIdremessa()
{
return $this->idremessa;
}
/**
* @param mixed $idremessa
*
* @return AbstractRemessa
*/
public function setIdremessa($idremessa)
{
$this->idremessa = $idremessa;
return $this;
}
/**
* @return PessoaContract
*/
public function getBeneficiario()
{
return $this->beneficiario;
}
/**
* @param $beneficiario
*
* @return AbstractRemessa
* @throws \Exception
*/
public function setBeneficiario($beneficiario)
{
Util::addPessoa($this->beneficiario, $beneficiario);
return $this;
}
/**
* Retorna o campo Número do documento da remessa
*
* @return string
*/
public function getNumeroDocumento()
{
return $this->numeroDocumento;
}
/**
* @return get document beneficiario
*/
public function getDocumento()
{
return $this->beneficiarioDocumento;
}
/**
* Retorna o número definido pelo cliente para controle da remessa
*
* @return int
*/
public function getNumeroControle()
{
return $this->numeroControle;
}
/**
* Define a agência
*
* @param int $agencia
*
* @return AbstractRemessa
*/
public function setAgencia($agencia)
{
$this->agencia = (string) $agencia;
return $this;
}
/**
* Retorna a agência
*
* @return int
*/
public function getAgencia()
{
return $this->agencia;
}
/**
* Define o número da conta
*
* @param int $conta
*
* @return AbstractRemessa
*/
public function setConta($conta)
{
$this->conta = (string) $conta;
return $this;
}
/**
* Retorna o número da conta
*
* @return int
*/
public function getConta()
{
return $this->conta;
}
/**
* Define o dígito verificador da conta
*
* @param int $contaDv
*
* @return AbstractRemessa
*/
public function setContaDv($contaDv)
{
$this->contaDv = substr($contaDv, - 1);
return $this;
}
/**
* Retorna o dígito verificador da conta
*
* @return int
*/
public function getContaDv()
{
return $this->contaDv;
}
/**
* Define o código da carteira (Com ou sem registro)
*
* @param string $carteira
*
* @return AbstractRemessa
* @throws \Exception
*/
public function setCarteira($carteira)
{
if (! in_array($carteira, $this->getCarteiras())) {
throw new \Exception("Carteira não disponível!");
}
$this->carteira = $carteira;
return $this;
}
/**
* Retorna o código da carteira (Com ou sem registro)
*
* @return string
*/
public function getCarteira()
{
return $this->carteira;
}
/**
* Retorna o código da carteira (Com ou sem registro)
*
* @return string
*/
public function getCarteiraNumero()
{
return $this->carteira;
}
/**
* Retorna as carteiras disponíveis para este banco
*
* @return array
*/
public function getCarteiras()
{
return $this->carteiras;
}
/**
* Método que valida se o banco tem todos os campos obrigadotorios preenchidos
*
* @return boolean
*/
public function isValid(&$messages)
{
foreach ($this->camposObrigatorios as $campo) {
$test = call_user_func([$this, 'get' . ucwords($campo)]);
if ($test === '' || is_null($test)) {
$messages .= "Campo $campo está em branco";
return false;
}
}
return true;
}
/**
* @return int
*/
public function getStatus()
{
return $this->status;
}
/**
* Get Count used for:
* > Número sequencial do registro no arquivo $add=2
* > Quantidade de documentos no arquivo $add=0
*
* @return int
*/
public function getCount($add)
{
return count($this->aRegistros[self::DETALHE]) + $add;
}
/**
* Função para adicionar multiplos boletos.
*
* @param array $boletos
*
* @return $this
*/
public function addBoletos(array $boletos)
{
foreach ($boletos as $boleto) {
$this->addBoleto($boleto);
}
return $this;
}
/**
* Função para add valor a linha nas posições informadas.
*
* @param integer $i
* @param integer $f
* @param $value
*
* @return array
* @throws \Exception
*/
public function add($i, $f, $value)
{
return $this->adiciona($this->atual, $i, $f, $value);
}
/**
* Retorna o header do arquivo.
*
* @return mixed
*/
public function getHeader()
{
return $this->aRegistros[self::HEADER];
}
/**
* Retorna os detalhes do arquivo
*
* @return \Illuminate\Support\Collection
*/
public function getDetalhes()
{
# !IMPORTANT collecttion will work only with PHP7+
//return collect($this->aRegistros[self::DETALHE]);
return $this->aRegistros[self::DETALHE];
}
/**
* Retorna o trailer do arquivo.
*
* @return mixed
*/
public function getTrailer()
{
return $this->aRegistros[self::TRAILER];
}
/**
* Valida se a linha esta correta.
*
* @param array $a
*
* @return string
* @throws \Exception
*/
public function valida(array $a)
{
if ($this->tamanho_linha === false) {
throw new \Exception('Classe remessa deve informar o tamanho da linha');
}
$a = array_filter($a, 'strlen');
if (count($a) != $this->tamanho_linha) {
throw new \Exception(sprintf('$a não possui %s posições, possui: %s', $this->tamanho_linha, count($a)));
}
return implode('', $a);
}
/**
* Salva o arquivo no path informado
*
* @param $path
*
* @return mixed
* @throws \Exception
*/
public function save($path)
{
$folder = dirname($path);
if (! is_dir($folder)) {
mkdir($folder, 0777, true);
}
if (! is_writable(dirname($path))) {
throw new \Exception('Path ' . $folder . ' não possui permissao de escrita');
}
$string = $this->gerar();
file_put_contents($path, $string);
return $path;
}
/**
* Realiza o download da string retornada do metodo gerar