50 lines
1.3 KiB
PHP
50 lines
1.3 KiB
PHP
<?php
|
|
namespace nulib\file\cache;
|
|
|
|
use nulib\cl;
|
|
use nulib\php\func;
|
|
use Traversable;
|
|
|
|
class CacheData {
|
|
/** @var string identifiant de cette donnée */
|
|
const NAME = null;
|
|
|
|
/** @var callable une fonction permettant de calculer la donnée */
|
|
const COMPUTE = null;
|
|
|
|
function __construct(?array $params=null) {
|
|
$this->name = $params["name"] ?? static::NAME;
|
|
$this->name ??= bin2hex(random_bytes(8));
|
|
$this->compute = func::withn($params["compute"] ?? static::COMPUTE);
|
|
}
|
|
|
|
protected string $name;
|
|
|
|
protected ?func $compute;
|
|
|
|
protected function compute() {
|
|
$compute = $this->compute;
|
|
return $compute !== null? $compute->invoke(): null;
|
|
}
|
|
|
|
/** obtenir la donnée, en l'itérant au préalable si elle est traversable */
|
|
function get(?string &$name, $compute=null) {
|
|
$name = $this->name;
|
|
$this->compute ??= func::withn($compute);
|
|
$data = $this->compute();
|
|
if ($data instanceof Traversable) {
|
|
$data = cl::all($data);
|
|
}
|
|
return $data;
|
|
}
|
|
|
|
/** obtenir un itérateur sur la donnée ou null s'il n'y a pas de données */
|
|
function all(?string &$name, $compute=null): ?iterable {
|
|
$name = $this->name;
|
|
$this->compute ??= func::withn($compute);
|
|
$data = $this->compute();
|
|
if ($data !== null && !is_iterable($data)) $data = [$data];
|
|
return $data;
|
|
}
|
|
}
|