residentes_pdf   A
last analyzed

Complexity

Total Complexity 42

Size/Duplication

Total Lines 318
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 198
dl 0
loc 318
rs 9.0399
c 2
b 0
f 0
wmc 42

7 Methods

Rating   Name   Duplication   Size   Complexity  
A calcular_tamanyo_logo() 0 16 3
A generar_pdf_lineas_fila() 0 37 2
B verificar_longitud_linea() 0 16 7
B generar_datos_residente() 0 63 6
B generar_pdf_lineas() 0 42 6
C generar_pdf_cabecera() 0 96 16
A generar_pdf_lineas_tablas() 0 25 2

How to fix   Complexity   

Complex Class

Complex classes like residentes_pdf often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use residentes_pdf, and based on these observations, apply Extract Interface, too.

1
<?php
2
/*
3
 * Copyright (C) 2018 Joe Nilson <joenilson at gmail.com>
4
 *
5
 * This program is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU Lesser General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public License
16
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
 */
18
require_once 'plugins/facturacion_base/extras/fs_pdf.php';
19
require_once 'plugins/residentes/extras/residentes_controller.php';
20
21
/**
22
 * Description of residentes_pdf
23
 *
24
 * @author Joe Nilson <joenilson at gmail.com>
25
 */
26
class residentes_pdf extends fs_pdf
0 ignored issues
show
Bug introduced by
The type fs_pdf 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...
27
{
28
    const LOGO_X = 40;
29
    const LOGO_Y = 700;
30
31
    public $cliente_residente;
32
    public $numpaginas;
33
34
    public function calcular_tamanyo_logo()
35
    {
36
        $tamanyo = $size = getimagesize($this->logo);
37
        if ($size[0] > 200) {
38
            $tamanyo[0] = 200;
39
            $tamanyo[1] = $tamanyo[1] * $tamanyo[0] / $size[0];
40
            $size[0] = $tamanyo[0];
41
            $size[1] = $tamanyo[1];
42
        }
43
44
        if ($size[1] > 80) {
45
            $tamanyo[1] = 80;
46
            $tamanyo[0] = $tamanyo[0] * $tamanyo[1] / $size[1];
47
        }
48
49
        return $tamanyo;
50
    }
51
52
    public function generar_pdf_cabecera(&$empresa, &$lppag)
53
    {
54
        /// ¿Añadimos el logo?
55
        if ($this->logo !== false) {
56
            if (function_exists('imagecreatefromstring')) {
57
                $lppag -= 2; /// si metemos el logo, caben menos líneas
58
59
                $tamanyo = $this->calcular_tamanyo_logo();
60
                if (strtolower(substr($this->logo, -4)) === '.png') {
61
                    $this->pdf->addPngFromFile($this->logo, self::LOGO_X, self::LOGO_Y, $tamanyo[0], $tamanyo[1]);
62
                } elseif (function_exists('imagepng')) {
63
                    /**
64
                     * La librería ezpdf tiene problemas al redimensionar jpegs,
65
                     * así que hacemos la conversión a png para evitar estos problemas.
66
                     */
67
                    if (imagepng(imagecreatefromstring(file_get_contents($this->logo)), FS_MYDOCS
68
                        . 'images/logo.png')) {
69
                        $this->pdf->addPngFromFile(
70
                            FS_MYDOCS . 'images/logo.png',
71
                            self::LOGO_X,
72
                            self::LOGO_Y,
73
                            $tamanyo[0],
74
                            $tamanyo[1]
75
                        );
76
                    } else {
77
                        $this->pdf->addJpegFromFile($this->logo, self::LOGO_X, self::LOGO_Y, $tamanyo[0], $tamanyo[1]);
78
                    }
79
                } else {
80
                    $this->pdf->addJpegFromFile($this->logo, self::LOGO_X, self::LOGO_Y, $tamanyo[0], $tamanyo[1]);
81
                }
82
83
                $this->pdf->ez['rightMargin'] = 40;
84
                $this->pdf->ezText(
85
                    "<b>" . fs_fix_html($empresa->nombre) . "</b>",
86
                    12,
87
                    array('justification' => 'right')
88
                );
89
                $this->pdf->ezText(FS_CIFNIF . ": " . $empresa->cifnif, 8, array('justification' => 'right'));
90
91
                $direccion = $empresa->direccion . "\n";
92
                if ($empresa->apartado) {
93
                    $direccion .= ucfirst(FS_APARTADO) . ': ' . $empresa->apartado . ' - ';
94
                }
95
96
                if ($empresa->codpostal) {
97
                    $direccion .= 'CP: ' . $empresa->codpostal . ' - ';
98
                }
99
100
                if ($empresa->ciudad) {
101
                    $direccion .= $empresa->ciudad . ' - ';
102
                }
103
104
                if ($empresa->provincia) {
105
                    $direccion .= '(' . $empresa->provincia . ')';
106
                }
107
108
                if ($empresa->telefono) {
109
                    $direccion .= "\nTeléfono: " . $empresa->telefono;
110
                }
111
112
                $this->pdf->ezText(fs_fix_html($direccion) . "\n", 8, array('justification' => 'right'));
113
                $this->set_y(self::LOGO_Y + 10);
114
            } else {
115
                die('ERROR: no se encuentra la función imagecreatefromstring(). '
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
116
                    . 'Y por tanto no se puede usar el logotipo en los documentos.');
117
            }
118
        } else {
119
            $this->pdf->ezText(
120
                "<b>" . fs_fix_html($empresa->nombre) . "</b>",
121
                12,
122
                array('justification' => 'center')
123
            );
124
            $this->pdf->ezText(FS_CIFNIF . ": " . $empresa->cifnif, 8, array('justification' => 'center'));
125
126
            $direccion = $empresa->direccion;
127
            if ($empresa->apartado) {
128
                $direccion .= ' - ' . ucfirst(FS_APARTADO) . ': ' . $empresa->apartado;
129
            }
130
131
            if ($empresa->codpostal) {
132
                $direccion .= ' - CP: ' . $empresa->codpostal;
133
            }
134
135
            if ($empresa->ciudad) {
136
                $direccion .= ' - ' . $empresa->ciudad;
137
            }
138
139
            if ($empresa->provincia) {
140
                $direccion .= ' (' . $empresa->provincia . ')';
141
            }
142
143
            if ($empresa->telefono) {
144
                $direccion .= ' - Teléfono: ' . $empresa->telefono;
145
            }
146
147
            $this->pdf->ezText(fs_fix_html($direccion), 8, array('justification' => 'center'));
148
        }
149
    }
150
151
    public function generar_datos_residente(&$pdf_doc, $tipo_documento, &$lppag, $table_width = 560)
152
    {
153
        $residente_controller = new residentes_controller();
154
        $width_campo1 = 110;
155
        $tipo_doc = $residente_controller->generar_tipo_doc($tipo_documento);
156
        $tipo_residente = ($this->cliente_residente->informacion->propietario) ? 'Propietario' : 'Inquilino';
157
        /*
158
         * Esta es la tabla con los datos del cliente:
159
         * Informe Cobros           Fecha:
160
         * Cliente:        Tipo Residente:
161
         * Dirección:           Teléfonos:
162
         */
163
        $pdf_doc->new_table();
164
        $pdf_doc->add_table_row(
165
            array(
166
                'campo1' => "<b>" . $tipo_doc . "</b>",
167
                'dato1' => '',
168
                'campo2' => "<b>Fecha Impresión:</b> " . \date('d-m-Y H:i:s')
169
            )
170
        );
171
172
        $pdf_doc->add_table_row(
173
            array(
174
                'campo1' => "<b>Residente:</b>",
175
                'dato1' => fs_fix_html($this->cliente_residente->nombre),
176
                'campo2' => "<b>Tipo Residente:</b> " . $tipo_residente
177
            )
178
        );
179
180
        $row = array(
181
            'campo1' => "<b>Inmueble:</b>",
182
            'dato1' => fs_fix_html($this->cliente_residente->inmueble->codigo_externo() .
183
                ' - ' . $this->cliente_residente->inmueble->numero),
184
            'campo2' => ''
185
        );
186
187
        if (!$this->cliente_residente) {
188
            /// nada
189
        } elseif ($this->cliente_residente->telefono1) {
190
            $row['campo2'] = "<b>Teléfonos:</b> " . $this->cliente_residente->telefono1;
191
            if ($this->cliente_residente->telefono2) {
192
                $row['campo2'] .= "\n" . $this->cliente_residente->telefono2;
193
                $lppag -= 2;
194
            }
195
        } elseif ($this->cliente_residente->telefono2) {
196
            $row['campo2'] = "<b>Teléfonos:</b> " . $this->cliente_residente->telefono2;
197
        }
198
        $pdf_doc->add_table_row($row);
199
200
        $pdf_doc->save_table(
201
            array(
202
                'cols' => array(
203
                    'campo1' => array('width' => $width_campo1, 'justification' => 'right'),
204
                    'dato1' => array('justification' => 'left'),
205
                    'campo2' => array('justification' => 'right')
206
                ),
207
                'showLines' => 0,
208
                'width' => $table_width,
209
                'shaded' => 0,
210
                'fontSize' => 8
211
            )
212
        );
213
        $pdf_doc->pdf->ezText("\n", 10);
214
    }
215
216
    public function generar_pdf_lineas(&$pdf_doc, &$items, &$linea_actual, &$lppag, $tipo, $table_width = 540)
217
    {
218
        /// calculamos el número de páginas
219
        if (!isset($this->numpaginas)) {
220
            $this->numpaginas = 0;
221
            $lineas = 0;
222
            while ($lineas < count($items)) {
223
                $lppag2 = $lppag;
224
                $this->verificar_longitud_linea($items, $lineas, $lppag2);
225
                $lineas += $lppag2;
226
                $this->numpaginas++;
227
            }
228
229
            if ($this->numpaginas === 0) {
230
                $this->numpaginas = 1;
231
            }
232
        }
233
234
        /// leemos las líneas para ver si hay que mostrar mas información
235
        $this->verificar_longitud_linea($items, $linea_actual, $lppag);
236
237
        /*
238
         * Creamos la tabla con las lineas de pendientes
239
         */
240
        $pdf_doc->new_table();
241
        [$table_header, $array_cols] = $this->generar_pdf_lineas_tablas($tipo);
242
        $pdf_doc->add_table_header($table_header);
243
244
        for ($i = $linea_actual; (($linea_actual < ($lppag + $i)) && ( $linea_actual < count($items)));) {
245
            $fila = $this->generar_pdf_lineas_fila($tipo, $items, $linea_actual);
246
            $pdf_doc->add_table_row($fila);
247
            $linea_actual++;
248
        }
249
250
        $pdf_doc->save_table(
251
            array(
252
                'fontSize' => 8,
253
                'cols' => $array_cols,
254
                'width' => $table_width,
255
                'shaded' => 1,
256
                'shadeCol' => array(0.95, 0.95, 0.95),
257
                'lineCol' => array(0.3, 0.3, 0.3),
258
            )
259
        );
260
    }
261
262
    public function generar_pdf_lineas_tablas($tipo)
263
    {
264
        $table_header = array(
265
            'item' => '<b>Pendiente de Pago</b>', 'fecha' => '<b>Fecha</b>',
266
            'vencimiento' => '<b>Vencimiento</b>', 'importe' => '<b>Monto</b>',
267
            'descuento' => '<b>Descuento</b>', 'total' => '<b>Total</b>', 'atraso' => '<b>Atraso</b>',
268
        );
269
        $array_cols = array(
270
            'item' => array('justification' => 'left'), 'fecha' => array('justification' => 'center'),
271
            'vencimiento' => array('justification' => 'center'), 'importe' => array('justification' => 'right'),
272
            'descuento' => array('justification' => 'right'),
273
            'total' => array('justification' => 'right'), 'atraso' => array('justification' => 'center')
274
        );
275
        if ($tipo === 'pagado') {
276
            $table_header = array(
277
                'item' => '<b>Pagos Realizados</b>', 'fecha' => '<b>Fecha</b>',
278
                'importe' => '<b>Monto</b>', 'f_pago' => '<b>F. Pago</b>'
279
            );
280
            $array_cols = array(
281
                'item' => array('justification' => 'left'), 'fecha' => array('justification' => 'center'),
282
                'importe' => array('justification' => 'right'), 'f_pago' => array('justification' => 'center')
283
            );
284
        }
285
286
        return array($table_header,$array_cols);
287
    }
288
289
    public function generar_pdf_lineas_fila($tipo, $items, $linea_actual)
290
    {
291
        $residentes_controller = new residentes_controller();
292
        $descripcion = fs_fix_html($items[$linea_actual]->descripcion);
293
        $fila = array(
294
            'item' => $descripcion,
295
            'fecha' => $items[$linea_actual]->fecha,
296
            'vencimiento' => $items[$linea_actual]->vencimiento,
297
            'importe' => $residentes_controller->show_precio(
298
                $items[$linea_actual]->pvpsindto,
299
                $residentes_controller->empresa->coddivisa,
300
                true,
301
                FS_NF0
302
            ),
303
            'descuento' => $residentes_controller->show_numero($items[$linea_actual]->dtopor) . " %",
304
            'total' => $residentes_controller->show_precio(
305
                $items[$linea_actual]->pvptotal,
306
                $residentes_controller->empresa->coddivisa,
307
                true,
308
                FS_NF0
309
            ),
310
            'atraso' => $items[$linea_actual]->dias_atraso
311
        );
312
        if ($tipo === 'pagado') {
313
            $fila = array(
314
                'item' => $descripcion,
315
                'fecha' => $items[$linea_actual]->fecha,
316
                'importe' => $residentes_controller->show_precio(
317
                    $items[$linea_actual]->pvptotal,
318
                    $residentes_controller->empresa->coddivisa,
319
                    true,
320
                    FS_NF0
321
                ),
322
                'f_pago' => $items[$linea_actual]->f_pago
323
            );
324
        }
325
        return $fila;
326
    }
327
328
    public function verificar_longitud_linea($items, &$lineas, &$lppag2)
329
    {
330
        foreach ($items as $i => $lin) {
331
            if ($i >= $lineas && $i < $lineas + $lppag2) {
332
                $linea_size = 1;
333
                $len = mb_strlen($lin->descripcion);
334
                while ($len > 85) {
335
                    $len -= 85;
336
                    $linea_size += 0.5;
337
                }
338
                $aux = explode("\n", $lin->descripcion);
339
                if (count($aux) > 1) {
340
                    $linea_size += 0.5 * ( count($aux) - 1);
341
                }
342
                if ($linea_size > 1) {
343
                    $lppag2 -= $linea_size - 1;
344
                }
345
            }
346
        }
347
    }
348
}