mercureact/tests/Broker/TopicTest.php

62 lines
2.2 KiB
PHP
Raw Normal View History

2024-03-12 00:45:21 +00:00
<?php
namespace NoccyLabs\Mercureact\Broker;
use NoccyLabs\Mercureact\Broker\Subscriber\SubscriberInterface;
2024-03-12 00:45:21 +00:00
use PHPUnit\Framework\Attributes\CoversClass;
#[CoversClass(Topic::class)]
2024-03-12 17:20:56 +00:00
#[CoversClass(Message::class)]
2024-03-12 00:45:21 +00:00
class TopicTest extends \PHPUnit\Framework\TestCase
{
public function testPublicMessagesAreDeliveredToAllSubscribers()
{
2024-03-13 23:45:26 +00:00
$authorizedSubscriber = new class extends _Subscriber {
public function isAuthenticated():bool { return true; }
2024-03-12 00:45:21 +00:00
};
2024-03-13 23:45:26 +00:00
$unauthorizedSubscriber = new class extends _Subscriber {
public function isAuthenticated():bool { return false; }
2024-03-12 00:45:21 +00:00
};
$topic = new Topic("foo");
$topic->addSubscriber($authorizedSubscriber);
$topic->addSubscriber($unauthorizedSubscriber);
$message = new Message(topic:["foo"], data:"test", private:false);
$topic->publish($message);
$this->assertEquals(1, count($authorizedSubscriber->messages));
$this->assertEquals(1, count($unauthorizedSubscriber->messages));
}
public function testPrivateMessagesAreNotDeliveredToUnauthorizedSubscribers()
{
2024-03-13 23:45:26 +00:00
$authorizedSubscriber = new class extends _Subscriber {
public function isAuthenticated():bool { return true; }
2024-03-12 00:45:21 +00:00
};
2024-03-13 23:45:26 +00:00
$unauthorizedSubscriber = new class extends _Subscriber {
public function isAuthenticated():bool { return false; }
2024-03-12 00:45:21 +00:00
};
$topic = new Topic("foo");
$topic->addSubscriber($authorizedSubscriber);
$topic->addSubscriber($unauthorizedSubscriber);
$message = new Message(topic:["foo"], data:"test", private:true);
$topic->publish($message);
$this->assertEquals(1, count($authorizedSubscriber->messages));
$this->assertEquals(0, count($unauthorizedSubscriber->messages));
}
2024-03-12 17:20:56 +00:00
}
2024-03-13 23:45:26 +00:00
abstract class _Subscriber implements SubscriberInterface {
public array $messages = [];
public function isAuthenticated():bool { return false; }
public function deliver(Message $message):void { $this->messages[] = $message; }
public function getMercureClaims(): ?array { return []; }
2024-03-13 23:45:26 +00:00
public function getPayload(): ?array { return null; }
public function getId(): string { return ""; }
};