Completed
Push — master ( 838a39...006edc )
by Carlos
04:45
created

AreaChart::getData()   B

Complexity

Conditions 8
Paths 13

Size

Total Lines 46
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 28
c 1
b 0
f 0
dl 0
loc 46
rs 8.4444
cc 8
nc 13
nop 0
1
<?php
2
/**
3
 * This file is part of FacturaScripts
4
 * Copyright (C) 2019 Carlos Garcia Gomez <[email protected]>
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as
8
 * published by the Free Software Foundation, either version 3 of the
9
 * License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public License
17
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18
 */
19
namespace FacturaScripts\Core\Lib\ReportChart;
20
21
use FacturaScripts\Core\Base\DataBase;
22
use FacturaScripts\Dinamic\Model\Report;
0 ignored issues
show
Bug introduced by
The type FacturaScripts\Dinamic\Model\Report 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...
23
24
/**
25
 * Description of AreaChart
26
 *
27
 * @author Carlos Garcia Gomez <[email protected]>
28
 */
29
class AreaChart
30
{
31
32
    /**
33
     *
34
     * @var Report
35
     */
36
    protected $report;
37
38
    /**
39
     * 
40
     * @param Report $report
41
     */
42
    public function __construct($report)
43
    {
44
        $this->report = $report;
45
    }
46
47
    /**
48
     * 
49
     * @return array
50
     */
51
    public function getData(): array
52
    {
53
        $sources = $this->getDataSources();
54
        if (empty($sources)) {
55
            return [];
56
        }
57
58
        $labels = [];
59
60
        /// mix data of sources
61
        $mix = [];
62
        $num = 1;
63
        $countSources = count($sources);
64
        foreach ($sources as $source) {
65
            foreach ($source as $row) {
66
                $xcol = $row['xcol'];
67
                if (!isset($mix[$xcol])) {
68
                    $labels[] = $xcol;
69
70
                    $newItem = ['xcol' => $xcol];
71
                    for ($count = 1; $count <= $countSources; $count++) {
72
                        $newItem['ycol' . $count] = 0;
73
                    }
74
                    $mix[$xcol] = $newItem;
75
                }
76
77
                $mix[$xcol]['ycol' . $num] = $row['ycol'];
78
            }
79
            $num++;
80
        }
81
82
        sort($labels);
83
        ksort($mix);
84
85
        $datasets = [];
86
        foreach (array_keys($sources) as $pos => $label) {
87
            $num = 1 + $pos;
88
            $data = [];
89
            foreach ($mix as $row) {
90
                $data[] = $row['ycol' . $num];
91
            }
92
93
            $datasets[] = ['label' => $label, 'data' => $data];
94
        }
95
96
        return ['labels' => $labels, 'datasets' => $datasets];
97
    }
98
99
    /**
100
     * 
101
     * @return string
102
     */
103
    public function render(): string
104
    {
105
        $data = $this->getData();
106
        if (empty($data)) {
107
            return '';
108
        }
109
110
        $canvasId = 'chart' . mt_rand();
111
        $html = '<canvas id="' . $canvasId . '" height="60"/>'
112
            . "<script>var ctx = document.getElementById('" . $canvasId . "').getContext('2d');"
113
            . "var myChart = new Chart(ctx, {
114
    type: 'line',
115
    data: {
116
        labels: ['" . implode("','", $data['labels']) . "'],
117
        datasets: [" . $this->renderDatasets($data['datasets']) . "]
118
    },
119
    options: {}
120
});</script>";
121
122
        return $html;
123
    }
124
125
    /**
126
     * 
127
     * @return array
128
     */
129
    protected function getDataSources(): array
130
    {
131
        $dataBase = new DataBase();
132
        $sql = $this->getSql($this->report);
133
        if (empty($sql) || !$dataBase->tableExists($this->report->table)) {
134
            return [];
135
        }
136
137
        $sources = [];
138
        $sources[$this->report->name] = $dataBase->select($sql);
139
140
        $comparedReport = new Report();
141
        if (!empty($this->report->compared) && $comparedReport->loadFromCode($this->report->compared)) {
142
            $sources[$comparedReport->name] = $dataBase->select($this->getSql($comparedReport));
143
        }
144
145
        return $sources;
146
    }
147
148
    /**
149
     * 
150
     * @param Report $report
151
     *
152
     * @return string
153
     */
154
    protected function getSql($report): string
155
    {
156
        if (empty($report->table) || empty($report->xcolumn)) {
157
            return '';
158
        }
159
160
        $xcol = $report->xcolumn;
161
        switch ($report->xoperation) {
162
            case 'DAY':
163
                $xcol = "DATE_FORMAT(" . $report->xcolumn . ", '%Y-%m-%d')";
164
                break;
165
166
            case 'MONTH':
167
                $xcol = "DATE_FORMAT(" . $report->xcolumn . ", '%Y-%m')";
168
                break;
169
170
            case 'UNIXTIME_DAY':
171
                $xcol = "DATE_FORMAT(FROM_UNIXTIME(" . $report->xcolumn . "), '%Y-%m-%d')";
172
                break;
173
174
            case 'UNIXTIME_MONTH':
175
                $xcol = "DATE_FORMAT(FROM_UNIXTIME(" . $report->xcolumn . "), '%Y-%m')";
176
                break;
177
178
            case 'UNIXTIME_YEAR':
179
                $xcol = "DATE_FORMAT(FROM_UNIXTIME(" . $report->xcolumn . "), '%Y')";
180
                break;
181
182
            case 'YEAR':
183
                $xcol = "DATE_FORMAT(" . $report->xcolumn . ", '%Y')";
184
                break;
185
        }
186
187
        $ycol = empty($report->ycolumn) ? 'COUNT(*)' : 'SUM(' . $report->ycolumn . ')';
188
189
        return 'SELECT ' . $xcol . ' as xcol, ' . $ycol . ' as ycol'
190
            . ' FROM ' . $report->table . ' GROUP BY xcol ORDER BY xcol ASC;';
191
    }
192
193
    /**
194
     * 
195
     * @param array $datasets
196
     *
197
     * @return string
198
     */
199
    protected function renderDatasets($datasets): string
200
    {
201
        $colors = ['255, 99, 132', '54, 162, 235', '255, 206, 86'];
202
203
        $items = [];
204
        $num = 0;
205
        foreach ($datasets as $dataset) {
206
            $color = isset($colors[$num]) ? $colors[$num] : '255, 206, 86';
207
            $num++;
208
209
            $items[] = "{
210
            label: '" . $dataset['label'] . "',
211
            data: [" . implode(",", $dataset['data']) . "],
212
            backgroundColor: [
213
                'rgba(" . $color . ", 0.2)'
214
            ],
215
            borderColor: [
216
                'rgba(" . $color . ", 1)'
217
            ],
218
            borderWidth: 1
219
        }";
220
        }
221
222
        return implode(',', $items);
223
    }
224
}
225