Completed
Push — master ( d95d7a...9b093a )
by Andrea
52:34 queued 49:57
created

StampatabellaController::esportaexcel()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 58
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 58
ccs 0
cts 33
cp 0
rs 9.639
c 0
b 0
f 0
cc 3
eloc 34
nc 4
nop 1
crap 12

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 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
                    } 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
                    //$arr_heights[] = $pdf->getNumLines($valore, $width);
0 ignored issues
show
Unused Code Comprehensibility introduced by
69% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
75
                }
76
            }
77
            // restore previous object
78 1
            $pdf->rollbackTransaction(true);
79
            //work out the number of lines required
80 1
            $rowcount = max($arr_heights);
81 1
            $startY = $pdf->GetY();
82 1
            if (($startY + $rowcount * $h) + $dimensions['bm'] > ($dimensions['hk'])) {
83
                // page break
84
                $pdf->AddPage('L');
85
                // stampa testata
86
                $this->stampaTestata($pdf, $nomicolonne, $modellicolonne, $larghezzaform, $h, $border, $align, $fill, $ln);
87
            }
88
            //now draw it
89 1
            foreach ($vettorecelle as $posizione => $valore) {
90 1
                if (!is_object($valore)) {
91 1
                    if (isset($modellicolonne[$posizione])) {
92 1
                        $width = ((297 * $modellicolonne[$posizione]['width']) / $larghezzaform) / 2;
93
                    } else {
94
                        $width = ((297 * 100) / $larghezzaform) / 2;
95
                    }
96 1
                    $pdf->MultiCell($width, $rowcount * $h, $valore, $border, $align, $fill, $ln);
97
                }
98
            }
99 1
            $pdf->Ln();
100
        }
101
102 1
        $pdf->Cell(0, 10, GrigliaFiltriUtils::traduciFiltri(array('filtri' => $risposta->filtri)), 0, false, 'L', 0, '', 0, false, 'T', 'M');
103
104
        /*
105
          I: send the file inline to the browser (default). The plug-in is used if available.
106
          The name given by name is used when one selects the “Save as” option on the link generating the PDF.
107
          D: send to the browser and force a file download with the name given by name.
108
          F: save to a local server file with the name given by name.
109
          S: return the document as a string (name is ignored).
110
          FI: equivalent to F + I option
111
          FD: equivalent to F + D option
112
          E: return the document as base64 mime multi-part email attachment (RFC 2045)
113
         */
114
115
        /* In caso il pdf stampato nel browser resti fisso a caricare la pagina,
116
          impostare 'D' per forzare lo scarico del file, oppure
117
          mettere exit al posto di return 0; questo opzione però non è accettata da gli strumenti di controllo del codice che non si
118
          aspettano exit nel codice
119
         */
120 1
        $pdf->Output($request->get('nometabella') . '.pdf', 'I');
121
122 1
        return 0;
123
    }
124
125
    public function esportaexcel($parametri = array())
126
    {
127
        set_time_limit(960);
128
        ini_set('memory_limit', '2048M');
129
130
        $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
131
        $cacheSettings = array('memoryCacheSize' => '8MB');
132
        \PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
133
134
        //Creare un nuovo file
135
        $objPHPExcel = new \PHPExcel();
136
137
        $objPHPExcel->setActiveSheetIndex(0);
138
139
        // Set properties
140
        $objPHPExcel->getProperties()->setCreator('Comune di Firenze');
141
        $objPHPExcel->getProperties()->setLastModifiedBy('Comune di Firenze');
142
143
        $testata = $parametri['testata'];
144
        $rispostaj = $parametri['griglia'];
145
146
        $modellicolonne = $testata['modellocolonne'];
147
148
        //Scrittura su file
149
        $sheet = $objPHPExcel->getActiveSheet();
150
        $titolosheet = 'Esportazione ' . $testata['tabella'];
151
        $sheet->setTitle(substr($titolosheet, 0, 30));
152
        $sheet->getParent()->getDefaultStyle()->getFont()->setName('Verdana');
153
154
        $this->printHeaderXls($modellicolonne, $testata, $sheet);
155
156
        $risposta = json_decode($rispostaj);
157
        if (isset($risposta->rows)) {
158
            $righe = $risposta->rows;
159
        } else {
160
            $righe = array();
161
        }
162
163
        $this->printBodyXls($righe, $modellicolonne, $sheet);
164
165
        //Si crea un oggetto
166
        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
167
        $todaydate = date('d-m-y');
168
169
        //$todaydate = $todaydate . '-' . date("H-i-s");
0 ignored issues
show
Unused Code Comprehensibility introduced by
42% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
170
        $filename = 'Exportazione_' . $testata['tabella'];
171
        $filename = $filename . '-' . $todaydate . '-' . strtoupper(md5(uniqid(rand(), true)));
172
        $filename = $filename . '.xls';
173
        $filename = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $filename;
174
175
        if (file_exists($filename)) {
176
            unlink($filename);
177
        }
178
179
        $objWriter->save($filename);
180
181
        return $filename;
182
    }
