Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion Helpers/ExampleMessageHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Okay\Modules\Sviat\TelegramNotifier\Helpers;

use Okay\Core\Request;
use Okay\Entities\CommentsEntity;

/**
* Генерація прикладів повідомлень для відображення в адмін-панелі
Expand Down Expand Up @@ -96,10 +97,19 @@ public function getExampleCommentMessage(): string
"Від: Леся Українка",
"Email: lesya.ukrainka@example.com",
"Сторінка: <a href=\"" . htmlspecialchars($exampleUrl, ENT_QUOTES, 'UTF-8') . "\">Смартфон Samsung Galaxy S23</a>",
];

// Прев'ю має збігатися з тим, що прийде насправді: у стоковій OkayCMS
// колонки `rating` немає, тож і рядка з оцінкою в повідомленні не буде.
if (in_array('rating', CommentsEntity::getFields(), true)) {
$message[] = "Оцінка: ★★★★★ (5/5)";
}

$message = array_merge($message, [
"",
"Коментар:",
"<i>Чудовий товар! Дуже задоволена якістю та швидкою доставкою. Рекомендую!</i>",
];
]);

return implode("\n", $message);
}
Expand Down
24 changes: 24 additions & 0 deletions Helpers/FormatterHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,10 @@ public function formatCommentMessage($comment): string
$pageUrl = $this->getCommentPageUrl($comment);
$message[] = $this->formatPageLink($pageUrl);

if ($rating = $this->formatRatingField($comment)) {
$message[] = $rating;
}

$message[] = "";
$message[] = "Коментар:";
$message[] = "<i>" . $this->escapeHtml($comment->text ?? '') . "</i>";
Expand Down Expand Up @@ -599,6 +603,26 @@ private function getEntityTitle(string $entityClass, string $url): ?string
}
}

/**
* Оцінки може не бути: у стоковій OkayCMS колонки `rating` немає взагалі,
* а до статей вона не обов'язкова.
*
* @param object $comment Об'єкт коментаря
* @return string|null Відформатований рядок з оцінкою або null
*/
private function formatRatingField($comment): ?string
{
$rating = $comment->rating ?? null;
if (empty($rating)) {
return null;
}

// Значення поза шкалою зіпсувало б рядок зірок, тож затискаємо.
$rating = max(1, min(5, (int)$rating));

return "Оцінка: " . str_repeat('★', $rating) . str_repeat('☆', 5 - $rating) . " ({$rating}/5)";
}

/**
* Форматує поле Email для повідомлення
*
Expand Down
2 changes: 1 addition & 1 deletion Init/module.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"Okay": "4.5.2",
"version": "1.0.7",
"version": "1.0.8",
"moduleName": "Telegram сповіщення",
"vendor": {
"email": "devsviat@proton.me",
Expand Down
68 changes: 68 additions & 0 deletions tests/FormatterHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -273,4 +273,72 @@ public function testCurrencySignFallsBackToHryvnia(): void

self::assertStringContainsString('100 ₴', $message);
}

/**
* Оцінки може не бути: у стоковій OkayCMS колонки `rating` немає взагалі,
* а до статей вона не обов'язкова. Рядок додається лише тоді, коли оцінка
* справді є.
*
* @dataProvider commentRatingProvider
*/
#[DataProvider('commentRatingProvider')]
public function testRatingLineAppearsOnlyWhenThereIsARating(object $comment, ?string $expected): void
{
$message = $this->formatter->formatCommentMessage($comment);

if ($expected === null) {
$this->assertStringNotContainsString('Оцінка:', $message);

return;
}

$this->assertStringContainsString($expected, $message);
}

public static function commentRatingProvider(): array
{
$base = ['type' => 'product', 'name' => 'Клієнт', 'email' => 'c@example.com', 'text' => 'Текст'];

return [
'товар з оцінкою' => [(object)($base + ['rating' => 5]), 'Оцінка: ★★★★★ (5/5)'],
'половина шкали' => [(object)($base + ['rating' => 3]), 'Оцінка: ★★★☆☆ (3/5)'],
// PDO віддає tinyint рядком, тож приведення типу має бути на місці.
'оцінка рядком' => [(object)($base + ['rating' => '4']), 'Оцінка: ★★★★☆ (4/5)'],
'стаття без оцінки' => [(object)(['type' => 'post'] + $base + ['rating' => null]), null],
'стокова CMS: поля немає' => [(object)$base, null],
'нуль оцінкою не є' => [(object)($base + ['rating' => 0]), null],
// Значення поза шкалою зіпсувало б рядок зірок.
'вище шкали' => [(object)($base + ['rating' => 99]), 'Оцінка: ★★★★★ (5/5)'],
'нижче шкали' => [(object)($base + ['rating' => -3]), 'Оцінка: ★☆☆☆☆ (1/5)'],
];
}

/**
* Прев'ю в адмінці показує, як виглядатиме повідомлення. Воно має
* збігатися з реальністю на обох CMS: там, де колонки `rating` немає,
* рядка з оцінкою не буде ні в прикладі, ні в справжньому сповіщенні.
*/
public function testExamplePreviewMatchesWhetherRatingsExist(): void
{
// Прев'ю будує абсолютний URL через Request::getRootUrl(), а той читає
// $_SERVER напряму - у CLI цих ключів немає.
$server = $_SERVER;
$_SERVER += ['SERVER_PROTOCOL' => 'HTTP/1.1', 'SERVER_PORT' => 80, 'HTTP_HOST' => 'example.com'];

try {
$reflector = new \ReflectionClass(\Okay\Modules\Sviat\TelegramNotifier\Helpers\ExampleMessageHelper::class);
$example = $reflector->newInstanceWithoutConstructor();
$preview = $reflector->getMethod('getExampleCommentMessage')->invoke($example);
} finally {
$_SERVER = $server;
}

$ratingsExist = in_array('rating', \Okay\Entities\CommentsEntity::getFields(), true);

$this->assertSame(
$ratingsExist,
str_contains($preview, 'Оцінка:'),
"прев'ю розходиться з тим, чи підтримує ця CMS оцінки"
);
}
}
Loading