27 lines
2.8 KiB
PHP
27 lines
2.8 KiB
PHP
<?php
|
|
require_once __DIR__ . '/labdb.class.php';
|
|
require_once __DIR__ . '/parametercatalog.class.php';
|
|
class Experiment {
|
|
private static function result(bool $ok, $data = null, array $errors = []): array { return $ok ? ['ok'=>true,'data'=>$data] : ['ok'=>false,'errors'=>$errors]; }
|
|
private static function row(array $r): array { $r['spec'] = json_decode($r['spec'], true); if (isset($r['spec']['parameters']) && $r['spec']['parameters']===[]) $r['spec']['parameters']=(object)[]; return $r; }
|
|
private static function specJson(array $spec): string { if (isset($spec['parameters']) && $spec['parameters']===[]) $spec['parameters']=(object)[]; return json_encode($spec,JSON_THROW_ON_ERROR); }
|
|
public static function all($owner): array {
|
|
$s=LabDb::connection()->prepare('SELECT * FROM experiments WHERE owner=? ORDER BY updated_at DESC LIMIT 200'); $s->execute([$owner]); return array_map([self::class,'row'],$s->fetchAll());
|
|
}
|
|
public static function get($id,$owner): ?array {
|
|
$s=LabDb::connection()->prepare('SELECT * FROM experiments WHERE id=? AND owner=?'); $s->execute([$id,$owner]); $r=$s->fetch(); return $r ? self::row($r) : null;
|
|
}
|
|
public static function save($owner,$data): array {
|
|
if (!is_array($data) || !is_string($data['name']??null) || trim($data['name'])==='' || !is_array($data['spec']??null)) return self::result(false,null,['experiment'=>'Name and spec are required.']);
|
|
if (!class_exists('ParameterCatalog') || !method_exists('ParameterCatalog','validate')) return self::result(false,null,['spec'=>'Parameter validation is unavailable.']);
|
|
$v=ParameterCatalog::validate($data['spec']); if (empty($v['ok'])) return self::result(false,null,$v['errors']??['spec'=>'Invalid spec.']); $data['spec']=$v['spec'];
|
|
$id=$data['id']??bin2hex(random_bytes(16)); if (!preg_match('/^[a-f0-9]{32}$/',$id)) return self::result(false,null,['id'=>'Invalid experiment ID.']);
|
|
$db=LabDb::connection(); $old=self::get($id,$owner); $now=gmdate('c');
|
|
if ($old) { $s=$db->prepare('UPDATE experiments SET name=?,spec=?,updated_at=? WHERE id=? AND owner=?'); $s->execute([trim($data['name']),self::specJson($data['spec']),$now,$id,$owner]); }
|
|
elseif ($data['id']??false) return self::result(false,null,['id'=>'Experiment not found.']);
|
|
else { $s=$db->prepare('INSERT INTO experiments VALUES(?,?,?,?,?,?)'); $s->execute([$id,$owner,trim($data['name']),self::specJson($data['spec']),$now,$now]); }
|
|
return self::result(true,self::get($id,$owner));
|
|
}
|
|
public static function delete($id,$owner): array { $s=LabDb::connection()->prepare('DELETE FROM experiments WHERE id=? AND owner=?'); $s->execute([$id,$owner]); return $s->rowCount() ? self::result(true,true) : self::result(false,null,['id'=>'Experiment not found.']); }
|
|
}
|