DataOutput::draw()   B
last analyzed

Complexity

Conditions 8
Paths 23

Size

Total Lines 34
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 8

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 20
c 1
b 0
f 0
nc 23
nop 2
dl 0
loc 34
ccs 20
cts 20
cp 1
crap 8
rs 8.4444
1
<?php
2
3
namespace CMEN\GoogleChartsBundle\Output\Javascript;
4
5
use CMEN\GoogleChartsBundle\Exception\GoogleChartsException;
6
use CMEN\GoogleChartsBundle\GoogleCharts\Data;
7
use CMEN\GoogleChartsBundle\Output\DataOutputInterface;
8
use CMEN\GoogleChartsBundle\Output\DateOutputInterface;
9
10
/**
11
 * @author Christophe Meneses
12
 */
13
class DataOutput implements DataOutputInterface
14
{
15 5
    public function __construct(private readonly DateOutputInterface $dateOutput)
16
    {
17 5
    }
18
19 5
    public function draw(Data $data, string $dataName): string
20
    {
21 5
        $arrayToDataTable = $data->getArrayToDataTable();
22
23 5
        if (empty($arrayToDataTable)) {
24 1
            throw new GoogleChartsException('There is no data for chart. Use method setArrayToDataTable() to provide data.');
25
        }
26
27 4
        $js = "var $dataName = new google.visualization.arrayToDataTable([";
28 4
        $lastKeyRow = array_key_last($arrayToDataTable);
29 4
        foreach ($data->getArrayToDataTable() as $keyRow => $row) {
30 4
            $js .= '[';
31 4
            $lastKeyValue = array_key_last($row);
32 4
            foreach ($row as $key => $value) {
33 4
                if ($value instanceof \DateTimeInterface) {
34 2
                    $js .= $this->dateOutput->draw($value);
35
                } else {
36 4
                    $js .= json_encode($value);
37
                }
38
39 4
                if ($key != $lastKeyValue) {
40 4
                    $js .= ', ';
41
                }
42
            }
43 4
            $js .= ']';
44
45 4
            if ($keyRow != $lastKeyRow) {
46 4
                $js .= ', ';
47
            }
48
        }
49
50 4
        $data->isFirstRowIsData() ? $js .= '], true);' : $js .= '], false);';
51
52 4
        return $js;
53
    }
54
}
55