File::save()   B
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 98
Code Lines 67

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 66
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 67
dl 0
loc 98
ccs 66
cts 66
cp 1
rs 8.72
c 0
b 0
f 0
cc 4
nc 5
nop 0
crap 4

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
namespace MrPrompt\CaixaEconomicaFederal\Shipment;
3
4
use MrPrompt\ShipmentCommon\Base\Address;
5
use MrPrompt\ShipmentCommon\Base\Bank;
6
use MrPrompt\ShipmentCommon\Base\Cart;
7
use MrPrompt\ShipmentCommon\Base\Charge;
8
use MrPrompt\ShipmentCommon\Base\Customer;
9
use MrPrompt\ShipmentCommon\Base\Document;
10
use MrPrompt\ShipmentCommon\Base\Occurrence;
11
use MrPrompt\ShipmentCommon\Base\Purchaser;
12
use MrPrompt\ShipmentCommon\Base\Seller;
13
use MrPrompt\ShipmentCommon\Base\Sequence;
14
use MrPrompt\ShipmentCommon\Util\Number;
15
use MrPrompt\CaixaEconomicaFederal\Factory;
16
use MrPrompt\CaixaEconomicaFederal\Shipment\Partial\Footer;
17
use MrPrompt\CaixaEconomicaFederal\Shipment\Partial\Header;
18
use Cnab\Banco;
19
use Cnab\Especie;
20
use Cnab\Remessa\Cnab240\Arquivo;
21
use DateTime;
22
23
/**
24
 * Billet file class
25
 *
26
 * @author Thiago Paes <[email protected]>
27
 */
