Files
lucent-laravel/src/Record/Record.php
T
2024-08-19 17:48:10 +03:00

80 lines
1.9 KiB
PHP

<?php
namespace Lucent\Record;
use JsonSerializable;
use stdClass;
use Illuminate\Support\Str;
class Record implements JsonSerializable
{
function __construct(
public string $id,
public string $schema,
public Status $status,
public System $_sys,
public RecordData $data,
public ?FileData $_file = null,
)
{
}
private function indexValues(array $arrObject){
return trim(Str::lower(collect($arrObject)
->map(function($value){
if(is_array($value)){
return $this->indexValues($value ?? []);
}
return str_replace(array("\r", "\n"), '', strip_tags((string)$value));
})
->values()->join(" ")." ". $this->_file?->originalName ?? ""));
}
public function toDB(): array
{
$searchIndex = $this->indexValues($this->data->toArray());
return [
"id" => $this->id,
"status" => $this->status->value,
"schema" => $this->schema,
"_sys" => json_encode($this->_sys),
"_file" => json_encode($this->_file),
"data" => json_encode($this->data),
"search" => $searchIndex,
];
}
public static function fromDB(stdClass $data): Record
{
$file = json_decode($data->_file, true);
if (!empty($file)) {
$file = new FileData(...$file);
} else {
$file = null;
}
return new Record(
id: $data->id,
schema: $data->schema,
status: Status::from($data->status),
_sys: System::fromArray(json_decode($data->_sys, true)),
data: new RecordData(json_decode($data->data, true)),
_file: $file,
);
}
public function jsonSerialize(): static
{
return $this;
}
}