chart.php 12 KB

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