Passed
Push — master ( 88d705...44ae42 )
by Andrea
12:16
created

StampatabellaController   B

Complexity

Total Complexity 42

Size/Duplication

Total Lines 331
Duplicated Lines 0 %

Test Coverage

Coverage 58.87%

Importance

Changes 0
Metric Value
dl 0
loc 331
ccs 136
cts 231
cp 0.5887
rs 8.295
c 0
b 0
f 0
wmc 42

7 Methods

Rating   Name   Duplication   Size   Complexity  
A esportaexcel() 0 56 3
A __construct() 0 4 2
D stampa() 0 104 11
A getValueCell() 0 19 4
C printBodyXls() 0 66 13
B printHeaderXls() 0 34 4
B stampaTestata() 0 31 5

How to fix   Complexity   

Complex Class

Complex classes like StampatabellaController 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 StampatabellaController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Fi\CoreBundle\Controller;
4
5
use Fi\CoreBundle\DependencyInjection\GrigliaFiltriUtils;
6
use TCPDF;
7
8
class StampatabellaController extends FiCoreController
9
{
10
11
    public function __construct($container = null)
12
    {
13
        if ($container) {
14
            $this->setContainer($container);
15
        }
16
    }
17
18 1
    public function stampa($parametri = array())
19
    {
20 1
        $testata = $parametri['testata'];
21 1
        $rispostaj = $parametri['griglia'];
22 1
        $request = $parametri['request'];
23 1
        $nomicolonne = $testata['nomicolonne'];
24
25 1
        $modellicolonne = $testata['modellocolonne'];
26 1
        $larghezzaform = 900;
27
28 1
        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
29
30
        //echo PDF_HEADER_LOGO;
31 1
        $pdftitle = isset($testata['titolo']) && ($testata['titolo'] != '') ? $testata['titolo'] : 'Elenco ' . $request->get('nometabella');
32 1
        $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, 'FiFree2', $pdftitle, array(0, 0, 0), array(0, 0, 0));
33 1
        $pdf->setFooterData(array(0, 0, 0), array(0, 0, 0));
34
35 1
        $pdf->setHeaderFont(array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
36 1
        $pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
37
38 1
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
39 1
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
40 1
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
41 1
        $pdf->SetFillColor(220, 220, 220);
42
43 1
        $pdf->AddPage('L');
44 1
        $h = 6;
45 1
        $border = 1;
46 1
        $ln = 0;
47 1
        $align = 'L';
48 1
        $fill = 0;
49
50 1
        $dimensions = $pdf->getPageDimensions();
51
52 1
        $this->stampaTestata($pdf, $nomicolonne, $modellicolonne, $larghezzaform, $h, $border, $align, $fill, $ln);
53
54
        // Dati
55 1
        $risposta = json_decode($rispostaj);
56 1
        $righe = $risposta->rows;
57 1
        $pdf->SetFont('helvetica', '', 9);
58 1
        foreach ($righe as $riga) {
59 1
            $fill = !$fill;
60 1
            $vettorecelle = $riga->cell;
61
62 1
            $arr_heights = array();
63
            // store current object
64 1
            $pdf->startTransaction();
65 1
            foreach ($vettorecelle as $posizione => $valore) {
66 1
                if (!is_object($valore)) {
67 1
                    if (isset($modellicolonne[$posizione])) {
68 1
                        $width = ((297 * $modellicolonne[$posizione]['width']) / $larghezzaform) / 2;
69 1
                    } else {
70
                        $width = ((297 * 100) / $larghezzaform) / 2;
71
                    }
72
                    // get the number of lines
73 1
                    $arr_heights[] = $pdf->MultiCell($width, 0, $valore, $border, $align, $fill, 0, '', '', true, 0, false, true, 0);
74 1
                }
75 1
            }
76
            // restore previous object
77 1
            $pdf->rollbackTransaction(true);
78
            //work out the number of lines required
79 1
            $rowcount = max($arr_heights);
80 1
            $startY = $pdf->GetY();
81 1
            if (($startY + $rowcount * $h) + $dimensions['bm'] > ($dimensions['hk'])) {
82
                // page break
83
                $pdf->AddPage('L');
84
                // stampa testata
85
                $this->stampaTestata($pdf, $nomicolonne, $modellicolonne, $larghezzaform, $h, $border, $align, $fill, $ln);
86
            }
87
            //now draw it
88 1
            foreach ($vettorecelle as $posizione => $valore) {
89 1
                if (!is_object($valore)) {
90 1
                    if (isset($modellicolonne[$posizione])) {
91 1
                        $width = ((297 * $modellicolonne[$posizione]['width']) / $larghezzaform) / 2;
92 1
                    } else {
93
                        $width = ((297 * 100) / $larghezzaform) / 2;
94
                    }
95 1
                    $pdf->MultiCell($width, $rowcount * $h, $valore, $border, $align, $fill, $ln);
96 1
                }
97 1
            }
98 1
            $pdf->Ln();
99 1
        }
100
101 1
        $pdf->Cell(0, 10, GrigliaFiltriUtils::traduciFiltri(array('filtri' => $risposta->filtri)), 0, false, 'L', 0, '', 0, false, 'T', 'M');
102
103
        /*
104
          I: send the file inline to the browser (default). The plug-in is used if available.
105
          The name given by name is used when one selects the “Save as” option on the link generating the PDF.
106
          D: send to the browser and force a file download with the name given by name.
107
          F: save to a local server file with the name given by name.
108
          S: return the document as a string (name is ignored).
109
          FI: equivalent to F + I option
110
          FD: equivalent to F + D option
111
          E: return the document as base64 mime multi-part email attachment (RFC 2045)
112
         */
113
114
        /* In caso il pdf stampato nel browser resti fisso a caricare la pagina,
115
          impostare 'D' per forzare lo scarico del file, oppure
116
          mettere exit al posto di return 0; questo opzione però non è accettata da gli strumenti di controllo del codice che non si
117
          aspettano exit nel codice
118
         */
119 1
        $pdf->Output($request->get('nometabella') . '.pdf', 'I');
120
121 1
        return 0;
122
    }
123
124
    public function esportaexcel($parametri = array())
125
    {
126
        set_time_limit(960);
127
        ini_set('memory_limit', '2048M');
128
129
        $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
130
        $cacheSettings = array('memoryCacheSize' => '8MB');
131
        \PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
132
133
        //Creare un nuovo file
134
        $objPHPExcel = new \PHPExcel();
135
136
        $objPHPExcel->setActiveSheetIndex(0);
137
138
        // Set properties
139
        $objPHPExcel->getProperties()->setCreator('Comune di Firenze');
140
        $objPHPExcel->getProperties()->setLastModifiedBy('Comune di Firenze');
141
142
        $testata = $parametri['testata'];
143
        $rispostaj = $parametri['griglia'];
144
145
        $modellicolonne = $testata['modellocolonne'];
146
147
        //Scrittura su file
148
        $sheet = $objPHPExcel->getActiveSheet();
149
        $titolosheet = 'Esportazione ' . $testata['tabella'];
150
        $sheet->setTitle(substr($titolosheet, 0, 30));
151
        $sheet->getParent()->getDefaultStyle()->getFont()->setName('Verdana');
152
153
        $this->printHeaderXls($modellicolonne, $testata, $sheet);
154
155
        $risposta = json_decode($rispostaj);
156
        if (isset($risposta->rows)) {
157
            $righe = $risposta->rows;
158
        } else {
159
            $righe = array();
160
        }
161
162
        $this->printBodyXls($righe, $modellicolonne, $sheet);
163
164
        //Si crea un oggetto
165
        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
166
        $todaydate = date('d-m-y');
167
168
        $filename = 'Exportazione_' . $testata['tabella'];
169
        $filename = $filename . '-' . $todaydate . '-' . strtoupper(md5(uniqid(rand(), true)));
170
        $filename = $filename . '.xls';
171
        $filename = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $filename;
172
173
        if (file_exists($filename)) {
174
            unlink($filename);
175
        }
176
177
        $objWriter->save($filename);
178
179
        return $filename;
180
    }
181
182 1
    private function printHeaderXls($modellicolonne, $testata, $sheet)
183
    {
184 1
        $indicecolonnaheader = 0;
185 1
        $letteracolonna = 0;
186 1
        foreach ($modellicolonne as $modellocolonna) {
187
            //Si imposta la larghezza delle colonne
188 1
            $letteracolonna = \PHPExcel_Cell::stringFromColumnIndex($indicecolonnaheader);
189 1
            $width = (int) $modellocolonna['width'] / 7;
190 1
            $indicecolonnaheadertitle = $testata['nomicolonne'][$indicecolonnaheader];
191 1
            $coltitlecalc = isset($indicecolonnaheadertitle) ? $indicecolonnaheadertitle : $modellocolonna['name'];
192 1
            $coltitle = strtoupper($coltitlecalc);
193 1
            $sheet->setCellValueByColumnAndRow($indicecolonnaheader, 1, $coltitle);
194 1
            $sheet->getColumnDimension($letteracolonna)->setWidth($width);
195
196 1
            ++$indicecolonnaheader;
197 1
        }
198
199 1
        if ($indicecolonnaheader > 0) {
200
            //Si imposta il colore dello sfondo delle celle
201
            //Colore header
202
            $style_header = array(
203
                'fill' => array(
204 1
                    'type' => \PHPExcel_Style_Fill::FILL_SOLID,
205 1
                    'color' => array('rgb' => '0404B4'),
206 1
                ),
207
                'font' => array(
208 1
                    'bold' => true,
209 1
                    'color' => array('rgb' => 'FFFFFF'),
210 1
                ),
211 1
            );
212 1
            $sheet->getStyle('A1:' . $letteracolonna . '1')->applyFromArray($style_header);
213 1
        }
214
215 1
        $sheet->getRowDimension('1')->setRowHeight(20);
216 1
    }
217
218
    private function getValueCell($tipocampo, $vettorecella)
219
    {
220
        $valore = null;
221
        switch ($tipocampo) {
222
            case 'date':
223
                $d = (int)substr($vettorecella, 0, 2);
224
                $m = (int)substr($vettorecella, 3, 2);
225
                $y = (int)substr($vettorecella, 6, 4);
226
                $t_date = \PHPExcel_Shared_Date::FormattedPHPToExcel($y, $m, $d);
227
                $valore = $t_date;
228
                break;
229
            case 'boolean':
230
                $valore = ($vettorecella == 1) ? 'SI' : 'NO';
231
                break;
232
            default:
233
                $valore = $vettorecella;
234
                break;
235
        }
236
        return $valore;
237
    }
238
239 1
    private function printBodyXls($righe, $modellicolonne, $sheet)
240
    {
241 1
        $row = 2;
242 1
        foreach ($righe as $riga) {
243 1
            $vettorecelle = $riga->cell;
244 1
            $col = 0;
245 1
            foreach ($vettorecelle as $vettorecella) {
246 1
                if ($vettorecella === '' || $vettorecella === null) {
247
                    $col = $col + 1;
248
                    continue;
249
                }
250 1
                $valore = $this->getValueCell($modellicolonne[$col]['tipocampo'], $vettorecella);
251 1
                $sheet->setCellValueByColumnAndRow($col, $row, $valore);
252 1
                $col = $col + 1;
253 1
            }
254 1
            $sheet->getRowDimension($row)->setRowHeight(18);
255 1
            ++$row;
256 1
        }
257
258 1
        $indicecolonna = 0;
259 1
        foreach ($modellicolonne as $modellocolonna) {
260 1
            $letteracolonna = \PHPExcel_Cell::stringFromColumnIndex($indicecolonna);
261 1
            switch ($modellocolonna['tipocampo']) {
262 1
                case 'text':
263
                    $sheet->getStyle($letteracolonna . '2:' . $letteracolonna . $row)
264
                            ->getNumberFormat()
265
                            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_GENERAL);
266
                    break;
267 1
                case 'string':
268 1
                    $sheet->getStyle($letteracolonna . '2:' . $letteracolonna . $row)
269 1
                            ->getNumberFormat()
270 1
                            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_GENERAL);
271 1
                    break;
272 1
                case 'integer':
273 1
                    $sheet->getStyle($letteracolonna . '2:' . $letteracolonna . $row)
274 1
                            ->getNumberFormat()
275 1
                            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_NUMBER);
276 1
                    break;
277
                case 'float':
278
                    $sheet->getStyle($letteracolonna . '2:' . $letteracolonna . $row)
279
                            ->getNumberFormat()
280
                            ->setFormatCode('#,##0.00');
281
                    break;
282
                case 'number':
283
                    $sheet->getStyle($letteracolonna . '2:' . $letteracolonna . $row)
284
                            ->getNumberFormat()
285
                            ->setFormatCode('#,##0.00');
286
                    break;
287
                case 'datetime':
288
                    $sheet->getStyle($letteracolonna . '2:' . $letteracolonna . $row)
289
                            ->getNumberFormat()
290
                            ->setFormatCode('dd/mm/yyyy');
291
                    break;
292
                case 'date':
293
                    $sheet->getStyle($letteracolonna . '2:' . $letteracolonna . $row)
294
                            ->getNumberFormat()
295
                            ->setFormatCode('dd/mm/yyyy');
296
                    break;
297
                default:
298
                    $sheet->getStyle($letteracolonna . '2:' . $letteracolonna . $row)
299
                            ->getNumberFormat()
300
                            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_GENERAL);
