summaryrefslogtreecommitdiffstats
path: root/library/Icinga/Chart/PieChart.php
blob: 1bcf3809829cd34484dc056322979d649d948348 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
<?php
/* Icinga Web 2 | (c) 2013 Icinga Development Team | GPLv2+ */

namespace Icinga\Chart;

use DOMElement;
use Icinga\Chart\Chart;
use Icinga\Chart\Primitive\Canvas;
use Icinga\Chart\Primitive\PieSlice;
use Icinga\Chart\Primitive\RawElement;
use Icinga\Chart\Primitive\Rect;
use Icinga\Chart\Render\RenderContext;
use Icinga\Chart\Render\LayoutBox;

/**
 * Graphing component for rendering Pie Charts.
 *
 * See the graphs.md documentation for further information about how to use this component
 */
class PieChart extends Chart
{
    /**
     * Stack multiple pies
     */
    const STACKED = "stacked";

    /**
     * Draw multiple pies beneath each other
     */
    const ROW = "row";

    /**
     * The drawing stack containing all pie definitions in the order they will be drawn
     *
     * @var array
     */
    private $pies = array();

    /**
     * The composition type currently used
     *
     * @var string
     */
    private $type = PieChart::STACKED;

    /**
     * Disable drawing of captions when set true
     *
     * @var bool
     */
    private $noCaption = false;

    public function __construct()
    {
        $this->title = t('Pie Chart');
        $this->description = t('Contains data in a pie chart.');
        parent::__construct();
    }

    /**
     * Test if the given pies have the correct format
     *
     * @return bool True when the given pies are correct, otherwise false
     */
    public function isValidDataFormat()
    {
        foreach ($this->pies as $pie) {
            if (!isset($pie['data']) || !is_array($pie['data'])) {
                return false;
            }
        }
        return true;
    }

    /**
     * Create renderer and normalize the dataset to represent percentage information
     */
    protected function build()
    {
        $this->renderer = new SVGRenderer(($this->type === self::STACKED) ? 1 : count($this->pies), 1);
        foreach ($this->pies as &$pie) {
            $this->normalizeDataSet($pie);
        }
    }

    /**
     * Normalize the given dataset to represent percentage information instead of absolute valuess
     *
     * @param array $pie The pie definition given in the drawPie call
     */
    private function normalizeDataSet(&$pie)
    {
        $total = array_sum($pie['data']);
        if ($total === 100) {
            return;
        }
        if ($total == 0) {
            return;
        }
        foreach ($pie['data'] as &$slice) {
            $slice = $slice/$total * 100;
        }
    }

    /**
     * Draw an arbitrary number of pies in this chart
     *
     * @param   array $dataSet,...  The pie definition, see graphs.md for further details concerning the format
     *
     * @return  $this                Fluent interface
     */
    public function drawPie(array $dataSet)
    {
        $dataSets = func_get_args();
        $this->pies += $dataSets;
        foreach ($dataSets as $dataSet) {
            $this->legend->addDataset($dataSet);
        }
        return $this;
    }

    /**
     * Return the SVG representation of this graph
     *
     * @param RenderContext $ctx    The context to use for drawings
     *
     * @return DOMElement           The SVG representation of this graph
     */
    public function toSvg(RenderContext $ctx)
    {
        $labelBox = $ctx->getDocument()->createElement('g');
        if (!$this->noCaption) {
            // Scale SVG to make room for captions
            $outerBox = new Canvas('outerGraph', new LayoutBox(33, -5, 40, 40));
            $innerBox = new Canvas('graph', new LayoutBox(0, 0, 100, 100));
            $innerBox->getLayout()->setPadding(10, 10, 10, 10);
        } else {
            $outerBox = new Canvas('outerGraph', new LayoutBox(1.5, -10, 124, 124));
            $innerBox = new Canvas('graph', new LayoutBox(0, 0, 100, 100));
            $innerBox->getLayout()->setPadding(0, 0, 0, 0);
        }
        $this->createContentClipBox($innerBox);
        $this->renderPies($innerBox, $labelBox);
        $innerBox->addElement(new RawElement($labelBox));
        $outerBox->addElement($innerBox);

        return $outerBox->toSvg($ctx);
    }

    /**
     * Render the pies in the draw stack using the selected algorithm for composition
     *
     * @param Canvas $innerBox      The canvas to use for inserting the pies
     * @param DOMElement $labelBox  The DOM element to add the labels to (so they can't be overlapped by pie elements)
     */
    private function renderPies(Canvas $innerBox, DOMElement $labelBox)
    {
        if ($this->type === self::STACKED) {
            $this->renderStackedPie($innerBox, $labelBox);
        } else {
            $this->renderPieRow($innerBox, $labelBox);
        }
    }

