|
| 1 | +<?php |
| 2 | + |
| 3 | +/* Icinga Kubernetes Web | (c) 2023 Icinga GmbH | GPLv2 */ |
| 4 | + |
| 5 | +namespace Icinga\Module\Kubernetes; |
| 6 | + |
| 7 | +use ipl\Html\BaseHtmlElement; |
| 8 | +use ipl\Html\Html; |
| 9 | +use ipl\Html\HtmlString; |
| 10 | + |
| 11 | +class Donut extends BaseHtmlElement |
| 12 | +{ |
| 13 | + protected $tag = 'div'; |
| 14 | + |
| 15 | + protected $defaultAttributes = ['class' => 'donut']; |
| 16 | + |
| 17 | + /** |
| 18 | + * The donut data |
| 19 | + * |
| 20 | + * @var array|\Traversable |
| 21 | + */ |
| 22 | + protected $data = []; |
| 23 | + |
| 24 | + protected $heading; |
| 25 | + |
| 26 | + protected $headingLevel; |
| 27 | + |
| 28 | + protected $labelCallback; |
| 29 | + |
| 30 | + /** |
| 31 | + * Get data to display |
| 32 | + * |
| 33 | + * @return array|\Traversable |
| 34 | + */ |
| 35 | + public function getData() |
| 36 | + { |
| 37 | + return $this->data; |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Set the data to display |
| 42 | + * |
| 43 | + * @param array|\Traversable $data |
| 44 | + * |
| 45 | + * @return $this |
| 46 | + */ |
| 47 | + public function setData($data) |
| 48 | + { |
| 49 | + if (! is_array($data) && ! $data instanceof \Traversable) { |
| 50 | + throw new \InvalidArgumentException('Data must be an array or an instance of Traversable'); |
| 51 | + } |
| 52 | + |
| 53 | + $this->data = $data; |
| 54 | + |
| 55 | + return $this; |
| 56 | + } |
| 57 | + |
| 58 | + public function setHeading($heading, $level) |
| 59 | + { |
| 60 | + $this->heading = $heading; |
| 61 | + $this->headingLevel = (int) $level; |
| 62 | + |
| 63 | + return $this; |
| 64 | + } |
| 65 | + |
| 66 | + public function setLabelCallback(callable $callback) |
| 67 | + { |
| 68 | + $this->labelCallback = $callback; |
| 69 | + |
| 70 | + return $this; |
| 71 | + } |
| 72 | + |
| 73 | + public function assemble() |
| 74 | + { |
| 75 | + $donut = new \Icinga\Chart\Donut(); |
| 76 | + $legend = new Table(); |
| 77 | + |
| 78 | + foreach ($this->data as $index => $value) { |
| 79 | + $donut->addSlice((int) $value, ['class' => 'segment-' . $index]); |
| 80 | + $legend->addRow( |
| 81 | + [ |
| 82 | + Html::tag('span', ['class' => 'badge badge-' . $index]), |
| 83 | + call_user_func($this->labelCallback, $index), |
| 84 | + $value |
| 85 | + ] |
| 86 | + ); |
| 87 | + } |
| 88 | + |
| 89 | + $this->add([Html::tag("h{$this->headingLevel}", $this->heading), new HtmlString($donut->render()), $legend]); |
| 90 | + } |
| 91 | +} |
0 commit comments