2024-07-04 23:54:37 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Lib\Editor;
|
|
|
|
|
|
|
|
use Spatie\LaravelData\Data;
|
|
|
|
|
2024-07-04 23:56:47 +02:00
|
|
|
/** @todo replace blocks with actual block data classes */
|
2024-07-06 15:08:13 +02:00
|
|
|
class EditorData extends Data implements Editorable
|
2024-07-04 23:54:37 +02:00
|
|
|
{
|
|
|
|
|
|
|
|
public function __construct(
|
|
|
|
public string $version,
|
|
|
|
public array $blocks,
|
|
|
|
public int $time
|
|
|
|
) {
|
|
|
|
}
|
|
|
|
|
|
|
|
public function placeholder(string $search, string $replacement): self
|
|
|
|
{
|
|
|
|
$replacedBlocks = str(json_encode($this->blocks))->replace('{' . $search . '}', $replacement);
|
2024-07-08 20:48:08 +02:00
|
|
|
$this->blocks = json_decode($replacedBlocks, true);
|
2024-07-04 23:54:37 +02:00
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param array<int, string> $wanted
|
|
|
|
*/
|
|
|
|
public function hasAll(array $wanted): bool
|
|
|
|
{
|
|
|
|
return collect($wanted)->first(fn ($search) => !str(json_encode($this->blocks))->contains($search)) === null;
|
|
|
|
}
|
|
|
|
|
2024-07-06 15:08:13 +02:00
|
|
|
public static function default(): self
|
|
|
|
{
|
|
|
|
return static::from([
|
|
|
|
'version' => '1.0',
|
|
|
|
'blocks' => [],
|
|
|
|
'time' => 0,
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function append(Editorable $editorable): self
|
|
|
|
{
|
2024-07-08 22:39:11 +02:00
|
|
|
$this->blocks = array_merge($this->blocks, $editorable->toEditorData()->blocks);
|
|
|
|
|
|
|
|
return $this;
|
2024-07-06 15:08:13 +02:00
|
|
|
}
|
|
|
|
|
2024-07-04 23:54:37 +02:00
|
|
|
public function replaceWithList(string $blockContent, array $replacements): self
|
|
|
|
{
|
2024-07-08 22:39:11 +02:00
|
|
|
$this->blocks = collect($this->blocks)->map(function ($block) use ($blockContent, $replacements) {
|
2024-07-04 23:54:37 +02:00
|
|
|
if (data_get($block, 'type') !== 'paragraph') {
|
|
|
|
return $block;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (data_get($block, 'data.text') === '{' . $blockContent . '}') {
|
|
|
|
return [
|
|
|
|
...((array)$block),
|
|
|
|
'type' => 'list',
|
|
|
|
'data' => [
|
|
|
|
'style' => 'unordered',
|
|
|
|
'items' => collect($replacements)->map(fn ($replacement) => [
|
|
|
|
'content' => $replacement,
|
|
|
|
'items' => [],
|
|
|
|
]),
|
|
|
|
]
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
return $block;
|
|
|
|
})->toArray();
|
|
|
|
|
2024-07-08 22:39:11 +02:00
|
|
|
|
|
|
|
return $this;
|
2024-07-06 15:08:13 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
public function toEditorData(): EditorData
|
|
|
|
{
|
2024-07-04 23:54:37 +02:00
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
}
|