1
0

chart.php 13 KB

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