PluginProbe
Metricool – Social media and site statistics / trunk
Metricool – Social media and site statistics vtrunk
2.1.0 2.0.2 2.0.1 2.0.0 1.27 trunk
metricool / app / Support / Builders / StatsChartTableBuilder.php

StatsChartTableBuilder.php in Metricool – Social media and site statistics trunk, at app/Support/Builders/StatsChartTableBuilder.php

100 lines 2.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Metricool\Support\Builders;
6
7 use Metricool\Support\Helpers\Collection;
8
9 /**
10 * Builds an array that creates the data for charts.
11 * Example:
12 * [
13 * [
14 * "value", "Country", "Visitors"
15 * ],
16 * [
17 * "nl", "Netherlands", "121321300"
18 * ],
19 * [
20 * "ar", "Argentina", "22342"
21 * ]
22 * ]
23 * @see DistributionStatisticsService::getChartsData() for usage example
24 */
25 class StatsChartTableBuilder
26 {
27 /** @var Collection */
28 private Collection $results;
29 private array $columns;
30
31 /**
32 * Sets the columns that holds the property names of the DTO to be used in the chart table.
33 * Example:
34 * [
35 * 'amount' => __('Amount', 'metricool'),
36 * 'metric' => __('Visitors', 'metricool')
37 * ]
38 */
39 public function setColumns(array $columns): self
40 {
41 $this->columns = $columns;
42
43 return $this;
44 }
45
46 /**
47 * Sets the results from the DistributionStatistics Entity
48 * @param Collection $results
49 */
50 public function setResults(Collection $results): self
51 {
52 $this->results = $results;
53
54 return $this;
55 }
56
57 /**
58 * Build the chart data
59 */
60 public function build(): array
61 {
62 $chartTable = [];
63
64 if ($this->results->count() === 0) {
65 return $chartTable;
66 }
67
68 $chartTable[] = $this->getColumnLabels();
69
70 foreach ($this->results as $result) {
71 $chartTable[] = $this->createRow($result);
72 }
73
74 return $chartTable;
75 }
76
77 /**
78 * Returns the row that holds the column labels
79 */
80 protected function getColumnLabels(): array
81 {
82 return array_values($this->columns);
83 }
84
85 /**
86 * Creates a row into the chart based on the chartColumns
87 * Each key of the chart column is a property of the DTO
88 */
89 protected function createRow(object $result): array
90 {
91 $row = [];
92
93 foreach ($this->columns as $property => $column) {
94 $row[] = $result->{$property};
95 }
96
97 return $row;
98 }
99 }
100