chart.php 2.2 KB

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