PHP code example of machinateur / php-sse

1. Go to this page and download the library: Download machinateur/php-sse library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

machinateur / php-sse example snippets




namespace App;

use Machinateur\SSE\MessageStream;
use Machinateur\SSE\Exception\TimeoutException;

// ...

$stream = new MessageStream();

// ...

// Count to 10, then quit at 5.
$stream->run(function () {
    foreach (\range(1, 10, 1) as $i) {
        if ($i > 5) {
            throw TimeoutException::toTriggerStreamShutdown();
        }

        yield $i;

        \sleep(1);
    }
});

$recommendedHeaders = \Machinateur\SSE\MessageStream::getRecommendedHeaders();

$stream = new \Machinateur\SSE\MessageStream();
$stream->setLogger($myLogger);
// ...



namespace App;

use Machinateur\SSE\Exception\TimeoutException;
use Machinateur\SSE\MessageStream;
use Machinateur\SSE\MessageStreamInterface;
use Machinateur\SSE\Message\MessageInterface;

/**
 * A naive implementation of {@see MessageStreamInterface}.
 */
class CustomMessageStream extends MessageStream implements MessageStreamInterface
{
    /**
     * @inheritDoc
     */
    public function run(callable $callback)
    {
        try {
            foreach ($callback() as $message) {
                \assert($message instanceof MessageInterface);

                $this->printOutput($message->getMessageFormat());
                $this->checkConnection();
            }
        } catch (TimeoutException $exception) {
        }
    }
}

// ...

$stream = new CustomMessageStream();




namespace App;

use Machinateur\SSE\Format\StreamFormat;
use Machinateur\SSE\Message\MessageInterface;

/**
 * Custom message to be yielded by a generator function. It holds a data array, which is given to `json_encode()`
 *  when sent by the message stream.
 */
class CustomMessage implements MessageInterface
{
    const FLAGS = \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE | \JSON_PRESERVE_ZERO_FRACTION;

    /** @var array */
    private $data = array();
    
    /**
     * @param array $data
     */
    public function setData($data)
    {
        $this->data = $data;
    }

    /**
     * @inheritDoc
     */
    public function getStreamFormat()
    {
        return [
            StreamFormat::FIELD_COMMENT => 'source: ' . self::class,
            StreamFormat::FIELD_DATA => \json_encode($this->data, self::FLAGS)
        ];
    }
}


use Machinateur\SSE\MessageStream;

// ...

$headers = array();

foreach (MessageStream::getRecommendedHeaders() as $header) {
    list($key, $value) = \explode(':', $header, 2);
    $headers[$key] = $value;
}

$response->headers->add($headers);

use Machinateur\SSE\MessageStream;

// ...

$headers = array();

foreach (MessageStream::getRecommendedHeaders() as $header) {
    list($key, $value) = \explode(':', $header, 2);
    $headers[$key] = $value;
}

$response->withHeaders($headers);
// or
$response->headers->add($headers);



namespace App;

use Hhxsv5\SSE\Event;
use Hhxsv5\SSE\StopSSEException;
use Machinateur\SSE\Exception\TimeoutException;
use Machinateur\SSE\Format\StreamFormat;
use Machinateur\SSE\MessageStream;

foreach (MessageStream::getRecommendedHeaders() as $header) {
    \header($header);
}

// The callback for `hhxsv5/php-sse`.
$callback = function () {
    $id = \mt_rand(1, 1000);

    // Get news from database or service.
    $news = [
        [
            'id' => $id,
            'title' => 'title ' . $id,
            'content' => 'content ' . $id,
        ],
    ];

    // Stop here when no news available.
    if (empty($news)) {
        return false;
    }
    
    // In case something went wrong.
    $shouldStop = false;
    if ($shouldStop) {
        throw new StopSSEException();
    }
    
    return \json_encode(\compact('news'));
    // return ['event' => 'ping', 'data' => 'ping data'];
    // return ['id' => uniqid(), 'data' => json_encode(compact('news'))];
};

$event = new Event($callback, 'news');
unset($callback);

/**
 * Wrapper for better access to protected fields of `\Hhxsv5\SSE\Event`.
 * 
 * @property string $id
 * @property string $event
 * @property string $data
 * @property string $retry
 * @property string $comment
 */
class EventWrapper extends Event
{
    /** @var Event */
    protected $eventObject;

    public function __construct(Event $event)
    {
        $this->eventObject = $event;
    }

    /**
     * @inheritDoc
     */
    public function __get($name)
    {
        if (\in_array($name, ['id', 'event', 'data', 'retry', 'comment']) && \property_exists($this, $name)) {
            return $this->eventObject->{$name};
        }

        throw new LogicException(\sprintf('Unknown property: %s', $name));
    }

    /**
     * @inheritDoc
     */
    public function fill()
    {
        $this->eventObject->fill();
    }

    public function __toString()
    {
        return $this->eventObject->__toString();
    }
}

$event = new EventWrapper($event);

// The callback for `machinateur/php-sse`.
$callback = function () use ($event) {
    try {
        $event->fill();
        yield [
            StreamFormat::FIELD_COMMENT => $event->comment;
            StreamFormat::FIELD_ID => $event->id;
            StreamFormat::FIELD_RETRY => $event->retry;
            StreamFormat::FIELD_EVENT => $event->event;
            StreamFormat::FIELD_DATA => $event->data;
        ];
    } catch (StopSSEException $exception) {
        throw TimeoutException::toTriggerStreamShutdown();
    }
};

$messageStream = new MessageStream();
$messageStream->setLogger($myLogger);
$messageStream->run($callback);