akuma / pacl
Asynchronous Centrifugo client
dev-master
2023-06-28 11:16 UTC
Requires
- php: >=8.1
- evenement/evenement: ^3.0 || ^2.0
- fresh/datetime: ^2.0
- guzzlehttp/psr7: ^2.0 || ^1.7
- psr/log: ^3.0
- ratchet/rfc6455: ^0.3.1
- react/socket: ^1.9
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.20
- johnkary/phpunit-speedtrap: ^4.0
- pedrotroller/php-cs-custom-fixer: ^2.32
- phpunit/phpunit: ^9.3 || ^5.7 || ^4.8
Suggests
- reactivex/rxphp: ~2.0
This package is auto-updated.
Last update: 2024-10-28 14:22:20 UTC
README
An asynchronous Centrifugo client in PHP
Install via composer:
composer require akuma/pacl
Usage
Pacl as a standalone app: Connect to an example server, send a message, display output:
<?php declare(strict_types=1); namespace Akuma\Centrifugo; use Akuma\Centrifugo\Client\WebSocketClient; use Akuma\Centrifugo\Connection\Configuration; use Akuma\Centrifugo\Encoder\HmacSignatureEncoder; use Akuma\Centrifugo\Model\CentrifugoUserInterface; use Akuma\Centrifugo\Model\Command\PublishCommand; use Akuma\Centrifugo\Security\CredentialsGenerator; use Akuma\Centrifugo\Security\JwtGenerator; use Psr\Log\AbstractLogger; use React\EventLoop\Loop; require_once './../vendor/autoload.php'; $signatureEncoder = new HmacSignatureEncoder('akuma-cent-token-hmac-secret-key'); $jwtGenerator = new JwtGenerator($signatureEncoder); $credentialsGenerator = new CredentialsGenerator($jwtGenerator); $config = new Configuration( 'ws://localhost:8569/connection/websocket', headers: [ 'Origin' => 'http://pacl.akuma.local', ] ); $client = new WebSocketClient($config); $user = new class implements CentrifugoUserInterface { public function getCentrifugoSubject(): string { return 'test-user-' . time(); } public function getCentrifugoUserInfo(): array { return []; } }; $logger = new class extends AbstractLogger { /** * {@inheritDoc} */ public function log($level, \Stringable|string $message, array $context = []): void { echo match ($level) { default => (string) $message } . PHP_EOL; } }; $token = $credentialsGenerator->generateJwtTokenForUser($user, channels: ['pacl-example']); $client->setLogger($logger); $client->connect($token); // Sleep 1 second to ensure that connection is established and client info provided Loop::get()->addTimer(1, function () use ($client) { if (!$client->isAuthenticated()) { throw new \RuntimeException('Unable to connect to Centrifuge'); } else { Loop::get()->addPeriodicTimer(2, function () use ($client) { if ($client->getClientInfo()) { $client->command(new PublishCommand( 'pacl-example', [ 'time' => (new \DateTimeImmutable())->format(DATE_ATOM), ] )); } }); } });