}> */ public static function blocks(?string $body): array { $blocks = []; $paragraph = []; $list = null; $flushParagraph = function () use (&$blocks, &$paragraph): void { if ($paragraph !== []) { $blocks[] = ['type' => 'paragraph', 'text' => implode(' ', $paragraph)]; $paragraph = []; } }; $flushList = function () use (&$blocks, &$list): void { if ($list !== null) { $blocks[] = ['type' => $list['type'], 'items' => $list['items']]; $list = null; } }; foreach (preg_split('/\R/u', trim((string) $body)) ?: [] as $line) { $line = rtrim($line); if (trim($line) === '') { $flushParagraph(); $flushList(); continue; } if (preg_match('/^##\s+(.+)$/u', $line, $match) === 1) { $flushParagraph(); $flushList(); $blocks[] = ['type' => 'heading', 'text' => trim($match[1])]; continue; } if (preg_match('/^\s*(?:[-•*])\s+(.+)$/u', $line, $match) === 1) { $flushParagraph(); if ($list === null || $list['type'] !== 'bullets') { $flushList(); $list = ['type' => 'bullets', 'items' => []]; } $list['items'][] = trim($match[1]); continue; } if (preg_match('/^\s*\d+[.)]\s+(.+)$/u', $line, $match) === 1) { $flushParagraph(); if ($list === null || $list['type'] !== 'numbered') { $flushList(); $list = ['type' => 'numbered', 'items' => []]; } $list['items'][] = trim($match[1]); continue; } $flushList(); $paragraph[] = trim($line); } $flushParagraph(); $flushList(); return $blocks; } }