Files
pilot-sdk/src/Entity/Metric.php
2025-12-16 16:39:07 +01:00

117 lines
2.6 KiB
PHP

<?php
namespace Bluesquare\Pilot\Entity;
abstract class Metric extends Widget
{
/**
* @var bool|int $cache Cache duration (in seconds) or FALSE to disable caching
*/
protected $cache = false;
protected $data = null;
abstract public function compute($entry = null);
public function handle($data)
{
$this->data = $data;
$cache_key = 'pilot-metric-'.$this->slug.'-'.json_encode($data);
if ($this->cache !== false && cache()->has($cache_key)) {
$computed = cache()->get($cache_key);
}
else {
$computed = $this->compute(
$data['entry'] ?? null
);
if ($this->cache !== false) {
cache()->put($cache_key, $computed, $this->cache);
}
}
return $this->output($computed);
}
public function output($data)
{
return [
'json' => [
'metric' => $data
]
];
}
protected function resolveFilter($filters)
{
$filter = collect($filters)->firstWhere('value', $this->data['filter'] ?? null) ?? collect($filters)->first();
$computed = is_array($filter) ? $filter['callback']() : [];
return [
'filter' => $filter['value'],
'filters' => collect($filters)->map(function ($filter) {
return [
'label' => $filter['label'],
'value' => $filter['value'],
];
})->values()->all(),
...$computed
];
}
public function filter(string $label, $value, callable $callback)
{
return ['label' => $label, 'value' => $value, 'callback' => $callback];
}
public function filters(array $filters)
{
return $this->resolveFilter($filters);
}
public function progress($current, $target)
{
return [
'type' => 'progress',
'value' => $current,
'target' => $target,
];
}
public function trend(array $values)
{
return [
'type' => 'trend',
'values' => $values,
];
}
public function partition(array $values)
{
return [
'type' => 'partition',
'values' => $values,
];
}
public function value($value, $previous = null)
{
return [
'type' => 'value',
'value' => $value,
'previous' => $previous,
];
}
public function monitor(bool $available)
{
return [
'type' => 'monitor',
'value' => $available,
];
}
}