1
0
mirror of synced 2024-11-29 00:25:30 +03:00
symfony-beanstalkd-messenger/Transport/BeanstalkSender.php

71 lines
2.0 KiB
PHP
Raw Normal View History

2021-02-02 11:59:25 +03:00
<?php
namespace RetailCrm\Messenger\Beanstalkd\Transport;
use Pheanstalk\Contract\PheanstalkInterface;
use Pheanstalk\Exception\ServerException;
use Pheanstalk\Response\ArrayResponse;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Stamp;
use Symfony\Component\Messenger\Transport\Sender\SenderInterface;
use Symfony\Component\Messenger\Transport\Serialization\SerializerInterface;
use Throwable;
/**
* Class BeanstalkSender
*
* @package RetailCrm\Messenger\Beanstalkd\Transport
*/
class BeanstalkSender implements SenderInterface
{
private $connection;
private $serializer;
/**
* BeanstalkSender constructor.
*
* @param Connection $connection
* @param SerializerInterface $serializer
*/
public function __construct(Connection $connection, SerializerInterface $serializer)
{
$this->connection = $connection;
$this->serializer = $serializer;
}
/**
* {@inheritdoc}
*/
public function send(Envelope $envelope): Envelope
{
$encodedMessage = $this->serializer->encode($envelope);
/** @var Stamp\DelayStamp|null $delayStamp */
$delayStamp = $envelope->last(Stamp\DelayStamp::class);
$delay = PheanstalkInterface::DEFAULT_DELAY;
if (null !== $delayStamp) {
$delay = $delayStamp->getDelay();
}
$message = $this->connection->serializeJob($encodedMessage['body'], $encodedMessage['headers'] ?? []);
2021-02-02 11:59:25 +03:00
if ($this->connection->isNotSendIfExists() && null !== $this->connection->getLockStorage()) {
2021-02-02 11:59:25 +03:00
$this->sendIfNotExist($message, $delay);
} else {
$this->connection->send($message, $delay);
}
return $envelope;
}
private function sendIfNotExist(string $jobData, int $delay): void
{
$messageKey = hash('crc32', $jobData);
2021-02-02 11:59:25 +03:00
if ($this->connection->getLockStorage()->setLock($messageKey)) {
2021-02-02 11:59:25 +03:00
$this->connection->send($jobData, $delay);
}
}
}