You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Services\Brief;
final class WeeklyBriefContentBuilder
{
/** @var list<array{type:string,text?:string,url?:string}> */
private array $blocks = [];
public function h1(string $text): self
{
$this->blocks[] = ['type' => 'h1', 'text' => $text];
return $this;
}
public function h2(string $text): self
{
$this->blocks[] = ['type' => 'h2', 'text' => $text];
return $this;
}
public function h3(string $text): self
{
$this->blocks[] = ['type' => 'h3', 'text' => $text];
return $this;
}
public function paragraph(string $text): self
{
$text = trim($text);
if ($text === '') {
return $this;
}
$this->blocks[] = ['type' => 'p', 'text' => $text];
return $this;
}
public function bullet(string $text): self
{
$this->blocks[] = ['type' => 'bullet', 'text' => $text];
return $this;
}
public function link(string $label, string $url): self
{
$this->blocks[] = ['type' => 'link', 'text' => $label, 'url' => $url];
return $this;
}
public function spacer(): self
{
$this->blocks[] = ['type' => 'spacer'];
return $this;
}
/**
* @return list<array{type:string,text?:string,url?:string}>
*/
public function blocks(): array
{
return $this->blocks;
}
public function toPlainText(): string
{
$lines = [];
foreach ($this->blocks as $block) {
$type = $block['type'] ?? '';
$text = trim((string) ($block['text'] ?? ''));
match ($type) {
'h1' => $lines[] = $text,
'h2' => $lines[] = $text,
'h3' => $lines[] = $text,
'p' => $lines[] = $text,
'bullet' => $lines[] = '· '.$text,
'link' => $lines[] = $text !== '' ? $text.''.($block['url'] ?? '') : (string) ($block['url'] ?? ''),
'spacer' => $lines[] = '',
default => null,
};
}
return trim(preg_replace("/\n{3,}/", "\n\n", implode("\n", $lines)) ?? '');
}
}