183
184 1
    private function printHeaderXls($modellicolonne, $testata, $sheet)
185
    {
186 1
        $indicecolonnaheader = 0;
187 1
        $letteracolonna = 0;
188 1
        foreach ($modellicolonne as $modellocolonna) {
189
            //Si imposta la larghezza delle colonne
190 1
            $letteracolonna = \PHPExcel_Cell::stringFromColumnIndex($indicecolonnaheader);
191 1
            $width = (int) $modellocolonna['width'] / 7;
192 1
            $indicecolonnaheadertitle = $testata['nomicolonne'][$indicecolonnaheader];
193 1
            $coltitlecalc = isset($indicecolonnaheadertitle) ? $indicecolonnaheadertitle : $modellocolonna['name'];
194 1
            $coltitle = strtoupper($coltitlecalc);
195 1
            $sheet->setCellValueByColumnAndRow($indicecolonnaheader, 1, $coltitle);
196 1
            $sheet->getColumnDimension($letteracolonna)->setWidth($width);
197
198 1
            ++$indicecolonnaheader;
199
        }
200
201 1
        if ($indicecolonnaheader > 0) {
202
            //Si imposta il colore dello sfondo delle celle
203
            //Colore header
204
            $style_header = array(
205 1
                'fill' => array(
206 1
                    'type' => \PHPExcel_Style_Fill::FILL_SOLID,
207
                    'color' => array('rgb' => '0404B4'),
208
                ),
209
                'font' => array(
210
                    'bold' => true,
211
                    'color' => array('rgb' => 'FFFFFF'),
212
                ),
213
            );
214 1
            $sheet->getStyle('A1:' . $letteracolonna . '1')->applyFromArray($style_header);
215
        }
216
217 1
        $sheet->getRowDimension('1')->setRowHeight(20);
218 1
    }
219
220
    private function getValueCell($tipocampo, $vettorecella)
221
    {
222
        $valore = null;
0 ignored issues
show
Unused Code introduced by
$valore is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
223
        switch ($tipocampo) {
224
            case 'date':
225
                $d = substr($vettorecella, 0, 2);
226
                $m = substr($vettorecella, 3, 2);
227
                $y = substr($vettorecella, 6, 4);
228
                $t_date = \PHPExcel_Shared_Date::FormattedPHPToExcel($y, $m, $d);
0 ignored issues
show
Documentation introduced by
$y is of type string, but the function expects a object<long>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
$m is of type string, but the function expects a object<long>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
$d is of type string, but the function expects a object<long>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
229
                $valore = $t_date;
230
                break;
231
            case 'boolean':
232
                $valore = ($vettorecella == 1) ? 'SI' : 'NO';
233
                break;
234
            default:
235
                $valore = $vettorecella;
236
                break;
237
        }
238
        return $valore;
239
    }
240
241 1
    private function printBodyXls($righe, $modellicolonne, $sheet)