    /**
     * Return the color to be used for the given pie slice
     *
     * @param array $pie    The pie configuration as provided in the drawPie call
     * @param int $dataIdx  The index of the pie slice in the pie configuration
     *
     * @return string       The hex color string to use for the pie slice
     */
    private function getColorForPieSlice(array $pie, $dataIdx)
    {
        if (isset($pie['colors']) && is_array($pie['colors']) && isset($pie['colors'][$dataIdx])) {
            return $pie['colors'][$dataIdx];
        }
        $type = Palette::NEUTRAL;
        if (isset($pie['palette']) && is_array($pie['palette']) && isset($pie['palette'][$dataIdx])) {
            $type = $pie['palette'][$dataIdx];
        }
        return $this->palette->getNext($type);
    }

    /**
     * Render a row of pies
     *
     * @param Canvas $innerBox      The canvas to insert the pies to
     * @param DOMElement $labelBox  The DOMElement to use for adding label elements
     */
    private function renderPieRow(Canvas $innerBox, DOMElement $labelBox)
    {
        $radius = 50 / count($this->pies);
        $x = $radius;
        foreach ($this->pies as $pie) {
            $labelPos = 0;
            $lastRadius = 0;

            foreach ($pie['data'] as $idx => $dataset) {
                $slice = new PieSlice($radius, $dataset, $lastRadius);
                $slice->setX($x)
                    ->setStrokeColor('#000')
                    ->setStrokeWidth(1)
                    ->setY(50)
                    ->setFill($this->getColorForPieSlice($pie, $idx));
                $innerBox->addElement($slice);
                // add caption if not disabled
                if (!$this->noCaption && isset($pie['labels'])) {
                    $slice->setCaption($pie['labels'][$labelPos++])
                        ->setLabelGroup($labelBox);
                }
                $lastRadius += $dataset;
            }
            // shift right for next pie
            $x += $radius*2;
        }
    }

    /**
     * Render pies in a stacked way so one pie is nested in the previous pie
     *
     * @param Canvas $innerBox      The canvas to insert the pie to
     * @param DOMElement $labelBox  The DOMElement to use for adding label elements
     */
    private function renderStackedPie(Canvas $innerBox, DOMElement $labelBox)
    {
        $radius = 40;
        $minRadius = 20;
        if (count($this->pies) == 0) {
            return;
        }
        $shrinkStep = ($radius - $minRadius) / count($this->pies);
        $x = $radius;

        for ($i = 0; $i < count($this->pies); $i++) {
            $pie = $this->pies[$i];
            // the offset for the caption path, outer caption indicator shouldn't point
            // to the middle of the slice as there will be another pie
            $offset = isset($this->pies[$i+1]) ? $radius - $shrinkStep : 0;
            $labelPos = 0;
            $lastRadius = 0;
            foreach ($pie['data'] as $idx => $dataset) {
                $color = $this->getColorForPieSlice($pie, $idx);
                if ($dataset == 0) {
                    $labelPos++;
                    continue;
                }
                $slice = new PieSlice($radius, $dataset, $lastRadius);
                $slice->setY(50)
                    ->setX($x)
                    ->setStrokeColor('#000')
                    ->setStrokeWidth(1)
                    ->setFill($color)
                    ->setLabelGroup($labelBox);

                if (!$this->noCaption && isset($pie['labels'])) {
                    $slice->setCaption($pie['labels'][$labelPos++])
                        ->setCaptionOffset($offset)
                        ->setOuterCaptionBound(50);
                }
                $innerBox->addElement($slice);
                $lastRadius += $dataset;
            }
            // shrinken the next pie
            $radius -= $shrinkStep;
        }
    }

    /**
     * Set the composition type of this PieChart
     *
     * @param string $type  Either self::STACKED or self::ROW
     *
     * @return $this         Fluent interface
     */
    public function setType($type)
    {
        $this->type = $type;
        return $this;
    }

    /**
     * Hide the caption from this PieChart
     *
     * @return $this         Fluent interface
     */
    public function disableLegend()
    {
        $this->noCaption = true;
        return $this;
    }

    /**
     * Create the content for this PieChart
     *
     * @param Canvas $innerBox      The innerbox to add the clip mask to
     */
    private function createContentClipBox(Canvas $innerBox)
    {
        $clipBox = new Canvas('clip', new LayoutBox(0, 0, 100, 100));
        $clipBox->toClipPath();
        $innerBox->addElement($clipBox);
        $rect = new Rect(0.1, 0, 100, 99.9);
        $clipBox->addElement($rect);
    }
}