File size: 1,865 Bytes
d2897cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<?php

namespace Mautic\CoreBundle\Helper\Chart;

class PieChart extends AbstractChart implements ChartInterface
{
    /**
     * Holds the suma of the all dataset values.
     *
     * @var float
     */
    protected $totalCount = 0;

    /**
     * @return array{labels: mixed[], datasets: mixed[]}
     */
    public function render($withCounts = true): array
    {
        $data = ['data' => [], 'backgroundColor' => [], 'hoverBackgroundColor' => []];

        foreach ($this->datasets as $datasetId => $value) {
            $color                          = $this->configureColorHelper($datasetId);
            $data['data'][]                 = $value;
            $data['backgroundColor'][]      = $color->toRgba(0.8);
            $data['hoverBackgroundColor'][] = $color->toRgba(0.9);
            if ($withCounts) {
                $this->labels[$datasetId] = $this->buildFullLabel($this->labels[$datasetId], $value);
            }
        }

        return [
            'labels'   => $this->labels,
            'datasets' => [$data],
        ];
    }

    /**
     * Define a dataset by name and count number. Method will add the rest.
     *
     * @param string $label
     * @param int    $value
     *
     * @return $this
     */
    public function setDataset($label, $value)
    {
        $this->totalCount += $value;
        $this->datasets[] = $value;
        $this->labels[]   = $label;

        return $this;
    }

    /**
     * Adds to the label also the value and the percentage.
     *
     * @param string $label
     * @param int    $value
     *
     * @return string
     */
    public function buildFullLabel($label, $value)
    {
        if (!$this->totalCount) {
            return $label;
        }
        $percentage = round($value / $this->totalCount * 100, 2);

        return $label.'; '.$value.'x, '.$percentage.'%';
    }
}