1. коррекция форматирования таблиц.

2. добавлена консольная утилита проверки форматирования
3. функция formatCheck удалена
This commit is contained in:
Ilgiz Kamelyev 2026-06-03 13:19:25 +05:00
parent 8465983be7
commit f12c12efc6
4 changed files with 86 additions and 29 deletions

View File

@ -43,6 +43,18 @@ php tests/import_description_formatter_test.php
Успешный результат: `OK`.
Для ручной проверки одного текста есть отдельный CLI-скрипт:
```bash
php tools/format_description.php "Описание и основные функции: Содержит 4 ступени фильтрации."
```
Или через stdin:
```bash
printf 'Строка 1\n\nСтрока 2' | php tools/format_description.php
```
## Как распознаются блоки
- Обычные строки становятся абзацами `<p>`.

View File

@ -25,8 +25,7 @@ final class ImportDescriptionFormatter
return;
}
// $html = (new self())->format($sourceText);
$html = (new self())->formatCheck($sourceText);
$html = (new self())->format($sourceText);
if ($html === '') {
return;
}
@ -47,8 +46,9 @@ final class ImportDescriptionFormatter
}
$html = [];
foreach ($this->splitIntoParagraphBlocks($text) as $blockLines) {
$blockHtml = $this->renderBlock($blockLines);
$blocks = $this->splitIntoParagraphBlocks($text);
foreach ($blocks as $blockIndex => $blockLines) {
$blockHtml = $this->renderBlock($blockLines, $blockIndex > 0);
if ($blockHtml !== '') {
$html[] = $blockHtml;
}
@ -63,11 +63,6 @@ final class ImportDescriptionFormatter
. '</div>';
}
public function formatCheck(string $text): string
{
return $this->format($text) . '&nbsp; &nbsp; &nbsp;';
}
private static function isGeneratedHtml(string $text): bool
{
return strpos($text, self::MARKER_ATTRIBUTE) !== false;
@ -179,8 +174,9 @@ final class ImportDescriptionFormatter
/**
* @param array<int, string> $lines
* @param bool $hasPriorContent
*/
private function renderBlock(array $lines): string
private function renderBlock(array $lines, bool $hasPriorContent): string
{
$html = [];
$count = count($lines);
@ -190,6 +186,9 @@ final class ImportDescriptionFormatter
$line = $lines[$index];
if ($this->isHeadingLine($line)) {
if ($hasPriorContent || $html !== []) {
$html[] = '<p>&nbsp;</p>';
}
$html[] = '<h3>' . $this->escape(rtrim($line, ':')) . '</h3>';
$index++;
continue;
@ -429,17 +428,21 @@ final class ImportDescriptionFormatter
private function renderTable(array $rows): string
{
$html = ['<table class="catalog-import-description__table">', '<tbody>'];
$headerRow = $this->isParameterValueHeaderRow($rows);
foreach ($rows as $row) {
foreach ($rows as $rowIndex => $row) {
if ($row === []) {
continue;
}
$html[] = '<tr>';
foreach (array_values($row) as $cellIndex => $cell) {
$tag = $cellIndex === 0 ? 'th' : 'td';
$scope = $cellIndex === 0 ? ' scope="row"' : '';
$html[] = '<' . $tag . $scope . '>' . $this->escape($cell) . '</' . $tag . '>';
if ($headerRow && $rowIndex === 0) {
$html[] = '<th scope="row">' . $this->escape($cell) . '</th>';
continue;
}
$html[] = '<td>' . $this->escape($cell) . '</td>';
}
$html[] = '</tr>';
}
@ -450,6 +453,21 @@ final class ImportDescriptionFormatter
return implode("\n", $html);
}
/**
* @param array<int, array<int, string>> $rows
*/
private function isParameterValueHeaderRow(array $rows): bool
{
if (!isset($rows[0]) || count($rows[0]) < 2) {
return false;
}
$firstRow = array_values($rows[0]);
return isset($firstRow[0], $firstRow[1])
&& trim($firstRow[0]) === 'Параметр'
&& trim($firstRow[1]) === 'Значение';
}
private function normalizeCell(string $cell): string
{
$cell = trim($cell);

View File

@ -14,16 +14,6 @@ function assertContainsText(string $needle, string $haystack, string $message):
}
}
function assertEndsWithText(string $suffix, string $haystack, string $message): void
{
if (substr($haystack, -strlen($suffix)) !== $suffix) {
fwrite(STDERR, $message . PHP_EOL);
fwrite(STDERR, 'Expected suffix: ' . $suffix . PHP_EOL);
fwrite(STDERR, $haystack . PHP_EOL);
exit(1);
}
}
$singleLine = $formatter->format('Корзина (600*300*100мм)');
assertContainsText('<p>Корзина (600*300*100мм)</p>', $singleLine, 'Single line description must become a paragraph.');
@ -33,13 +23,18 @@ assertContainsText('<p>Второй абзац</p>', $paragraphs, 'Second paragr
$keyValue = $formatter->format("Торговая марка: BRITA\nАртикул: 102828\nВес нетто, кг: 1,90");
assertContainsText('<table class="catalog-import-description__table">', $keyValue, 'Key-value block must become a table.');
assertContainsText('<th scope="row">Артикул</th>', $keyValue, 'Key cell is missing.');
assertContainsText('<td>Артикул</td>', $keyValue, 'Key cell is missing.');
assertContainsText('<td>102828</td>', $keyValue, 'Value cell is missing.');
$tabular = $formatter->format("Длина\t2400 мм\nЦвет\tхром");
assertContainsText('<th scope="row">Длина</th>', $tabular, 'Tabular first column must become row heading.');
assertContainsText('<td>Длина</td>', $tabular, 'Tabular first column must be a normal cell.');
assertContainsText('<td>2400 мм</td>', $tabular, 'Tabular value is missing.');
$parameterHeader = $formatter->format("Параметр\tЗначение\nДлина\t2400 мм\nЦвет\tхром");
assertContainsText('<th scope="row">Параметр</th>', $parameterHeader, 'Header row first cell is missing.');
assertContainsText('<th scope="row">Значение</th>', $parameterHeader, 'Header row second cell is missing.');
assertContainsText('<td>Длина</td>', $parameterHeader, 'Regular row after header is missing.');
$unordered = $formatter->format("* Первый пункт\n- Второй пункт");
assertContainsText('<ul>', $unordered, 'Unordered list is missing.');
assertContainsText('<li>Первый пункт</li>', $unordered, 'Unordered list item is missing.');
@ -52,6 +47,10 @@ $heading = $formatter->format("Описание и основные функци
assertContainsText('<h3>Описание и основные функции</h3>', $heading, 'Heading is missing.');
assertContainsText('<p>Содержит 4 ступени фильтрации.</p>', $heading, 'Paragraph after heading is missing.');
$headingGap = $formatter->format("Текст перед заголовком.\n\nОписание и основные функции:\nСодержит 4 ступени фильтрации.");
assertContainsText('<p>&nbsp;</p>', $headingGap, 'Heading spacer is missing.');
assertContainsText('<h3>Описание и основные функции</h3>', $headingGap, 'Heading after spacer is missing.');
$unsafeHtml = $formatter->format('<script>alert(1)</script><p>Текст</p>');
assertContainsText('&lt;script&gt;alert(1)&lt;/script&gt;&lt;p&gt;Текст&lt;/p&gt;', $unsafeHtml, 'Unsafe HTML must be escaped.');
@ -61,7 +60,4 @@ if ($empty !== '') {
exit(1);
}
$checkVersion = $formatter->formatCheck('Проверка');
assertEndsWithText('&nbsp; &nbsp; &nbsp;', $checkVersion, 'Check version must append the tail.');
echo 'OK' . PHP_EOL;

View File

@ -0,0 +1,31 @@
<?php
require_once __DIR__ . '/../local/php_interface/lib/ImportDescriptionFormatter.php';
$input = '';
if ($argc > 1 && $argv[1] !== '--stdin' && $argv[1] !== '-') {
$input = implode(' ', array_slice($argv, 1));
} else {
$stdin = fopen('php://stdin', 'rb');
if ($stdin !== false) {
while (!feof($stdin)) {
$chunk = fread($stdin, 8192);
if ($chunk === false) {
break;
}
$input .= $chunk;
}
fclose($stdin);
}
}
if ($input === '') {
fwrite(STDERR, "Usage:\n");
fwrite(STDERR, " php tools/format_description.php \"text\"\n");
fwrite(STDERR, " printf 'line1\\nline2' | php tools/format_description.php\n");
exit(1);
}
$formatter = new \Local\Catalog\ImportDescriptionFormatter();
echo $formatter->format($input), PHP_EOL;