chart.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. class Chart {
  3. private $id = "";
  4. private $title = "Untitled";
  5. private $type = "bar";
  6. private $datasets = [];
  7. private $labels = [];
  8. public function __construct() {
  9. $this->id = bin2hex(random_bytes(8));
  10. }
  11. public function getID() {
  12. return $this->id;
  13. }
  14. public function getTitle() {
  15. return $this->title;
  16. }
  17. public function setTitle($title) {
  18. $this->title = $title;
  19. }
  20. public function setType($type) {
  21. $this->type = $type;
  22. }
  23. public function addDataset($label, $data, $options = []) {
  24. $background_colours = $options["background_colours"] ?? false;
  25. $border_colours = $options["border_colours"] ?? false;
  26. $border_width = $options["border_width"] ?? false;
  27. $dataset = [
  28. "label" => $label,
  29. "data" => $data,
  30. ];
  31. if($background_colours) $dataset["backgroundColor"] = $background_colours;
  32. if($border_colours) $dataset["borderColor"] = $border_colours;
  33. if($border_width) $dataset["borderWidth"] = (int) $border_width;
  34. $this->datasets[] = $dataset;
  35. }
  36. public function setLabels($labels) {
  37. $this->labels = $labels;
  38. }
  39. public function getJSON() {
  40. return json_encode([
  41. "type" => $this->type,
  42. "data" => [
  43. "labels" => $this->labels,
  44. "datasets" => $this->datasets
  45. ],
  46. "options" => [
  47. "title" => [
  48. "display" => true,
  49. "fontSize" => 32,
  50. "fontFamily" => "Roboto",
  51. "fontStyle" => "300",
  52. "text" => $this->title
  53. ],
  54. "legend" => [
  55. "position" => "top",
  56. ],
  57. ],
  58. ]);
  59. }
  60. }
  61. ?>