ChartJsDataset   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 0
dl 0
loc 69
c 0
b 0
f 0
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A setData() 0 5 1
B convert() 0 19 5
A pack() 0 7 1
1
<?php
2
3
namespace Spiral\Statistics\Extract\Dataset;
4
5
use Spiral\Statistics\Extract\DatasetInterface;
6
use Spiral\Statistics\Extract\Events\Row;
7
8
class ChartJsDataset implements DatasetInterface
9
{
10
    /** @var array|Row[] */
11
    private $raw = [];
12
13
    /** @var array */
14
    private $data = [];
15
16
    /** @var array */
17
    private $params = [];
18
19
    /** @var array */
20
    private $labels = [];
21
22
    /**
23
     * ChartDataset constructor.
24
     *
25
     * @param array $params - assoc array, where key is event name and value is an options array
26
     *                      for this event dataset like: "label" => "Event Label", etc.
27
     */
28
    public function __construct(array $params = [])
29
    {
30
        $this->params = $params;
31
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36
    public function setData(array $data)
37
    {
38
        $this->raw = $data;
39
        $this->convert();
40
    }
41
42
    /**
43
     * Convert to real format.
44
     */
45
    protected function convert()
46
    {
47
        foreach ($this->raw as $row) {
48
            $label = $row->getLabel();
49
            $this->labels[] = $label;
50
51
            foreach ($row->getEvents() as $event => $value) {
52
                if (!array_key_exists($event, $this->data)) {
53
                    if (array_key_exists($event, $this->params)) {
54
                        $this->data[$event] = $this->params[$event];
55
                    }
56
57
                    $this->data[$event]['data'] = [];
58
                }
59
60
                $this->data[$event]['data'][] = $value;
61
            }
62
        }
63
    }
64
65
66
    /**
67
     * {@inheritdoc}
68
     */
69
    public function pack(): array
70
    {
71
        return [
72
            'labels'   => $this->labels,
73
            'datasets' => array_values($this->data)
74
        ];
75
    }
76
}