chart.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. <?php
  2. class Chart {
  3. private $id = "";
  4. private $title = "Untitled";
  5. private $type = "bar";
  6. private $datasets = [];
  7. private $labels = [];
  8. private $yAxes = [];
  9. public function __construct() {
  10. $this->id = bin2hex(random_bytes(8));
  11. }
  12. public function addYAxis($type, $position, $id, $grid_lines = true, $tick_config = []) {
  13. $axis = [
  14. "type" => $type,
  15. "display" => true,
  16. "position" => $position,
  17. "id" => $id,
  18. "gridLines" => [
  19. "drawOnChartArea" => $grid_lines
  20. ],
  21. ];
  22. if($tick_config) {
  23. $axis["ticks"] = $tick_config;
  24. }
  25. $this->yAxes[] = $axis;
  26. }
  27. public function getID() {
  28. return $this->id;
  29. }
  30. public function getTitle() {
  31. return $this->title;
  32. }
  33. public function setTitle($title) {
  34. $this->title = $title;
  35. }
  36. public function setType($type) {
  37. $this->type = $type;
  38. }
  39. public function addDataset($label, $data, $options = []) {
  40. $background_colours = $options["background_colours"] ?? false;
  41. $border_colours = $options["border_colours"] ?? false;
  42. $border_width = $options["border_width"] ?? false;
  43. $y_axis_id = $options["y_axis_id"] ?? false;
  44. $type = $options["type"] ?? false;
  45. $datalabels = $options["datalabels"] ?? false;
  46. $dataset = [
  47. "label" => $label,
  48. "data" => $data,
  49. ];
  50. if($background_colours) $dataset["backgroundColor"] = $background_colours;
  51. if($border_colours) $dataset["borderColor"] = $border_colours;
  52. if($border_width) $dataset["borderWidth"] = (int) $border_width;
  53. if($y_axis_id) $dataset["yAxisID"] = $y_axis_id;
  54. if($type) $dataset["type"] = $type;
  55. if($datalabels) $dataset["datalabels"] = $datalabels;
  56. $this->datasets[] = $dataset;
  57. }
  58. public function setLabels($labels) {
  59. $this->labels = $labels;
  60. }
  61. public function getJSON() {
  62. $object = (object) [
  63. "type" => $this->type,
  64. "data" => (object) [
  65. "labels" => $this->labels,
  66. "datasets" => $this->datasets
  67. ],
  68. "options" => (object) [
  69. "title" => (object) [
  70. "display" => true,
  71. "fontSize" => 32,
  72. "fontFamily" => "Roboto",
  73. "fontStyle" => "300",
  74. "text" => $this->title
  75. ],
  76. "legend" => (object) [
  77. "position" => "top",
  78. ],
  79. "plugins" => (object) [
  80. "datalabels" => [
  81. "color" => "white",
  82. ],
  83. ],
  84. ],
  85. ];
  86. if($this->yAxes) {
  87. $object->options->scales = new stdClass;
  88. $object->options->scales->yAxes = $this->yAxes;
  89. }
  90. return json_encode($object);
  91. }
  92. }
  93. ?>