| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Metricool\Services; |
| 6 |
|
| 7 |
use Metricool\Support\Builders\StatsTimelineBuilder; |
| 8 |
use Metricool\Support\Helpers\Collection; |
| 9 |
use Metricool\Http\Metricool\DTOs\TimelineDTO; |
| 10 |
|
| 11 |
class RealtimeService |
| 12 |
{ |
| 13 |
/** |
| 14 |
* @var array<string, array{ |
| 15 |
* name: string, |
| 16 |
* label: string, |
| 17 |
* results: Collection|TimelineDTO[], |
| 18 |
* useInTimeline: bool, |
| 19 |
* }> Metrics holds the name, label and results of the metric |
| 20 |
**/ |
| 21 |
protected array $metrics = []; |
| 22 |
/** |
| 23 |
* @var array<string, array{ |
| 24 |
* label: string, |
| 25 |
* totalAmount: int, |
| 26 |
* }> Totals holds the values to be shown in the totals |
| 27 |
**/ |
| 28 |
protected array $totals = []; |
| 29 |
|
| 30 |
/** |
| 31 |
* Sets the metrics to be used in the realtime service. The metrics contains the name, label and results of each metric. |
| 32 |
*/ |
| 33 |
public function addMetric(string $metric, string $label, array $results, bool $useInTimeline = true, bool $useInTotals = true): self |
| 34 |
{ |
| 35 |
$results = $this->hydrateResults($results)->sortBy('timestamp'); |
| 36 |
|
| 37 |
if ($useInTimeline) { |
| 38 |
$this->metrics[$metric] = [ |
| 39 |
'name' => $metric, |
| 40 |
'label' => $label, |
| 41 |
'results' => $results, |
| 42 |
]; |
| 43 |
} |
| 44 |
|
| 45 |
if ($useInTotals) { |
| 46 |
$this->addTotals($metric, $label, $results->sum('amount')); |
| 47 |
} |
| 48 |
|
| 49 |
return $this; |
| 50 |
} |
| 51 |
|
| 52 |
/** |
| 53 |
* Orders and hydrates the results of a Metricool timeline into a collection of TimelineDTO objects. |
| 54 |
*/ |
| 55 |
protected function hydrateResults(array $results): Collection |
| 56 |
{ |
| 57 |
$collection = new Collection(); |
| 58 |
|
| 59 |
foreach ($results as $timestamp => $amount) { |
| 60 |
$collection->push( |
| 61 |
new TimelineDTO((int) $timestamp, (float) $amount) |
| 62 |
); |
| 63 |
} |
| 64 |
|
| 65 |
return $collection; |
| 66 |
} |
| 67 |
|
| 68 |
/** |
| 69 |
* Adds a total to be used in the response |
| 70 |
* @param int|float $amount |
| 71 |
*/ |
| 72 |
public function addTotals(string $metric, string $label, $amount): void |
| 73 |
{ |
| 74 |
$this->totals[$metric] = [ |
| 75 |
'label' => $label, |
| 76 |
'totalAmount' => $amount, |
| 77 |
]; |
| 78 |
} |
| 79 |
|
| 80 |
/** |
| 81 |
* Gets the totals to be used in the response |
| 82 |
*/ |
| 83 |
public function getTotals(): array |
| 84 |
{ |
| 85 |
return $this->totals; |
| 86 |
} |
| 87 |
|
| 88 |
/** |
| 89 |
* Builds the timeline |
| 90 |
* @see \Metricool\Http\Endpoints\RealtimeEndpoint |
| 91 |
*/ |
| 92 |
public function getTimelineData(): array |
| 93 |
{ |
| 94 |
return (new StatsTimelineBuilder())->setDateFormat('LT') |
| 95 |
->setMetrics($this->metrics) |
| 96 |
->build(); |
| 97 |
} |
| 98 |
} |
| 99 |
|