chart.php 13 KB

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