Completed
Branch master (3ee61a)
by Patrick
03:04
created

ExcelSerializer::serializeData()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 31
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 2 Features 1
Metric Value
cc 6
eloc 21
c 3
b 2
f 1
nc 6
nop 2
dl 0
loc 31
rs 8.439
1
<?php
2
namespace Serialize;
3
4
require_once dirname(__FILE__).'/../libs/PHPExcel/Classes/PHPExcel.php';
5
6
class ExcelSerializer extends SpreadSheetSerializer
7
{
8
    protected $types = array('xlsx', 'xls', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel');
9
10
    protected function setRowFromArray(&$sheat, $row, $array, $count=0)
11
    {
12
        if($count === 0)
13
        {
14
            $count = count($array);
15
        }
16
        for($i = 0; $i < $count; $i++)
17
        {
18
            $sheat->setCellValueByColumnAndRow($i, $row, $array[$i]);
19
        }
20
    }
21
22
    public function serializeData($type, $array)
23
    {
24
        if($this->supportsType($type) === false)
25
        {
26
            return null;
27
        }
28
        if(count($array) === 0)
29
        {
30
            return null;
31
        }
32
        $data = $this->getArray($array);
33
        $ssheat = new \PHPExcel();
34
        $sheat = $ssheat->setActiveSheetIndex(0);
35
        $keys = array_shift($data);
36
        $rowCount = count($data);
37
        $colCount = count($keys);
38
        $this->setRowFromArray($sheat, 1, $keys, $colCount);
39
        for($i = 0; $i < $rowCount; $i++)
40
        {
41
            $this->setRowFromArray($sheat, (2 + $i), $data[$i], $colCount);
42
        }
43
        $writerType = 'Excel5';
44
        if(strcasecmp($type, 'xlsx') === 0 || strcasecmp($type, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') === 0)
45
        {
46
            $writerType = 'Excel2007';
47
        }
48
        $writer = \PHPExcel_IOFactory::createWriter($ssheat, $writerType);
49
        ob_start();
50
        $writer->save('php://output');
51
        return ob_get_clean();
52
    }
53
}
54