-
Notifications
You must be signed in to change notification settings - Fork 4
/
Chart.php
267 lines (226 loc) · 7.73 KB
/
Chart.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
<?php
declare(strict_types=1);
namespace Atk4\Chart;
use Atk4\Core\Exception;
use Atk4\Data\Model;
use Atk4\Ui\JsExpression;
use Atk4\Ui\View;
class Chart extends View
{
/** @var string HTML element type */
public $element = 'canvas';
/** @var string Type of chart - bar|pie etc. */
public $type;
/** @var bool should we add JS include into application body? Set "false" if you do it manually. */
public $js_include = true;
/** @var array We will use these colors in charts */
public $nice_colors = [
['rgba(255, 99, 132, 0.2)', 'rgba(255,99,132,1)'],
['rgba(54, 162, 235, 0.2)', 'rgba(54, 162, 235, 1)'],
['rgba(255, 206, 86, 0.2)', 'rgba(255, 206, 86, 1)'],
['rgba(75, 192, 192, 0.2)', 'rgba(75, 192, 192, 1)'],
['rgba(153, 102, 255, 0.2)', 'rgba(153, 102, 255, 1)'],
['rgba(255, 159, 64, 0.2)', 'rgba(255, 159, 64, 1)'],
];
/** @var array Options for chart.js widget */
public $options = [];
/** @var array Labels for axis. Fills with setModel(). */
protected $labels;
/** @var array Datasets. Fills with setModel(). */
protected $datasets;
protected function init(): void
{
parent::init();
if ($this->js_include) {
$this->getApp()->requireJs('https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.js');
}
}
public function renderView(): void
{
$this->js(true, new JsExpression('new Chart([], []);', [$this->name, $this->getConfig()]));
parent::renderView();
}
public function getConfig(): array
{
return [
'type' => $this->type,
'data' => [
'labels' => $this->getLabels(),
'datasets' => $this->getDatasets(),
],
'options' => $this->getOptions(),
];
}
public function getLabels(): array
{
return $this->labels;
}
public function getDatasets(): array
{
return array_values($this->datasets);
}
public function getOptions(): array
{
return $this->options;
}
/**
* @return $this
*/
public function setOptions(array $options)
{
// IMPORTANT: use replace not merge here to preserve numeric keys !!!
$this->options = array_replace_recursive($this->options, $options);
return $this;
}
/**
* Specify data source for this chart. The column must contain
* the textual column first followed by sumber of data columns:
* setModel($month_report, ['month', 'total_sales', 'total_purchases']);.
*
* This component will automatically figure out name of the chart,
* series titles based on column captions etc.
*/
public function setModel(Model $model, array $columns = []): void
{
if (!$columns) {
throw new Exception('Second argument must be specified to Chart::setModel()');
}
$this->datasets = [];
// initialize data-sets
foreach ($columns as $key => $column) {
if ($key === 0) {
$titleColumn = $column;
continue; // skipping labels
}
$colors = array_shift($this->nice_colors);
$this->datasets[$column] = [
'label' => $model->getField($column)->getCaption(),
'backgroundColor' => $colors[0],
'borderColor' => $colors[1],
'borderWidth' => 1,
'data' => [],
];
}
// prepopulate data-sets
foreach ($model as $row) {
$this->labels[] = $row->get($titleColumn); // @phpstan-ignore-line
foreach ($this->datasets as $key => &$dataset) {
$dataset['data'][] = $row->get($key);
}
}
}
/**
* Add currency label.
*
* @param string $char Currency symbol
* @param string $axis y or x
*
* @return $this
*/
public function withCurrency(string $char = '€', string $axis = 'y')
{
// magic regex adds commas as thousand separators: http://009co.com/?p=598
$options['scales'][$axis . 'Axes'] =
[['ticks' => [
'userCallback' => new JsExpression('{}', ['function(value) { value=Math.round(value*1000000)/1000000; return "' . $char . ' " + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); }']),
]]];
$options['tooltips'] = [
'enabled' => true,
'mode' => 'single',
'callbacks' => ['label' => new JsExpression('{}', ['function(item, data) { return item.' . $axis . 'Label ? "' . $char . ' " + item.' . $axis . 'Label.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : "No Data"; }'])],
];
$this->setOptions($options);
return $this;
}
/**
* Add currency label to X axis.
*
* @param string $char Currency symbol
*
* @return $this
*/
public function withCurrencyX(string $char = '€')
{
return $this->withCurrency($char, 'x');
}
/**
* Add currency label to Y axis.
*
* @param string $char Currency symbol
*
* @return $this
*/
public function withCurrencyY(string $char = '€')
{
return $this->withCurrency($char, 'y');
}
/**
* Will produce a graph showing summary of a certain model by grouping and aggregating data.
*
* Example:
*
* // Pie or Bar chart
* $chart->summarize($users, ['by' => 'status', 'fx' => 'count']);
* $chart->summarize($users, ['by' => 'status', 'fx' => 'sum', 'field' => 'total_net']);
*
* or
*
* // Bar chart
* $orders = $clients->ref('Orders');
* $chart->summarize($orders, [
* 'by'=>$orders->expr('year([date])'),
* 'fields'=>[
* 'purchase' => $orders->expr('sum(if([is_purchase], [amount], 0)'),
* 'sale' => $orders->expr('sum(if([is_purchase], 0, [amount])'),
* ],
* ])->withCurrency('$');
*
* @return $this
*/
public function summarize(Model $model, array $options = [])
{
$fields = ['by'];
// first lets query data
if (isset($options['fields'])) {
$qq = $model->action('select', [[]]);
// now add fields
foreach ($options['fields'] as $alias => $field) {
if (is_numeric($alias)) {
$alias = $field;
}
if (is_string($field)) {
// sanitization needed!
$field = $model->expr(($options['fx'] ?? '') . '([' . $field . '])');
}
$qq->field($field, $alias);
$fields[] = $alias;
}
} else {
$fx = $options['fx'] ?? 'count';
if ($fx === 'count') {
$qq = $model->action('count', ['alias' => $fx]);
$fields[] = $fx;
} elseif (isset($options['fx'])) {
$qq = $model->action('fx', [$fx, $options['field'] ?? $model->expr('*'), 'alias' => $fx]);
$fields[] = $fx;
} else {
$qq = $model->action('select', [[$model->titleField]]);
$fields[] = $model->titleField;
}
}
// next we need to group
if ($options['by'] ?? null) {
$field = $options['by'];
if (is_string($field)) {
$field = $model->getField($field);
}
$qq->field($field, 'by');
$qq->group('by');
} else {
$qq->field($model->getField($model->titleField), 'by');
}
// and then set it as chart source
$this->setSource($qq->getRows(), $fields);
return $this;
}
}