chart.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. <?php /** @noinspection DuplicatedCode */
  2. /** @noinspection PhpUnused */
  3. /** @noinspection PhpUndefinedMethodInspection */
  4. /** @noinspection PhpUnusedLocalVariableInspection */
  5. use PhpOffice\PhpPresentation\Slide;
  6. use PhpOffice\PhpPresentation\Style\Alignment;
  7. class Chart {
  8. const DATALABELS_BOX = [
  9. "backgroundColor" => "rgba(0, 0, 0, 0.75)",
  10. "borderRadius" => "2",
  11. ];
  12. const COLOURS = [
  13. "#f44336",
  14. "#673ab7",
  15. "#03a9f4",
  16. "#4caf50",
  17. "#ffeb3b",
  18. "#ff5722",
  19. "#607d8b",
  20. "#e91e63",
  21. "#3f51b5",
  22. "#00bcd4",
  23. "#8bc34a",
  24. "#ffc107",
  25. "#795548",
  26. "#9c27b0",
  27. "#2196f3",
  28. "#009688",
  29. "#cddc39",
  30. "#ff9800",
  31. "#9e9e9e",
  32. ];
  33. private $id = "";
  34. private $title = "Untitled";
  35. private $type = "bar";
  36. private $datasets = [];
  37. private $printDatasets = [];
  38. private $labels = [];
  39. private $printLabels = null;
  40. private $tooltipsMode = "nearest";
  41. private $tooltipsIntersect = true;
  42. private $xAxes = [];
  43. private $yAxes = [];
  44. private $datalabelSuffixes = [];
  45. private $datalabelFormatterCallback = false;
  46. private $printSuffixes = null;
  47. public $beforeHtml = null;
  48. public $afterHtml = null;
  49. public $print = false;
  50. public $printPercentages = false;
  51. public $printTotalColumn = false;
  52. /**
  53. * Chart constructor.
  54. * @throws Exception
  55. */
  56. public function __construct() {
  57. $this->id = bin2hex(random_bytes(8));
  58. }
  59. public function addXAxis($options = []) {
  60. $type = $options["type"] ?? "linear";
  61. $position = $options["position"] ?? "bottom";
  62. $id = $options["id"] ?? "x-axis";
  63. $grid_lines = $options["grid_lines"] ?? true;
  64. $tick_config = $options["tick_config"] ?? null;
  65. $scale_label_config = $options["scale_label_config"] ?? null;
  66. $stacked = $options["stacked"] ?? false;
  67. $axis = [
  68. "type" => $type,
  69. "display" => true,
  70. "position" => $position,
  71. "id" => $id,
  72. "gridLines" => [
  73. "drawOnChartArea" => $grid_lines
  74. ],
  75. "stacked" => $stacked,
  76. ];
  77. if($tick_config) {
  78. $axis["ticks"] = $tick_config;
  79. }
  80. if($scale_label_config) {
  81. $axis["scaleLabel"] = $scale_label_config;
  82. }
  83. $this->xAxes[] = $axis;
  84. }
  85. public function addYAxis($options = []) {
  86. $type = $options["type"] ?? "linear";
  87. $position = $options["position"] ?? "left";
  88. $id = $options["id"] ?? "y-axis-0";
  89. $grid_lines = $options["grid_lines"] ?? true;
  90. $tick_config = $options["tick_config"] ?? null;
  91. $scale_label_config = $options["scale_label_config"] ?? null;
  92. $stacked = $options["stacked"] ?? false;
  93. $axis = [
  94. "type" => $type,
  95. "display" => true,
  96. "position" => $position,
  97. "id" => $id,
  98. "gridLines" => [
  99. "drawOnChartArea" => $grid_lines
  100. ],
  101. "stacked" => $stacked,
  102. ];
  103. if($tick_config) {
  104. $axis["ticks"] = $tick_config;
  105. }
  106. $this->yAxes[] = $axis;
  107. }
  108. public function getID() {
  109. return $this->id;
  110. }
  111. public function getTitle() {
  112. return $this->title;
  113. }
  114. public function setTitle($title) {
  115. $this->title = $title;
  116. }
  117. public function setType($type) {
  118. $this->type = $type;
  119. }
  120. public function addDataset($label, $data, $options = []) {
  121. $background_colours = $options["background_colours"] ?? false;
  122. $border_colours = $options["border_colours"] ?? false;
  123. $border_width = $options["border_width"] ?? false;
  124. $y_axis_id = $options["y_axis_id"] ?? false;
  125. $type = $options["type"] ?? false;
  126. $datalabels = $options["datalabels"] ?? false;
  127. $line_tension = $options["line_tension"] ?? null;
  128. $dataset = [
  129. "label" => $label,
  130. "data" => $data,
  131. ];
  132. if($background_colours) $dataset["backgroundColor"] = $background_colours;
  133. if($border_colours) $dataset["borderColor"] = $border_colours;
  134. if($border_width) $dataset["borderWidth"] = (int) $border_width;
  135. if($y_axis_id) $dataset["yAxisID"] = $y_axis_id;
  136. if($type) $dataset["type"] = $type;
  137. if($datalabels) $dataset["datalabels"] = $datalabels;
  138. if(isset($line_tension)) $dataset["lineTension"] = $line_tension;
  139. $this->datasets[] = (object) $dataset;
  140. }
  141. public function addPrintDataset($label, $data) {
  142. $dataset = [
  143. "label" => $label,
  144. "data" => $data,
  145. ];
  146. $this->printDatasets[] = (object) $dataset;
  147. }
  148. public function getDatasets() {
  149. return $this->datasets;
  150. }
  151. public function getPrintDatasets() {
  152. return $this->printDatasets;
  153. }
  154. public function getLabels() {
  155. return $this->labels;
  156. }
  157. public function setLabels($labels) {
  158. $this->labels = $labels;
  159. }
  160. public function getPrintLabels() {
  161. return $this->printLabels;
  162. }
  163. public function setPrintLabels($labels) {
  164. $this->printLabels = $labels;
  165. }
  166. public function getDatalabelSuffixes() {
  167. return $this->datalabelSuffixes;
  168. }
  169. public function setDatalabelSuffixes(... $suffixes) {
  170. $this->datalabelSuffixes = $suffixes;
  171. }
  172. public function setDatalabelFormatterCallback($callback) {
  173. $this->datalabelFormatterCallback = $callback;
  174. }
  175. public function getPrintSuffixes() {
  176. return $this->printSuffixes;
  177. }
  178. public function setPrintSuffixes(... $suffixes) {
  179. $this->printSuffixes = $suffixes;
  180. }
  181. public function getJSON() {
  182. $object = (object) [
  183. "type" => $this->type,
  184. "data" => (object) [
  185. "labels" => $this->labels,
  186. "datasets" => $this->datasets
  187. ],
  188. "options" => (object) [
  189. "title" => (object) [
  190. "display" => true,
  191. "fontSize" => 32,
  192. "fontFamily" => "Roboto",
  193. "fontStyle" => "300",
  194. "text" => $this->title
  195. ],
  196. "legend" => (object) [
  197. "position" => "top",
  198. ],
  199. "tooltips" => (object) [
  200. "mode" => $this->tooltipsMode,
  201. "intersect" => $this->tooltipsIntersect,
  202. ],
  203. "plugins" => (object) [
  204. "datalabels" => [
  205. "color" => "white",
  206. ],
  207. ],
  208. ],
  209. ];
  210. if($this->xAxes || $this->yAxes) {
  211. $object->options->scales = new stdClass;
  212. if($this->xAxes) {
  213. $object->options->scales->xAxes = $this->xAxes;
  214. }
  215. if($this->yAxes) {
  216. $object->options->scales->yAxes = $this->yAxes;
  217. }
  218. }
  219. if($this->datalabelSuffixes) {
  220. $object->options->datalabelSuffixes = $this->datalabelSuffixes;
  221. }
  222. if($this->datalabelFormatterCallback) {
  223. $object->datalabelFormatterCallback = $this->datalabelFormatterCallback;
  224. }
  225. return json_encode($object);
  226. }
  227. public function renderCanvasHtml() {
  228. ?>
  229. <canvas id="<?=$this->getID()?>" data-chart="<?=htmlspecialchars($this->getJSON())?>" width="400" height="300">
  230. </canvas>
  231. <?php
  232. }
  233. public function printDataTable(): void {
  234. $row_labels = $this->printLabels ?? $this->labels;
  235. $print_total_row = $this->printTotalColumn;
  236. $print_percentage_column = $this->printPercentages;
  237. $suffixes = $this->printSuffixes ?? $this->datalabelSuffixes;
  238. $datasets = array_merge($this->datasets, $this->printDatasets);
  239. $total_count = array_sum($datasets[0]->data);
  240. ?>
  241. <table class="mt-3 w-100 table table-sm small table-bordered">
  242. <thead>
  243. <tr>
  244. <th>Name</th>
  245. <?php
  246. foreach($datasets as $dataset) {
  247. ?>
  248. <th><?=htmlspecialchars($dataset->label)?></th>
  249. <?php
  250. }
  251. if($print_percentage_column) {
  252. ?>
  253. <th><?=htmlspecialchars(__("Percentage"))?></th>
  254. <?php
  255. }
  256. ?>
  257. </tr>
  258. </thead>
  259. <tbody>
  260. <?php
  261. $data = [];
  262. foreach($datasets as $column_index => $dataset) {
  263. foreach($dataset->data as $row_index => $value) {
  264. $data[$row_index][$column_index] = $value;
  265. }
  266. }
  267. foreach($data as $row_index => $columns) {
  268. ?>
  269. <tr>
  270. <td><?=htmlspecialchars($row_labels[$row_index])?></td>
  271. <?php
  272. foreach($columns as $column_index => $value) {
  273. $suffix = $suffixes[$column_index] ?? "";
  274. ?>
  275. <td class="text-right">
  276. <?php
  277. if($value === null) {
  278. ?>
  279. <small class="text-muted"><?=htmlspecialchars(__("N/A"))?></small>
  280. <?php
  281. continue;
  282. }
  283. ?>
  284. <?=number_format($value)?><?=htmlspecialchars($suffix)?>
  285. </td>
  286. <?php
  287. }
  288. if($print_percentage_column) {
  289. $value = $columns[0] ?? 0;
  290. if($total_count > 0) {
  291. $percentage = floor(($value / $total_count) * 10000) / 100;
  292. }
  293. else {
  294. $percentage = 0;
  295. }
  296. ?>
  297. <td class="text-right">
  298. <?=number_format($percentage, 2)?>%
  299. </td>
  300. <?php
  301. }
  302. ?>
  303. </tr>
  304. <?php
  305. }
  306. ?>
  307. </tbody>
  308. <?php
  309. if($print_total_row) {
  310. ?>
  311. <tfoot>
  312. <tr>
  313. <th><?=htmlspecialchars(__("Total"))?></th>
  314. <?php
  315. foreach($datasets as $dataset) {
  316. ?>
  317. <td class="text-right">
  318. <?=number_format(array_sum($dataset->data))?>
  319. </td>
  320. <?php
  321. }
  322. ?>
  323. </tr>
  324. </tfoot>
  325. <?php
  326. }
  327. ?>
  328. </table>
  329. <?php
  330. }
  331. public function setBeforeHtml($html) {
  332. $this->beforeHtml = $html;
  333. }
  334. public function setAfterHtml($html) {
  335. $this->afterHtml = $html;
  336. }
  337. public function setTooltipsMode($mode) {
  338. $this->tooltipsMode = $mode;
  339. }
  340. public function setTooltipsIntersect($intersect) {
  341. $this->tooltipsIntersect = $intersect;
  342. }
  343. // Presentation methods
  344. public function addChart(Slide $slide, string $path) {
  345. $chart_offset_y = 100;
  346. if($this->print) {
  347. $chart_offset_y = 10;
  348. }
  349. $shape = $slide->createDrawingShape();
  350. $shape->setName("Chart")
  351. ->setDescription("Chart")
  352. ->setPath($path)
  353. ->setHeight(520)
  354. ->setOffsetX(133)
  355. ->setOffsetY($chart_offset_y);
  356. return true;
  357. }
  358. /**
  359. * @param Slide $slide
  360. * @param int $offset_x
  361. * @param int $offset_y
  362. * @throws Exception
  363. */
  364. public function addDataTable(Slide $slide, int $offset_x = 30, int $offset_y = 540) {
  365. $labels = $this->getLabels();
  366. $datasets = array_merge($this->getDatasets(), $this->getPrintDatasets());
  367. $column_count = 1 + count($labels);
  368. // Table
  369. if($this->printTotalColumn) ++$column_count;
  370. $shape = $slide->createTableShape($column_count)
  371. ->setWidth(900)
  372. ->setOffsetX($offset_x)
  373. ->setOffsetY($offset_y);
  374. // Create header row
  375. $row = $shape->createRow();
  376. $row->setHeight(20);
  377. $cell = $row->nextCell();
  378. $labels = $this->getPrintLabels() ?? $this->getLabels();
  379. if($this->printTotalColumn) $labels[] = "Total";
  380. foreach($labels as $label) {
  381. $cell = $row->nextCell();
  382. $cell->getActiveParagraph()->getAlignment()
  383. ->setMarginBottom(4)
  384. ->setMarginLeft(4)
  385. ->setMarginRight(4)
  386. ->setMarginTop(4);
  387. $cell->createTextRun($label)
  388. ->getFont()->setBold(true);
  389. }
  390. $suffixes = $this->getPrintSuffixes() ?? $this->getDatalabelSuffixes();
  391. // Datasets
  392. foreach($datasets as $index => $dataset) {
  393. $label = $dataset->label;
  394. $data = $dataset->data;
  395. $print_data = array_slice($data, 0);
  396. $total = array_sum($data);
  397. $suffix = $suffixes[$index] ?? "";
  398. if($this->printTotalColumn) {
  399. $print_data[] = ($suffix == "%") ? "" : number_format(array_sum($data)) . $suffix;
  400. }
  401. $row = $shape->createRow();
  402. $row->setHeight(20);
  403. $cell = $row->nextCell();
  404. $cell->getActiveParagraph()->getAlignment()
  405. ->setMarginBottom(4)
  406. ->setMarginLeft(4)
  407. ->setMarginRight(4)
  408. ->setMarginTop(4);
  409. $cell->createTextRun($label)
  410. ->getFont()->setBold(true);
  411. foreach($print_data as $value) {
  412. $string = strlen($value) == 0 ? "" : $value . $suffix;
  413. $cell = $row->nextCell();
  414. $cell->getActiveParagraph()->getAlignment()
  415. ->setHorizontal(Alignment::HORIZONTAL_RIGHT)
  416. ->setMarginBottom(4)
  417. ->setMarginLeft(4)
  418. ->setMarginRight(4)
  419. ->setMarginTop(4);
  420. $cell->createTextRun($string);
  421. }
  422. if($this->printPercentages) {
  423. $percentages = [];
  424. foreach($data as $value) {
  425. if($total == 0) {
  426. $percentages[] = 0;
  427. continue;
  428. }
  429. $percentages[] = (floor(($value * 10000) / $total) / 100) . "%";
  430. }
  431. $row = $shape->createRow();
  432. $row->setHeight(20);
  433. $cell = $row->nextCell();
  434. $cell->getActiveParagraph()->getAlignment()
  435. ->setMarginBottom(4)
  436. ->setMarginLeft(4)
  437. ->setMarginRight(4)
  438. ->setMarginTop(4);
  439. $cell->createTextRun("Percentage")
  440. ->getFont()->setBold(true);
  441. foreach($percentages as $string) {
  442. $cell = $row->nextCell();
  443. $cell->getActiveParagraph()->getAlignment()
  444. ->setHorizontal(Alignment::HORIZONTAL_RIGHT)
  445. ->setMarginBottom(4)
  446. ->setMarginLeft(4)
  447. ->setMarginRight(4)
  448. ->setMarginTop(4);
  449. $cell->createTextRun($string);
  450. }
  451. }
  452. }
  453. }
  454. }