28
final class File
29
{
30
    /**
31
     * File name template
32
     *
33
     * @var string
34
     */
35
    const TEMPLATE_GENERATED = '{CLIENT}_{DDMMYYYY}_{SEQUENCE}.TXT';
36
37
    /**
38
     * @var DateTime
39
     */
40
    protected $now;
41
42
    /**
43
     * @var Cart
44
     */
45
    protected $cart;
46
47
    /**
48
     * @var Sequence
49
     */
50
    protected $sequence;
51
52
    /**
53
     * @var Customer
54
     */
55
    protected $customer;
56
57
    /**
58
     * @var string
59
     */
60
    protected $storage;
61
62
    /**
63
     * @var string
64
     */
65
    protected $header;
66
67
    /**
68
     * @var string
69
     */
70
    protected $footer;
71
72
    /**
73
     * @param Customer $customer
74
     * @param Sequence $sequence
75
     * @param DateTime $today
76
     * @param string   $storageDir
77
     */
78 3
    public function __construct(Customer $customer, Sequence $sequence, DateTime $today, $storageDir = null)
79
    {
80 3
        $this->customer     = $customer;
81 3
        $this->sequence     = $sequence;
82 3
        $this->now          = $today;
83 3
        $this->storage      = $storageDir;
84 3
    }
85
86
    /**
87
     * Return the cart
88
     *
89
     * @return Cart
90
     */
91 1
    public function getCart()
92
    {
93 1
        return $this->cart;
94
    }
95
96
    /**
97
     * Set the for with the payments
98
     *
99
     * @param Cart $cart
100
     */
101 1
    public function setCart(Cart $cart)
102
    {
103 1
        $this->cart = $cart;
104 1
    }
105
106
    /**
107
     * Create the file name
108
     *
109
     * @return string
110
     */
111
    protected function createFilename()
112
    {
113
        $search = [
114
            '{CLIENT}',
115
            '{DDMMYYYY}',
116
            '{SEQUENCE}'
117
        ];
118
119
        $replace = [
120
            Number::zeroFill($this->customer->getCode(), 6, Number::FILL_LEFT),
121
            $this->now->format('dmY'),
122
            Number::zeroFill($this->sequence->getValue(), 5, Number::FILL_LEFT),
123
        ];
124
125
        return str_replace($search, $replace, self::TEMPLATE_GENERATED);
126
    }
127
128
    /**
129
     * Save the output result
130
     *
131
     * @return string
132
     */
133 1
    public function save()
134
    {
135
        /* @var $item \MrPrompt\CaixaEconomicaFederal\Shipment\Partial\Detail */
136 1
        $item       = $this->cart->offsetGet(0);
137
138
        /* @var filename string */
139 1
        $filename   = $this->createFilename();
140
141
        /* @var $outputFile string */
142 1
        $outputFile = $this->storage . DIRECTORY_SEPARATOR . $filename;
143
144
        /* @var $seller Seller */
145 1
        $seller = $item->getSeller();
146
        
147
        /* @var $address Address */
148 1
        $address = $seller->getAddress();
149
150
        /* @var $file \Cnab\Remessa\Cnab240\Arquivo */
151 1
        $file = new Arquivo(Banco::CEF, 'sigcb');
152 1
        $file->configure([
153 1
            'data_geracao'              => new DateTime(),
154 1
            'data_gravacao'             => new DateTime(),
155 1
            'nome_fantasia'             => $seller->getName(),
156 1
            'razao_social'              => $seller->getName(),
157 1
            'codigo_inscricao'          => '01',
158 1
            'cnpj'                      => $seller->getDocument()->getNumber(),
159 1
            'banco'                     => Banco::CEF,
160 1
            'logradouro'                => sprintf('%s %s', $address->getAddress(), $address->getComplement()),
161 1
            'numero'                    => $address->getNumber(),
162 1
            'bairro'                    => $address->getDistrict(),
163 1
            'cidade'                    => $address->getCity(),
164 1
            'uf'                        => $address->getState(),
165 1
            'cep'                       => $address->getPostalCode(),
166 1
            'agencia'                   => $item->getBillet()->getBankAccount()->getBank()->getAgency(),
167 1
            'agencia_dv'                => $item->getBillet()->getBankAccount()->getBank()->getDigit(),
168 1
            'conta'                     => $item->getBillet()->getBankAccount()->getNumber(),
169 1
            'operacao'                  => $item->getBillet()->getBankAccount()->getOperation(),
170 1
            'codigo_cedente'            => $seller->getCode(),
171 1
            'codigo_cedente_dac'        => '2',
172 1
            'numero_sequencial_arquivo' => $this->sequence->getValue(),
173
        ]);
174
175
        /* @var $parcels \MrPrompt\ShipmentCommon\Base\Parcels */
176 1
        $parcels = $item->getParcels();
177
178
        /* @var $parcel \MrPrompt\ShipmentCommon\Base\Parcel */
179 1
        foreach ($parcels as $parcel) {
180
            /* @var $purchaser Purchaser */
181 1
            $purchaser  = $item->getPurchaser();
182
            
183
            /* @var $address Address */
184 1
            $address    = $purchaser->getAddress();
185
186
            /* @var $document Document */
187 1
            $document   = $purchaser->getDocument();
188 1
            $docType    = $document->getType() === Document::CPF ? 'sacado_cpf' : 'sacado_cnpj';
189
190
            $rowFile    = [
191 1
                'codigo_ocorrencia'             => 1,
192 1
                'nosso_numero'                  => $item->getAuthorization()->getNumber(),
193 1
                'numero_documento'              => sprintf('%s/%s', $item->getBillet()->getNumber(), $this->sequence->getValue()),
194 1
                'modalidade_carteira'           => 14,
195 1
                'especie'                       => Especie::CEF_OUTROS,
196 1
                'aceite'                        => 'N',
197
                'registrado'                    => true,
198 1
                'valor'                         => $parcel->getPrice(),
199 1
                'instrucao1'                    => 1,
200 1
                'instrucao2'                    => 0,
201 1
                'sacado_nome'                   => $purchaser->getName(),
202 1
                'sacado_tipo'                   => $document->getType() === Document::CPF ? 'cpf' : 'cnpj',
203 1
                'sacado_logradouro'             => $address->getAddress(),
204 1
                'sacado_bairro'                 => $address->getDistrict(),
205 1
                'sacado_cep'                    => $address->getPostalCode(),
206 1
                'sacado_cidade'                 => $address->getCity(),
207 1
                'sacado_uf'                     => $address->getState(),
208 1
                'data_vencimento'               => $parcel->getMaturity(),
209 1
                'data_cadastro'                 => new DateTime(),
210 1
                'juros_de_um_dia'               => 0.02,
211 1
                'data_desconto'                 => $parcel->getMaturity(),
212 1
                'valor_desconto'                => $parcel->getPrice(),
213 1
                'prazo'                         => 0,
214 1
                'taxa_de_permanencia'           => 0,
215 1
                'mensagem'                      => '',
216 1
                'data_multa'                    => $parcel->getMaturity(),
217 1
                'valor_multa'                   => 0.0,
218 1
                'identificacao_distribuicao'    => 0,
219 1
                "{$docType}"                    => $document->getNumber(),
220
            ];
221
222
            // Fix
223 1
            $file->headerLote->uso_exclusivo_banco = '00000000000000';
224
225 1
            $file->insertDetalhe($rowFile);
226
        }
227
228 1
        $file->save($outputFile);
229
230 1
        return $outputFile;
231
    }
232
}
233