From 244653a283fcaac1590ab880dab76da2b62b5be6 Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Sun, 1 Nov 2026 21:49:58 -0800 Subject: [PATCH 1/2] feat: section columns Section::$columns (Columns: count, space, separator, and per-column widths and per-gap spaces for unequal columns) is written as after in the section's and read back by SectionReader. DocumentBuilder::columns() sets the current section's columns, and newSection() takes them too. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++ README.md | 8 +- docs/de/README.md | 9 +- docs/ru/README.md | 8 +- docs/zh/README.md | 7 +- scripts/conformance/generate.php | 9 +- src/Build/DocumentBuilder.php | 18 ++- src/Reader/DocxReader.php | 1 + src/Reader/SectionReader.php | 49 +++++++- src/Section.php | 3 + src/Style/Columns.php | 75 ++++++++++++ src/Writer/Word2007Writer.php | 19 +++ tests/Build/SectionsBuilderTest.php | 20 ++++ tests/Writer/SectionColumnsTest.php | 178 ++++++++++++++++++++++++++++ 14 files changed, 402 insertions(+), 11 deletions(-) create mode 100644 src/Style/Columns.php create mode 100644 tests/Writer/SectionColumnsTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index a56f370..66f6bca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,15 @@ file. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added +- Section columns: `Section::$columns` (`Columns`: `count`, `spaceTwips`, + `separator`, and for unequal columns `widthsTwips` and `spacesTwips`) is + written as `` in the section's `` and read back by + `DocxReader`. `DocumentBuilder::columns()` sets the current section's + columns, and `newSection()` takes them too. + ## [1.18.0] — 2026-10-28 ### Added diff --git a/README.md b/README.md index 8a6eebf..66a6343 100644 --- a/README.md +++ b/README.md @@ -673,6 +673,12 @@ DocumentBuilder::new() landscape when it is wider than it is tall. - Without the builder: `new Document($first, followingSections: [$second, …])`; `Document::sections()` lists them all. +- `columns(new Columns(count: 2, separator: true))` sets the current section's + text columns (`newSection(columns: …)` sets the next one's; a new section is + single-column otherwise). `Columns` takes a `count`, the `spaceTwips` + between columns and a `separator` line; `widthsTwips` (one per column) and + `spacesTwips` (one per gap) make the columns unequal. Written as + ``, read back by `DocxReader`. - Every section but the last ends with its `` in the properties of its last paragraph (a paragraph is added when the section ends in a table). `DocxReader` reads each section back with its own body, page @@ -734,7 +740,7 @@ All elements live under `Dskripchenko\PhpDocx\Element` namespace. | Element | Type | Notes | |---|---|---| | `Document` | root | `{ section: Section, watermarkText: ?string, coreProperties: ?CoreProperties, followingSections: Section[] }` | -| `Section` | container | `{ body, header, footer, pageSetup, firstHeader, firstFooter, evenHeader, evenFooter, start: SectionStart }` | +| `Section` | container | `{ body, header, footer, pageSetup, firstHeader, firstFooter, evenHeader, evenFooter, start: SectionStart, columns: ?Columns }` | | `Paragraph` | BlockElement | `{ children: InlineElement[], style: ParagraphStyle, headingLevel: ?int, styleId: ?string }` | | `Run` | InlineElement | `{ text: string, style: RunStyle }` | | `Hyperlink` | InlineElement | `{ href: ?string, anchor: ?string, children: InlineElement[] }` | diff --git a/docs/de/README.md b/docs/de/README.md index 496a043..8578680 100644 --- a/docs/de/README.md +++ b/docs/de/README.md @@ -595,6 +595,13 @@ DocumentBuilder::new() quer, wenn sie breiter als hoch ist. - Ohne Builder: `new Document($first, followingSections: [$second, …])`; `Document::sections()` liefert alle. +- `columns(new Columns(count: 2, separator: true))` setzt die Textspalten des + aktuellen Abschnitts (`newSection(columns: …)` die des nächsten; sonst ist + ein neuer Abschnitt einspaltig). `Columns` nimmt die Spaltenzahl `count`, + den Abstand `spaceTwips` und eine Trennlinie `separator`; `widthsTwips` + (eine Breite je Spalte) und `spacesTwips` (ein Abstand je Zwischenraum) + machen die Spalten ungleich breit. Geschrieben als ``, von + `DocxReader` zurückgelesen. - Jeder Abschnitt außer dem letzten endet mit seinem `` in den Eigenschaften seines letzten Absatzes (endet er mit einer Tabelle, wird ein Absatz angefügt). `DocxReader` liest jeden Abschnitt mit eigenem Inhalt, @@ -658,7 +665,7 @@ Alle Elemente leben unter `Dskripchenko\PhpDocx\Element`. | Element | Typ | Hinweise | |---|---|---| | `Document` | root | `{ section: Section, watermarkText: ?string, coreProperties: ?CoreProperties, followingSections: Section[] }` | -| `Section` | container | `{ body, header, footer, pageSetup, firstHeader, firstFooter, evenHeader, evenFooter, start: SectionStart }` | +| `Section` | container | `{ body, header, footer, pageSetup, firstHeader, firstFooter, evenHeader, evenFooter, start: SectionStart, columns: ?Columns }` | | `Paragraph` | BlockElement | `{ children: InlineElement[], style, headingLevel: ?int, styleId: ?string }` | | `Run` | InlineElement | `{ text: string, style: RunStyle }` | | `Hyperlink` | InlineElement | `{ href: ?string, anchor: ?string, children }` | diff --git a/docs/ru/README.md b/docs/ru/README.md index a4f1143..1d5fb53 100644 --- a/docs/ru/README.md +++ b/docs/ru/README.md @@ -588,6 +588,12 @@ DocumentBuilder::new() страница альбомная, если она шире, чем выше. - Без builder'а: `new Document($first, followingSections: [$second, …])`; `Document::sections()` возвращает все разделы. +- `columns(new Columns(count: 2, separator: true))` задаёт колонки текста + текущего раздела (`newSection(columns: …)` — следующего; иначе новый раздел + одноколоночный). `Columns` принимает число колонок `count`, промежуток + `spaceTwips` и разделительную линию `separator`; `widthsTwips` (по одной + ширине на колонку) и `spacesTwips` (по одному промежутку) делают колонки + неравными. Пишется как ``, `DocxReader` читает обратно. - Каждый раздел, кроме последнего, заканчивается своим `` в свойствах последнего абзаца (если раздел заканчивается таблицей, добавляется абзац). `DocxReader` читает каждый раздел с его содержимым, @@ -650,7 +656,7 @@ foreach ($variables as $v) { | Элемент | Тип | Заметки | |---|---|---| | `Document` | root | `{ section: Section, watermarkText: ?string, coreProperties: ?CoreProperties, followingSections: Section[] }` | -| `Section` | container | `{ body, header, footer, pageSetup, firstHeader, firstFooter, evenHeader, evenFooter, start: SectionStart }` | +| `Section` | container | `{ body, header, footer, pageSetup, firstHeader, firstFooter, evenHeader, evenFooter, start: SectionStart, columns: ?Columns }` | | `Paragraph` | BlockElement | `{ children: InlineElement[], style, headingLevel: ?int, styleId: ?string }` | | `Run` | InlineElement | `{ text: string, style: RunStyle }` | | `Hyperlink` | InlineElement | `{ href: ?string, anchor: ?string, children }` | diff --git a/docs/zh/README.md b/docs/zh/README.md index ffab753..97be10a 100644 --- a/docs/zh/README.md +++ b/docs/zh/README.md @@ -573,6 +573,11 @@ DocumentBuilder::new() - `PageSetup(widthTwips:, heightTwips:)` 可设置任意页面尺寸;宽大于高时为横向。 - 不用构造器:`new Document($first, followingSections: [$second, …])`; `Document::sections()` 返回所有节。 +- `columns(new Columns(count: 2, separator: true))` 设置当前节的分栏 + (`newSection(columns: …)` 设置下一节的;否则新节为单栏)。`Columns` 接受栏数 + `count`、栏间距 `spaceTwips` 和分隔线 `separator`;`widthsTwips`(每栏一个宽度) + 和 `spacesTwips`(每个栏间距一个值)可使各栏不等宽。写为 ``,由 + `DocxReader` 读回。 - 除最后一节外,每节以其 `` 结束,写在该节最后一个段落的属性中(若该节以 表格结束,则添加一个段落)。`DocxReader` 逐节读回内容、页面设置、起始方式和页眉; HTML 序列化器依次输出各节内容,并在每个从新页开始的节之前加分页符。 @@ -630,7 +635,7 @@ foreach ($variables as $v) { | 元素 | 类型 | 备注 | |---|---|---| | `Document` | root | `{ section: Section, watermarkText: ?string, coreProperties: ?CoreProperties, followingSections: Section[] }` | -| `Section` | container | `{ body, header, footer, pageSetup, firstHeader, firstFooter, evenHeader, evenFooter, start: SectionStart }` | +| `Section` | container | `{ body, header, footer, pageSetup, firstHeader, firstFooter, evenHeader, evenFooter, start: SectionStart, columns: ?Columns }` | | `Paragraph` | BlockElement | `{ children: InlineElement[], style, headingLevel: ?int, styleId: ?string }` | | `Run` | InlineElement | `{ text: string, style: RunStyle }` | | `Hyperlink` | InlineElement | `{ href: ?string, anchor: ?string, children }` | diff --git a/scripts/conformance/generate.php b/scripts/conformance/generate.php index 81ba4a0..2740ac0 100644 --- a/scripts/conformance/generate.php +++ b/scripts/conformance/generate.php @@ -7,8 +7,8 @@ * writer feature at once: headings, justified paragraphs with spacing and * indents, tables with header rows, nested ordered lists, multi-part * headers/footers with page-number fields, bookmarks, hyperlinks, a text - * watermark, a second section (landscape, its own header, a custom page - * size) whose first section ends in a table, and floating pictures (one + * watermark, a second section (landscape, its own header, two unequal + * columns with a separator, a custom page size) whose first section ends in a table, and floating pictures (one * behind the text on every page from the header, one in the body with text * wrapped around it). Validated by: * @@ -23,6 +23,7 @@ use Dskripchenko\PhpDocx\Element\ImageFormat; use Dskripchenko\PhpDocx\Element\ListFormat; use Dskripchenko\PhpDocx\Style\Alignment; +use Dskripchenko\PhpDocx\Style\Columns; use Dskripchenko\PhpDocx\Style\HorizontalAnchor; use Dskripchenko\PhpDocx\Style\ImagePosition; use Dskripchenko\PhpDocx\Style\ImageWrap; @@ -83,10 +84,10 @@ ->text('Link: ') ->link('https://github.com/dskripchenko/php-docx', 'repository')) ->table(fn ($t) => $t->row(['A section that ends in a table', 'w:sectPr in an added paragraph'])) - ->newSection(new PageSetup(orientation: Orientation::Landscape)) + ->newSection(new PageSetup(orientation: Orientation::Landscape), columns: new Columns(count: 2, separator: true, widthsTwips: [5000, 9418], spacesTwips: [720])) ->header(fn ($h) => $h->paragraph('Landscape section header')) ->heading(2, 'Sections') - ->paragraph('A landscape section with a header of its own.') + ->paragraph('A landscape section with a header of its own, in two unequal columns with a separator.') ->newSection(new PageSetup(widthTwips: 8391, heightTwips: 11906), SectionStart::OddPage) ->paragraph('A custom page size, starting on an odd page; it inherits the header.') ->toFile($outDir.'/reference.docx'); diff --git a/src/Build/DocumentBuilder.php b/src/Build/DocumentBuilder.php index 5d5781b..2b25297 100644 --- a/src/Build/DocumentBuilder.php +++ b/src/Build/DocumentBuilder.php @@ -7,6 +7,7 @@ use Dskripchenko\PhpDocx\Document; use Dskripchenko\PhpDocx\Section; use Dskripchenko\PhpDocx\Style\CoreProperties; +use Dskripchenko\PhpDocx\Style\Columns; use Dskripchenko\PhpDocx\Style\PageSetup; use Dskripchenko\PhpDocx\Style\SectionStart; use Dskripchenko\PhpDocx\Style\StyleRegistry; @@ -69,6 +70,8 @@ final class DocumentBuilder private SectionStart $start = SectionStart::NextPage; + private ?Columns $columns = null; + /** @var list
sections closed by newSection(), in order */ private array $closedSections = []; @@ -209,9 +212,10 @@ public function evenFooter(callable $builderCallback): self * Ends the current section and starts a new one: the content, headers and * footers added from here on belong to it. It keeps the page setup unless * given one, and shows the previous section's headers and footers until it - * sets its own (Word's rule). + * sets its own (Word's rule). Columns are not kept: a new section is + * single-column unless given `$columns`. */ - public function newSection(?PageSetup $pageSetup = null, SectionStart $start = SectionStart::NextPage): self + public function newSection(?PageSetup $pageSetup = null, SectionStart $start = SectionStart::NextPage, ?Columns $columns = null): self { $this->closedSections[] = $this->currentSection(); $this->blocks = []; @@ -220,6 +224,15 @@ public function newSection(?PageSetup $pageSetup = null, SectionStart $start = S $this->evenHeaderBlocks = $this->evenFooterBlocks = []; $this->pageSetup = $pageSetup ?? $this->pageSetup; $this->start = $start; + $this->columns = $columns; + + return $this; + } + + /** Sets the current section's text columns; null for a single column. */ + public function columns(?Columns $columns): self + { + $this->columns = $columns; return $this; } @@ -248,6 +261,7 @@ private function currentSection(): Section evenHeader: $this->evenHeaderBlocks, evenFooter: $this->evenFooterBlocks, start: $this->start, + columns: $this->columns, ); } diff --git a/src/Reader/DocxReader.php b/src/Reader/DocxReader.php index a01fa6a..6c89b10 100644 --- a/src/Reader/DocxReader.php +++ b/src/Reader/DocxReader.php @@ -99,6 +99,7 @@ public function readPackage(DocxPackage $pkg): Document evenHeader: $usesEven ? $headersBy['even'] : [], evenFooter: $usesEven ? $footersBy['even'] : [], start: $sectionReader->start($sectPr), + columns: $sectionReader->columns($sectPr), ); } diff --git a/src/Reader/SectionReader.php b/src/Reader/SectionReader.php index 318b9a1..5c81704 100644 --- a/src/Reader/SectionReader.php +++ b/src/Reader/SectionReader.php @@ -4,13 +4,14 @@ namespace Dskripchenko\PhpDocx\Reader; +use Dskripchenko\PhpDocx\Style\Columns; use Dskripchenko\PhpDocx\Style\Orientation; use Dskripchenko\PhpDocx\Style\PageSetup; use Dskripchenko\PhpDocx\Style\PaperSize; use Dskripchenko\PhpDocx\Style\SectionStart; /** - * Phase 8 — SectionReader: `` → PageSetup. + * Phase 8 — SectionReader: `` → PageSetup, SectionStart and Columns. * * A Word document has one `` per section: DocxReader reads each with * fromSectPr(). readPageSetup() takes the LAST one in the body, the final @@ -100,6 +101,52 @@ public function start(?\DOMElement $sectPr): SectionStart return $type === null ? SectionStart::NextPage : (SectionStart::tryFrom($type->getAttributeNS(OoxmlNs::W, 'val')) ?? SectionStart::NextPage); } + /** The section's ``; null when it has none (a single column). */ + public function columns(?\DOMElement $sectPr): ?Columns + { + $cols = $sectPr === null ? null : OoxmlNs::firstChild($sectPr, OoxmlNs::W, 'cols'); + if ($cols === null) { + return null; + } + $twips = static function (\DOMElement $el, string $attr): ?int { + $v = $el->getAttributeNS(OoxmlNs::W, $attr); + + return ctype_digit($v) ? (int) $v : null; + }; + $separator = in_array($cols->getAttributeNS(OoxmlNs::W, 'sep'), ['1', 'true', 'on'], true); + $space = $twips($cols, 'space') ?? 720; + + $widths = []; + $spaces = []; + if (! in_array($cols->getAttributeNS(OoxmlNs::W, 'equalWidth'), ['0', 'false', 'off'], true)) { + $widths = null; + } else { + foreach ($cols->childNodes as $col) { + if ($col instanceof \DOMElement && $col->namespaceURI === OoxmlNs::W && $col->localName === 'col') { + $widths[] = $twips($col, 'w') ?? 0; + $spaces[] = $twips($col, 'space') ?? $space; + } + } + // Unequal columns without a usable list read as equal ones. + if ($widths === [] || min($widths) <= 0) { + $widths = null; + } else { + array_pop($spaces); + } + } + + $num = $twips($cols, 'num'); + $count = $widths !== null ? count($widths) : max(1, $num ?? 1); + + // Word writes a bare in ordinary documents: + // that is a single column, which is null here. + if ($widths === null && $count === 1 && ! $separator) { + return null; + } + + return new Columns($count, $space, $separator, $widths, $widths !== null ? $spaces : null); + } + private function findLastSectPr(\DOMElement $body): ?\DOMElement { $last = null; diff --git a/src/Section.php b/src/Section.php index 3bbb306..217bf81 100644 --- a/src/Section.php +++ b/src/Section.php @@ -5,6 +5,7 @@ namespace Dskripchenko\PhpDocx; use Dskripchenko\PhpDocx\Element\BlockElement; +use Dskripchenko\PhpDocx\Style\Columns; use Dskripchenko\PhpDocx\Style\PageSetup; use Dskripchenko\PhpDocx\Style\SectionStart; @@ -56,6 +57,8 @@ public function __construct( public array $evenFooter = [], /** Where this section begins; see SectionStart. */ public SectionStart $start = SectionStart::NextPage, + /** Text columns; null is a single column. */ + public ?Columns $columns = null, ) {} /** diff --git a/src/Style/Columns.php b/src/Style/Columns.php new file mode 100644 index 0000000..4971917 --- /dev/null +++ b/src/Style/Columns.php @@ -0,0 +1,75 @@ +` in its ``). + * + * Equal columns share the width left between the margins, with `$spaceTwips` + * between each two. Unequal columns give each column its own width in + * `$widthsTwips` (one per column) and, optionally, each gap its own space in + * `$spacesTwips` (one fewer than there are columns); a gap without one uses + * `$spaceTwips`. `$separator` draws a line between the columns. + * + * Text flows down one column and on into the next; `ColumnBreak` moves it to + * the next column early. + */ +final readonly class Columns +{ + /** + * @param list|null $widthsTwips One width per column; null for equal columns. + * @param list|null $spacesTwips One space per gap between columns (count − 1); only with `$widthsTwips`. + */ + public function __construct( + public int $count = 2, + public int $spaceTwips = 720, // 0.5in, Word's default + public bool $separator = false, + public ?array $widthsTwips = null, + public ?array $spacesTwips = null, + ) { + if ($count < 1) { + throw new \InvalidArgumentException('A section needs at least one column.'); + } + if ($spaceTwips < 0) { + throw new \InvalidArgumentException('The space between columns cannot be negative.'); + } + if ($widthsTwips === null) { + if ($spacesTwips !== null) { + throw new \InvalidArgumentException('Per-gap spaces need per-column widths.'); + } + + return; + } + if (count($widthsTwips) !== $count) { + throw new \InvalidArgumentException('Column widths need one width per column.'); + } + foreach ($widthsTwips as $width) { + if ($width <= 0) { + throw new \InvalidArgumentException('A column width must be positive.'); + } + } + if ($spacesTwips !== null) { + if (count($spacesTwips) !== $count - 1) { + throw new \InvalidArgumentException('Column spaces need one space per gap between columns.'); + } + foreach ($spacesTwips as $space) { + if ($space < 0) { + throw new \InvalidArgumentException('The space between columns cannot be negative.'); + } + } + } + } + + public function isEqualWidth(): bool + { + return $this->widthsTwips === null; + } + + /** The space after column `$index` (0-based), the common one unless set per gap. */ + public function spaceAfter(int $index): int + { + return $this->spacesTwips[$index] ?? $this->spaceTwips; + } +} diff --git a/src/Writer/Word2007Writer.php b/src/Writer/Word2007Writer.php index fae6c80..59fd71f 100644 --- a/src/Writer/Word2007Writer.php +++ b/src/Writer/Word2007Writer.php @@ -7,6 +7,7 @@ use Dskripchenko\PhpDocx\Document; use Dskripchenko\PhpDocx\Exception\DocxException; use Dskripchenko\PhpDocx\Section; +use Dskripchenko\PhpDocx\Style\Columns; use Dskripchenko\PhpDocx\Style\SectionStart; use Dskripchenko\PhpDocx\Style\StyleRegistry; @@ -394,6 +395,10 @@ private function renderSectPr(Section $section, array $headerRefs, array $footer $inner .= '' .''; + if ($section->columns !== null) { + $inner .= $this->renderCols($section->columns); + } + // Word requires a when a first-page header or footer is // set — otherwise the type="first" reference is ignored. if ($section->hasFirstPageHeaderOrFooter()) { @@ -403,6 +408,20 @@ private function renderSectPr(Section $section, array $headerRefs, array $footer return ''.$inner.''; } + private function renderCols(Columns $columns): string + { + $sep = $columns->separator ? ' w:sep="1"' : ''; + if ($columns->widthsTwips === null) { + return ''; + } + $cols = ''; + foreach ($columns->widthsTwips as $i => $width) { + $cols .= 'count - 1 ? ' w:space="'.$columns->spaceAfter($i).'"' : '').'/>'; + } + + return ''.$cols.''; + } + private function renderDocumentXml(string $bodyXml, string $sectPr): string { return '' diff --git a/tests/Build/SectionsBuilderTest.php b/tests/Build/SectionsBuilderTest.php index c3ccd73..3a756b3 100644 --- a/tests/Build/SectionsBuilderTest.php +++ b/tests/Build/SectionsBuilderTest.php @@ -6,6 +6,7 @@ use Dskripchenko\PhpDocx\Build\DocumentBuilder; use Dskripchenko\PhpDocx\Element\Paragraph; +use Dskripchenko\PhpDocx\Style\Columns; use Dskripchenko\PhpDocx\Style\Orientation; use Dskripchenko\PhpDocx\Style\PageSetup; use Dskripchenko\PhpDocx\Style\SectionStart; @@ -58,4 +59,23 @@ public function without_new_section_there_is_one(): void { self::assertCount(1, DocumentBuilder::new()->paragraph('x')->build()->sections()); } + + #[Test] + public function columns_belong_to_the_section_they_are_set_in(): void + { + $two = new Columns(count: 2, separator: true); + $doc = DocumentBuilder::new() + ->columns($two) + ->paragraph('one') + ->newSection(start: SectionStart::Continuous) + ->paragraph('two') + ->newSection(columns: new Columns(count: 3)) + ->paragraph('three') + ->build(); + + [$a, $b, $c] = $doc->sections(); + self::assertSame($two, $a->columns); + self::assertNull($b->columns, 'a new section starts single-column'); + self::assertEquals(new Columns(count: 3), $c->columns); + } } diff --git a/tests/Writer/SectionColumnsTest.php b/tests/Writer/SectionColumnsTest.php new file mode 100644 index 0000000..a1df424 --- /dev/null +++ b/tests/Writer/SectionColumnsTest.php @@ -0,0 +1,178 @@ +` in the section's ``. */ +final class SectionColumnsTest extends TestCase +{ + private static function documentXml(Document $doc): string + { + $tmp = (string) tempnam(sys_get_temp_dir(), 'docx-cols-'); + file_put_contents($tmp, (new Word2007Writer)->write($doc)); + $zip = new \ZipArchive; + $zip->open($tmp); + $xml = (string) $zip->getFromName('word/document.xml'); + $zip->close(); + unlink($tmp); + + return $xml; + } + + private static function oneSection(?Columns $columns): Document + { + return new Document(new Section([new Paragraph([new Run('x')])], columns: $columns)); + } + + #[Test] + public function a_section_without_columns_writes_no_cols(): void + { + self::assertStringNotContainsString('', $xml); + } + + #[Test] + public function the_separator_writes_sep(): void + { + $xml = self::documentXml(self::oneSection(new Columns(count: 2, separator: true))); + self::assertStringContainsString('', $xml); + } + + #[Test] + public function unequal_columns_write_each_width_and_gap(): void + { + $columns = new Columns(count: 3, separator: true, widthsTwips: [3000, 4000, 2000], spacesTwips: [500, 700]); + $xml = self::documentXml(self::oneSection($columns)); + self::assertStringContainsString( + '' + .'' + .'', + $xml, + ); + } + + #[Test] + public function unequal_columns_without_gaps_use_the_common_space(): void + { + $xml = self::documentXml(self::oneSection(new Columns(count: 2, spaceTwips: 400, widthsTwips: [3000, 6000]))); + self::assertStringContainsString('', $xml); + } + + #[Test] + public function cols_sits_after_pgMar_and_before_titlePg(): void + { + $section = new Section( + [new Paragraph([new Run('x')])], + firstHeader: [new Paragraph([new Run('Title')])], + columns: new Columns(count: 2), + ); + $xml = self::documentXml(new Document($section)); + $pgMar = strpos($xml, ''), strpos($xml, 'write(self::oneSection($columns)); + $read = (new DocxReader)->read($bytes)->section->columns; + self::assertEquals($columns, $read); + } + } + + #[Test] + public function a_section_without_columns_reads_back_without(): void + { + $read = (new DocxReader)->read((new Word2007Writer)->write(self::oneSection(null))); + self::assertNull($read->section->columns); + } + + #[Test] + public function columns_are_read_per_section(): void + { + $doc = new Document( + new Section([new Paragraph([new Run('one')])]), + followingSections: [new Section([new Paragraph([new Run('two')])], columns: new Columns(count: 2, separator: true))], + ); + $read = (new DocxReader)->read((new Word2007Writer)->write($doc))->sections(); + self::assertNull($read[0]->columns); + self::assertEquals(new Columns(count: 2, separator: true), $read[1]->columns); + } + + #[Test] + public function invalid_columns_are_refused(): void + { + foreach ([ + fn () => new Columns(count: 0), + fn () => new Columns(count: 2, spaceTwips: -1), + fn () => new Columns(count: 2, widthsTwips: [3000]), + fn () => new Columns(count: 2, widthsTwips: [3000, 0]), + fn () => new Columns(count: 3, widthsTwips: [1, 2, 3], spacesTwips: [100]), + fn () => new Columns(count: 2, spacesTwips: [100]), + ] as $make) { + try { + $make(); + self::fail('expected InvalidArgumentException'); + } catch (\InvalidArgumentException) { + $this->addToAssertionCount(1); + } + } + } + + #[Test] + public function a_bare_cols_from_word_is_a_single_column(): void + { + $bytes = (new Word2007Writer)->write(self::oneSection(new Columns(count: 2))); + $tmp = (string) tempnam(sys_get_temp_dir(), 'docx-cols-'); + file_put_contents($tmp, $bytes); + $zip = new \ZipArchive; + $zip->open($tmp); + $xml = str_replace('', '', (string) $zip->getFromName('word/document.xml')); + $zip->addFromString('word/document.xml', $xml); + $zip->close(); + + self::assertStringContainsString('', $xml); + self::assertNull((new DocxReader)->read((string) file_get_contents($tmp))->section->columns); + unlink($tmp); + } +} From 2b6741b38b925fbd1cef6c0fda33a10d27b0e88c Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Sun, 1 Nov 2026 21:51:03 -0800 Subject: [PATCH 2/2] feat: column break ColumnBreak is written as and read back by BodyReader, which splits a paragraph around it as it does for a page break. The builder gets columnBreak(). The PHPStan baseline gains the same inline/block mismatch entries PageBreak already has in BodyReader. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +++ README.md | 4 +++- docs/de/README.md | 5 ++++- docs/ru/README.md | 4 +++- docs/zh/README.md | 4 +++- phpstan-baseline.neon | 14 +++++++++++++- scripts/conformance/generate.php | 2 ++ src/Build/AddsBlockContent.php | 9 +++++++++ src/Element/BlockElement.php | 2 +- src/Element/ColumnBreak.php | 13 +++++++++++++ src/Reader/BodyReader.php | 16 +++++++++++----- src/Writer/BodyXmlBuilder.php | 7 +++++++ tests/Build/SectionsBuilderTest.php | 8 ++++++++ tests/Reader/BodyReaderTest.php | 26 ++++++++++++++++++++++++++ tests/Writer/BodyXmlBuilderTest.php | 8 ++++++++ tests/Writer/SectionColumnsTest.php | 14 ++++++++++++++ 16 files changed, 128 insertions(+), 11 deletions(-) create mode 100644 src/Element/ColumnBreak.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 66f6bca..e5feaf1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,9 @@ follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). written as `` in the section's `` and read back by `DocxReader`. `DocumentBuilder::columns()` sets the current section's columns, and `newSection()` takes them too. +- `ColumnBreak` (``) and the builder's `columnBreak()`: + the text after it starts in the next column. `DocxReader` reads it back, + splitting the paragraph around it as it does for a page break. ## [1.18.0] — 2026-10-28 diff --git a/README.md b/README.md index 66a6343..bd39497 100644 --- a/README.md +++ b/README.md @@ -679,6 +679,8 @@ DocumentBuilder::new() between columns and a `separator` line; `widthsTwips` (one per column) and `spacesTwips` (one per gap) make the columns unequal. Written as ``, read back by `DocxReader`. +- `columnBreak()` (a `ColumnBreak` block) moves the text after it to the top + of the next column; `DocxReader` reads Word's column break back as one. - Every section but the last ends with its `` in the properties of its last paragraph (a paragraph is added when the section ends in a table). `DocxReader` reads each section back with its own body, page @@ -747,7 +749,7 @@ All elements live under `Dskripchenko\PhpDocx\Element` namespace. | `Bookmark` | InlineElement | `{ name: string, children: InlineElement[] }` | | `Image` | both | `{ binary, format, widthEmu, heightEmu, altText, offsetYEmu, position: ?ImagePosition }` | | `Field` | InlineElement | `{ instruction: string, style: RunStyle }` | -| `LineBreak`, `PageBreak`, `HorizontalRule` | both | marker elements | +| `LineBreak`, `PageBreak`, `ColumnBreak`, `HorizontalRule` | both | marker elements; `ColumnBreak` is `` and has no HTML form | | `Table` | BlockElement | `{ rows: TableRow[], style, caption, gridColumnsTwips }` | | `TableRow` | element | `{ cells: TableCell[], isHeader, heightTwips, cantSplit, heightRule }` | | `TableCell` | element | `{ children: BlockElement[], style: CellStyle }` | diff --git a/docs/de/README.md b/docs/de/README.md index 8578680..c9ad07d 100644 --- a/docs/de/README.md +++ b/docs/de/README.md @@ -602,6 +602,9 @@ DocumentBuilder::new() (eine Breite je Spalte) und `spacesTwips` (ein Abstand je Zwischenraum) machen die Spalten ungleich breit. Geschrieben als ``, von `DocxReader` zurückgelesen. +- `columnBreak()` (ein `ColumnBreak`-Block) setzt den folgenden Text an den + Anfang der nächsten Spalte; `DocxReader` liest den Spaltenumbruch von Word + zurück. - Jeder Abschnitt außer dem letzten endet mit seinem `` in den Eigenschaften seines letzten Absatzes (endet er mit einer Tabelle, wird ein Absatz angefügt). `DocxReader` liest jeden Abschnitt mit eigenem Inhalt, @@ -672,7 +675,7 @@ Alle Elemente leben unter `Dskripchenko\PhpDocx\Element`. | `Bookmark` | InlineElement | `{ name: string, children }` | | `Image` | beides | `{ binary, format, widthEmu, heightEmu, altText, offsetYEmu, position: ?ImagePosition }` | | `Field` | InlineElement | `{ instruction: string, style: RunStyle }` | -| `LineBreak`, `PageBreak`, `HorizontalRule` | beides | Marker-Elemente | +| `LineBreak`, `PageBreak`, `ColumnBreak`, `HorizontalRule` | beides | Marker-Elemente; `ColumnBreak` ist ``, ohne HTML-Form | | `Table` | BlockElement | `{ rows: TableRow[], style, caption, gridColumnsTwips }` | | `TableRow` | element | `{ cells: TableCell[], isHeader, heightTwips, cantSplit, heightRule }` | | `TableCell` | element | `{ children: BlockElement[], style: CellStyle }` | diff --git a/docs/ru/README.md b/docs/ru/README.md index 1d5fb53..d97f0db 100644 --- a/docs/ru/README.md +++ b/docs/ru/README.md @@ -594,6 +594,8 @@ DocumentBuilder::new() `spaceTwips` и разделительную линию `separator`; `widthsTwips` (по одной ширине на колонку) и `spacesTwips` (по одному промежутку) делают колонки неравными. Пишется как ``, `DocxReader` читает обратно. +- `columnBreak()` (блок `ColumnBreak`) переносит следующий за ним текст в + начало следующей колонки; `DocxReader` читает разрыв колонки Word обратно. - Каждый раздел, кроме последнего, заканчивается своим `` в свойствах последнего абзаца (если раздел заканчивается таблицей, добавляется абзац). `DocxReader` читает каждый раздел с его содержимым, @@ -663,7 +665,7 @@ foreach ($variables as $v) { | `Bookmark` | InlineElement | `{ name: string, children }` | | `Image` | both | `{ binary, format, widthEmu, heightEmu, altText, offsetYEmu, position: ?ImagePosition }` | | `Field` | InlineElement | `{ instruction: string, style: RunStyle }` | -| `LineBreak`, `PageBreak`, `HorizontalRule` | both | marker-элементы | +| `LineBreak`, `PageBreak`, `ColumnBreak`, `HorizontalRule` | both | marker-элементы; `ColumnBreak` — ``, в HTML его нет | | `Table` | BlockElement | `{ rows: TableRow[], style, caption, gridColumnsTwips }` | | `TableRow` | element | `{ cells: TableCell[], isHeader, heightTwips, cantSplit, heightRule }` | | `TableCell` | element | `{ children: BlockElement[], style: CellStyle }` | diff --git a/docs/zh/README.md b/docs/zh/README.md index 97be10a..5a57b60 100644 --- a/docs/zh/README.md +++ b/docs/zh/README.md @@ -578,6 +578,8 @@ DocumentBuilder::new() `count`、栏间距 `spaceTwips` 和分隔线 `separator`;`widthsTwips`(每栏一个宽度) 和 `spacesTwips`(每个栏间距一个值)可使各栏不等宽。写为 ``,由 `DocxReader` 读回。 +- `columnBreak()`(`ColumnBreak` 块)使其后的文本从下一栏顶部开始;`DocxReader` + 会读回 Word 的分栏符。 - 除最后一节外,每节以其 `` 结束,写在该节最后一个段落的属性中(若该节以 表格结束,则添加一个段落)。`DocxReader` 逐节读回内容、页面设置、起始方式和页眉; HTML 序列化器依次输出各节内容,并在每个从新页开始的节之前加分页符。 @@ -642,7 +644,7 @@ foreach ($variables as $v) { | `Bookmark` | InlineElement | `{ name: string, children }` | | `Image` | 两者 | `{ binary, format, widthEmu, heightEmu, altText, offsetYEmu, position: ?ImagePosition }` | | `Field` | InlineElement | `{ instruction: string, style: RunStyle }` | -| `LineBreak`、`PageBreak`、`HorizontalRule` | 两者 | 标记元素 | +| `LineBreak`、`PageBreak`、`ColumnBreak`、`HorizontalRule` | 两者 | 标记元素;`ColumnBreak` 即 ``,无 HTML 形式 | | `Table` | BlockElement | `{ rows: TableRow[], style, caption, gridColumnsTwips }` | | `TableRow` | element | `{ cells: TableCell[], isHeader, heightTwips, cantSplit, heightRule }` | | `TableCell` | element | `{ children: BlockElement[], style: CellStyle }` | diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index fd82c3a..e6595ad 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -54,6 +54,12 @@ parameters: count: 1 path: src/Html/StyleApplier/RunStyleApplier.php + - + message: '#^Instanceof between Dskripchenko\\PhpDocx\\Element\\InlineElement and Dskripchenko\\PhpDocx\\Element\\ColumnBreak will always evaluate to false\.$#' + identifier: instanceof.alwaysFalse + count: 2 + path: src/Reader/BodyReader.php + - message: '#^Instanceof between Dskripchenko\\PhpDocx\\Element\\InlineElement and Dskripchenko\\PhpDocx\\Element\\PageBreak will always evaluate to false\.$#' identifier: instanceof.alwaysFalse @@ -67,7 +73,7 @@ parameters: path: src/Reader/BodyReader.php - - message: '#^Method Dskripchenko\\PhpDocx\\Reader\\BodyReader\:\:readRunWithFieldState\(\) should return array\{inlines\: list\, state\: string\|null, instr\: string, style\: Dskripchenko\\PhpDocx\\Style\\RunStyle, default\: string, valueSeen\: bool\} but returns array\{inlines\: list\, state\: string\|null, instr\: string, style\: Dskripchenko\\PhpDocx\\Style\\RunStyle, default\: string, valueSeen\: bool\}\.$#' + message: '#^Method Dskripchenko\\PhpDocx\\Reader\\BodyReader\:\:readRunWithFieldState\(\) should return array\{inlines\: list\, state\: string\|null, instr\: string, style\: Dskripchenko\\PhpDocx\\Style\\RunStyle, default\: string, valueSeen\: bool\} but returns array\{inlines\: list\, state\: string\|null, instr\: string, style\: Dskripchenko\\PhpDocx\\Style\\RunStyle, default\: string, valueSeen\: bool\}\.$#' identifier: return.type count: 1 path: src/Reader/BodyReader.php @@ -78,6 +84,12 @@ parameters: count: 1 path: src/Reader/BodyReader.php + - + message: '#^Result of \|\| is always false\.$#' + identifier: booleanOr.alwaysFalse + count: 1 + path: src/Reader/BodyReader.php + - message: '#^Result of \|\| is always true\.$#' identifier: booleanOr.alwaysTrue diff --git a/scripts/conformance/generate.php b/scripts/conformance/generate.php index 2740ac0..8bb1a87 100644 --- a/scripts/conformance/generate.php +++ b/scripts/conformance/generate.php @@ -88,6 +88,8 @@ ->header(fn ($h) => $h->paragraph('Landscape section header')) ->heading(2, 'Sections') ->paragraph('A landscape section with a header of its own, in two unequal columns with a separator.') + ->columnBreak() + ->paragraph('After a column break: the second column.') ->newSection(new PageSetup(widthTwips: 8391, heightTwips: 11906), SectionStart::OddPage) ->paragraph('A custom page size, starting on an odd page; it inherits the header.') ->toFile($outDir.'/reference.docx'); diff --git a/src/Build/AddsBlockContent.php b/src/Build/AddsBlockContent.php index 28df996..ff59ba3 100644 --- a/src/Build/AddsBlockContent.php +++ b/src/Build/AddsBlockContent.php @@ -7,6 +7,7 @@ use Dskripchenko\PhpDocx\Element\BlockElement; use Dskripchenko\PhpDocx\Element\HorizontalRule; use Dskripchenko\PhpDocx\Element\Image; +use Dskripchenko\PhpDocx\Element\ColumnBreak; use Dskripchenko\PhpDocx\Element\PageBreak; use Dskripchenko\PhpDocx\Element\Paragraph; use Dskripchenko\PhpDocx\Element\Run; @@ -72,6 +73,14 @@ public function pageBreak(): self return $this; } + /** Moves the text after it to the next column of the section. */ + public function columnBreak(): self + { + $this->blocks[] = new ColumnBreak; + + return $this; + } + public function horizontalRule(): self { $this->blocks[] = new HorizontalRule; diff --git a/src/Element/BlockElement.php b/src/Element/BlockElement.php index 5aa3bbe..b55b90c 100644 --- a/src/Element/BlockElement.php +++ b/src/Element/BlockElement.php @@ -6,6 +6,6 @@ /** * A marker interface for the block-level elements of a body, header or footer - * (Paragraph, Table, PageBreak). + * (Paragraph, Table, PageBreak, ColumnBreak). */ interface BlockElement {} diff --git a/src/Element/ColumnBreak.php b/src/Element/ColumnBreak.php new file mode 100644 index 0000000..dce62e0 --- /dev/null +++ b/src/Element/ColumnBreak.php @@ -0,0 +1,13 @@ +`): the + * text after it starts at the top of the next column of the section (see + * `Style\Columns`). In a section with a single column Word treats it as a + * page break. + */ +final readonly class ColumnBreak implements BlockElement {} diff --git a/src/Reader/BodyReader.php b/src/Reader/BodyReader.php index cef98bc..0d8808d 100644 --- a/src/Reader/BodyReader.php +++ b/src/Reader/BodyReader.php @@ -14,6 +14,7 @@ use Dskripchenko\PhpDocx\Element\LineBreak; use Dskripchenko\PhpDocx\Element\ListItem; use Dskripchenko\PhpDocx\Element\ListNode; +use Dskripchenko\PhpDocx\Element\ColumnBreak; use Dskripchenko\PhpDocx\Element\PageBreak; use Dskripchenko\PhpDocx\Element\Paragraph; use Dskripchenko\PhpDocx\Element\Run; @@ -33,6 +34,7 @@ * - `` → the text * - `` → a PageBreak (a split: everything after it goes * into a new paragraph) + * - `` → a ColumnBreak (split the same way) * - `` → a LineBreak * - `` → a "\t" in the text * - `` — proxied as inline children for now (phase 7 replaces it @@ -150,7 +152,7 @@ private function classifyParagraph(\DOMElement $p): ?array // items; when they are there we flatten them as an ordinary inline). $cleanInlines = array_values(array_filter( $inlines, - fn ($i) => ! $i instanceof PageBreak, + fn ($i) => ! $i instanceof PageBreak && ! $i instanceof ColumnBreak, )); return [ @@ -302,7 +304,7 @@ private function buildRecursive(array $items, int $from, int $to, int $depth, in } /** - * Parses a `` into one or more blocks (a PageBreak may split it). + * Parses a `` into one or more blocks (a PageBreak or ColumnBreak may split it). * * @return list */ @@ -577,7 +579,11 @@ private function readRunWithFieldState( $flushText(); if ($state !== 'value') { $type = $child->getAttributeNS(OoxmlNs::W, 'type'); - $emitted[] = $type === 'page' ? new PageBreak : new LineBreak; + $emitted[] = match ($type) { + 'page' => new PageBreak, + 'column' => new ColumnBreak, + default => new LineBreak, + }; } break; case 'footnoteReference': @@ -616,7 +622,7 @@ private function readRunWithFieldState( } /** - * Splits an inline list into paragraphs at the page breaks. + * Splits an inline list into paragraphs at the page and column breaks. * * @param list $inlines * @return list @@ -626,7 +632,7 @@ private function splitOnPageBreak(array $inlines, ParagraphStyle $style, ?int $h $blocks = []; $current = []; foreach ($inlines as $i) { - if ($i instanceof PageBreak) { + if ($i instanceof PageBreak || $i instanceof ColumnBreak) { if ($current !== []) { $blocks[] = new Paragraph($current, $style, $headingLevel); $current = []; diff --git a/src/Writer/BodyXmlBuilder.php b/src/Writer/BodyXmlBuilder.php index ded1e8a..948f3ee 100644 --- a/src/Writer/BodyXmlBuilder.php +++ b/src/Writer/BodyXmlBuilder.php @@ -14,6 +14,7 @@ use Dskripchenko\PhpDocx\Element\LineBreak; use Dskripchenko\PhpDocx\Element\ListItem; use Dskripchenko\PhpDocx\Element\ListNode; +use Dskripchenko\PhpDocx\Element\ColumnBreak; use Dskripchenko\PhpDocx\Element\PageBreak; use Dskripchenko\PhpDocx\Element\Paragraph; use Dskripchenko\PhpDocx\Element\Run; @@ -99,6 +100,7 @@ private function renderBlock(BlockElement $block): string $block instanceof Paragraph => $this->renderParagraph($block), $block instanceof Table => $this->renderTable($block), $block instanceof PageBreak => $this->renderPageBreak(), + $block instanceof ColumnBreak => $this->renderColumnBreak(), $block instanceof HorizontalRule => $this->renderHr(), $block instanceof Image => $this->renderBlockImage($block), $block instanceof ListNode => $this->renderListNode($block), @@ -499,6 +501,11 @@ private function renderPageBreak(): string return ''; } + private function renderColumnBreak(): string + { + return ''; + } + private function renderHr(): string { return '' diff --git a/tests/Build/SectionsBuilderTest.php b/tests/Build/SectionsBuilderTest.php index 3a756b3..4057677 100644 --- a/tests/Build/SectionsBuilderTest.php +++ b/tests/Build/SectionsBuilderTest.php @@ -5,6 +5,7 @@ namespace Dskripchenko\PhpDocx\Tests\Build; use Dskripchenko\PhpDocx\Build\DocumentBuilder; +use Dskripchenko\PhpDocx\Element\ColumnBreak; use Dskripchenko\PhpDocx\Element\Paragraph; use Dskripchenko\PhpDocx\Style\Columns; use Dskripchenko\PhpDocx\Style\Orientation; @@ -78,4 +79,11 @@ public function columns_belong_to_the_section_they_are_set_in(): void self::assertNull($b->columns, 'a new section starts single-column'); self::assertEquals(new Columns(count: 3), $c->columns); } + + #[Test] + public function column_break_adds_a_break_block(): void + { + $doc = DocumentBuilder::new()->columns(new Columns(count: 2))->paragraph('a')->columnBreak()->paragraph('b')->build(); + self::assertInstanceOf(ColumnBreak::class, $doc->section->body[1]); + } } diff --git a/tests/Reader/BodyReaderTest.php b/tests/Reader/BodyReaderTest.php index de5d53c..c425f74 100644 --- a/tests/Reader/BodyReaderTest.php +++ b/tests/Reader/BodyReaderTest.php @@ -5,6 +5,7 @@ namespace Dskripchenko\PhpDocx\Tests\Reader; use Dskripchenko\PhpDocx\Element\LineBreak; +use Dskripchenko\PhpDocx\Element\ColumnBreak; use Dskripchenko\PhpDocx\Element\PageBreak; use Dskripchenko\PhpDocx\Element\Paragraph; use Dskripchenko\PhpDocx\Element\Run; @@ -84,6 +85,31 @@ public function line_break_within_run(): void self::assertSame('B', $p->children[2]->text); } + #[Test] + public function column_break_splits_paragraph(): void + { + $body = $this->loadBody( + 'Before' + .'' + .'After' + ); + $blocks = (new BodyReader)->read($body); + self::assertCount(3, $blocks); + self::assertInstanceOf(Paragraph::class, $blocks[0]); + self::assertInstanceOf(ColumnBreak::class, $blocks[1]); + self::assertInstanceOf(Paragraph::class, $blocks[2]); + self::assertSame('Before', $blocks[0]->children[0]->text); + self::assertSame('After', $blocks[2]->children[0]->text); + } + + #[Test] + public function a_paragraph_holding_only_a_column_break_reads_as_the_break(): void + { + $blocks = (new BodyReader)->read($this->loadBody('')); + self::assertCount(1, $blocks); + self::assertInstanceOf(ColumnBreak::class, $blocks[0]); + } + #[Test] public function page_break_splits_paragraph(): void { diff --git a/tests/Writer/BodyXmlBuilderTest.php b/tests/Writer/BodyXmlBuilderTest.php index 003b303..b79c4ba 100644 --- a/tests/Writer/BodyXmlBuilderTest.php +++ b/tests/Writer/BodyXmlBuilderTest.php @@ -9,6 +9,7 @@ use Dskripchenko\PhpDocx\Element\LineBreak; use Dskripchenko\PhpDocx\Element\ListItem; use Dskripchenko\PhpDocx\Element\ListNode; +use Dskripchenko\PhpDocx\Element\ColumnBreak; use Dskripchenko\PhpDocx\Element\PageBreak; use Dskripchenko\PhpDocx\Element\Paragraph; use Dskripchenko\PhpDocx\Element\Run; @@ -122,6 +123,13 @@ public function it_renders_page_break(): void self::assertStringContainsString('', $xml); } + #[Test] + public function it_renders_column_break(): void + { + $xml = (new BodyXmlBuilder)->render([new ColumnBreak]); + self::assertStringContainsString('', $xml); + } + #[Test] public function it_renders_horizontal_rule_as_paragraph_with_bottom_border(): void { diff --git a/tests/Writer/SectionColumnsTest.php b/tests/Writer/SectionColumnsTest.php index a1df424..6fa70c2 100644 --- a/tests/Writer/SectionColumnsTest.php +++ b/tests/Writer/SectionColumnsTest.php @@ -5,6 +5,7 @@ namespace Dskripchenko\PhpDocx\Tests\Writer; use Dskripchenko\PhpDocx\Document; +use Dskripchenko\PhpDocx\Element\ColumnBreak; use Dskripchenko\PhpDocx\Element\Paragraph; use Dskripchenko\PhpDocx\Element\Run; use Dskripchenko\PhpDocx\Reader\DocxReader; @@ -175,4 +176,17 @@ public function a_bare_cols_from_word_is_a_single_column(): void self::assertNull((new DocxReader)->read((string) file_get_contents($tmp))->section->columns); unlink($tmp); } + + #[Test] + public function a_column_break_survives_a_round_trip(): void + { + $doc = new Document(new Section( + [new Paragraph([new Run('left')]), new ColumnBreak, new Paragraph([new Run('right')])], + columns: new Columns(count: 2), + )); + $read = (new DocxReader)->read((new Word2007Writer)->write($doc))->section; + self::assertCount(3, $read->body); + self::assertInstanceOf(ColumnBreak::class, $read->body[1]); + self::assertEquals(new Columns(count: 2), $read->columns); + } }