242
    {
243 1
        $row = 2;
244 1
        foreach ($righe as $riga) {
245 1
            $vettorecelle = $riga->cell;
246 1
            $col = 0;
247 1
            foreach ($vettorecelle as $vettorecella) {
248 1
                if ($vettorecella === '' || $vettorecella === null) {
249
                    $col = $col + 1;
250
                    continue;
251
                }
252 1
                $valore = $this->getValueCell($modellicolonne[$col]['tipocampo'], $vettorecella);
253 1
                $sheet->setCellValueByColumnAndRow($col, $row, $valore);
254 1
                $col = $col + 1;
255
            }
256 1
            $sheet->getRowDimension($row)->setRowHeight(18);
257 1
            ++$row;
258
        }
259
260 1
        $indicecolonna = 0;
261 1
        foreach ($modellicolonne as $modellocolonna) {
262 1
            $letteracolonna = \PHPExcel_Cell::stringFromColumnIndex($indicecolonna);
263 1
            switch ($modellocolonna['tipocampo']) {
264
                case 'text':
265
                    $sheet->getStyle($letteracolonna . '2:' . $letteracolonna . $row)
266
                            ->getNumberFormat()
267
                            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_GENERAL);
268
                    break;
269
                case 'string':
270 1
                    $sheet->getStyle($letteracolonna . '2:' . $letteracolonna . $row)
271 1
                            ->getNumberFormat()
272 1
                            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_GENERAL);
273 1
                    break;
274
                case 'integer':
275 1
                    $sheet->getStyle($letteracolonna . '2:' . $letteracolonna . $row)
276 1
                            ->getNumberFormat()
277 1
                            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_NUMBER);
278 1
                    break;
279
                case 'float':
280
                    $sheet->getStyle($letteracolonna . '2:' . $letteracolonna . $row)
281
                            ->getNumberFormat()
282
                            ->setFormatCode('#,##0.00');
283
                    break;
284
                case 'number':
285
                    $sheet->getStyle($letteracolonna . '2:' . $letteracolonna . $row)
286
                            ->getNumberFormat()
287
                            ->setFormatCode('#,##0.00');
288
                    break;
289
                case 'datetime':
290
                    $sheet->getStyle($letteracolonna . '2:' . $letteracolonna . $row)
291
                            ->getNumberFormat()
292
                            ->setFormatCode('dd/mm/yyyy');
293
                    break;
294
                case 'date':
295
                    $sheet->getStyle($letteracolonna . '2:' . $letteracolonna . $row)
296
                            ->getNumberFormat()
297
                            ->setFormatCode('dd/mm/yyyy');
298
                    break;
299
                default:
300
                    $sheet->getStyle($letteracolonna . '2:' . $letteracolonna . $row)
301
                            ->getNumberFormat()
302
                            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_GENERAL);
303
                    break;
304
            }
305
306 1
            ++$indicecolonna;
307
        }
308 1
    }
309
310 1
    private function stampaTestata($pdf, $nomicolonne, $modellicolonne, $larghezzaform, $h, $border, $align, $fill, $ln)
311
    {
312
        // Testata
313 1
        $pdf->SetFont('helvetica', 'B', 9);
314 1
        $arr_heights = array();
315
        // store current object
316 1
        $pdf->startTransaction();
317 1
        foreach ($nomicolonne as $posizione => $nomecolonna) {
318 1
            if (isset($modellicolonne[$posizione])) {
319 1
                $width = ((297 * $modellicolonne[$posizione]['width']) / $larghezzaform) / 2;
320
            } else {
321
                $width = ((297 * 100) / $larghezzaform) / 2;
322
            }
323
            // get the number of lines
324 1
            $arr_heights[] = $pdf->MultiCell($width, 0, $nomecolonna, $border, $align, $fill, 0, '', '', true, 0, false, true, 0);
325
            //$arr_heights[] = $pdf->getNumLines($nomecolonna, $width, FALSE, TRUE, '', 1);
0 ignored issues
show
Unused Code Comprehensibility introduced by
68% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
326
        }
327
        // restore previous object
328 1
        $pdf->rollbackTransaction(true);
329
        //work out the number of lines required
330 1
        $rowcount = max($arr_heights);
331
        //now draw it
332 1
        foreach ($nomicolonne as $posizione => $nomecolonna) {
333 1
            if (isset($modellicolonne[$posizione])) {
334 1
                $width = ((297 * $modellicolonne[$posizione]['width']) / $larghezzaform) / 2;
335
            } else {
336
                $width = ((297 * 100) / $larghezzaform) / 2;
337
            }
338 1
            $pdf->MultiCell($width, $rowcount * $h, $nomecolonna, $border, $align, $fill, $ln);
339
        }
340 1
        $pdf->SetFont('helvetica', '', 9);
341 1
        $pdf->Ln();
342 1
    }
343
}
344