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();
|
|
|
|
}
|
|
|
|
|
2021-02-05 16:21:54 +03:00
|
|
|
$message = $this->connection->serializeJob($encodedMessage['body'], $encodedMessage['headers'] ?? []);
|
2021-02-02 11:59:25 +03:00
|
|
|
|
2023-09-30 19:15:45 +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
|
|
|
|
{
|
2023-09-30 19:15:45 +03:00
|
|
|
$messageKey = hash('crc32', $jobData);
|
2021-02-02 11:59:25 +03:00
|
|
|
|
2023-09-30 19:15:45 +03:00
|
|
|
if ($this->connection->getLockStorage()->setLock($messageKey)) {
|
2021-02-02 11:59:25 +03:00
|
|
|
$this->connection->send($jobData, $delay);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|