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.

60 lines
1.9 KiB

<?php
namespace App\Services\Brief;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;
class WeeklyBriefDocxWriter
{
/**
* @param list<array{type:string,text?:string,url?:string}> $blocks
*/
public function write(array $blocks, string $absolutePath): void
{
$phpWord = new PhpWord;
$phpWord->setDefaultFontName('Microsoft YaHei');
$phpWord->setDefaultFontSize(11);
$section = $phpWord->addSection([
'marginTop' => 1200,
'marginBottom' => 1200,
'marginLeft' => 1200,
'marginRight' => 1200,
]);
foreach ($blocks as $block) {
match ($block['type']) {
'h1' => $section->addTitle($block['text'] ?? '', 1),
'h2' => $section->addTitle($block['text'] ?? '', 2),
'h3' => $section->addTitle($block['text'] ?? '', 3),
'p' => $section->addText($block['text'] ?? '', null, ['spaceAfter' => 120]),
'bullet' => $section->addListItem($block['text'] ?? '', 0, null, null, ['spaceAfter' => 60]),
'link' => $this->addLinkParagraph($section, $block['text'] ?? '来源', $block['url'] ?? ''),
'spacer' => $section->addTextBreak(1),
default => null,
};
}
$dir = dirname($absolutePath);
if (! is_dir($dir)) {
mkdir($dir, 0755, true);
}
$writer = IOFactory::createWriter($phpWord, 'Word2007');
$writer->save($absolutePath);
}
protected function addLinkParagraph($section, string $label, string $url): void
{
if ($url !== '' && preg_match('~^https?://~i', $url)) {
$section->addLink($url, $label, ['color' => '0563C1', 'underline' => 'single']);
$section->addTextBreak(1);
return;
}
$section->addText($label, null, ['spaceAfter' => 120]);
}
}