chart.php 13 KB

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