first commit

This commit is contained in:
2024-07-09 11:31:28 +02:00
commit cc835b3692
9 changed files with 461 additions and 0 deletions

116
src/Entity/Metric.php Normal file
View File

@@ -0,0 +1,116 @@
<?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']($this->data) : [];
return [
'filter' => $filter['value'],
'filters' => collect($filters)->map(function ($filter) {
return [
'label' => $filter['label'],
'value' => $filter['value'],
];
})->values()->all(),
...$computed
];
}
public function filter($label, $value, callable $callback)
{
return ['label' => $label, 'value' => $value, 'callback' => $callback];
}
public function filters($filters)
{
return $this->resolveFilter($filters);
}
public function progress($current, $target)
{
return $this->output([
'type' => 'progress',
'value' => $current,
'target' => $target,
]);
}
public function trend($value, $previous = null)
{
return [
'type' => 'trend',
'value' => $value,
'previous' => $previous,
];
}
public function partition($values)
{
return [
'type' => 'partition',
'values' => $values,
];
}
public function value($value)
{
return [
'type' => 'value',
'value' => $value,
];
}
public function monitor($available)
{
return [
'type' => 'monitor',
'value' => $available,
];
}
}