chart.php 12 KB

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