1
0

chart.php 13 KB

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