301
                    break;
302 1
            }
303
304 1
            ++$indicecolonna;
305 1
        }
306 1
    }
307
308 1
    private function stampaTestata($pdf, $nomicolonne, $modellicolonne, $larghezzaform, $h, $border, $align, $fill, $ln)
309
    {
310
        // Testata
311 1
        $pdf->SetFont('helvetica', 'B', 9);
312 1
        $arr_heights = array();
313
        // store current object
314 1
        $pdf->startTransaction();
315 1
        foreach ($nomicolonne as $posizione => $nomecolonna) {
316 1
            if (isset($modellicolonne[$posizione])) {
317 1
                $width = ((297 * $modellicolonne[$posizione]['width']) / $larghezzaform) / 2;
318 1
            } else {
319
                $width = ((297 * 100) / $larghezzaform) / 2;
320
            }
321
            // get the number of lines
322 1
            $arr_heights[] = $pdf->MultiCell($width, 0, $nomecolonna, $border, $align, $fill, 0, '', '', true, 0, false, true, 0);
323 1
        }
324
        // restore previous object
325 1
        $pdf->rollbackTransaction(true);
326
        //work out the number of lines required
327 1
        $rowcount = max($arr_heights);
328
        //now draw it
329 1
        foreach ($nomicolonne as $posizione => $nomecolonna) {
330 1
            if (isset($modellicolonne[$posizione])) {
331 1
                $width = ((297 * $modellicolonne[$posizione]['width']) / $larghezzaform) / 2;
332 1
            } else {
333
                $width = ((297 * 100) / $larghezzaform) / 2;
334
            }
335 1
            $pdf->MultiCell($width, $rowcount * $h, $nomecolonna, $border, $align, $fill, $ln);
336 1
        }
337 1
        $pdf->SetFont('helvetica', '', 9);
338 1
        $pdf->Ln();
339 1
    }
340
}
341