chart.php 13 KB

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